import * as React from 'react';
import React__default, { useCallback, useState, useMemo, useEffect } from 'react';
import { a3 as get, a1 as Input, ao as Icon, p as i18n$2, ap as Checkbox, an as GeoTypeIcon, q as appContext, s as IconButton, al as Button, y as Scrollbar, aq as Drawer, ah as LazyLoad, ar as userInfo, as as queryDataPkgs, at as apiDataPkgFunc, au as getTheme, av as FormItem, aw as Select, ax as GEO_TYPES_LABEL_MAP, t as toastApi, ay as jsxRuntimeExports, I as Icon$1, a as __awaiter, az as getMap, aA as getMapStyle, a7 as Spin, aB as updateMap, aC as apiMapFunc, aD as drawerApi, u as useStaticCallback, aE as ModuleRouteEnum, aF as UpdateDataType, a5 as Menu, a6 as MenuItem, M as MapTypeSet, aG as Dropdown, am as Tooltip, aH as Authorized, aI as Previleges, aJ as NavButton, r as Popconfirm, l as iconsUtil } from './MapEditView-f6381866.js';
import { observer, useLocalStore } from 'mobx-react';
import classNames from 'classnames';
import 'perfect-scrollbar';
import { uniq, filter, map, size, find, get as get$1, uniqBy, findIndex } from 'lodash';
import { P as PromptPlaceholder } from './index-e5d60647.js';
import { T as Transfer, a as TransferMode } from './Transfer-b219601e.js';
import { useMount as useMount$1, useClickAway } from 'react-use';
import { useSetState, useRequest, useMount, useDebounceEffect } from 'ahooks';
import 'maptalks';
import 'uuid';
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 'jquery';
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 '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-rnd';
import 'react-beautiful-dnd';

const prefixCls$5 = 'dm-rename';
const Rename = React__default.memo(({ value, classname, onChangeValue, placeholder, disabled }) => {
    const prevValue = React__default.useRef(value);
    const [unControlVal, setUnControlVal] = React__default.useState(() => value);
    const inputRef = React__default.useRef({});
    const onChange = React__default.useCallback((e) => setUnControlVal(e.target.value), []);
    const updateVal = React__default.useCallback((e) => {
        const currentVal = get(e, 'target.value');
        if (!currentVal) {
            setUnControlVal(prevValue.current);
            onChangeValue(prevValue.current);
            return;
        }
        if (!!currentVal && currentVal !== value) {
            setUnControlVal(currentVal);
            onChangeValue(currentVal);
        }
    }, [onChangeValue, value]);
    const onPressEnter = React__default.useCallback(() => {
        var _a;
        // updateVal(e);
        (_a = inputRef.current) === null || _a === void 0 ? void 0 : _a.blur();
    }, []);
    React__default.useEffect(() => {
        if (prevValue.current !== value) {
            setUnControlVal(value);
            prevValue.current = value;
        }
    }, [value]);
    const renameCls = classNames(prefixCls$5, classname);
    return (React__default.createElement("div", { className: renameCls },
        React__default.createElement(Input, { value: unControlVal, onChange: onChange, size: "compact", onBlur: updateVal, block: true, allowClear: false, placeholder: placeholder || '', className: `${prefixCls$5}-edit-input`, onPressEnter: onPressEnter, ref: inputRef, "data-test": 'rename-input', disabled: disabled }),
        React__default.createElement(Icon, { icon: "edit", size: 16, className: `${prefixCls$5}-edit-icon` })));
});

const prefixCls$4 = 'dm-map-package-item';
const i18n$1 = i18n$2.mapEdit;
const PackageItem = React.memo(function _PackageItem(props) {
    const { id, text, isCurrent, type, onClick, checkedIds, handleCheckChange } = props;
    const handleCheckboxChange = useCallback((v) => {
        if (v) {
            handleCheckChange(uniq([...checkedIds, id]));
        }
        else {
            handleCheckChange(filter(checkedIds, (checkedId) => checkedId !== id));
        }
    }, [checkedIds, handleCheckChange, id]);
    return (React.createElement("div", { style: { marginBottom: 6 }, className: classNames(prefixCls$4, {
            [`${prefixCls$4}-current`]: isCurrent,
        }), onClick: onClick },
        React.createElement(Checkbox, { defaultChecked: true, onChange: handleCheckboxChange, checked: checkedIds.includes(id) }),
        React.createElement(GeoTypeIcon, { type: type, size: 12, className: `${prefixCls$4}-type-icon` }),
        React.createElement("div", { className: `${prefixCls$4}-content` }, text),
        React.createElement("div", { className: `${prefixCls$4}-btn-preview` }, i18n$1.preview)));
});

