import { inject, onUnmounted, ref, watch, provide } from 'vue';
import mitt from 'mitt';
import { isString, isArray, isFunction, getObjClassName, removeEmpty, isEmptyObj, kebabCase } from '../utils/util';
import { mergeDescriptors } from '../utils/merge-descriptors';
import { getInstanceListener, getVcParentInstance } from '../utils/private/vm';
import * as cesiumProps from '../utils/cesium-props';
import { vcKey } from '../utils/config';
import { t } from '../locale';
import { DrawStatus } from '../vc-shared';
import useTimeout from '../composables/private/use-timeout';
import * as coordtransform from '../utils/coordtransform';
import cloneDeep from 'lodash/cloneDeep';
import differenceBy from 'lodash/differenceBy';

/*! *****************************************************************************
Copyright (c) Microsoft Corporation.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */

function __awaiter(thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
}

function useLog (vcInstance) {
    const makeLog = (prefix = '') => {
        return function (...args) {
            if (prefix) {
                if (isString(args[0])) {
                    args[0] = prefix.trim() + ' ' + args[0];
                }
                else {
                    args = [prefix.trim(), ...args];
                }
            }
            console.log(...args);
        };
    };
    const makeWarn = (prefix = '') => {
        return function (...args) {
            if (prefix) {
                if (isString(args[0])) {
                    args[0] = prefix.trim() + ' ' + args[0];
                }
                else {
                    args = [prefix.trim(), ...args];
                }
            }
            console.warn(...args);
        };
    };
    const makeError = (prefix = '') => {
        return function (...args) {
            if (prefix) {
                if (isString(args[0])) {
                    args[0] = prefix.trim() + ' ' + args[0];
                }
                else {
                    args = [prefix.trim(), ...args];
                }
            }
            console.error(...args);
        };
    };
    const makeDebug = (prefix = '') => {
        return function (...args) {
            if (prefix) {
                if (isString(args[0])) {
                    args[0] = prefix.trim() + ' ' + args[0];
                }
                else {
                    args = [prefix.trim(), ...args];
                }
            }
            if (process.env.NODE_ENV === 'development') ;
        };
    };
    const typeColor = (type = 'default') => {
        let color = '';
        switch (type) {
            case 'default':
                color = '#35495E';
                break;
            case 'primary':
                color = '#3488ff';
                break;
            case 'success':
                color = '#43B883';
                break;
            case 'warning':
                color = '#e6a23c';
                break;
            case 'danger':
                color = '#f56c6c';
                break;
        }
        return color;
    };
    const capsule = (title, info, type = 'primary') => {
        console.log(`%c ${title} %c ${info} %c`, 'background:#35495E; padding: 1px; border-radius: 3px 0 0 3px; color: #fff;', `background:${typeColor(type)}; padding: 1px; border-radius: 0 3px 3px 0;  color: #fff;`, 'background:transparent');
    };
    const colorful = textArr => {
        console.log(`%c${textArr.map(t => t.text || '').join('%c')}`, ...textArr.map(t => `color: ${typeColor(t.type)};`));
    };
    const success = text => {
        colorful([{ text, type: 'success' }]);
    };
    const warning = text => {
        colorful([{ text, type: 'warning' }]);
    };
    const danger = text => {
        colorful([{ text, type: 'danger' }]);
    };
    const primary = text => {
        colorful([{ text, type: 'primary' }]);
    };
    return {
        log: makeLog(`[VueCesium] ${vcInstance.proxy.$options.name}`),
        warn: makeWarn(`[VueCesium] WARN ${vcInstance.proxy.$options.name}`),
        error: makeError(`[VueCesium] ERR ${vcInstance.proxy.$options.name}`),
        debug: makeDebug(`[VueCesium] Debug ${vcInstance.proxy.$options.name}`),
        capsule,
        success,
        warning,
        danger,
        primary
    };
}

function useEvents (props, vcInstance, logger) {
    const bindEvents = (cesiumObject, cesiumEvents, register = true) => {
        const ev = cesiumEvents || vcInstance.cesiumEvents || [];
        ev &&
            ev.forEach(eventName => {
                if (cesiumObject[eventName]) {
                    const listener = getInstanceListener(vcInstance, eventName);
                    const methodName = register ? 'addEventListener' : 'removeEventListener';
                    listener && cesiumObject[eventName][methodName](listener);
                }
                else if (process.env.VUECESIUM_DEBUG) {
                    logger.warn('Add event linstener of ' + eventName + ' failed, try to upgrade Cesium to latest version.');
                }
            });
    };
    const registerEvents = register => {
        var _a;
        const { viewer, cesiumObject } = vcInstance;
        const { ScreenSpaceEventHandler, ScreenSpaceEventType } = Cesium;
        if (!viewer._vcPickScreenSpaceEventHandler || !viewer._vcViewerScreenSpaceEventHandler) {
            viewer._vcPickScreenSpaceEventHandler = new ScreenSpaceEventHandler(viewer.canvas);
            viewer._vcViewerScreenSpaceEventHandler = new ScreenSpaceEventHandler(viewer.canvas);
            viewerScreenSpaceEvents.forEach(type => {
                const listener = getInstanceListener(vcInstance, type);
                listener && viewer._vcViewerScreenSpaceEventHandler.setInputAction(listener, ScreenSpaceEventType[type]);
                viewer._vcPickScreenSpaceEventHandler.setInputAction(pickedAction.bind({ eventName: type, viewer }), ScreenSpaceEventType[type]);
            });
        }
        bindEvents(cesiumObject, vcInstance.cesiumEvents || [], register);
        (_a = vcInstance.cesiumMembersEvents) === null || _a === void 0 ? void 0 : _a.forEach(eventName => {
            const cesiumIntanceMember = isArray(eventName.name) && eventName.name.length > 0 && cesiumObject[eventName.name[0]]
                ? cesiumObject[eventName.name[0]][eventName.name[1]]
                : cesiumObject[eventName.name];
            cesiumIntanceMember && bindEvents(cesiumIntanceMember, eventName.events, register);
        });
        if (props.enableMouseEvent) {
            pickEvents.forEach(eventName => {
                const listener = getInstanceListener(vcInstance, eventName);
                if (register) {
                    listener && (cesiumObject[eventName] = listener);
                }
                else {
                    listener && delete cesiumObject[eventName];
                }
            });
        }
    };
    function pickedAction(movement) {
        if (!props.enableMouseEvent) {
            return;
        }
        const { viewer, eventName } = this;
        const position = movement.position || movement.endPosition;
        if (!position) {
            return;
        }
        const pickedFeatureAndCallbackNames = [];
        let callbackName;
        if (eventName.indexOf('LEFT_DOUBLE_CLICK') !== -1) {
            callbackName = 'dblclick';
        }
        else if (eventName.indexOf('CLICK') !== -1) {
            callbackName = 'click';
        }
        else if (eventName.indexOf('DOWN') !== -1) {
            callbackName = 'mousedown';
        }
        else if (eventName.indexOf('UP') !== -1) {
            callbackName = 'mouseup';
        }
        else if (eventName.indexOf('MOUSE_MOVE') !== -1) {
            callbackName = 'mousemove';
        }
        let callbackNameOut;
        if (callbackName === 'mousemove') {
            callbackNameOut = 'mouseout';
        }
        else if (callbackName === 'click') {
            callbackNameOut = 'clickout';
        }
        const pickedFeature = viewer.scene.pick(position);
        if (!Cesium.defined(pickedFeature)) {
            if (this.pickedFeature) {
                pickedFeatureAndCallbackNames.push({
                    callbackName: callbackNameOut,
                    pickedFeature: this.pickedFeature,
                });
            }
            this.pickedFeature = undefined;
        }
        else {
            if (this.pickedFeature && this.pickedFeature.id !== pickedFeature.id) {
                pickedFeatureAndCallbackNames.push({
                    callbackName: callbackNameOut,
                    pickedFeature: this.pickedFeature,
                });
            }
            if (callbackName === 'mousemove' && (!this.pickedFeature || this.pickedFeature.id !== pickedFeature.id)) {
                pickedFeatureAndCallbackNames.push({
                    callbackName: 'mouseover',
                    pickedFeature,
                });
            }
            pickedFeatureAndCallbackNames.push({
                callbackName,
                pickedFeature,
            });
        }
        if (pickedFeatureAndCallbackNames.length === 0) {
            return;
        }
        let intersection;
        const scene = viewer.scene;
        if (scene.mode === Cesium.SceneMode.SCENE3D) {
            const ray = scene.camera.getPickRay(position);
            intersection = scene.globe.pick(ray, scene);
        }
        else {
            intersection = scene.camera.pickEllipsoid(position, scene.globe.ellipsoid);
        }
        let button = -1;
        if (eventName.indexOf('LEFT') !== -1) {
            button = 0;
        }
        else if (eventName.indexOf('MIDDLE') !== -1) {
            button = 1;
        }
        else if (eventName.indexOf('RIGHT') !== -1) {
            button = 2;
        }
        const eventSourceList = [];
        pickedFeatureAndCallbackNames.forEach(item => {
            const callbackName = item.callbackName;
            const pickedFeature = item.pickedFeature;
            if (pickedFeature.id) {
                if (isArray(pickedFeature.id) && pickedFeature.id[0] instanceof Cesium.Entity) {
                    eventSourceList.push({
                        callbackName,
                        cesiumObject: pickedFeature.id[0].entityCollection.owner,
                        pickedFeature,
                    });
                }
                else if (pickedFeature.id instanceof Cesium.Entity) {
                    eventSourceList.push({
                        callbackName,
                        cesiumObject: pickedFeature.id,
                        pickedFeature,
                    });
                    eventSourceList.push({
                        callbackName,
                        cesiumObject: pickedFeature.id.entityCollection.owner,
                        pickedFeature,
                    });
                }
            }
            if (pickedFeature.primitive) {
                eventSourceList.push({
                    callbackName,
                    cesiumObject: pickedFeature.primitive,
                    pickedFeature,
                });
            }
            const getParentCollection = e => {
                eventSourceList.push({
                    callbackName,
                    cesiumObject: e,
                    pickedFeature,
                });
                if (e._vcParent) {
                    getParentCollection(e._vcParent);
                }
            };
            if (pickedFeature.collection) {
                eventSourceList.push({
                    callbackName,
                    cesiumObject: pickedFeature.collection,
                    pickedFeature,
                });
                if (pickedFeature.collection._vcParent) {
                    getParentCollection(pickedFeature.collection._vcParent);
                }
            }
        });
        eventSourceList.forEach(event => {
            event.cesiumObject[event.callbackName] &&
                event.cesiumObject[event.callbackName]({
                    type: `on${event.callbackName}`,
                    windowPosition: position,
                    surfacePosition: intersection,
                    pickedFeature: event.pickedFeature,
                    button,
                    cesiumObject: event.cesiumObject,
                });
        });
        this.pickedFeature = pickedFeature;
    }
    return {
        bindEvents,
        registerEvents,
    };
}
const viewerScreenSpaceEvents = [
    'LEFT_CLICK',
    'LEFT_DOUBLE_CLICK',
    'LEFT_DOWN',
    'LEFT_UP',
    'MIDDLE_CLICK',
    'MIDDLE_DOWN',
    'MIDDLE_UP',
    'MOUSE_MOVE',
    'PINCH_END',
    'PINCH_MOVE',
    'PINCH_START',
    'RIGHT_CLICK',
    'RIGHT_DOWN',
    'RIGHT_UP',
    'WHEEL',
];
const pickEvents = ['mousedown', 'mouseup', 'click', 'clickout', 'dblclick', 'mousemove', 'mouseover', 'mouseout'];

