import * as React from 'react';
import React__default, { useEffect, useState, useRef, useCallback } from 'react';
import { observer } from 'mobx-react';
import { A as getDefaultExportFromCjs, B as _baseToString, H as toString_1, w as GeometryType, J as LayerIcon, K as LineIcon, N as _default, O as map, Q as uniqBy, U as find, V as filter, W as Dropmenu, X as dataTreeFilterMenu, s as IconButton, Y as getTheme, Z as ThemeEnum, $ as Tag, a0 as debounce, u as useStaticCallback, a1 as Input, a2 as i18n, a3 as get, a4 as FOLDER_STRUCTURE_TEMP_UUID, a as __awaiter, a5 as Menu, a6 as MenuItem, a7 as Spin, a8 as Tree, d as __rest, a9 as includes, aa as useStore, ab as DataSideBarStore, ac as ALL_SOURCE_MENUS, q as appContext, v as MAP_DRAG_PACKAGE } from './MapEditView-f6381866.js';
import classNames from 'classnames';
import { u as useDataValue } from './useDataValue-6bd3790f.js';
import FolderOutlined from './index-210f9111.js';
import FileIcon from './index-3f35165c.js';
import LocationIcon from './index-814b2553.js';
import LocationToLocationIcon from './index-23029f1e.js';
import LocationToPolygonIcon from './index-f7347652.js';
import GeoGlobalIcon from './index-64073dd1.js';
import { _ as _castSlice, a as _charsStartIndex, b as _stringToArray, c as compact, u as useContextMenu } from './compact-f89fbdd0.js';
import { v4 } from 'uuid';
import $ from 'jquery';
import 'maptalks';
import 'lodash';
import 'mobx';
import 'lz-string';
import 'dayjs';
import 'react-dom';
import 'react-is';
import '@loadable/component';
import 'js-beautify';
import 'axios';
import 'superstruct';
import '@tanem/react-nprogress';
import 'chroma-js';
import 'js-cookie';
import 'is-email';
import 'is-uuid';
import 'is-url';
import 'anymatch';
import '@syncpoint/wkx';
import 'buffer';
import '@turf/turf';
import '@mapbox/polylabel';
import 'turf-multipolygon';
import 'turf-polygon';
import 'gcoord';
import 'eventemitter2';
import 'geobuf';
import 'localforage';
import 'rc-menu';
import 'perfect-scrollbar';
import 'ahooks';
import 'jszip';
import 'file-saver';
import 'screenfull';
import 'sql-formatter-fork';
import 'array-move';
import 'turf-multilinestring';
import 'copy-to-clipboard';
import 'maptalks.three';
import 'ajv';
import 'spark-md5';
import 'react-draggable';
import 'react-virtualized';
import 'turf-point';
import 'decamelize';
import 'rbush';
import 'qs';
import 'maptalks.snap';
import 'react-use';
import 'react-rnd';
import 'react-beautiful-dnd';

var baseToString = _baseToString,
    castSlice = _castSlice,
    charsStartIndex = _charsStartIndex,
    stringToArray = _stringToArray,
    toString = toString_1;

/** Used to match leading whitespace. */
var reTrimStart = /^\s+/;

/**
 * Removes leading whitespace or specified characters from `string`.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category String
 * @param {string} [string=''] The string to trim.
 * @param {string} [chars=whitespace] The characters to trim.
 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
 * @returns {string} Returns the trimmed string.
 * @example
 *
 * _.trimStart('  abc  ');
 * // => 'abc  '
 *
 * _.trimStart('-_-abc-_-', '_-');
 * // => 'abc-_-'
 */
function trimStart(string, chars, guard) {
  string = toString(string);
  if (string && (guard || chars === undefined)) {
    return string.replace(reTrimStart, '');
  }
  if (!string || !(chars = baseToString(chars))) {
    return string;
  }
  var strSymbols = stringToArray(string),
      start = charsStartIndex(strSymbols, stringToArray(chars));

  return castSlice(strSymbols, start).join('');
}

var trimStart_1 = trimStart;