const prefixCls$3 = 'dm-map-search-settings';
const i18n = i18n$2.mapEdit;
const MapSearchSettingsContent = observer(function _MapSearchSettings() {
    var _a;
    const { routeStore } = React.useContext(appContext.getContext());
    const { MapSettingStore, SuppFiltersStore, GeoFiltersStore } = routeStore;
    const { currentSuppFilter, setCurrentSuppFilter, getCol: getSuppCol, getColList: getSuppColList, getColUuid: getSuppColUuid, getColClassification: getSuppColClassification, } = SuppFiltersStore;
    const { currentGeoFilter, setCurrentGeoFilter, getCol: getGeoCol, getColList: getGeoColList, getColUuid: getGeoColUuid, getColClassification: getGeoColClassification, } = GeoFiltersStore;
    // const [init, setInit] = useState(true);
    const [packageType, setPackageType] = useState(currentSuppFilter ? 'supp' : 'geo');
    const suppFilters = SuppFiltersStore.suppFilters.slice();
    const geoFilters = GeoFiltersStore.geoFilters.slice();
    const { setShowSearchSettings, searchItemDisplayFields, setSearchItemDisplayFields, searchSettingEnabledPackagesUuids, setSearchSettingEnabledPackagesUuids, } = MapSettingStore;
    const [_searchItemDisplayFields, _setSearchItemDisplayFields] = useState(searchItemDisplayFields);
    const [_searchSettingEnabledPackagesUuids, _setSearchSettingEnabledPackagesUuids] = useState(searchSettingEnabledPackagesUuids);
    const curPkg = useMemo(() => (packageType === 'supp' ? currentSuppFilter : currentGeoFilter), [currentGeoFilter, currentSuppFilter, packageType]);
    const [currentSelectUuid, setCurrentSelectUuid] = useState(curPkg);
    // 用于界面上的操作数据，仅在提交时更新数据
    useEffect(() => {
        _setSearchItemDisplayFields(searchItemDisplayFields);
    }, [searchItemDisplayFields]);
    useEffect(() => {
        _setSearchSettingEnabledPackagesUuids(searchSettingEnabledPackagesUuids);
    }, [searchSettingEnabledPackagesUuids]);
    // 默认选中第一个分析数据包
    useEffect(() => {
        var _a, _b;
        if ((suppFilters.length || geoFilters.length) && !currentSelectUuid) {
            setCurrentSelectUuid(((_a = suppFilters[0]) === null || _a === void 0 ? void 0 : _a.uuid) || ((_b = geoFilters[0]) === null || _b === void 0 ? void 0 : _b.uuid));
            setPackageType(suppFilters.length ? 'supp' : 'geo');
        }
    }, [currentSelectUuid, geoFilters, geoFilters.length, suppFilters, suppFilters.length]);
    // const currentSuppColumns = useMemo(() => {
    //   return getSuppColList({ uuid: currentSuppFilter })?.map((i) => ({
    //     // label: i,
    //     label: i,
    //     value: i,
    //     type: getSuppColClassification({ uuid: currentSuppFilter, col: i }),
    //   }));
    // }, [currentSuppFilter, getSuppColClassification, getSuppColList]);
    const handleCancel = useCallback(() => {
        setShowSearchSettings(false);
        _setSearchItemDisplayFields(searchItemDisplayFields);
        _setSearchSettingEnabledPackagesUuids(searchSettingEnabledPackagesUuids);
    }, [setShowSearchSettings, searchItemDisplayFields, searchSettingEnabledPackagesUuids]);
    const handleOk = useCallback(() => {
        setSearchItemDisplayFields(_searchItemDisplayFields);
        setSearchSettingEnabledPackagesUuids(_searchSettingEnabledPackagesUuids);
        setShowSearchSettings(false);
    }, [
        setSearchItemDisplayFields,
        _searchItemDisplayFields,
        setSearchSettingEnabledPackagesUuids,
        _searchSettingEnabledPackagesUuids,
        setShowSearchSettings,
    ]);
    // 渲染左侧数据包
    const RenderPackageItem = useCallback(({ items, type }) => {
        var _a;
        return (React.createElement(React.Fragment, null, (_a = items === null || items === void 0 ? void 0 : items.map) === null || _a === void 0 ? void 0 : _a.call(items, (item, index) => {
            const { geometryType, objectType, uuid } = item;
            const _onClick = () => {
                if (packageType !== type) {
                    setPackageType(type);
                }
                type === 'supp' ? setCurrentSuppFilter(uuid) : setCurrentGeoFilter(uuid);
                setCurrentSelectUuid(uuid);
            };
            return (React.createElement("div", { key: index },
                React.createElement(PackageItem, { id: uuid, isCurrent: uuid === currentSelectUuid, key: index, type: geometryType, text: objectType, onClick: _onClick, checkedIds: _searchSettingEnabledPackagesUuids, handleCheckChange: _setSearchSettingEnabledPackagesUuids })));
        })));
    }, [
        currentSelectUuid,
        _searchSettingEnabledPackagesUuids,
        packageType,
        setCurrentSuppFilter,
        setCurrentGeoFilter,
    ]);
    const currentCheckListValues = useMemo(() => {
        return map(_searchItemDisplayFields[curPkg], (uuid) => {
            return packageType === 'supp'
                ? getSuppCol({ uuid: curPkg, fieldId: uuid })
                : getGeoCol({ uuid: curPkg, fieldId: uuid });
        });
    }, [_searchItemDisplayFields, curPkg, packageType, getSuppCol, getGeoCol]);
    const handleSelectedColumnsChange = useCallback((selected) => {
        // 至少有一个显示字段
        if (selected.length === 0) {
            return;
        }
        _setSearchItemDisplayFields(Object.assign(Object.assign({}, _searchItemDisplayFields), { [curPkg]: selected === null || selected === void 0 ? void 0 : selected.map((i) => packageType === 'supp'
                ? getSuppColUuid({ uuid: curPkg, col: i })
                : getGeoColUuid({ uuid: curPkg, col: i })) }));
    }, [_searchItemDisplayFields, curPkg, packageType, getSuppColUuid, getGeoColUuid]);
    // 更改数据包下显示字段顺序
    const handleChangeSearchItemDisplayFieldsOrder = useCallback((items) => {
        // 至少有一个显示字段
        if (items.length === 0) {
            return;
        }
        _setSearchItemDisplayFields(Object.assign(Object.assign({}, _searchItemDisplayFields), { [curPkg]: items === null || items === void 0 ? void 0 : items.map((i) => packageType === 'supp'
                ? getSuppColUuid({ uuid: curPkg, col: i })
                : getGeoColUuid({ uuid: curPkg, col: i })) }));
    }, [_searchItemDisplayFields, curPkg, packageType, getSuppColUuid, getGeoColUuid]);
    // TODO 需优化 由于首次加载 allColumns 数据为历史数据，即使 drawer DOM 未挂载
    // memo 已经缓存了旧数据
    let checklistItems;
    if (packageType === 'supp') {
        const { list = [] } = getSuppColList({ uuid: curPkg }) || {};
        checklistItems = list.map((i) => ({
            title: i,
            key: i,
            type: getSuppColClassification({ uuid: curPkg, col: i }),
        }));
    }
    else if (packageType === 'geo') {
        checklistItems = (_a = getGeoColList({ uuid: curPkg })) === null || _a === void 0 ? void 0 : _a.map((i) => ({
            title: i,
            key: i,
            type: getGeoColClassification({ uuid: curPkg, col: i }),
        }));
    }
    return (React.createElement("div", { className: prefixCls$3 },
        React.createElement("div", { className: `${prefixCls$3}-header` },
            React.createElement("div", { className: `${prefixCls$3}-header-title` },
                React.createElement(IconButton, { icon: "close", type: "only-icon", onClick: handleCancel }),
                React.createElement("span", null, i18n.searchSettings)),
            React.createElement("div", null,
                React.createElement(Button, { className: `${prefixCls$3}-header-cancel-button`, onClick: handleCancel }, i18n.cancelText),
                React.createElement(Button, { type: "primary", onClick: handleOk }, i18n.okText))),
        suppFilters.length || geoFilters.length ? (React.createElement("div", { className: `${prefixCls$3}-body` },
            React.createElement("div", { className: `${prefixCls$3}-body-item` },
                React.createElement(Scrollbar, null,
                    React.createElement("div", { className: `${prefixCls$3}-body-item-title` }, i18n.packageConfig.dataTitle),
                    React.createElement("div", { className: `${prefixCls$3}-body-item-sub-title` }, i18n.packageConfig.dataSubTitle),
                    React.createElement(RenderPackageItem, { items: suppFilters, type: "supp" }),
                    React.createElement("div", { className: `${prefixCls$3}-body-item-title` }, i18n.packageConfig.fenceTitle),
                    React.createElement("div", { className: `${prefixCls$3}-body-item-sub-title` }, i18n.packageConfig.fenceSubTitle),
                    React.createElement(RenderPackageItem, { items: geoFilters, type: "geo" }))),
            React.createElement(Transfer, { height: "100%", showCount: false, 
                // allowClear
                mode: TransferMode.plain, value: currentCheckListValues, options: checklistItems, sortable: true, checkListDescriptionText: i18n$2.mapEdit.selectedFieldsToDisplayInSearching, onChange: handleSelectedColumnsChange, onRemove: handleChangeSearchItemDisplayFieldsOrder, checkListDynamicRowHeight: true }))) : (React.createElement(PromptPlaceholder, { imgType: "no-content", description: i18n.noSearchSettingData }))));
});
const MapSearchSettings = observer(() => {
    const { routeStore } = React.useContext(appContext.getContext());
    const { MapSettingStore } = routeStore;
    const { showSearchSettings, setShowSearchSettings } = MapSettingStore;
    const handleClose = useCallback(() => {
        setShowSearchSettings(false);
    }, [setShowSearchSettings]);
    return (React.createElement(Drawer, { level: null, handler: false, open: showSearchSettings, onClose: handleClose, width: 766, className: "map-drawer", maskClosable: false }, showSearchSettings && React.createElement(MapSearchSettingsContent, null)));
});