function useCommon (props, { emit }, vcInstance) {
    const logger = useLog(vcInstance);
    vcInstance.alreadyListening = [];
    let unwatchFns = [];
    vcInstance.mounted = false;
    const vcMitt = mitt();
    vcInstance.vcMitt = vcMitt;
    const $services = inject(vcKey);
    if ($services === void 0) {
        console.error(`${vcInstance.cesiumClass} ${t('vc.loadError')}`);
        return;
    }
    const parentVcInstance = getVcParentInstance(vcInstance);
    const eventsState = useEvents(props, vcInstance, logger);
    vcInstance.children = [];
    const entityGraphics = [
        'billboard',
        'box',
        'corridor',
        'cylinder',
        'ellipse',
        'ellipsoid',
        'label',
        'model',
        'tileset',
        'path',
        'plane',
        'point',
        'polygon',
        'polyline',
        'polylineVolume',
        'rectangle',
        'wall'
    ];
    const beforeLoad = () => __awaiter(this, void 0, void 0, function* () {
        emit('beforeLoad', vcInstance);
        if (parentVcInstance.nowaiting) {
            return true;
        }
        else {
            yield parentVcInstance.proxy.createPromise;
        }
    });
    const load = () => __awaiter(this, void 0, void 0, function* () {
        var _a;
        if (vcInstance.mounted) {
            return false;
        }
        logger.debug(`${vcInstance.cesiumClass}---loading`);
        yield beforeLoad();
        const { Cesium, viewer } = $services;
        vcInstance.viewer = viewer;
        vcInstance.Cesium = Cesium;
        if (!parentVcInstance.cesiumObject && !parentVcInstance.nowaiting) {
            return yield ((_a = parentVcInstance.proxy) === null || _a === void 0 ? void 0 : _a.load());
        }
        setPropsWatcher(true);
        return createCesiumObject().then((cesiumObject) => __awaiter(this, void 0, void 0, function* () {
            vcInstance.cesiumObject = cesiumObject;
            return mount().then(() => {
                vcInstance.mounted = true;
                parentVcInstance.children.push(vcInstance);
                const readyObj = { Cesium, viewer, cesiumObject, vm: vcInstance.proxy };
                emit('ready', readyObj);
                vcMitt.emit('ready', readyObj);
                logger.debug(`${vcInstance.cesiumClass}---loaded`);
                Object.assign(vcInstance.proxy, {
                    cesiumObject: vcInstance.cesiumObject
                });
                return readyObj;
            });
        }));
    });
    const beforeUnload = () => __awaiter(this, void 0, void 0, function* () {
        yield vcInstance.unloadingPromise;
    });
    const unload = () => __awaiter(this, void 0, void 0, function* () {
        yield beforeUnload();
        for (let i = 0; i < vcInstance.children.length; i++) {
            const vcChildCmp = vcInstance.children[i].proxy;
            yield vcChildCmp.unload();
        }
        vcInstance.children.length = 0;
        return vcInstance.mounted ? unmount().then(() => __awaiter(this, void 0, void 0, function* () {
            setPropsWatcher(false);
            vcInstance.cesiumObject = undefined;
            vcInstance.mounted = false;
            emit('destroyed', vcInstance);
            logger.debug(`${vcInstance.cesiumClass}---unmounted`);
            return vcInstance.renderByParent && !vcInstance.unloadingPromise ? parentVcInstance.proxy.unload() : true;
        })) : false;
    });
    const reload = () => __awaiter(this, void 0, void 0, function* () {
        return unload().then(() => {
            return load();
        });
    });
    const mount = () => __awaiter(this, void 0, void 0, function* () {
        var _b;
        eventsState.registerEvents(true);
        return ((_b = vcInstance.mount) === null || _b === void 0 ? void 0 : _b.call(vcInstance)) || true;
    });
    const unmount = () => __awaiter(this, void 0, void 0, function* () {
        var _c;
        eventsState.registerEvents(false);
        return ((_c = vcInstance.unmount) === null || _c === void 0 ? void 0 : _c.call(vcInstance)) || true;
    });
    const createCesiumObject = () => __awaiter(this, void 0, void 0, function* () {
        logger.debug('do createCesiumObject');
        if (isFunction(vcInstance.createCesiumObject)) {
            return vcInstance.createCesiumObject();
        }
        else {
            const options = transformProps(props);
            return new Cesium[vcInstance.cesiumClass](options);
        }
    });
    const setPropsWatcher = register => {
        if (register) {
            if (!vcInstance.cesiumClass || !Cesium[vcInstance.cesiumClass]) {
                return;
            }
            props &&
                Object.keys(props).forEach(vueProp => {
                    var _a, _b;
                    let cesiumProp = vueProp;
                    if (vueProp === 'labelStyle' || vueProp === 'wmtsStyle') {
                        cesiumProp = 'style';
                    }
                    else if (vueProp === 'bmKey') {
                        cesiumProp = 'key';
                    }
                    if (((_a = vcInstance.proxy.$options.watch) === null || _a === void 0 ? void 0 : _a[vueProp]) || vcInstance.alreadyListening.indexOf(vueProp) !== -1) {
                        return;
                    }
                    const watcherOptions = (_b = vcInstance.proxy.$options.props[vueProp]) === null || _b === void 0 ? void 0 : _b.watcherOptions;
                    const unwatch = vcInstance.proxy.$watch(vueProp, (val) => __awaiter(this, void 0, void 0, function* () {
                        yield vcInstance.proxy.createPromise;
                        const { cesiumObject } = vcInstance;
                        const pd = cesiumObject && Object.getOwnPropertyDescriptor(cesiumObject, cesiumProp);
                        const pdProto = cesiumObject && Object.getOwnPropertyDescriptor(Object.getPrototypeOf(cesiumObject), cesiumProp);
                        const hasSetter = (pd && (pd.writable || pd.set)) || (pdProto && (pdProto.writable || pdProto.set));
                        if (hasSetter) {
                            if (watcherOptions && watcherOptions.cesiumObjectBuilder) {
                                const newVal = watcherOptions.cesiumObjectBuilder.call(vcInstance, val, vcInstance.viewer.scene.globe.ellipsoid);
                                if (!(Cesium.defined(cesiumObject[cesiumProp]) && Cesium.defined(cesiumObject[cesiumProp]._callback))) {
                                    cesiumObject[cesiumProp] = newVal;
                                }
                            }
                            else {
                                cesiumObject[cesiumProp] = transformProp(cesiumProp, val);
                            }
                            return true;
                        }
                        else {
                            return vcInstance.proxy.reload();
                        }
                    }), {
                        deep: watcherOptions === null || watcherOptions === void 0 ? void 0 : watcherOptions.deep
                    });
                    unwatchFns.push(unwatch);
                });
        }
        else {
            unwatchFns.forEach(item => item());
            unwatchFns = [];
        }
    };
    const transformProps = (props) => {
        let options = {};
        props &&
            Object.keys(props).forEach(vueProp => {
                let cesiumProp = vueProp;
                if (vueProp === 'labelStyle' || vueProp === 'wmtsStyle') {
                    cesiumProp = 'style';
                }
                else if (vueProp === 'bmKey') {
                    cesiumProp = 'key';
                }
                const className = getObjClassName(props[vueProp]);
                if (className &&
                    className.indexOf('Graphics') === -1 &&
                    entityGraphics.indexOf(cesiumProp) !== -1 &&
                    (vcInstance.cesiumClass === 'Entity' || vcInstance.cesiumClass.indexOf('DataSource') > 0)) {
                    options[cesiumProp] = transformProps(props[vueProp]);
                }
                else {
                    options[cesiumProp] = transformProp(vueProp, props[vueProp]);
                }
            });
        options = removeEmpty(options);
        return options;
    };
    const transformProp = (prop, value) => {
        const className = getObjClassName(value);
        if (className &&
            className.indexOf('Graphics') === -1 &&
            entityGraphics.indexOf(prop) !== -1 &&
            (vcInstance.cesiumClass === 'Entity' || vcInstance.cesiumClass.indexOf('DataSource') > 0)) {
            return transformProps(value);
        }
        else {
            const cmpName = vcInstance.proxy.$options.name;
            const propOption = vcInstance.proxy.$options.props[prop] || (cesiumProps[prop] && cesiumProps[prop][prop]);
            return (propOption === null || propOption === void 0 ? void 0 : propOption.watcherOptions) && !isEmptyObj(value)
                ? propOption.watcherOptions.cesiumObjectBuilder.call(vcInstance, value, vcInstance.viewer.scene.globe.ellipsoid)
                : isFunction(value) && cmpName && (cmpName.indexOf('Graphics') !== -1 || cmpName === 'VcEntity')
                    ? new Cesium.CallbackProperty(value, false)
                    : value;
        }
    };
    const getServices = () => {
        return mergeDescriptors({}, $services || {});
    };
    const createPromise = new Promise((resolve, reject) => {
        try {
            let isLoading = false;
            if ($services.viewer) {
                isLoading = true;
                load().then(e => {
                    resolve(e);
                    isLoading = false;
                });
            }
            parentVcInstance.vcMitt.on('ready', () => {
                if (!isLoading && !vcInstance.isUnmounted) {
                    resolve(load());
                }
            });
        }
        catch (e) {
            reject(e);
        }
    });
    logger.debug(`${vcInstance.cesiumClass}---onCreated`);
    onUnmounted(() => {
        logger.debug(`${vcInstance.cesiumClass}---onUnmounted`);
        vcInstance.unloadingPromise = new Promise((resolve, reject) => {
            unload().then(() => {
                logger.debug(`${vcInstance.cesiumClass}---unloaded`);
                resolve(true);
                vcInstance.unloadingPromise = undefined;
                vcMitt.all.clear();
            });
        });
        vcInstance.alreadyListening = [];
    });
    Object.assign(vcInstance.proxy, {
        createPromise: createPromise,
        load: load,
        unload: unload,
        reload: reload,
        getCesiumObject: () => vcInstance.cesiumObject
    });
    return {
        $services,
        load,
        unload,
        reload,
        createPromise,
        transformProp,
        transformProps,
        unwatchFns,
        setPropsWatcher,
        logger,
        getServices
    };
}