var trimStart$1 = /*@__PURE__*/getDefaultExportFromCjs(trimStart_1);

const GEO_TYPE_ONLY_ICON_MAP = {
    [`${GeometryType.plain}`]: FileIcon,
    [`${GeometryType.polygon}`]: LayerIcon,
    [`${GeometryType.line}`]: LineIcon,
    [`${GeometryType.point}`]: LocationIcon,
    [`${GeometryType.pointToPoint}`]: LocationToLocationIcon,
    [`${GeometryType.pointToPolygon}`]: LocationToPolygonIcon,
    'geo-global': GeoGlobalIcon,
};
const prefixCls$1 = 'dm-data-list';
const getAttrNum = (style, key) => {
    const val = `${style.getPropertyValue(key).replace('px', '')}`;
    return val ? parseFloat(val) : 0;
};
const DataSideBarHeader = observer(() => {
    const { store } = React__default.useContext(DataSideBarContext);
    const { changeSource, source, dataSourceOpts, changeDSOpts, originDSOpts } = store;
    const [list, setList] = React__default.useState({
        viewList: [],
        hiddenList: [],
    });
    const [ref, { width }] = _default();
    const visible = dataSourceOpts.length > 0;
    const _onClick = useDataValue((v) => changeSource(v));
    const getChild = React__default.useCallback((it, hidden) => {
        const itemCls = classNames(`${prefixCls$1}-header-item`, {
            [`${prefixCls$1}-header-item-active`]: source === it.value,
            [`${prefixCls$1}-header-item-hidden`]: hidden,
        });
        return (React__default.createElement("div", { key: it.value, className: itemCls, "data-value": it.value, onClick: _onClick, "data-test": hidden ? 'data-side-bar-package-type' : undefined }, it.label));
    }, [_onClick, source]);
    const compactHiddenList = compact(list.hiddenList);
    const showAll = compactHiddenList.length === 0;
    const menus = map(compactHiddenList, (it) => ({
        key: it.value,
        title: it.label,
    }));
    const allChildren = React__default.useMemo(() => {
        return map(dataSourceOpts, (it) => it && getChild(it, true));
    }, [dataSourceOpts, getChild]);
    const children = React__default.useMemo(() => {
        return map(list.viewList, (it) => it && getChild(it, false));
    }, [getChild, list.viewList]);
    React__default.useEffect(() => {
        const eleList = document.querySelectorAll(`.${prefixCls$1}-header-item-hidden`);
        let totalW = 0;
        const vlLen = list.viewList.length;
        const opts = uniqBy([
            ...originDSOpts.slice(0, vlLen - 1),
            find(dataSourceOpts, { value: source }),
            ...filter(originDSOpts.slice(vlLen - 1), (it) => it.value !== source),
        ], 'value');
        const vl = [];
        const hl = [];
        for (let index = 0; index < eleList.length; index++) {
            const ele = eleList[index];
            const it = opts[index];
            if (it) {
                const ist = window.getComputedStyle(ele);
                const itemW = getAttrNum(ist, 'width') +
                    getAttrNum(ist, 'margin-left') +
                    getAttrNum(ist, 'margin-right');
                totalW += itemW;
                totalW <= width ? vl.push(it) : hl.push(it);
            }
        }
        setList({ viewList: vl, hiddenList: hl });
    }, [dataSourceOpts, list.viewList.length, originDSOpts, source, width]);
    return (React__default.createElement("div", { className: `${prefixCls$1}-header` }, visible ? (React__default.createElement(React__default.Fragment, null,
        React__default.createElement("div", { className: `${prefixCls$1}-header-wrapper`, ref: ref },
            React__default.createElement("div", { className: `${prefixCls$1}-header-tabs` }, children),
            React__default.createElement("div", { className: `${prefixCls$1}-header-tabs ${prefixCls$1}-header-tabs-hidden` }, allChildren)),
        !showAll && (React__default.createElement(Dropmenu, { menus: menus, values: [], onClickMenuItem: (params) => {
                changeSource(params.key + '');
                changeDSOpts();
            }, onlyText: true }, "\u66F4\u591A")))) : null));
});
DataSideBarHeader.displayName = 'DataSideBarHeader';
DataSideBarHeader.whyDidYouRender = true;
const DataTreeDropmenu = observer(() => {
    const { store } = React__default.useContext(DataSideBarContext);
    const { changeGroup, groupValues } = store;
    return (React__default.createElement("div", { className: `${prefixCls$1}-filter-wrapper-item` },
        React__default.createElement(Dropmenu, { menus: dataTreeFilterMenu, values: groupValues, type: "assist-bg", onClickMenuItem: changeGroup, renderDropNode: () => React__default.createElement(IconButton, { icon: "sort" }), overlayClassName: `${prefixCls$1}-filter-dropmenu` })));
});
DataTreeDropmenu.displayName = 'DataTreeDropmenu';
const DataTreeFilterTags = observer(() => {
    const { store } = React__default.useContext(DataSideBarContext);
    const { tags, clearTags } = store;
    const isDarkTheme = getTheme('') === ThemeEnum.dark;
    return tags.length > 0 ? (React__default.createElement("div", { className: `${prefixCls$1}-filter-tags` }, map(tags, (it) => it && (React__default.createElement(Tag, { tag: it.title, color: isDarkTheme ? 'plain-blue-900' : 'blue-700', closable: true, onClickClose: () => clearTags(it), key: it.title }))))) : null;
});
DataTreeFilterTags.displayName = 'DataTreeFilterTags';
const Search = observer((props) => {
    const { store } = React__default.useContext(DataSideBarContext);
    const { search, changeSearch } = store;
    const [value, setValue] = React__default.useState(search);
    const timeRef = React__default.useRef();
    // eslint-disable-next-line react-hooks/exhaustive-deps
    const debounceSetRouteStoreValue = React__default.useCallback(debounce((v) => changeSearch(v), 500), []);
    const onChange = useStaticCallback((e) => {
        const vl = trimStart$1(e.target.value);
        setValue(vl);
        debounceSetRouteStoreValue(vl);
        if (timeRef.current) {
            clearTimeout(timeRef.current);
        }
    });
    useEffect(() => {
        if (timeRef.current) {
            clearTimeout(timeRef.current);
        }
        timeRef.current = setTimeout(() => setValue(search), 300);
    }, [search]);
    return (React__default.createElement(Input, Object.assign({ value: value, onChange: onChange, prefixIcon: "search" }, props, { "data-test": "data-side-bar-search-input" })));
});
const DataTreeFilter = React__default.memo(({ renderExtraFilterNode }) => {
    return (React__default.createElement("div", { className: `${prefixCls$1}-filter` },
        React__default.createElement("div", { className: `${prefixCls$1}-filter-wrapper` },
            React__default.createElement("div", { className: `${prefixCls$1}-filter-wrapper-item` },
                React__default.createElement(Search, { placeholder: i18n.dataSideBar.searchData, size: "compact" })),
            React__default.createElement(DataTreeDropmenu, null),
            renderExtraFilterNode && renderExtraFilterNode(prefixCls$1)),
        React__default.createElement(DataTreeFilterTags, null)));
});
DataTreeFilter.displayName = 'DataTreeFilter';
DataTreeFilter.whyDidYouRender = true;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const loop = (data, key, callback, parentKey = '') => {
    data.forEach((item) => {
        if (item.key === key) {
            callback(item, parentKey);
            return;
        }
        if (item.children) {
            loop(item.children, key, callback, item.key);
        }
    });
};
// const FolderInput = (value: string) => {
//   const [val, setVal] = useState(value);
//   const handleChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
//     setVal(e.target.value);
//   }, []);
//   return <Input value={val} onChange={handleChange} />;
// };
const uuid = v4();
const DataTree = observer((props) => {
    var _a;
    const { store } = React__default.useContext(DataSideBarContext);
    const { isEmptyList, noSearchList, loading, dataSideBarRcTreeData, source, dataSourceOpts, findDropTargetPath, _moveItemsByDrag, newFolderTargetPath, setNewFolderTargetPath, editCardId, renameFolder, traversalTree, clearTempFolderItem, _createFolder, createTempNewFolder, search, handleExpandSubFolder, expandedKeys, setExpandedKeys, insertExpandKeys, onScroll, } = store;
    const [isProcessingDrop, setIsProcessingDrop] = useState(false);
    const treeWrapperRef = useRef(null);
    const { onDragStart, onDragEnd, onDrop, onRightClick, resizing = false, onSelect } = props;
    const scrollElRef = useRef(null);
    // 文件夹功能选中拖拽项
    const [selectedItemsForDrag, setSelectedItemsForDrag] = useState([]);
    // shift key down
    const shiftKeyPressed = useRef(false);
    const emptyText = React__default.useMemo(() => React__default.createElement("div", { className: `${prefixCls$1}-empty` }, i18n.dataSideBar.emptyText), []);
    const noSearchText = React__default.useMemo(() => React__default.createElement("div", { className: `${prefixCls$1}-nosearch` }, i18n.dataSideBar.noSearchText), []);
    const treeHidden = React__default.useMemo(() => (isEmptyList && emptyText) || (noSearchList && noSearchText), [emptyText, isEmptyList, noSearchList, noSearchText]);
    const phNode = React__default.useMemo(() => {
        let node = null;
        isEmptyList && emptyText && (node = emptyText);
        noSearchList && noSearchText && (node = noSearchText);
        return node;
    }, [emptyText, isEmptyList, noSearchList, noSearchText]);
    const tempNewFolderNameRef = useRef('');
    const handleInputChange = useCallback((e) => {
        tempNewFolderNameRef.current = e.target.value;
    }, []);
    const handleRename = useCallback((originalPath) => {
        if (tempNewFolderNameRef.current) {
            renameFolder(originalPath, tempNewFolderNameRef.current, true);
            tempNewFolderNameRef.current = '';
        }
    }, [renameFolder]);
    const handleCreateNewFolderByInput = useCallback(() => {
        const folderName = tempNewFolderNameRef.current;
        if (folderName) {
            _createFolder(newFolderTargetPath ? `${newFolderTargetPath}/${folderName}` : folderName, true);
        }
        else {
            clearTempFolderItem();
        }
        setNewFolderTargetPath(undefined);
        tempNewFolderNameRef.current = '';
    }, [setNewFolderTargetPath, _createFolder, newFolderTargetPath, clearTempFolderItem]);
    //在最近使用数据中增加对数据来源的显示
    const treeData = React__default.useMemo(() => {
        const list = source === 'recentData'
            ? map(dataSideBarRcTreeData, (it) => {
                var _a, _b, _c;
                return (Object.assign(Object.assign({}, it), { 
                    // 最近使用使用表明来源
                    name: ((_a = it.extra) === null || _a === void 0 ? void 0 : _a.displaySource) === 'recentData'
                        ? `${it.name}(${(_c = (_b = find(dataSourceOpts, { value: it.source })) === null || _b === void 0 ? void 0 : _b.label) !== null && _c !== void 0 ? _c : i18n.dataSideBar.marketData})`
                        : it.name }));
            })
            : dataSideBarRcTreeData;
        const res = source === 'recentData'
            ? list
            : map(list, (it) => (Object.assign(Object.assign({}, it), { title: get(it, 'extra.packageType') !== 'collaboration_v2' ? (it.title) : (React__default.createElement("div", { style: {
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'space-between',
                        overflow: 'hidden',
                        width: '100%',
                    } },
                    React__default.createElement("div", { style: {
                            overflow: 'hidden',
                            textOverflow: 'ellipsis',
                            whiteSpace: 'nowrap',
                            width: `calc( 100% - 56px)`,
                        } }, typeof it.title === 'function' ? it.title(it) : it.title),
                    React__default.createElement(Tag, { tag: i18n.dataSideBar.collaboration, color: 'purple-900' }))) })));
        if (editCardId) {
            let toEditFolder;
            traversalTree(res, editCardId, (i) => {
                toEditFolder = i;
            });
            if (toEditFolder) {
                const { title } = toEditFolder;
                tempNewFolderNameRef.current = title;
                toEditFolder.title = () => (React__default.createElement(Input, { autoFocus: true, defaultValue: title, onChange: handleInputChange, onPressEnter: () => handleRename(toEditFolder === null || toEditFolder === void 0 ? void 0 : toEditFolder.key), onBlur: () => handleRename(toEditFolder === null || toEditFolder === void 0 ? void 0 : toEditFolder.key) }));
            }
        }
        traversalTree(res, FOLDER_STRUCTURE_TEMP_UUID, (i) => {
            i.title = (React__default.createElement(Input, { autoFocus: true, defaultValue: '', onChange: handleInputChange, onPressEnter: handleCreateNewFolderByInput, onBlur: handleCreateNewFolderByInput }));
        });
        return res;
    }, [
        dataSideBarRcTreeData,
        source,
        editCardId,
        traversalTree,
        handleInputChange,
        handleRename,
        handleCreateNewFolderByInput,
        dataSourceOpts,
    ]);
    const defaultDragStart = useCallback((info) => {
        var _a, _b;
        const { node } = info;
        //@ts-ignore
        (_a = store.setDragSourceId) === null || _a === void 0 ? void 0 : _a.call(store, ((_b = node.packageUuid) === null || _b === void 0 ? void 0 : _b.toString()) || node.key.toString());
    }, [store]);
    const defaultDrop = useCallback((info) => __awaiter(void 0, void 0, void 0, function* () {
        if (isProcessingDrop)
            return;
        setIsProcessingDrop(true);
        const { node, dragNode } = info;
        const dropKey = node.packageUuid || node.key;
        const dragKey = (dragNode.packageUuid || dragNode.key);
        const dropPos = node.pos.split('-');
        const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1]);
        let path = '';
        const data = [...treeData];
        if (dropPosition === 0) {
            // Drop on the content
            path = findDropTargetPath(dropKey);
        }
        else {
            // Drop on the gap (insert before or insert after)
            loop(data, dropKey, (_item, parentKey) => {
                path = parentKey;
            });
        }
        if (path !== undefined && source !== 'recentData') {
            // 拖拽元素不在多选选中目标之内
            if (selectedItemsForDrag.length > 1 && !includes(selectedItemsForDrag, dragKey))
                return;
            _moveItemsByDrag({
                dragItemIds: selectedItemsForDrag.length > 1 ? selectedItemsForDrag : [dragKey],
                dropFolderId: path,
            });
        }
        console.log('dragKey: ', dragKey);
        console.log('dropKey: ', dropKey);
        console.log('dropPosition: ', dropPosition);
        console.log('dropToGap: ', info.dropToGap);
        setSelectedItemsForDrag([]);
        setIsProcessingDrop(false);
    }), [
        isProcessingDrop,
        treeData,
        source,
        findDropTargetPath,
        selectedItemsForDrag,
        _moveItemsByDrag,
    ]);
    const handleSelect = useCallback((_selectedKeys, info) => {
        if (source === 'recentData')
            return;
        if (shiftKeyPressed.current) {
            setSelectedItemsForDrag((prev) => [...prev, info.node.key]);
        }
        else {
            setSelectedItemsForDrag(() => [info.node.key]);
        }
    }, [source]);
    const handleSelectPackage = useCallback((_e, node) => {
        // 非文件夹节点
        if (!node.children) {
            // 文件夹内部资源节点（treeNode） 与原有外层数据结构（allList）不同 需要使用原有数据
            const packageUuid = node.packageUuid || node.key;
            let item;
            dataSideBarRcTreeData.forEach((i) => {
                if (i.isFolder) {
                    const lt = i.children || [], it = lt.find((k) => k.packageUuid === packageUuid);
                    if (it) {
                        item = it;
                        return true;
                    }
                }
                else {
                    if (i.packageUuid === packageUuid) {
                        item = i;
                        return true;
                    }
                }
            });
            if (item) {
                onSelect === null || onSelect === void 0 ? void 0 : onSelect(item);
            }
        }
    }, [dataSideBarRcTreeData, onSelect]);
    const handleExpand = useCallback((keys) => {
        setExpandedKeys(keys);
    }, [setExpandedKeys]);
    const iconRender = useCallback((nodeProps) => {
        var _a, _b;
        let IconView;
        if ((_a = nodeProps.data) === null || _a === void 0 ? void 0 : _a.children) {
            IconView = FolderOutlined;
        }
        else {
            const type = nodeProps.geometryType;
            IconView = (_b = GEO_TYPE_ONLY_ICON_MAP[type]) !== null && _b !== void 0 ? _b : FileIcon;
        }
        return React__default.createElement(IconView, { className: "dmc-icon" });
    }, []);
    const handleKeydown = useCallback((e) => {
        if (e.shiftKey) {
            shiftKeyPressed.current = true;
        }
    }, []);
    const handleKeyup = useCallback((e) => {
        if (e.key === 'Shift') {
            shiftKeyPressed.current = false;
        }
    }, []);
    const handleCreateNewFolderByContextMenu = useCallback(() => {
        createTempNewFolder('');
    }, [createTempNewFolder]);
    useEffect(() => {
        document.body.addEventListener('keydown', handleKeydown);
        document.body.addEventListener('keyup', handleKeyup);
        return () => {
            document.body.removeEventListener('keydown', handleKeydown);
            document.body.removeEventListener('keyup', handleKeyup);
        };
    }, [handleKeydown, handleKeyup]);
    useEffect(() => {
        if (newFolderTargetPath) {
            if (!expandedKeys.find((i) => i === newFolderTargetPath)) {
                insertExpandKeys(newFolderTargetPath);
            }
        }
    }, [expandedKeys, insertExpandKeys, newFolderTargetPath]);
    useEffect(() => {
        setExpandedKeys([]);
    }, [source, search, setExpandedKeys]);
    const createFolderContextMenu = useContextMenu({
        triggerElement: (_a = treeWrapperRef.current) === null || _a === void 0 ? void 0 : _a.componentWrapper,
        menuRender: () => (React__default.createElement(Menu, null,
            React__default.createElement(MenuItem, { onClick: handleCreateNewFolderByContextMenu }, i18n.common.newFolder))),
        disabled: source === 'recentData' || loading || !!search,
        triggerByChild: false,
        blackList: ['dmc-input', 'dmc-input-textarea', 'INPUT', 'TEXTAREA'],
    });
    const handleWheel = useCallback((e) => {
        const el = scrollElRef.current;
        if (el) {
            onScroll === null || onScroll === void 0 ? void 0 : onScroll(e, el.clientHeight, el.scrollHeight, el.scrollTop);
        }
        else {
            let el = e.target;
            while (el) {
                if (el.classList.contains('dmc-tree-list-holder')) {
                    scrollElRef.current = el;
                    onScroll === null || onScroll === void 0 ? void 0 : onScroll(e, el.clientHeight, el.scrollHeight, el.scrollTop);
                    break;
                }
                el = el.parentElement;
            }
        }
    }, [onScroll]);
    useEffect(() => {
        if (loading)
            return;
        const item = document.querySelector(`.${prefixCls$1}-${uuid}`);
        if (item) {
            item.addEventListener('wheel', handleWheel);
        }
        return () => {
            if (item) {
                item.removeEventListener('wheel', handleWheel);
            }
        };
    }, [handleWheel, loading]);
    return (React__default.createElement("div", { className: `${prefixCls$1}-tree` },
        createFolderContextMenu,
        loading ? (React__default.createElement(Spin, null)) : treeHidden ? (phNode) : (React__default.createElement(Tree, { expandedKeys: expandedKeys, onExpand: handleExpand, icon: iconRender, treeData: treeData, onDragStart: onDragStart || defaultDragStart, onDrop: onDrop || defaultDrop, onDragEnd: onDragEnd, draggable: !resizing, type: "assist-bg", onSelect: handleSelect, onDoubleClick: handleSelectPackage, selectedKeys: selectedItemsForDrag, multiple: selectedItemsForDrag.length > 1, onRightClick: onRightClick, itemHeight: 24, virtual: true, withoutHoverEffect: resizing, loadData: handleExpandSubFolder, ref: treeWrapperRef }))));
});
DataTree.displayName = 'DataTree';
DataTree.whyDidYouRender = true;
const DataSideBarView = React__default.memo((_a) => {
    var { renderExtraFilterNode, renderFooter } = _a, treeProps = __rest(_a, ["renderExtraFilterNode", "renderFooter"]);
    return (React__default.createElement("div", { className: `${prefixCls$1} ${prefixCls$1}-${uuid}` },
        React__default.createElement(DataSideBarHeader, null),
        React__default.createElement(DataTreeFilter, { renderExtraFilterNode: renderExtraFilterNode }),
        React__default.createElement(DataTree, Object.assign({}, treeProps)),
        renderFooter && renderFooter()));
});