const dataLayerPageView = (type, behavior, time, name) => {
    if (window.dataLayer) {
        window.dataLayer.push({
            event: 'page_view',
            type: type,
            behavior: behavior || '-',
            name: name || '-',
            time: time || 0,
        });
    }
};
// (function () {
//   let start = new Date().getTime();
//   let text = '';
//   if ((window.location.hash.split('#/')[1] || '').startsWith('my-project')) {
//     let dataVal = '';
//     let timer = -1;
//     let allNav = document.querySelectorAll('.dmc-side-nav-item');
//     const pageModule = () => {
//       const event = function () {
//         const now = new Date().getTime();
//         dataLayerPageView(PageTypeMap[dataVal], '-', now - start, '-');
//         start = now;
//         dataVal = (this as HTMLDivElement).getAttribute('data-value') || '';
//       };
//       const curNav = document.querySelector('.dmc-side-nav-item-actived') as HTMLDivElement;
//       if (curNav) {
//         dataVal = curNav.getAttribute('data-value') || '';
//       }
//       (allNav || []).forEach((nav) => {
//         nav.removeEventListener('click', event);
//         nav.addEventListener('click', event);
//       });
//     };
//     timer = window.setInterval(() => {
//       allNav = document.querySelectorAll('.dmc-side-nav-item');
//       if (allNav.length > 0) {
//         clearInterval(timer);
//         pageModule();
//       }
//     }, 300);
//     if (allNav.length === 0) return;
//   }
//   //headMenu
//   let headMenus = document.querySelectorAll('dm-app-header-menu-item');
//   if (!headMenus.length) {
//     let headMenuTimer = -1;
//     const headMenusModule = () => {
//       const event = function () {
//         const now = new Date().getTime();
//         // dataLayerPageView(PageTypeMap[dataVal], '-', now - start, '-');
//         start = now;
//         // @ts-ignore
//         dataVal = (this as HTMLDivElement).getAttribute('data-value') || '';
//       };
//       const headMenus = document.querySelectorAll('dm-app-header-menu-item');
//       (headMenus || []).forEach((menu) => {
//         menu.removeEventListener('click', event);
//         menu.addEventListener('click', event);
//       });
//     };
//     headMenuTimer = window.setInterval(() => {
//       headMenus = document.querySelectorAll('dm-app-header-menu-item');
//       if (headMenus.length > 0) {
//         clearInterval(headMenuTimer);
//         headMenusModule();
//       }
//     }, 300);
//   }
// })();
const sendPage = (type, behavior, title, time) => {
    const now = new Date().getTime();
    if (time) {
        const dis = now - time;
        dataLayerPageView(type, behavior, dis, title || '');
    }
    return now;
};