function index (props, ctx, vcInstance) {
    vcInstance.cesiumEvents = ['definitionChanged'];
    useCommon(props, ctx, vcInstance);
    vcInstance.mount = () => __awaiter(this, void 0, void 0, function* () {
        const { cesiumObject } = vcInstance;
        const cmpNameArr = kebabCase(vcInstance.proxy.$options.name).split('-');
        const emitType = (cmpNameArr.length === 3 ? `update:${cmpNameArr[2]}` : 'update:polylineVolume');
        const parentVM = getVcParentInstance(vcInstance).proxy;
        return parentVM && parentVM.__updateGraphics(cesiumObject, emitType);
    });
    vcInstance.unmount = () => __awaiter(this, void 0, void 0, function* () {
        const cmpNameArr = kebabCase(vcInstance.proxy.$options.name).split('-');
        const emitType = (cmpNameArr.length === 3 ? `update:${cmpNameArr[2]}` : 'update:polylineVolume');
        const parentVM = getVcParentInstance(vcInstance).proxy;
        return (parentVM && parentVM.__updateGraphics(undefined, emitType));
    });
}

function index$1 ($services, { handleMouseClick = undefined, handleMouseDown = undefined, handleMouseUp = undefined, handleMouseMove = undefined, handleDoubleClick = undefined, handleMouseWheel = undefined, handlePinch = undefined }) {
    const handler = ref(null);
    const isActive = ref(false);
    const activate = () => {
        if (isActive.value) {
            return;
        }
        const { ScreenSpaceEventType, KeyboardEventModifier, ScreenSpaceEventHandler } = Cesium;
        if (!handler.value) {
            const { viewer } = $services;
            handler.value = new ScreenSpaceEventHandler(viewer.canvas);
        }
        const sseh = handler.value;
        sseh.setInputAction(onLeftClick, ScreenSpaceEventType.LEFT_CLICK);
        sseh.setInputAction(onLeftClickShift, ScreenSpaceEventType.LEFT_CLICK, KeyboardEventModifier.SHIFT);
        sseh.setInputAction(onLeftClickCtrl, ScreenSpaceEventType.LEFT_CLICK, KeyboardEventModifier.CTRL);
        sseh.setInputAction(onLeftDown, ScreenSpaceEventType.LEFT_DOWN);
        sseh.setInputAction(onLeftDownShift, ScreenSpaceEventType.LEFT_DOWN, KeyboardEventModifier.SHIFT);
        sseh.setInputAction(onLeftDownCtrl, ScreenSpaceEventType.LEFT_DOWN, KeyboardEventModifier.CTRL);
        sseh.setInputAction(onLeftUp, ScreenSpaceEventType.LEFT_UP);
        sseh.setInputAction(onLeftUpShift, ScreenSpaceEventType.LEFT_UP, KeyboardEventModifier.SHIFT);
        sseh.setInputAction(onLeftUpCtrl, ScreenSpaceEventType.LEFT_UP, KeyboardEventModifier.CTRL);
        sseh.setInputAction(onRightClick, ScreenSpaceEventType.RIGHT_CLICK);
        sseh.setInputAction(onRightClickShift, ScreenSpaceEventType.RIGHT_CLICK, KeyboardEventModifier.SHIFT);
        sseh.setInputAction(onRightClickCtrl, ScreenSpaceEventType.RIGHT_CLICK, KeyboardEventModifier.CTRL);
        sseh.setInputAction(onRightDown, ScreenSpaceEventType.RIGHT_DOWN);
        sseh.setInputAction(onRightDownShift, ScreenSpaceEventType.RIGHT_DOWN, KeyboardEventModifier.SHIFT);
        sseh.setInputAction(onRightDownCtrl, ScreenSpaceEventType.RIGHT_DOWN, KeyboardEventModifier.CTRL);
        sseh.setInputAction(onRightUp, ScreenSpaceEventType.RIGHT_UP);
        sseh.setInputAction(onRightUpShift, ScreenSpaceEventType.RIGHT_UP, KeyboardEventModifier.SHIFT);
        sseh.setInputAction(onRightUpCtrl, ScreenSpaceEventType.RIGHT_UP, KeyboardEventModifier.CTRL);
        sseh.setInputAction(onMiddleClick, ScreenSpaceEventType.MIDDLE_CLICK);
        sseh.setInputAction(onMiddleClickShift, ScreenSpaceEventType.MIDDLE_CLICK, KeyboardEventModifier.SHIFT);
        sseh.setInputAction(onMiddleClickCtrl, ScreenSpaceEventType.MIDDLE_CLICK, KeyboardEventModifier.CTRL);
        sseh.setInputAction(onMiddleDown, ScreenSpaceEventType.MIDDLE_DOWN);
        sseh.setInputAction(onMiddleDownShift, ScreenSpaceEventType.MIDDLE_DOWN, KeyboardEventModifier.SHIFT);
        sseh.setInputAction(onMiddleDownCtrl, ScreenSpaceEventType.MIDDLE_DOWN, KeyboardEventModifier.CTRL);
        sseh.setInputAction(onMiddleUp, ScreenSpaceEventType.MIDDLE_UP);
        sseh.setInputAction(onMiddleUpShift, ScreenSpaceEventType.MIDDLE_UP, KeyboardEventModifier.SHIFT);
        sseh.setInputAction(onMiddleUpCtrl, ScreenSpaceEventType.MIDDLE_UP, KeyboardEventModifier.CTRL);
        sseh.setInputAction(onDoubleClick, ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
        sseh.setInputAction(onDoubleClickShift, ScreenSpaceEventType.LEFT_DOUBLE_CLICK, KeyboardEventModifier.SHIFT);
        sseh.setInputAction(onDoubleClickCtrl, ScreenSpaceEventType.LEFT_DOUBLE_CLICK, KeyboardEventModifier.CTRL);
        sseh.setInputAction(onMouseMove, ScreenSpaceEventType.MOUSE_MOVE);
        sseh.setInputAction(onMouseMoveShift, ScreenSpaceEventType.MOUSE_MOVE, KeyboardEventModifier.SHIFT);
        sseh.setInputAction(onMouseMoveCtrl, ScreenSpaceEventType.MOUSE_MOVE, KeyboardEventModifier.CTRL);
        sseh.setInputAction(onMouseWheel, ScreenSpaceEventType.WHEEL);
        sseh.setInputAction(onMouseWheelShift, ScreenSpaceEventType.WHEEL, KeyboardEventModifier.SHIFT);
        sseh.setInputAction(onMouseWheelCtrl, ScreenSpaceEventType.WHEEL, KeyboardEventModifier.CTRL);
        sseh.setInputAction(onPinchStart, ScreenSpaceEventType.PINCH_START);
        sseh.setInputAction(onPinchStartShift, ScreenSpaceEventType.PINCH_START, KeyboardEventModifier.SHIFT);
        sseh.setInputAction(onPinchStartCtrl, ScreenSpaceEventType.PINCH_START, KeyboardEventModifier.CTRL);
        sseh.setInputAction(onPinchEnd, ScreenSpaceEventType.PINCH_END);
        sseh.setInputAction(onPinchEndShift, ScreenSpaceEventType.PINCH_END, KeyboardEventModifier.SHIFT);
        sseh.setInputAction(onPinchEndCtrl, ScreenSpaceEventType.PINCH_END, KeyboardEventModifier.CTRL);
        sseh.setInputAction(onPinchMove, ScreenSpaceEventType.PINCH_MOVE);
        sseh.setInputAction(onPinchMoveShift, ScreenSpaceEventType.PINCH_MOVE, KeyboardEventModifier.SHIFT);
        sseh.setInputAction(onPinchMoveCtrl, ScreenSpaceEventType.PINCH_MOVE, KeyboardEventModifier.CTRL);
        isActive.value = true;
    };
    const deactivate = () => {
        if (!isActive.value) {
            return;
        }
        const { ScreenSpaceEventType, KeyboardEventModifier } = Cesium;
        const sseh = handler.value;
        if (!sseh) {
            return;
        }
        sseh.removeInputAction(ScreenSpaceEventType.LEFT_CLICK);
        sseh.removeInputAction(ScreenSpaceEventType.LEFT_CLICK, KeyboardEventModifier.SHIFT);
        sseh.removeInputAction(ScreenSpaceEventType.LEFT_CLICK, KeyboardEventModifier.CTRL);
        sseh.removeInputAction(ScreenSpaceEventType.LEFT_DOWN);
        sseh.removeInputAction(ScreenSpaceEventType.LEFT_DOWN, KeyboardEventModifier.SHIFT);
        sseh.removeInputAction(ScreenSpaceEventType.LEFT_DOWN, KeyboardEventModifier.CTRL);
        sseh.removeInputAction(ScreenSpaceEventType.LEFT_UP);
        sseh.removeInputAction(ScreenSpaceEventType.LEFT_UP, KeyboardEventModifier.SHIFT);
        sseh.removeInputAction(ScreenSpaceEventType.LEFT_UP, KeyboardEventModifier.CTRL);
        sseh.removeInputAction(ScreenSpaceEventType.RIGHT_CLICK);
        sseh.removeInputAction(ScreenSpaceEventType.RIGHT_CLICK, KeyboardEventModifier.SHIFT);
        sseh.removeInputAction(ScreenSpaceEventType.RIGHT_CLICK, KeyboardEventModifier.CTRL);
        sseh.removeInputAction(ScreenSpaceEventType.RIGHT_DOWN);
        sseh.removeInputAction(ScreenSpaceEventType.RIGHT_DOWN, KeyboardEventModifier.SHIFT);
        sseh.removeInputAction(ScreenSpaceEventType.RIGHT_DOWN, KeyboardEventModifier.CTRL);
        sseh.removeInputAction(ScreenSpaceEventType.RIGHT_UP);
        sseh.removeInputAction(ScreenSpaceEventType.RIGHT_UP, KeyboardEventModifier.SHIFT);
        sseh.removeInputAction(ScreenSpaceEventType.RIGHT_UP, KeyboardEventModifier.CTRL);
        sseh.removeInputAction(ScreenSpaceEventType.MIDDLE_CLICK);
        sseh.removeInputAction(ScreenSpaceEventType.MIDDLE_CLICK, KeyboardEventModifier.SHIFT);
        sseh.removeInputAction(ScreenSpaceEventType.MIDDLE_CLICK, KeyboardEventModifier.CTRL);
        sseh.removeInputAction(ScreenSpaceEventType.MIDDLE_DOWN);
        sseh.removeInputAction(ScreenSpaceEventType.MIDDLE_DOWN, KeyboardEventModifier.SHIFT);
        sseh.removeInputAction(ScreenSpaceEventType.MIDDLE_DOWN, KeyboardEventModifier.CTRL);
        sseh.removeInputAction(ScreenSpaceEventType.MIDDLE_UP);
        sseh.removeInputAction(ScreenSpaceEventType.MIDDLE_UP, KeyboardEventModifier.SHIFT);
        sseh.removeInputAction(ScreenSpaceEventType.MIDDLE_UP, KeyboardEventModifier.CTRL);
        sseh.removeInputAction(ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
        sseh.removeInputAction(ScreenSpaceEventType.LEFT_DOUBLE_CLICK, KeyboardEventModifier.SHIFT);
        sseh.removeInputAction(ScreenSpaceEventType.LEFT_DOUBLE_CLICK, KeyboardEventModifier.CTRL);
        sseh.removeInputAction(ScreenSpaceEventType.MOUSE_MOVE);
        sseh.removeInputAction(ScreenSpaceEventType.MOUSE_MOVE, KeyboardEventModifier.SHIFT);
        sseh.removeInputAction(ScreenSpaceEventType.MOUSE_MOVE, KeyboardEventModifier.CTRL);
        sseh.removeInputAction(ScreenSpaceEventType.WHEEL);
        sseh.removeInputAction(ScreenSpaceEventType.WHEEL, KeyboardEventModifier.SHIFT);
        sseh.removeInputAction(ScreenSpaceEventType.WHEEL, KeyboardEventModifier.CTRL);
        sseh.removeInputAction(ScreenSpaceEventType.PINCH_START);
        sseh.removeInputAction(ScreenSpaceEventType.PINCH_START, KeyboardEventModifier.SHIFT);
        sseh.removeInputAction(ScreenSpaceEventType.PINCH_START, KeyboardEventModifier.CTRL);
        sseh.removeInputAction(ScreenSpaceEventType.PINCH_END);
        sseh.removeInputAction(ScreenSpaceEventType.PINCH_END, KeyboardEventModifier.SHIFT);
        sseh.removeInputAction(ScreenSpaceEventType.PINCH_END, KeyboardEventModifier.CTRL);
        sseh.removeInputAction(ScreenSpaceEventType.PINCH_MOVE);
        sseh.removeInputAction(ScreenSpaceEventType.PINCH_MOVE, KeyboardEventModifier.SHIFT);
        sseh.removeInputAction(ScreenSpaceEventType.PINCH_MOVE, KeyboardEventModifier.CTRL);
        isActive.value = false;
    };
    const destroy = () => {
        var _a;
        (_a = handler.value) === null || _a === void 0 ? void 0 : _a.destroy();
        handler.value = undefined;
    };
    const onLeftClick = movement => {
        handleMouseClick === null || handleMouseClick === void 0 ? void 0 : handleMouseClick(movement, {
            button: 0
        });
    };
    const onLeftClickShift = movement => {
        handleMouseClick === null || handleMouseClick === void 0 ? void 0 : handleMouseClick(movement, {
            button: 0,
            shift: true
        });
    };
    const onLeftClickCtrl = movement => {
        handleMouseClick === null || handleMouseClick === void 0 ? void 0 : handleMouseClick(movement, {
            button: 0,
            ctrl: true
        });
    };
    const onMiddleClick = movement => {
        handleMouseClick === null || handleMouseClick === void 0 ? void 0 : handleMouseClick(movement, {
            button: 1
        });
    };
    const onMiddleClickShift = movement => {
        handleMouseClick === null || handleMouseClick === void 0 ? void 0 : handleMouseClick(movement, {
            button: 1,
            shift: true
        });
    };
    const onMiddleClickCtrl = movement => {
        handleMouseClick === null || handleMouseClick === void 0 ? void 0 : handleMouseClick(movement, {
            button: 1,
            ctrl: true
        });
    };
    const onRightClick = movement => {
        handleMouseClick(movement, {
            button: 2
        });
    };
    const onRightClickShift = movement => {
        handleMouseClick(movement, {
            button: 2,
            shift: true
        });
    };
    const onRightClickCtrl = movement => {
        handleMouseClick(movement, {
            button: 2,
            ctrl: true
        });
    };
    const onLeftDown = movement => {
        handleMouseDown === null || handleMouseDown === void 0 ? void 0 : handleMouseDown(movement, {
            button: 0
        });
    };
    const onLeftDownShift = movement => {
        handleMouseDown === null || handleMouseDown === void 0 ? void 0 : handleMouseDown(movement, {
            button: 0,
            shift: true
        });
    };
    const onLeftDownCtrl = movement => {
        handleMouseDown === null || handleMouseDown === void 0 ? void 0 : handleMouseDown(movement, {
            button: 0,
            ctrl: true
        });
    };
    const onMiddleDown = movement => {
        handleMouseDown === null || handleMouseDown === void 0 ? void 0 : handleMouseDown(movement, {
            button: 1
        });
    };
    const onMiddleDownShift = movement => {
        handleMouseDown === null || handleMouseDown === void 0 ? void 0 : handleMouseDown(movement, {
            button: 1,
            shift: true
        });
    };
    const onMiddleDownCtrl = movement => {
        handleMouseDown === null || handleMouseDown === void 0 ? void 0 : handleMouseDown(movement, {
            button: 1,
            ctrl: true
        });
    };
    const onRightDown = movement => {
        handleMouseDown === null || handleMouseDown === void 0 ? void 0 : handleMouseDown(movement, {
            button: 2
        });
    };
    const onRightDownShift = movement => {
        handleMouseDown === null || handleMouseDown === void 0 ? void 0 : handleMouseDown(movement, {
            button: 2,
            shift: true
        });
    };
    const onRightDownCtrl = movement => {
        handleMouseDown === null || handleMouseDown === void 0 ? void 0 : handleMouseDown(movement, {
            button: 2,
            ctrl: true
        });
    };
    const onLeftUp = movement => {
        handleMouseUp === null || handleMouseUp === void 0 ? void 0 : handleMouseUp(movement, {
            button: 0
        });
    };
    const onLeftUpShift = movement => {
        handleMouseUp === null || handleMouseUp === void 0 ? void 0 : handleMouseUp(movement, {
            button: 0,
            shift: true
        });
    };
    const onLeftUpCtrl = movement => {
        handleMouseUp === null || handleMouseUp === void 0 ? void 0 : handleMouseUp(movement, {
            button: 0,
            ctrl: true
        });
    };
    const onMiddleUp = movement => {
        handleMouseUp === null || handleMouseUp === void 0 ? void 0 : handleMouseUp(movement, {
            button: 1,
            ctrl: true
        });
    };
    const onMiddleUpShift = movement => {
        handleMouseUp === null || handleMouseUp === void 0 ? void 0 : handleMouseUp(movement, {
            button: 1,
            shift: true
        });
    };
    const onMiddleUpCtrl = movement => {
        handleMouseUp === null || handleMouseUp === void 0 ? void 0 : handleMouseUp(movement, {
            button: 1,
            ctrl: true
        });
    };
    const onRightUp = movement => {
        handleMouseUp === null || handleMouseUp === void 0 ? void 0 : handleMouseUp(movement, {
            button: 2
        });
    };
    const onRightUpShift = movement => {
        handleMouseUp === null || handleMouseUp === void 0 ? void 0 : handleMouseUp(movement, {
            button: 2,
            shift: true
        });
    };
    const onRightUpCtrl = movement => {
        handleMouseUp === null || handleMouseUp === void 0 ? void 0 : handleMouseUp(movement, {
            button: 2,
            ctrl: true
        });
    };
    const onDoubleClick = movement => {
        handleDoubleClick === null || handleDoubleClick === void 0 ? void 0 : handleDoubleClick(movement, {
            button: 0
        });
    };
    const onDoubleClickShift = movement => {
        handleDoubleClick === null || handleDoubleClick === void 0 ? void 0 : handleDoubleClick(movement, {
            button: 0,
            shift: true
        });
    };
    const onDoubleClickCtrl = movement => {
        handleDoubleClick === null || handleDoubleClick === void 0 ? void 0 : handleDoubleClick(movement, {
            button: 0,
            ctrl: true
        });
    };
    const onMouseMove = movement => {
        handleMouseMove === null || handleMouseMove === void 0 ? void 0 : handleMouseMove(movement);
    };
    const onMouseMoveShift = movement => {
        handleMouseMove === null || handleMouseMove === void 0 ? void 0 : handleMouseMove(movement, {
            shift: true
        });
    };
    const onMouseMoveCtrl = movement => {
        handleMouseMove === null || handleMouseMove === void 0 ? void 0 : handleMouseMove(movement, {
            ctrl: true
        });
    };
    const onMouseWheel = e => {
        handleMouseWheel === null || handleMouseWheel === void 0 ? void 0 : handleMouseWheel(e);
    };
    const onMouseWheelShift = e => {
        handleMouseWheel === null || handleMouseWheel === void 0 ? void 0 : handleMouseWheel(e, {
            shift: true
        });
    };
    const onMouseWheelCtrl = e => {
        handleMouseWheel === null || handleMouseWheel === void 0 ? void 0 : handleMouseWheel(e, {
            ctrl: true
        });
    };
    const onPinchStart = e => {
        handlePinch === null || handlePinch === void 0 ? void 0 : handlePinch(e, {
            start: true
        });
    };
    const onPinchStartShift = e => {
        handlePinch === null || handlePinch === void 0 ? void 0 : handlePinch(e, {
            start: true,
            shift: true
        });
    };
    const onPinchStartCtrl = e => {
        handlePinch === null || handlePinch === void 0 ? void 0 : handlePinch(e, {
            start: true,
            ctrl: true
        });
    };
    const onPinchEnd = e => {
        handlePinch === null || handlePinch === void 0 ? void 0 : handlePinch(e, {
            end: true
        });
    };
    const onPinchEndShift = e => {
        handlePinch === null || handlePinch === void 0 ? void 0 : handlePinch(e, {
            end: true,
            shift: true
        });
    };
    const onPinchEndCtrl = e => {
        handlePinch === null || handlePinch === void 0 ? void 0 : handlePinch(e, {
            end: true,
            ctrl: true
        });
    };
    const onPinchMove = e => {
        handlePinch === null || handlePinch === void 0 ? void 0 : handlePinch(e, {
            move: true
        });
    };
    const onPinchMoveShift = e => {
        handlePinch === null || handlePinch === void 0 ? void 0 : handlePinch(e, {
            move: true,
            shift: true
        });
    };
    const onPinchMoveCtrl = e => {
        handlePinch === null || handlePinch === void 0 ? void 0 : handlePinch(e, {
            move: true,
            ctrl: true
        });
    };
    return {
        activate,
        deactivate,
        destroy,
        isActive
    };
}

function index$2 (props, $services, drawTipOpts, ctx) {
    const polylines = ref([]);
    const drawStatus = ref(DrawStatus.BeforeDraw);
    const canShowDrawTip = ref(false);
    const drawTipPosition = ref([0, 0, 0]);
    const drawTip = ref('');
    const showEditor = ref(false);
    const editorPosition = ref([0, 0, 0]);
    const mouseoverPoint = ref(null);
    const editingPoint = ref(null);
    const { emit } = ctx;
    let editorType = '';
    let lastClickPosition = undefined;
    let restorePosition = undefined;
    const { registerTimeout, removeTimeout } = useTimeout();
    const mouseDelta = 10;
    const startNew = () => {
        const polyline = {
            positions: [],
            tempPositions: [],
            show: false,
            drawStatus: DrawStatus.BeforeDraw,
            loop: props.loop
        };
        polylines.value.push(polyline);
        canShowDrawTip.value = true;
        drawTip.value = drawTipOpts.drawTip1;
    };
    const stop = () => {
        if (drawStatus.value === DrawStatus.Drawing) {
            polylines.value.pop();
        }
        drawStatus.value = DrawStatus.BeforeDraw;
        canShowDrawTip.value = false;
        drawTipPosition.value = [0, 0, 0];
    };
    const handleMouseClick = (movement, options) => {
        if (options.button === 2 && options.ctrl) {
            stop();
            return {
                windowPoistion: movement,
                finished: true
            };
        }
        if (drawStatus.value === DrawStatus.AfterDraw) {
            startNew();
        }
        const index = editingPoint.value ? editingPoint.value._vcPolylineIndx : polylines.value.length - 1;
        const polyline = polylines.value[index];
        const tempPositions = polyline.tempPositions;
        const { viewer, getWorldPosition } = $services;
        if (options.button === 2 && editingPoint.value) {
            drawStatus.value = DrawStatus.AfterDraw;
            polyline.drawStatus = DrawStatus.AfterDraw;
            polyline.positions[editingPoint.value._index] = restorePosition;
            editingPoint.value = undefined;
            drawTip.value = drawTipOpts.drawTip1;
            return {
                index: index,
                polylines: polylines,
                finished: true,
                position: restorePosition,
                windowPoistion: movement,
                type: editorType
            };
        }
        const { defined, Cartesian2 } = Cesium;
        lastClickPosition = lastClickPosition || new Cesium.Cartesian2(Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY);
        if ((Cartesian2.magnitude(Cartesian2.subtract(lastClickPosition, movement, {})) < mouseDelta)) {
            return;
        }
        if (options.button === 2 && drawStatus.value === DrawStatus.Drawing) {
            if (tempPositions.length > 1) {
                tempPositions.pop();
                handleMouseMove(movement);
            }
        }
        if (options.button !== 0) {
            return;
        }
        const scene = viewer.scene;
        const position = getWorldPosition(scene, movement, {});
        let finished = false;
        let type = 'new';
        if (defined(position)) {
            if (editingPoint.value) {
                drawStatus.value = DrawStatus.AfterDraw;
                editingPoint.value = undefined;
                finished = true;
                type = editorType;
                drawTip.value = drawTipOpts.drawTip1;
            }
            else {
                tempPositions.push(position);
                polyline.positions = tempPositions;
                polyline.show = true;
                polyline.drawStatus = DrawStatus.Drawing;
                drawStatus.value = DrawStatus.Drawing;
                canShowDrawTip.value = true;
                drawTip.value = drawTipOpts.drawTip2;
            }
            Cartesian2.clone(movement, lastClickPosition);
            return {
                index: index,
                polylines: polylines,
                finished: finished,
                position: position,
                windowPoistion: movement,
                type: type
            };
        }
    };
    const handleMouseMove = (movement) => {
        const { viewer, getWorldPosition } = $services;
        const scene = viewer.scene;
        const position = getWorldPosition(scene, movement, {});
        const { defined } = Cesium;
        if (!defined(position)) {
            return;
        }
        drawTipPosition.value = position;
        if (drawStatus.value !== DrawStatus.Drawing) {
            return;
        }
        const index = editingPoint.value ? editingPoint.value._vcPolylineIndx : polylines.value.length - 1;
        const polyline = polylines.value[index];
        let type = 'new';
        if (editingPoint.value) {
            const positions = polyline.positions;
            positions.splice(editingPoint.value._index, 1, position);
            type = editorType;
        }
        else {
            const tempPositions = polyline.tempPositions.slice();
            tempPositions.push(position);
            polyline.positions = tempPositions;
        }
        return {
            index: index,
            polylines: polylines,
            finished: false,
            position: position,
            windowPoistion: movement,
            type: type
        };
    };
    const handleDoubleClick = movement => {
        if (drawStatus.value === DrawStatus.Drawing) {
            const index = editingPoint.value ? editingPoint.value._vcPolylineIndx : polylines.value.length - 1;
            const polyline = polylines.value[index];
            polyline.positions = polyline.tempPositions;
            polyline.drawStatus = DrawStatus.AfterDraw;
            drawStatus.value = DrawStatus.AfterDraw;
            drawTip.value = drawTipOpts.drawTip1;
            return {
                index: index,
                polylines: polylines,
                finished: true,
                position: polyline.positions[polyline.positions.length - 1],
                windowPoistion: movement,
                type: 'new'
            };
        }
    };
    const onMouseoverPoints = function (e) {
        const { drawingHandlerActive, viewer } = $services;
        if (props.editable && drawStatus.value !== DrawStatus.Drawing && drawingHandlerActive) {
            e.pickedFeature.primitive.pixelSize = props.pointOpts.pixelSize * 1.5;
            removeTimeout();
            registerTimeout(() => {
                mouseoverPoint.value = e.pickedFeature.primitive;
                editorPosition.value = e.pickedFeature.primitive.position;
                showEditor.value = true;
                canShowDrawTip.value = false;
                drawTipPosition.value = [0, 0, 0];
            }, props.editorOpts.delay);
        }
        emit('mouseEvt', {
            type: e.type,
            name: this,
            target: e
        }, viewer);
    };
    const onMouseoutPoints = function (e) {
        const { viewer, selectedMeasurementOption } = $services;
        if (props.editable) {
            e.pickedFeature.primitive.pixelSize = props.pointOpts.pixelSize * 1.0;
            removeTimeout();
            registerTimeout(() => {
                editorPosition.value = [0, 0, 0];
                mouseoverPoint.value = undefined;
                showEditor.value = false;
            }, props.editorOpts.hideDelay);
            selectedMeasurementOption && (canShowDrawTip.value = true);
        }
        emit('mouseEvt', {
            type: e.type,
            target: e,
            name: this
        }, viewer);
    };
    const onMouseenterEditor = evt => {
        removeTimeout();
    };
    const onMouseleaveEditor = evt => {
        removeTimeout();
        registerTimeout(() => {
            editorPosition.value = [0, 0, 0];
            mouseoverPoint.value.pixelSize = props.pointOpts.pixelSize * 1.0;
            mouseoverPoint.value = undefined;
            showEditor.value = false;
        }, props.editorOpts.hideDelay);
    };
    const onEditorClick = function (e) {
        editorPosition.value = [0, 0, 0];
        showEditor.value = false;
        if (!props.editable) {
            return;
        }
        const { viewer } = $services;
        editorType = e;
        if (e === 'move') {
            drawTip.value = drawTipOpts.drawTip3;
            drawStatus.value = DrawStatus.Drawing;
            editingPoint.value = mouseoverPoint.value;
            canShowDrawTip.value = true;
            restorePosition = polylines.value[editingPoint.value._vcPolylineIndx].positions[editingPoint.value._index];
        }
        else if (e === 'insert') {
            const index = mouseoverPoint.value._vcPolylineIndx;
            const polyline = polylines.value[index];
            polyline.positions.splice(mouseoverPoint.value._index, 0, mouseoverPoint.value.position);
            editingPoint.value = mouseoverPoint.value;
            canShowDrawTip.value = true;
            drawStatus.value = DrawStatus.Drawing;
            drawTip.value = drawTipOpts.drawTip3;
        }
        else if (e === 'remove') {
            const index = mouseoverPoint.value._vcPolylineIndx;
            const polyline = polylines.value[index];
            polyline.positions.length > 2 && polyline.positions.splice(mouseoverPoint.value._index, 1);
        }
        else if (e === 'removeAll') {
            const index = mouseoverPoint.value._vcPolylineIndx;
            polylines.value.splice(index, 1);
        }
        emit('editorEvt', {
            type: e,
            polylines: polylines,
            name: this,
            index: mouseoverPoint.value._vcPolylineIndx
        }, viewer);
    };
    return {
        handleMouseClick,
        handleMouseMove,
        handleDoubleClick,
        polylines,
        startNew,
        stop,
        onMouseoverPoints,
        onMouseoutPoints,
        onEditorClick,
        onMouseenterEditor,
        onMouseleaveEditor,
        canShowDrawTip,
        drawTipPosition,
        drawTip,
        showEditor,
        editorPosition,
        mouseoverPoint
    };
}

function index$3 (props, ctx, vcInstance) {
    vcInstance.cesiumEvents = ['errorEvent'];
    const commonState = useCommon(props, ctx, vcInstance);
    vcInstance.mount = () => __awaiter(this, void 0, void 0, function* () {
        var _a;
        const { viewer } = commonState.$services;
        if (vcInstance.cesiumClass.indexOf('ImageryProvider') !== -1) {
            vcInstance.renderByParent = true;
            const imageryProvider = vcInstance.cesiumObject;
            (_a = imageryProvider === null || imageryProvider === void 0 ? void 0 : imageryProvider.readyPromise) === null || _a === void 0 ? void 0 : _a.then(() => {
                const listener = getInstanceListener(vcInstance, 'readyPromise');
                listener && ctx.emit('readyPromise', imageryProvider, viewer, vcInstance.proxy);
            });
            if (props.projectionTransforms && props.projectionTransforms.from !== props.projectionTransforms.to) {
                const ignoreTransforms = vcInstance.proxy.$options.name === 'VcProviderImageryBaidumap' ||
                    (vcInstance.proxy.$options.name === 'VcProviderImageryTianditu' && imageryProvider._epsgCode === '4490');
                if (!ignoreTransforms) {
                    const { WebMercatorTilingScheme, Cartographic, Math: CesiumMath } = Cesium;
                    const tilingScheme = new WebMercatorTilingScheme();
                    const projection = tilingScheme.projection;
                    const nativeProject = projection.project;
                    const nativeUnProject = projection.unproject;
                    let projectMethods;
                    let unprojectMethods;
                    if (props.projectionTransforms.to.toUpperCase() === 'WGS84') {
                        projectMethods = 'wgs84togcj02';
                        unprojectMethods = 'gcj02towgs84';
                    }
                    else if (props.projectionTransforms.to.toUpperCase() === 'GCJ02') {
                        projectMethods = 'gcj02towgs84';
                        unprojectMethods = 'wgs84togcj02';
                    }
                    if (projectMethods && unprojectMethods) {
                        projection.project = function (cartographic, result) {
                            result = result || new Cesium.Cartesian3();
                            result = coordtransform[projectMethods](CesiumMath.toDegrees(cartographic.longitude), CesiumMath.toDegrees(cartographic.latitude));
                            return nativeProject.call(this, new Cartographic(CesiumMath.toRadians(result[0]), CesiumMath.toRadians(result[1])));
                        };
                        projection.unproject = function (cartesian2, result) {
                            result = result || new Cartographic();
                            const cartographic = nativeUnProject.call(this, cartesian2);
                            result = coordtransform[unprojectMethods](CesiumMath.toDegrees(cartographic.longitude), CesiumMath.toDegrees(cartographic.latitude));
                            return new Cartographic(CesiumMath.toRadians(result[0]), CesiumMath.toRadians(result[1]));
                        };
                        imageryProvider._tilingScheme = tilingScheme;
                    }
                }
            }
            const parentVM = getVcParentInstance(vcInstance).proxy;
            return parentVM && parentVM.__updateProvider(imageryProvider);
        }
        else {
            const terrainProvider = vcInstance.cesiumObject;
            terrainProvider.readyPromise.then(() => {
                const listener = getInstanceListener(vcInstance, 'readyPromise');
                listener && ctx.emit('readyPromise', terrainProvider, viewer, vcInstance.proxy);
            });
            viewer.terrainProvider = terrainProvider;
            return true;
        }
    });
    vcInstance.unmount = () => __awaiter(this, void 0, void 0, function* () {
        const { viewer } = commonState.$services;
        if (vcInstance.cesiumClass.indexOf('ImageryProvider') !== -1) {
            const parentVM = getVcParentInstance(vcInstance).proxy;
            return parentVM && parentVM.__updateProvider(undefined);
        }
        else {
            const terrainProvider = new Cesium.EllipsoidTerrainProvider();
            terrainProvider.readyPromise.then(() => {
                const listener = getInstanceListener(vcInstance, 'readyPromise');
                listener && ctx.emit('readyPromise', terrainProvider, viewer, vcInstance.proxy);
            });
            viewer.terrainProvider = terrainProvider;
            return true;
        }
    });
    return {
        transformProps: commonState.transformProps,
        unwatchFns: commonState.unwatchFns,
        setPropsWatcher: commonState.setPropsWatcher
    };
}

function index$4 (props, ctx, vcInstance) {
    vcInstance.cesiumEvents = ['changedEvent', 'errorEvent', 'loadingEvent'];
    if (vcInstance.cesiumClass === 'KmlDataSource') {
        vcInstance.cesiumEvents.push('refreshEvent');
        vcInstance.cesiumEvents.push('unsupportedNodeEvent');
    }
    vcInstance.cesiumMembersEvents = [
        {
            name: 'clock',
            events: ['definitionChanged']
        },
        {
            name: 'clustering',
            events: ['clusterEvent']
        },
        {
            name: 'entities',
            events: ['collectionChanged']
        }
    ];
    const commonState = useCommon(props, ctx, vcInstance);
    vcInstance.alreadyListening.push('entities');
    let unwatchFns = [];
    unwatchFns.push(watch(() => cloneDeep(props.entities), (newVal, oldVal) => {
        if (!vcInstance.mounted) {
            return;
        }
        const datasource = vcInstance.cesiumObject;
        if (newVal.length === oldVal.length) {
            const modifies = [];
            for (let i = 0; i < newVal.length; i++) {
                const options = newVal[i];
                const oldOptions = oldVal[i];
                if (JSON.stringify(options) !== JSON.stringify(oldOptions)) {
                    modifies.push({
                        newOptions: options,
                        oldOptions: oldOptions
                    });
                }
            }
            modifies.forEach(v => {
                const modifyEntity = datasource.entities.getById(v.oldOptions.id);
                if (v.oldOptions.id === v.newOptions.id) {
                    modifyEntity && Object.keys(v.newOptions).forEach(prop => {
                        if (v.oldOptions[prop] !== v.newOptions[prop]) {
                            modifyEntity[prop] = commonState.transformProp(prop, v.newOptions[prop]);
                        }
                    });
                }
                else {
                    datasource.entities.remove(modifyEntity);
                    const entityOptions = v.newOptions;
                    const entityOptionsTransform = commonState.transformProps(entityOptions);
                    const entityAdded = datasource.entities.add(entityOptionsTransform);
                    entityAdded.id !== entityOptions.id && (entityOptions.id = entityAdded.id);
                }
            });
        }
        else {
            const adds = differenceBy(newVal, oldVal, 'id');
            const deletes = differenceBy(oldVal, newVal, 'id');
            const deletedEntities = [];
            for (let i = 0; i < deletes.length; i++) {
                const deleteEntity = datasource.entities.getById(deletes[i].id);
                deletedEntities.push(deleteEntity);
            }
            deletedEntities.forEach(v => {
                datasource.entities.remove(v);
            });
            for (let i = 0; i < adds.length; i++) {
                const entityOptions = adds[i];
                const entityOptionsTransform = commonState.transformProps(entityOptions);
                const entityAdded = datasource.entities.add(entityOptionsTransform);
                entityAdded.id !== entityOptions.id && (entityOptions.id = entityAdded.id);
            }
        }
    }, {
        deep: true
    }));
    vcInstance.mount = () => __awaiter(this, void 0, void 0, function* () {
        const dataSources = commonState.$services.dataSources;
        const datasource = vcInstance.cesiumObject;
        datasource.show = props.show;
        for (let i = 0; i < props.entities.length; i++) {
            const entityOptions = props.entities[i];
            const entityOptionsTransform = commonState.transformProps(entityOptions);
            const entity = datasource.entities.add(entityOptionsTransform);
            entityOptions.id !== entity.id && (entityOptions.id = entity.id);
        }
        return dataSources.add(datasource).then(() => {
            return true;
        });
    });
    vcInstance.unmount = () => __awaiter(this, void 0, void 0, function* () {
        const dataSources = commonState.$services.dataSources;
        const datasource = vcInstance.cesiumObject;
        return dataSources && dataSources.remove(datasource, props.destroy);
    });
    const getServices = () => {
        return mergeDescriptors(commonState.getServices(), {
            get datasource() {
                return vcInstance.cesiumObject;
            },
            get entities() {
                var _a;
                return (_a = vcInstance.cesiumObject) === null || _a === void 0 ? void 0 : _a.entities;
            }
        });
    };
    onUnmounted(() => {
        unwatchFns.forEach(item => item());
        unwatchFns = [];
    });
    provide(vcKey, getServices());
    return {
        transformProps: commonState.transformProps,
        unwatchFns: commonState.unwatchFns,
        setPropsWatcher: commonState.setPropsWatcher
    };
}

function index$5 (props, ctx, vcInstance) {
    const commonState = useCommon(props, ctx, vcInstance);
    const childCount = ref(0);
    const instances = ref([]);
    vcInstance.createCesiumObject = () => __awaiter(this, void 0, void 0, function* () {
        var _a, _b;
        const options = commonState.transformProps(props);
        if (!options.asynchronous) {
            yield ((_b = (_a = Cesium[vcInstance.cesiumClass]).initializeTerrainHeights) === null || _b === void 0 ? void 0 : _b.call(_a));
        }
        if (props.geometryInstances) {
            if (isArray(props.geometryInstances)) {
                instances.value.push(...props.geometryInstances);
                childCount.value += props.geometryInstances.length;
            }
            else {
                childCount.value += 1;
                instances.value.push(props.geometryInstances);
            }
        }
        return new Cesium[vcInstance.cesiumClass](options);
    });
    vcInstance.mount = () => __awaiter(this, void 0, void 0, function* () {
        const primitives = vcInstance.cesiumClass.includes('Ground') ? commonState.$services.groundPrimitives : commonState.$services.primitives;
        const primitive = vcInstance.cesiumObject;
        primitive.readyPromise && primitive.readyPromise.then(e => {
            const listener = getInstanceListener(vcInstance, 'readyPromise');
            listener && ctx.emit('readyPromise', e, commonState.$services.viewer, vcInstance.proxy);
        });
        primitive._vcParent = primitives;
        const object = primitives && primitives.add(primitive);
        if (vcInstance.cesiumClass === 'ParticleSystem') {
            const intervalId = setInterval(() => {
                if (Cesium.defined(object._billboardCollection)) {
                    object._billboardCollection._vcParent = object;
                    clearInterval(intervalId);
                }
            }, 500);
        }
        return Cesium.defined(object);
    });
    vcInstance.unmount = () => __awaiter(this, void 0, void 0, function* () {
        childCount.value = 0;
        instances.value = [];
        const primitives = vcInstance.cesiumClass.includes('Ground') ? commonState.$services.groundPrimitives : commonState.$services.primitives;
        const primitive = vcInstance.cesiumObject;
        return primitives && primitives.remove(primitive);
    });
    const updateGeometryInstances = (instance, index) => {
        instances.value.push(instance);
        if (index === childCount.value - 1) {
            const listener = getInstanceListener(vcInstance, 'update:geometryInstances');
            if (listener) {
                ctx.emit('update:geometryInstances', instances);
            }
            else {
                const primitive = vcInstance.cesiumObject;
                primitive.geometryInstances = index === 0 ? instance : instances.value;
            }
        }
        return true;
    };
    const getServices = () => {
        return mergeDescriptors(commonState.getServices(), {
            get primitive() {
                return vcInstance.cesiumObject;
            }
        });
    };
    provide(vcKey, getServices());
    Object.assign(vcInstance.proxy, {
        __updateGeometryInstances: updateGeometryInstances,
        __childCount: childCount
    });
    return {
        transformProps: commonState.transformProps,
        unwatchFns: commonState.unwatchFns,
        setPropsWatcher: commonState.setPropsWatcher
    };
}

function index$6 (props, ctx, vcInstance) {
    vcInstance.cesiumEvents = [];
    vcInstance.renderByParent = true;
    const commonState = useCommon(props, ctx, vcInstance);
    vcInstance.mount = () => __awaiter(this, void 0, void 0, function* () {
        const geometry = vcInstance.cesiumObject;
        const parentVM = getVcParentInstance(vcInstance).proxy;
        return parentVM.__updateGeometry(geometry);
    });
    return {
        transformProps: commonState.transformProps,
        unwatchFns: commonState.unwatchFns,
        setPropsWatcher: commonState.setPropsWatcher
    };
}

function index$7 (props, ctx, vcInstance) {
    const commonState = useCommon(props, ctx, vcInstance);
    vcInstance.mount = () => __awaiter(this, void 0, void 0, function* () {
        const primitives = commonState.$services.primitives;
        const collection = vcInstance.cesiumObject;
        const object = primitives && primitives.add(collection);
        return Cesium.defined(object);
    });
    vcInstance.unmount = () => __awaiter(this, void 0, void 0, function* () {
        const primitives = commonState.$services.primitives;
        const collection = vcInstance.cesiumObject;
        return primitives && primitives.remove(collection);
    });
    const getServices = () => {
        return mergeDescriptors(commonState.getServices(), {
            get primitives() {
                return vcInstance.cesiumObject;
            }
        });
    };
    const addCustomProp = (obj, options) => {
        for (const prop in options) {
            if (!obj[prop]) {
                obj[prop] = options[prop];
            }
        }
    };
    provide(vcKey, getServices());
    return {
        transformProps: commonState.transformProps,
        transformProp: commonState.transformProp,
        unwatchFns: commonState.unwatchFns,
        setPropsWatcher: commonState.setPropsWatcher,
        addCustomProp: addCustomProp
    };
}

function index$8 (props, ctx, vcInstance) {
    const commonState = useCommon(props, ctx, vcInstance);
    vcInstance.createCesiumObject = () => __awaiter(this, void 0, void 0, function* () {
        const options = commonState.transformProps(props);
        const primitives = commonState.$services.primitives;
        return primitives && primitives.add(options);
    });
    vcInstance.mount = () => __awaiter(this, void 0, void 0, function* () {
        const primitives = commonState.$services.primitives;
        const collectionItem = vcInstance.cesiumObject;
        return primitives && primitives.contains(collectionItem);
    });
    vcInstance.unmount = () => __awaiter(this, void 0, void 0, function* () {
        const primitives = commonState.$services.primitives;
        const collectionItem = vcInstance.cesiumObject;
        return primitives && !primitives.isDestroyed() && primitives.remove(collectionItem);
    });
    return {
        transformProps: commonState.transformProps,
        unwatchFns: commonState.unwatchFns,
        setPropsWatcher: commonState.setPropsWatcher
    };
}

function useVueCesium() {
    return inject(vcKey);
}

export { useCommon, index$4 as useDatasources, useEvents, index$6 as useGeometries, index as useGraphics, index$1 as useHandler, index$2 as usePolylineDrawing, index$8 as usePrimitiveCollectionItems, index$7 as usePrimitiveCollections, index$5 as usePrimitives, index$3 as useProviders, useVueCesium };