const DataSideBarContext = React.createContext({
    //@ts-ignore
    store: {},
});
const DataSideBar = (_a) => {
    var { rStore, projectOption } = _a, restProps = __rest(_a, ["rStore", "projectOption"]);
    const selfRStore = useStore(() => new DataSideBarStore({ projectOption }));
    const rsRef = React.useRef(rStore);
    const routeStoreRef = rStore ? rsRef : selfRStore;
    React.useEffect(() => {
        var _a, _b;
        if (!rStore) {
            //默认是地图的dataSourceMenu，也就是全部的datasourcemenus
            (_a = routeStoreRef.current) === null || _a === void 0 ? void 0 : _a.initDataSourceMenus(ALL_SOURCE_MENUS);
            (_b = routeStoreRef.current) === null || _b === void 0 ? void 0 : _b.getRecentData();
            routeStoreRef.current && routeStoreRef.current.initDataList();
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);
    const value = React.useMemo(() => ({
        store: routeStoreRef.current,
    }), [routeStoreRef]);
    return (React.createElement(DataSideBarContext.Provider, { value: value },
        React.createElement(DataSideBarView, Object.assign({}, restProps))));
};

const suppArr = [
    GeometryType.point,
    GeometryType.line,
    GeometryType.polygon,
    GeometryType.pointToPolygon,
];
const geoArr = [GeometryType.polygon, GeometryType.pointToPolygon];
const prefixCls = 'map-data-package-list';
const DataPackageList = observer(() => {
    const { routeStore } = React.useContext(appContext.getContext());
    const { MapSettingStore, inEditPage, projectOption } = routeStore;
    const { packageConfigShow, changePackageConfigShow } = MapSettingStore;
    return (React.createElement("div", { className: prefixCls },
        React.createElement(DataSideBar, { onDragStart: (e) => {
                if (inEditPage && !packageConfigShow) {
                    changePackageConfigShow();
                }
                const { event, node: defaultNode } = e;
                // source除了customer | sql 都是market
                const node = Object.assign(Object.assign({}, defaultNode), { source: defaultNode.source === 'customer' || defaultNode.source === 'sql'
                        ? defaultNode.source
                        : 'market' });
                if (node.geoType === 'plain') {
                    return;
                }
                const nodeStr = JSON.stringify(node);
                event.dataTransfer.setData(MAP_DRAG_PACKAGE, nodeStr);
                sessionStorage.setItem(MAP_DRAG_PACKAGE, nodeStr);
                const { geoType, geometryType } = node;
                const _type = geoType || geometryType;
                if (suppArr.indexOf(_type) > -1) {
                    $('.dm-map-packages-config-list-wrapper.supp-filters').addClass('can-dragover');
                }
                if (geoArr.indexOf(_type) > -1) {
                    $('.dm-map-packages-config-list-wrapper.geo-filters').addClass('can-dragover');
                }
            }, onDragEnd: () => {
                $('.dm-map-packages-config-list-wrapper.supp-filters').removeClass('can-dragover');
                $('.dm-map-packages-config-list-wrapper.geo-filters').removeClass('can-dragover');
            }, projectOption: projectOption })));
});
var DataPackageList$1 = DataPackageList;

export { DataPackageList$1 as default };