const MapSettings = LazyLoad(() => {
    return import('./index-df29a824.js');
});
const prefixCls$2 = 'dm-map-menu-setting';
const MenuSettings = observer(() => {
    return (React.createElement("div", { className: prefixCls$2 },
        React.createElement(MapSettings, null)));
});

const ReplacePackage = (props) => {
    const { originState = {}, originPackage = {}, changeRef } = props;
    console.log(props);
    // if (!originPackage) return null;
    const { objectType, packageUuid, geometryType, useColumns = [] } = originPackage;
    const [state, setState] = useSetState({
        searchText: '',
        searchList: [],
        datapkgId: originState.selectedPackageUuid || '',
        objectType: originState.selectedObjectType || '',
        geometryType: originState.selectedGeometryType || '',
        columns: [],
        selectColumns: originState.selectedColumns || {},
    });
    console.log(originState, 'originState');
    console.log(state, 'state');
    const { data: packageResp, loading: packageLoading } = useRequest(() => {
        const params = {
            dataPkgsQuery: {
                privilege: 'read',
            },
            apps: userInfo.getAllAppIds(),
            pageSize: 50,
            pageNum: 0,
        };
        if (state.searchText) {
            // @ts-ignore
            params.dataPkgsQuery.name = state.searchText;
        }
        return queryDataPkgs(params);
    }, {
        cacheKey: 'package-cache-key' + packageUuid,
        refreshDeps: [state.searchText],
        // staleTime: 30000,
        debounceWait: 300,
        // manual: true,
    });
    const { data: columnsResp, runAsync: getColumns } = useRequest(() => apiDataPkgFunc().getDataPkgColumns({
        datapkgId: state.datapkgId,
    }), {
        cacheKey: 'package-cache-column' + packageUuid,
        refreshDeps: [state.datapkgId],
        ready: !!state.datapkgId,
    });
    useMount(() => {
        console.log('ReplacePackage====', originState);
        setState({
            datapkgId: originState.selectedPackageUuid || '',
            objectType: originState.selectedObjectType || '',
            geometryType: originState.selectedGeometryType || '',
            selectColumns: originState.selectedColumns || {},
        });
    });
    useDebounceEffect(() => {
        var _a;
        console.log(columnsResp);
        const columns = map(((_a = columnsResp === null || columnsResp === void 0 ? void 0 : columnsResp.data) === null || _a === void 0 ? void 0 : _a.result) || [], (column) => {
            return Object.assign({ key: column.id, label: column.name, value: column.name }, column);
        });
        console.log(useColumns, 'useColumns');
        const selectColumns = {};
        for (let i = 0; i < size(columns); i++) {
            const item = columns[i];
            if (find(useColumns, { column: item.value })) {
                // @ts-ignore
                selectColumns[item.value] = item.value;
            }
        }
        columns.unshift({
            key: i18n$2.mapEdit.replacePackage.empty,
            label: i18n$2.mapEdit.replacePackage.empty,
            value: i18n$2.mapEdit.replacePackage.empty,
        });
        setState({
            columns,
            selectColumns,
        });
    }, [columnsResp]);
    React__default.useEffect(() => {
        const data = packageResp;
        const result = map(get$1(data, 'data.result') || [], (item) => {
            console.log(item, 'item');
            const geometryType = item.geometry_type;
            const name = GEO_TYPES_LABEL_MAP[geometryType];
            return Object.assign({ key: item.id, label: name + '-' + item.name, value: item.id }, item);
        });
        if (size(result) > 0) {
            result.unshift({
                key: i18n$2.mapEdit.replacePackage.empty,
                label: i18n$2.mapEdit.replacePackage.empty,
                value: i18n$2.mapEdit.replacePackage.empty,
            });
        }
        const searchList = (size(result) > 0
            ? result
            : [
                {
                    key: i18n$2.mapEdit.replacePackage.none,
                    label: i18n$2.mapEdit.replacePackage.none,
                    value: i18n$2.mapEdit.replacePackage.none,
                },
            ]);
        setState({
            searchList: searchList,
        });
    }, [packageResp, setState]);
    const _onSearch = (value) => {
        setState({
            searchText: value,
        });
    };
    const _onSelectPackage = (value) => {
        const isNone = value === i18n$2.mapEdit.replacePackage.empty;
        if (isNone) {
            setState({
                datapkgId: '',
                geometryType: '',
                objectType: '',
                columns: [],
                selectColumns: {},
            });
        }
        else {
            const pkg = find(get$1(packageResp, 'data.result'), { id: value });
            setState({
                datapkgId: value,
                geometryType: (pkg === null || pkg === void 0 ? void 0 : pkg.geometry_type) || '',
                objectType: (pkg === null || pkg === void 0 ? void 0 : pkg.name) || '',
            });
        }
    };
    const _onSelectColumn = (originColumn, column) => {
        const isNone = column === i18n$2.mapEdit.replacePackage.empty;
        const selectColumns = state.selectColumns;
        if (isNone) {
            delete selectColumns[originColumn];
        }
        else {
            selectColumns[originColumn] = column;
        }
        const values = Object.values(selectColumns);
        const lenOrigin = values === null || values === void 0 ? void 0 : values.length;
        const len = [...new Set(values)].length;
        if (lenOrigin !== len) {
            toastApi.warning('重复选择列:' + column);
        }
        console.log(state.columns, 'columns');
        console.log(selectColumns, 'selectColumns');
        setState({
            selectColumns,
        });
    };
    // React.useImperativeHandle(ref, () => {
    //   return {
    //     originPackageUuid: packageUuid,
    //     selectedPackageUuid: state.datapkgId,
    //     selectedObjectType: state.objectType,
    //     selectedGeometryType: state.geometryType,
    //     selectedColumns: state.selectColumns,
    //   };
    // });
    useDebounceEffect(() => {
        console.log('state change');
        // TODO modify father comp state
        const data = {
            originPackageUuid: packageUuid,
            selectedPackageUuid: state.datapkgId,
            selectedObjectType: state.objectType,
            selectedGeometryType: state.geometryType,
            selectedColumns: state.selectColumns,
        };
        changeRef === null || changeRef === void 0 ? void 0 : changeRef(data);
    }, [state.datapkgId, state.objectType, state.geometryType, state.selectColumns], {
        wait: 200,
    });
    return (React__default.createElement("div", { className: "dmc-replace-package", "data-theme": getTheme() },
        React__default.createElement("div", { className: "dmc-replace-package-content" },
            React__default.createElement(FormItem, { label: "\u66FF\u6362\u6570\u636E\u5305", required: true, direction: "column" },
                React__default.createElement(Select, { placeholder: i18n$2.mapEdit.replacePackage.placeholderPkg, showSearch: true, value: state.objectType, options: state.searchList, onSearch: _onSearch, onSelect: _onSelectPackage, loading: packageLoading, showTip: true, className: "mb16" }))),
        size(useColumns) > 0 && (React__default.createElement(FormItem, { label: "\u66FF\u6362\u5B57\u6BB5", required: true, direction: "column" },
            React__default.createElement("div", { className: "dmc-replace-package-column-content" }, map(useColumns, (column, index) => {
                var _a;
                return (React__default.createElement("div", { className: "mt4", style: { display: 'flex', alignItems: 'center' }, key: index },
                    React__default.createElement("div", { style: { flex: 1 } },
                        React__default.createElement("div", { className: "dmc-replace-package-origin-package small" }, column.column)),
                    React__default.createElement("div", { className: "dmc-replace-package-content-equal" }, "="),
                    React__default.createElement("div", { style: { flex: 1 } },
                        React__default.createElement(Select, { placeholder: i18n$2.mapEdit.replacePackage.placeholderCol, showSearch: true, value: (_a = state.selectColumns) === null || _a === void 0 ? void 0 : _a[column.column], 
                            // @ts-ignore
                            options: state.columns, onSearch: _onSearch, showTip: true, onSelect: (value) => _onSelectColumn(column.column, value) }))));
            }))))));
};

var __assign = undefined && undefined.__assign || function () {
  __assign = Object.assign || function (t) {
    for (var s, i = 1, n = arguments.length; i < n; i++) {
      s = arguments[i];

      for (var p in s) {
        if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
      }
    }

    return t;
  };

  return __assign.apply(this, arguments);
};

var __rest = undefined && undefined.__rest || function (s, e) {
  var t = {};

  for (var p in s) {
    if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
  }

  if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
    if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
  }
  return t;
};
var prefixCls$1 = 'dmc-page-header';

var PageHeader = function PageHeader(props) {
  var className = props.className,
      style = props.style,
      children = props.children,
      restProps = __rest(props, ["className", "style", "children"]);

  return jsxRuntimeExports.jsx("div", __assign({}, restProps, {
    className: classNames(prefixCls$1, className),
    style: style
  }, {
    children: children
  }), void 0);
};

PageHeader.displayName = 'PageHeader';
var PageHeaderMemo = /*#__PURE__*/React.memo(PageHeader);
PageHeaderMemo.displayName = 'PageHeaderMemo';

const GeoIcon = (props) => {
    const { geoType } = props || {};
    if (geoType === 'polygon') {
        return React__default.createElement(Icon$1, { icon: "layer", size: 14 });
    }
    else if (geoType === 'line') {
        return React__default.createElement(Icon$1, { icon: "line", size: 14 });
    }
    else if (geoType === 'point') {
        return React__default.createElement(Icon$1, { icon: "location", size: 14 });
    }
    else {
        return React__default.createElement(Icon$1, { icon: "help", size: 14 });
    }
};
const OriginPackageButton = (props) => {
    const { onClick, className, geometryType, objectType, packageUuid } = props;
    return (React__default.createElement("div", { className: classNames(['dmc-replace-package-origin-package', className], {}), onClick: onClick },
        React__default.createElement(GeoIcon, { geoType: geometryType }),
        objectType || packageUuid));
};

const GeoType = 'geo';
const SuppType = 'supp';
const ReplacePackageDialogContent = (props) => {
    const { mapUid, mapStyleUid, onClose, onOk, projectOption } = props;
    const { data: mapData, loading: mapDataLoading } = useRequest(() => __awaiter(void 0, void 0, void 0, function* () {
        let resp = yield getMap({
            id: mapUid,
            versionId: projectOption === null || projectOption === void 0 ? void 0 : projectOption.version,
        });
        resp = get$1(resp, 'data.result');
        return resp;
    }), {
        cacheKey: 'mapUid',
        refreshDeps: [mapUid],
    });
    const { data: mapStyleData, loading: mapStyleDataLoading } = useRequest(() => __awaiter(void 0, void 0, void 0, function* () {
        let resp = yield getMapStyle({
            id: mapStyleUid,
            versionId: projectOption === null || projectOption === void 0 ? void 0 : projectOption.version,
        });
        resp = get$1(resp, 'data.result');
        return resp;
    }), {
        cacheKey: 'mapStyleUid',
        refreshDeps: [mapStyleUid],
    });
    const [state, setState] = useSetState({
        suppFilters: [],
        geoFilters: [],
        selectedType: SuppType,
        selectedIndex: 0,
    });
    React__default.useEffect(() => {
        // @ts-ignore
        const { dbInfo = {} } = mapData || {};
        const suppFilters = map(dbInfo.suppFilters, (f) => {
            return f;
        });
        const geoFilters = map(dbInfo.geoFilters, (f) => {
            return f;
        });
        setState({
            suppFilters,
            geoFilters,
        });
    }, [mapData, setState]);
    const suppRefs = React__default.useRef([]);
    const geoRefs = React__default.useRef([]);
    const _onOk = () => __awaiter(void 0, void 0, void 0, function* () {
        if (mapStyleDataLoading || mapDataLoading) {
            return;
        }
        if (!mapStyleData || !mapData) {
            toastApi.warning('need map data; please refresh and try again.');
            return;
        }
        // TODO dialog confirm
        console.log(suppRefs, 'suppRefs');
        const changeFilter = (f, ref) => {
            if (!ref) {
                return f;
            }
            if (ref.selectedPackageUuid)
                f.packageUuid = ref.selectedPackageUuid;
            if (ref.selectedGeometryType)
                f.geometryType = ref.selectedGeometryType;
            if (ref.selectedObjectType)
                f.objectType = ref.selectedObjectType;
            if (size(ref.selectedColumns) > 0 && f.useColumns) {
                for (const key in ref.selectedColumns) {
                    const index = findIndex(f.useColumns, { column: key });
                    if (index > -1) {
                        f.useColumns[index].column = ref.selectedColumns[key];
                    }
                }
            }
            return f;
        };
        // check useColumns name 重复
        let isRepeat = false;
        const suppFilters = map(state.suppFilters, (f, index) => {
            const ref = suppRefs.current[index];
            const _f = changeFilter(f, ref);
            const len = size(_f.useColumns);
            const lenUniq = size(uniqBy(_f.useColumns, 'column'));
            if (len !== lenUniq) {
                isRepeat = true;
            }
            return _f;
        });
        const geoFilters = map(state.geoFilters, (f, index) => {
            const ref = geoRefs.current[index];
            const _f = changeFilter(f, ref);
            const len = size(_f.useColumns);
            const lenUniq = size(uniqBy(_f.useColumns, 'column'));
            if (len !== lenUniq) {
                isRepeat = true;
            }
            return _f;
        });
        const dbInfo = { suppFilters, geoFilters };
        console.log(dbInfo, 'dbInfo');
        if (isRepeat) {
            toastApi.warning(i18n$2.mapEdit.replacePackage.errorMessage);
            return;
        }
        const updateResp = yield updateMap({
            id: mapUid,
            // @ts-ignore
            revision: mapData.update_time,
            map1: {
                // @ts-ignore
                dbInfo: dbInfo,
            },
            versionId: projectOption === null || projectOption === void 0 ? void 0 : projectOption.version,
        });
        console.log(mapStyleData, 'mapStyleData');
        const cards = map(get$1(mapStyleData, 'cards') || [], (card) => {
            card.name = '';
            return card;
        });
        yield apiMapFunc().patchSingleMapStyle({
            id: mapStyleUid,
            // @ts-ignore
            revision: mapStyleData.update_time,
            mapStyle1: {
                cards,
            },
            versionId: projectOption === null || projectOption === void 0 ? void 0 : projectOption.version,
        });
        console.log(updateResp, 'updateResp');
        if (get$1(updateResp, 'data.rc') === 0) {
            toastApi.success('替换成功');
        }
        onOk === null || onOk === void 0 ? void 0 : onOk();
        onClose === null || onClose === void 0 ? void 0 : onClose();
    });
    const selectedFilters = state.selectedType === SuppType ? state.suppFilters : state.geoFilters;
    console.log(suppRefs, 'suppRefs');
    console.log(geoRefs, 'geoRefs');
    const replaceRefs = state.selectedType === SuppType ? suppRefs : geoRefs;
    return (React__default.createElement("div", { className: "dmc-map-replace-package-dialog-content" },
        React__default.createElement(PageHeader, null,
            React__default.createElement("div", { className: "dmc-map-replace-package-header" },
                React__default.createElement(Icon$1, { style: { marginRight: 12, cursor: 'pointer' }, icon: "close", size: 16, onClick: onClose }),
                React__default.createElement("div", null, "\u66FF\u6362\u6570\u636E"),
                React__default.createElement("div", { style: { flex: 1 } }),
                React__default.createElement(Button, { onClick: onClose, className: "mr8" }, i18n$2.mapEdit.cancelText),
                React__default.createElement(Button, { type: "primary", onClick: _onOk, disabled: mapDataLoading || mapStyleDataLoading }, i18n$2.mapEdit.okText))),
        (mapDataLoading || mapStyleDataLoading) && (React__default.createElement("div", { className: 'dmc-map-replace-package-dialog-loading' },
            React__default.createElement(Spin, null))),
        !mapDataLoading && !mapStyleDataLoading && (React__default.createElement("div", { className: "dmc-map-replace-package-content" },
            React__default.createElement("div", { className: "dmc-map-replace-package-content-left" },
                size(state.suppFilters) > 0 && (React__default.createElement("div", null, i18n$2.mapEdit.packageConfig.dataTitle)),
                map(state.suppFilters, (f, index) => {
                    let className;
                    if (state.selectedType === SuppType && state.selectedIndex === index) {
                        className = 'selected';
                    }
                    return (React__default.createElement(OriginPackageButton, { key: index, className: className, geometryType: f.geometryType || '', packageUuid: f.packageUuid, objectType: f.objectType, onClick: () => {
                            setState({
                                selectedIndex: index,
                                selectedType: SuppType,
                            });
                        } }));
                }),
                size(state.geoFilters) > 0 && (React__default.createElement("div", { className: "mt20" }, i18n$2.mapEdit.packageConfig.fenceTitle)),
                map(state.geoFilters, (f, index) => {
                    let className;
                    if (state.selectedType === GeoType && state.selectedIndex === index) {
                        className = 'selected';
                    }
                    return (React__default.createElement(OriginPackageButton, { key: index, className: className, geometryType: f.geometryType || '', packageUuid: f.packageUuid, objectType: f.objectType, onClick: () => {
                            setState({
                                selectedIndex: index,
                                selectedType: GeoType,
                            });
                        } }));
                })),
            React__default.createElement("div", { className: "dmc-map-replace-package-content-right" },
                React__default.createElement(ReplacePackage, { key: state.selectedType + state.selectedIndex, originState: replaceRefs.current[state.selectedIndex], originPackage: selectedFilters[state.selectedIndex], changeRef: (f) => {
                        replaceRefs.current[state.selectedIndex] = f;
                    } }))))));
};

const openReplacePackage = (props) => __awaiter(void 0, void 0, void 0, function* () {
    drawerApi.open((onClose) => {
        const { mapUid, mapStyleUid, onOk, projectOption } = props;
        return (React__default.createElement(ReplacePackageDialogContent, { mapUid: mapUid, mapStyleUid: mapStyleUid, onClose: onClose, projectOption: projectOption, onOk: onOk }));
    }, {
        width: '900px',
    });
});

const { toggleShowCustomIconSetting } = iconsUtil;
const prefixCls = 'dm-map-edit-header';
const EditHeader = observer(() => {
    const { routeStore, appStore, _onSave, _onClose } = React.useContext(appContext.getContext());
    const { MapSettingStore, SaveStore, mapName, changeMapName, SearchStore: { clearSearch }, noData, dataReady, type, projectOption, mapUid, mapStyleUid, EmitStore: { resetMapStyle }, } = routeStore;
    const { setShowSearchSettings, changeShowMapSettings, setShowMapSettings, changePackageConfigShow, setPackageConfigShow, showMapSettings, packageConfigShow, changeCurrentDataList, can3D, } = MapSettingStore;
    const { saveMap, loading } = SaveStore;
    const store = useLocalStore(() => {
        return {
            showPackageModelList: false,
            showMoreSettings: false,
        };
    });
    const { showMoreSettings, showPackageModelList } = store;
    const toggleShowPackageModelList = useCallback(() => {
        store['showPackageModelList'] = !store['showPackageModelList'];
    }, [store]);
    const toggleShowMoreSettings = useCallback(() => {
        store['showMoreSettings'] = !store['showMoreSettings'];
    }, [store]);
    const dataLayerRef = React.useRef({
        time: 0,
    });
    useMount$1(() => {
        dataLayerRef.current = {
            time: new Date().getTime(),
        };
    });
    // const history = useHistory();
    const ref = React.useRef(null);
    const refList = React.useRef(null);
    const wrapperRef = React.useRef(null);
    const handleShowCustomIconSetting = useCallback(() => {
        toggleShowCustomIconSetting(undefined, (show) => {
            if (show && packageConfigShow) {
                changePackageConfigShow();
            }
        });
    }, [changePackageConfigShow, packageConfigShow]);
    const back = useStaticCallback(() => {
        if (dataLayerRef.current && dataLayerRef.current.time) {
            const now = sendPage('map', 'edit', mapName || '', dataLayerRef.current.time);
            dataLayerRef.current.time = now;
        }
        if (_onClose) {
            _onClose && _onClose();
            return;
        }
        let route = appStore.getTypeRoute(ModuleRouteEnum.MyProject);
        if (projectOption === null || projectOption === void 0 ? void 0 : projectOption.id) {
            route = appStore.getTypeRoute(ModuleRouteEnum.Projects) + `?projectid=${projectOption.id}`;
            // route = route.replace(':id', projectOption.id);
        }
        appStore.goToRoute(route);
    });
    const replacetoEditRoute = useStaticCallback((id) => {
        if (!id)
            return;
        let route = appStore.getTypeRoute(ModuleRouteEnum.MapEdit);
        route = route.replace(':type', UpdateDataType.edit).replace(':id', id);
        if (projectOption === null || projectOption === void 0 ? void 0 : projectOption.version) {
            route += `?projectid=${projectOption.id}&versionid=${projectOption.version}`;
        }
        appStore.goToRoute(route);
    });
    const _saveAndLeaveMap = useStaticCallback(() => {
        if (_onSave) {
            saveMap((uuid, preview) => {
                _onSave(uuid, preview);
                back();
            });
            return;
        }
        saveMap(back);
    });
    const _saveMap = useStaticCallback(() => {
        const cb = _onSave ? undefined : replacetoEditRoute;
        saveMap(cb);
    });
    const handleAddPackage = useStaticCallback(() => {
        changePackageConfigShow();
        clearSearch();
    });
    const renderMoreSettings = useMemo(() => {
        const handleClick = () => {
            setShowSearchSettings(true);
            toggleShowMoreSettings();
            setPackageConfigShow(false);
            setShowMapSettings(false);
        };
        return (React.createElement(Menu, null,
            React.createElement(MenuItem, { onMouseLeave: toggleShowMoreSettings, key: i18n$2.mapEdit.searchSettings, title: i18n$2.mapEdit.searchSettings, onClick: handleClick }, i18n$2.mapEdit.searchSettings)));
    }, [setShowSearchSettings, setPackageConfigShow, toggleShowMoreSettings, setShowMapSettings]);
    useClickAway(refList, (e) => {
        var _a;
        const clickInsideWrap = !!((_a = wrapperRef.current) === null || _a === void 0 ? void 0 : _a.contains(e.target));
        if (!clickInsideWrap) {
            store.showPackageModelList = false;
        }
    });
    const renderMoreList = useMemo(() => {
        return (React.createElement("div", { ref: wrapperRef },
            React.createElement(Menu, null,
                React.createElement(MenuItem, { key: i18n$2.mapEdit.package, title: i18n$2.mapEdit.package, onClick: () => {
                        changeCurrentDataList('package');
                        store.showPackageModelList = false;
                    } }, i18n$2.mapEdit.package),
                React.createElement(MenuItem, { key: i18n$2.mapEdit.model, title: i18n$2.mapEdit.model, onClick: () => {
                        if (!can3D) {
                            toastApi.warning(i18n$2.mapEdit.setMapViewWarning);
                            return;
                        }
                        changeCurrentDataList('model');
                        store.showPackageModelList = false;
                    } }, i18n$2.mapEdit.model))));
    }, [can3D, changeCurrentDataList, store]);
    let cantSave;
    if (MapTypeSet.add === type) {
        cantSave = loading;
    }
    else {
        cantSave = loading || !dataReady;
    }
    return (React.createElement("div", { className: prefixCls, ref: ref },
        React.createElement("div", { className: `${prefixCls}-name` },
            React.createElement("div", { className: `${prefixCls}-name-icon` },
                React.createElement(IconButton, { icon: "map-outlined" })),
            React.createElement(Rename, { value: mapName, placeholder: i18n$2.mapEdit.untitledMap, classname: `${prefixCls}-rename`, onChangeValue: changeMapName }),
            React.createElement("div", null,
                React.createElement(Button, { size: "compact", onClick: handleAddPackage, "data-test": "map-package-config-button" }, packageConfigShow ? (React.createElement(React.Fragment, null,
                    React.createElement(Icon$1, { icon: "fold-left", className: `mr8`, size: 16 }),
                    i18n$2.mapEdit.collapsePanel)) : (React.createElement(React.Fragment, null,
                    React.createElement(Icon$1, { icon: "add", className: `mr8`, size: 16 }),
                    i18n$2.mapEdit.addPackage)))),
            React.createElement(Dropdown, { trigger: "click", visible: showPackageModelList, overlay: renderMoreList, placement: "bottomLeft" },
                React.createElement("div", { ref: refList },
                    React.createElement(Button, { size: "compact", className: `${prefixCls}-icon-button ml6`, onClick: toggleShowPackageModelList },
                        React.createElement(Icon$1, { icon: "arrow-down", size: 16 })))),
            React.createElement(Dropdown, { trigger: "click", visible: showMoreSettings, overlay: renderMoreSettings, placement: "bottomLeft" },
                React.createElement(Button, { size: "compact", onClick: toggleShowMoreSettings, className: `ml6`, "data-test": "map-header-show-more-settings" },
                    React.createElement(Icon$1, { icon: "more-horizontal" })))),
        React.createElement(Dropdown, { destroyPopupOnHide: true, overlayClassName: "map-drawer", trigger: "click", visible: showMapSettings, overlay: React.createElement(MenuSettings, null), placement: "bottomLeft" },
            React.createElement("div", { className: `${prefixCls}-setting` },
                type === MapTypeSet.edit && (React.createElement(Tooltip, { title: i18n$2.mapEdit.replacePackage.replaceData },
                    React.createElement(Button, { leftIcon: "swap-horiz", size: "compact", onClick: () => {
                            openReplacePackage({
                                projectOption,
                                mapStyleUid,
                                mapUid: mapUid || '',
                                onOk: resetMapStyle,
                            });
                        }, className: "mr4" }, "\u6570\u636E\u66FF\u6362"))),
                React.createElement(Authorized, { authority: Previleges.updateAppPreference },
                    React.createElement(Tooltip, { title: i18n$2.mapEdit.customIcon },
                        React.createElement(Button, { onlyIcon: "location-3", size: "compact", onClick: handleShowCustomIconSetting, className: "mr4" }))),
                React.createElement(Tooltip, { title: i18n$2.mapEdit.mapSettings.mapSettings },
                    React.createElement(Button, { onlyIcon: "setting", size: "compact", onClick: changeShowMapSettings, "data-test": "map-settings-btn" })))),
        React.createElement(MapSearchSettings, null),
        React.createElement("div", { className: `${prefixCls}-btns` },
            React.createElement(NavButton, { onClick: _saveMap, disabled: cantSave }, i18n$2.mapEdit.save),
            React.createElement("div", { className: `${prefixCls}-btns-line` }),
            noData ? (React.createElement(NavButton, { type: "danger", className: 'mr8', onClick: back }, i18n$2.mapEdit.giveUp)) : (React.createElement(Popconfirm, { destroyTooltipOnHide: true, overlayClassName: `${prefixCls}-pop`, placement: "bottomRight", okText: i18n$2.mapEdit.okText, cancelText: i18n$2.mapEdit.cancelText, message: `${i18n$2.mapEdit.confirmGiveUp}${i18n$2.mapEdit.questionMark}`, trigger: "click", emotion: 'help-2', onConfirm: back },
                React.createElement(NavButton, { type: "danger", className: 'mr8' }, i18n$2.mapEdit.giveUp))),
            React.createElement(NavButton, { type: "success", onClick: _saveAndLeaveMap, disabled: cantSave }, i18n$2.mapEdit.finish))));
});
EditHeader.whyDidYouRender = true;
EditHeader.displayName = 'EditHeader';
var EditHeader$1 = EditHeader;

export { EditHeader$1 as default };
