import { ay as jsxRuntimeExports, aK as createI18n, aL as LANGUAGE, t as toastApi, a as __awaiter, am as Tooltip, I as Icon, aM as dialogApi, aN as IconAction, a1 as Input, x as SortList, s as IconButton, al as Button, ap as Checkbox, aO as ToastContainer, aq as Drawer, a7 as Spin, l as iconsUtil, aP as IconsUtil, aQ as reduce, aR as uniq, U as find, V as filter, aS as findIndex, aT as uploadCustomIcon, aU as deleteCustomIcon, aV as PreferenceError, aW as CUSTOM_ICON_PREFIX, aX as CUSTOM_ICON_SUFFIX } from './MapEditView-f6381866.js';
import * as React from 'react';
import { useMemo, useState, useRef, useCallback, useEffect } from 'react';
import ReactDOM__default from 'react-dom';
import classNames from 'classnames';
import { observer } from 'mobx-react';
import { v4 } from 'uuid';
import { useDropzone } from 'react-dropzone';
import { map } from 'lodash';
import 'maptalks';
import 'mobx';
import 'lz-string';
import 'dayjs';
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 '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 __assign$1 = undefined && undefined.__assign || function () {
  __assign$1 = 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$1.apply(this, arguments);
};

var __rest$1 = 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$2 = 'dmc-dropzone';
var Dropzone = /*#__PURE__*/React.forwardRef(function (props, ref) {
  var _a, _b;

  var children = props.children,
      className = props.className,
      tip = props.tip,
      desc = props.desc,
      size = props.size,
      restProps = __rest$1(props, ["children", "className", "tip", "desc", "size"]);

  var _c = useDropzone(restProps),
      getRootProps = _c.getRootProps,
      getInputProps = _c.getInputProps;

  var cls = classNames(prefixCls$2, (_a = {}, _a[prefixCls$2 + "-" + size] = size, _a), (_b = {}, _b[prefixCls$2 + "-disabled"] = restProps.disabled, _b), className);
  var node = children ? children : !!tip ? jsxRuntimeExports.jsxs(React.Fragment, {
    children: [jsxRuntimeExports.jsx("div", __assign$1({
      className: prefixCls$2 + "-tip"
    }, {
      children: tip
    }), void 0), !!desc && jsxRuntimeExports.jsx("div", __assign$1({
      className: prefixCls$2 + "-desc"
    }, {
      children: desc
    }), void 0)]
  }, void 0) : null;
  return jsxRuntimeExports.jsx("div", __assign$1({
    className: cls
  }, {
    children: jsxRuntimeExports.jsxs("div", __assign$1({}, getRootProps({
      className: prefixCls$2 + "-container",
      ref: ref
    }), {
      children: [jsxRuntimeExports.jsx("input", __assign$1({}, getInputProps()), void 0), jsxRuntimeExports.jsx("div", {
        className: prefixCls$2 + "-icon"
      }, void 0), node]
    }), void 0)
  }), void 0);
});
Dropzone.defaultProps = {
  multiple: true
};
Dropzone.displayName = 'Dropzone';
var DropzoneMemo = /*#__PURE__*/React.memo(Dropzone);
DropzoneMemo.displayName = 'DropzoneMemo';

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-dropelement';

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

  var _a = useDropzone(restProps),
      getRootProps = _a.getRootProps,
      getInputProps = _a.getInputProps;

  var cls = classNames(prefixCls$1, className);
  return jsxRuntimeExports.jsx("div", __assign({
    className: cls
  }, {
    children: jsxRuntimeExports.jsxs("div", __assign({}, getRootProps({
      className: prefixCls$1 + "-container"
    }), {
      children: [jsxRuntimeExports.jsx("input", __assign({}, getInputProps()), void 0), children]
    }), void 0)
  }), void 0);
};

Dropelement.defaultProps = {
  multiple: true
};
Dropelement.displayName = 'Dropelement';
var DropelementMemo = /*#__PURE__*/React.memo(Dropelement);
DropelementMemo.displayName = 'DropelementMemo';

const cn$1 = {
    customIconManager: {
        defaultIcon: '系统图标',
        customIcon: '自定义图标',
        markerStyle: '图标样式',
        markerSize: '点位大小',
        iconLib: '图标库',
        searchIcon: '搜索图标',
        iconName: '图标名称：',
        iconNameLimit: '*只支持英文字母开头，可包含英文字母、数字',
        iconNameInputHint: '请输入图标名称',
        dragImageHint: '点击或拖拽图片文件到此区域',
        imageSuffixSupport: '支持 svg 格式文件',
        replaceIcon: '替换图片',
        localImgRequirement: '本地图片要求：',
        localImgRequirementHint: '建议为svg格式，需将图标进行轮廓化处理',
        localImgRequirementHint2: '文件需小于',
        localImgRequirementHint3: '若图标文件有多种颜色，请勾选“按原色彩显示”',
        localImgRequirementHint4: '推荐尺寸： 16px * 16px',
        uploadIcon: '应用到图标库',
        uploadingIcon: '正在应用到图标库',
        uploadSuccess: '上传成功',
        uploadFailed: '上传失败',
        updateSuccess: '更新成功',
        updateFailed: '更新失败',
        deleteSuccess: '删除成功',
        deleteFailed: '删除失败',
        editIcon: '编辑图标',
        changeIcon: '修改图标',
        saveChanges: '保存修改',
        deleteConfirm: '确定删除自定义图标',
        deleteHint: '删除自定义图标后，所有应用该图标的图层将还原成系统默认设置。',
        invalidName: '图标名不合法',
        duplicateName: '图标名重复',
        originalColor: '按原色彩显示',
        invalidFileType: '文件格式错误，只支持 svg 格式文件',
        invalidFileSize: '图标最大尺寸为：48*48px',
        orderByName: '按名称排序',
        orderByLastUpdateTime: '按创建时间排序',
        orderByUser: '自定义排序',
        okText: '确定',
        cancelText: '取消',
        loadingText: '刷新中，请稍候...',
        refresh: '刷新',
        refreshTip: '当前图标数据缓存已过时，继续操作会导致数据丢失，建议刷新',
    },
};

const cn = Object.assign({}, cn$1);

const us$1 = {
    customIconManager: {
        defaultIcon: 'Default Icon',
        customIcon: 'Custom Icon',
        markerStyle: 'Marker Style',
        markerSize: 'Marker Size',
        iconLib: 'Icon Library',
        searchIcon: 'Search Icon',
        iconName: 'Icon Name: ',
        iconNameLimit: '*Only supports beginning with English letters, can contain English letters, numbers',
        iconNameInputHint: 'Please enter the icon name',
        dragImageHint: 'Click or drag the image file to this area',
        imageSuffixSupport: 'Support svg format files',
        replaceIcon: 'Replace picture',
        localImgRequirement: 'Local Image Requirement:',
        localImgRequirementHint: 'It is recommended to be in svg format, and the icon needs to be contoured',
        localImgRequirementHint2: 'The file must be less than ',
        localImgRequirementHint3: 'If the icon file has multiple colors, please check "Display by original color"',
        localImgRequirementHint4: 'Recommended size: 16px * 16px',
        uploadIcon: 'Apply to icon library',
        uploadingIcon: 'Applying to icon library',
        uploadSuccess: 'Upload Success',
        uploadFailed: 'Upload Failed',
        updateSuccess: 'Update Success',
        updateFailed: 'Update Failed',
        deleteSuccess: 'Delete Success',
        deleteFailed: 'Delete Failed',
        editIcon: 'Edit Icon',
        changeIcon: 'Edit Icon',
        saveChanges: 'Save changes',
        deleteConfirm: 'Confirm to delete custom icon',
        deleteHint: 'After deleting a custom icon, all layers with the icon will be restored to the system default settings.',
        invalidName: 'Invalid name',
        duplicateName: 'Duplicate icon name',
        originalColor: 'Display in original color',
        invalidFileType: 'File format error, only svg format file is supported',
        invalidFileSize: 'The maximum size of the icon is: 48*48px',
        orderByName: 'Sort By Name',
        orderByLastUpdateTime: 'Sort By Last Update Time',
        orderByUser: 'Sort By User',
        okText: 'Conform',
        cancelText: 'Cancel',
        loadingText: 'Refreshing, please wait...',
        refresh: 'refresh',
        refreshTip: 'The current icon data cache is out of date. Continued operation will result in data loss. It is recommended to refresh',
    },
};

const us = Object.assign({}, us$1);

const localeMap = {
    'zh-CN': cn,
    'en-US': us,
};
const locale = localeMap[LANGUAGE];
const i18n$1 = createI18n({
    defaultLocale: { key: LANGUAGE, values: locale },
});
i18n$1._.locale(LANGUAGE);

const prefixCls = 'dm-custom-icon-manager';
const i18n = i18n$1.customIconManager;
const { toggleShowCustomIconSetting, getIconLabel } = iconsUtil;
const { formatIconName } = IconsUtil;
const CustomIconManager = observer(function _CustomIconManager() {
    const { getIconUrl, getIconColorPref, updateIconListCache, showCustomIconSetting, isInitialized, appId, needRefresh, iconPreferenceCache, updateOrderPref, batchUpdateIconPref, setNeedRefresh, iconCache, } = iconsUtil;
    const orderPreferenceCache = useMemo(() => map(iconPreferenceCache, (i) => i.name), [iconPreferenceCache]);
    const [visible, setVisible] = useState(false);
    const [iconList, setIconList] = useState({
        customIconList: [],
        defaultIconList: [],
    });
    const [showEditPanel, setShowEditPanel] = useState(false);
    const [uploading, setUploading] = useState(false);
    // 当前待上传文件
    const [file, setFile] = useState();
    // 当前预览文件 objUrl / base64 (上传时临时使用 objUrl， 编辑使用 base64)
    const [curIconSrc, setCurIconSrc] = useState('');
    // 当前选中/激活的图标 name 用于更新图标
    const curtActiveIconRef = useRef();
    // 图标名称
    const [iconName, setIconName] = useState('');
    // 图标名称合法
    const [iconNameValid, setIconNameValid] = useState(true);
    // 图标尺寸大小合法
    const [iconSizeValid, setIconSizeValid] = useState(true);
    // 图标搜索关键字
    const [searchText, setSearchText] = useState('');
    const dropZoneRef = useRef(null);
    // 不可见的下载用 <a>
    const downloadAnchor = useRef(null);
    // outmost drawer ref
    const customIconSettingDrawerRef = useRef(null);
    // 按原色彩显示
    const [originalColor, setOriginalColor] = useState(false);
    const [loading, setLoading] = useState(true);
    const [refreshList, setRefreshList] = useState(false);
    const { customIconList, defaultIconList } = iconList;
    // 搜索图标
    const handleIconSearchChange = useCallback((e) => {
        setSearchText(e.target.value);
    }, []);
    const handleVisibleChange = useCallback(() => {
        toggleShowCustomIconSetting(false);
    }, []);
    // 检查文件名合法性
    const processIconName = useCallback((name, silent = false) => {
        if (name) {
            const legal = /^[a-z][a-z0-9_-]*$/.test(name);
            const duplicate = customIconList.findIndex((i) => i === name) >= 0;
            const iconNameValid = legal && !duplicate;
            setIconNameValid(iconNameValid);
            if (!silent) {
                if (!legal) {
                    toastApi.warning(i18n.invalidName);
                }
                else if (duplicate) {
                    toastApi.warning(i18n.duplicateName);
                }
            }
            return iconNameValid;
        }
    }, [customIconList]);
    const handleChangeIconName = useCallback((e) => {
        const name = (typeof e === 'string' ? e : e.target.value).toLowerCase();
        processIconName(name);
        setIconName(name);
    }, [processIconName]);
    const handleDownloadIcon = useCallback(function (iconName) {
        return __awaiter(this, void 0, void 0, function* () {
            const link = downloadAnchor.current;
            if (link) {
                link.href = getIconUrl(iconName) || '#';
                link.setAttribute('download', iconName);
                link.click();
            }
        });
    }, [getIconUrl]);
    const getOrderCustomIconList = (order, iconList) => {
        const orderedList = reduce(uniq(order), (acc, name) => {
            const item = find(iconList, (i) => i === name);
            item && acc.push(item);
            return acc;
        }, []);
        // 保证所有图标都显示
        // 举例：偏好删除成功 图标删除失败 导致偏好缺少该图标 但图标实际存在
        return [
            ...orderedList,
            ...filter(iconList, (i) => findIndex(orderedList, (j) => j === i) === -1),
        ];
    };
    // 根据用户排序接口数据重新排序数据
    const reOrderCustomIconList = useCallback((order) => {
        setIconList((prev) => (Object.assign(Object.assign({}, prev), { customIconList: getOrderCustomIconList(order, prev.customIconList) })));
    }, []);
    const uploadNewIcon = useCallback((iconName, file) => __awaiter(this, void 0, void 0, function* () {
        const tmpForm = new FormData();
        tmpForm.append('file', file);
        yield uploadCustomIcon({ name: iconName }, tmpForm, { action: 'update' });
    }), []);
    const handleClearState = useCallback(() => {
        try {
            URL.revokeObjectURL(curIconSrc);
        }
        catch (_a) { }
        setShowEditPanel(false);
        setFile(undefined);
        setCurIconSrc('');
        setIconName('');
        setOriginalColor(false);
        setIconSizeValid(true);
    }, [curIconSrc]);
    // 编辑图标项
    const handleEditItem = useCallback((action) => __awaiter(this, void 0, void 0, function* () {
        if (action !== IconAction.delete && (!iconName || !iconNameValid)) {
            toastApi.warning(i18n.invalidName);
            return;
        }
        const newIconName = `${CUSTOM_ICON_PREFIX}${iconName}${CUSTOM_ICON_SUFFIX}`;
        const clickItemName = curtActiveIconRef.current || '';
        switch (action) {
            case IconAction.create:
                setUploading(true);
                try {
                    // 先更改偏好设置 再进行文件上传
                    yield batchUpdateIconPref({
                        actions: {
                            [IconAction.create]: [
                                {
                                    name: newIconName,
                                    originalColor,
                                },
                            ],
                        },
                    });
                    if (file) {
                        yield uploadNewIcon(newIconName.substring(1), file);
                    }
                    updateIconListCache();
                    toastApi.success(`"${iconName}"${i18n.uploadSuccess}`);
                }
                catch (e) {
                    // eslint-disable-next-line no-console
                    console.error(e instanceof Error ? e.message : e);
                    toastApi.error(`"${iconName}"${i18n.uploadFailed}`);
                    if (e instanceof PreferenceError) {
                        setNeedRefresh(true);
                    }
                }
                setUploading(false);
                break;
            case IconAction.update:
                try {
                    // 先更改偏好设置 再进行文件上传
                    yield batchUpdateIconPref({
                        actions: {
                            [IconAction.update]: [
                                {
                                    name: clickItemName,
                                    originalColor,
                                },
                            ],
                        },
                    });
                    updateIconListCache();
                    toastApi.success(`"${iconName}"${i18n.updateSuccess}`);
                }
                catch (e) {
                    // eslint-disable-next-line no-console
                    console.error(e instanceof Error ? e.message : e);
                    toastApi.error(`"${iconName}"${i18n.updateFailed}`);
                    if (e instanceof PreferenceError) {
                        setNeedRefresh(true);
                    }
                }
                setUploading(false);
                break;
            case IconAction.delete:
                const index = customIconList.findIndex((i) => i === clickItemName);
                if (index >= 0) {
                    try {
                        // debugger;
                        // 先更改偏好设置 再进行文件删除
                        yield batchUpdateIconPref({
                            actions: {
                                [IconAction.delete]: [
                                    {
                                        name: clickItemName,
                                        originalColor,
                                    },
                                ],
                            },
                        });
                        yield deleteCustomIcon({
                            name: clickItemName,
                        });
                        updateIconListCache();
                        toastApi.success(`"${clickItemName}"${i18n.deleteSuccess}`);
                    }
                    catch (e) {
                        toastApi.error(`"${clickItemName}"${i18n.deleteFailed}`);
                        // eslint-disable-next-line no-console
                        console.error(e instanceof Error ? e.message : e);
                        setNeedRefresh(true);
                    }
                }
                break;
        }
        handleClearState();
    }), [
        batchUpdateIconPref,
        customIconList,
        file,
        handleClearState,
        iconName,
        iconNameValid,
        originalColor,
        setNeedRefresh,
        updateIconListCache,
        uploadNewIcon,
    ]);
    const handleOpenEditPanel = useCallback((item) => {
        setShowEditPanel(true);
        curtActiveIconRef.current = item.name;
        // setIconName(item.name);
        setIconName(item.label);
        setCurIconSrc(getIconUrl(item.name));
        setOriginalColor(getIconColorPref(item.name));
    }, [getIconColorPref, getIconUrl]);
    // const handleImagePreviewLoad: React.ReactEventHandler<HTMLImageElement> = (e) => {
    //   const { naturalWidth, naturalHeight } = e.target as HTMLImageElement;
    //   if (naturalWidth > 48 || naturalHeight > 48) {
    //     setIconSizeValid(false);
    //     toast.warning(i18n.invalidFileSize);
    //   }
    // };
    const rowRenderer = useCallback((item, type, prefixEl) => {
        var _a, _b;
        const url = getIconUrl(item.name);
        const isCustom = (_b = (_a = item.name) === null || _a === void 0 ? void 0 : _a.startsWith) === null || _b === void 0 ? void 0 : _b.call(_a, '.');
        return (React.createElement("div", { className: `list-item ${type === 'custom' ? 'pl3' : ''}` },
            React.createElement("div", { className: "action-part" }, prefixEl || null),
            React.createElement("span", { className: "list-item-content" },
                getIconColorPref(item.name) ? (React.createElement("img", { className: "list-item-content-icon", src: url, alt: "" })) : (React.createElement("span", { className: "list-item-content-icon", style: {
                        maskImage: `url(${url})`,
                        WebkitMaskImage: `url(${url})`,
                        maskSize: 'contain',
                        WebkitMaskSize: 'contain',
                        maskRepeat: 'no-repeat',
                        WebkitMaskRepeat: 'no-repeat',
                        maskPosition: 'center center',
                        WebkitMaskPosition: 'center center',
                        mask: `url(${url}) no-repeat center contain`,
                        backgroundColor: 'var(--dmc-text-7)',
                    } })),
                React.createElement("span", { className: "list-item-content-name" }, item.label)),
            React.createElement("span", { className: "list-item-edit action-part" },
                isCustom && (React.createElement(Tooltip, { title: i18n.editIcon },
                    React.createElement(Icon, { icon: "edit", size: 12, onClick: () => handleOpenEditPanel(item) }))),
                React.createElement(Icon, { icon: "download", size: 12, onClick: () => {
                        handleDownloadIcon(item.value);
                    } }),
                isCustom && (React.createElement(Icon, { icon: "delete-2", size: 12, onClick: () => {
                        curtActiveIconRef.current = item.name;
                        setCurIconSrc(item.objectUrl);
                        dialogApi.warning({
                            title: `${i18n.deleteConfirm}"${item.label}"?`,
                            description: i18n.deleteHint,
                            okText: i18n.okText,
                            cancelText: i18n.cancelText,
                            onOk: (e, onClose) => {
                                onClose && onClose();
                                handleEditItem(IconAction.delete);
                            },
                            getContainer: ReactDOM__default.findDOMNode(customIconSettingDrawerRef.current) || document.body,
                        });
                    } })))));
    }, [getIconColorPref, getIconUrl, handleDownloadIcon, handleEditItem, handleOpenEditPanel]);
    const renderLeftListItem = useCallback((provided, item) => (React.createElement("div", Object.assign({ ref: provided.innerRef }, provided.draggableProps, { className: "custom-icon-item", key: item.value }),
        React.createElement("div", null, rowRenderer(item, 'custom', React.createElement(Icon, Object.assign({ icon: "drag-handle", className: "dmc-sort-list-handle" }, provided.dragHandleProps)))))), [rowRenderer]);
    const handleLeftListChange = useCallback((result) => __awaiter(this, void 0, void 0, function* () {
        try {
            const order = result.map((i) => i.name);
            reOrderCustomIconList(order);
            yield updateOrderPref(order);
        }
        catch (e) {
            reOrderCustomIconList(orderPreferenceCache);
            // eslint-disable-next-line no-console
            console.error('failed to update custom-icon order: ', e instanceof Error ? e.message : e);
            if (e instanceof PreferenceError) {
                setNeedRefresh(true);
            }
        }
    }), [orderPreferenceCache, reOrderCustomIconList, setNeedRefresh, updateOrderPref]);
    const renderLeftList = useCallback(() => {
        const list = searchText
            ? customIconList.reduce((acc, i) => {
                if (i.includes(searchText)) {
                    acc.push({
                        label: getIconLabel(i),
                        name: i,
                    });
                }
                return acc;
            }, [])
            : customIconList.map((i) => ({ label: getIconLabel(i), name: i }));
        return (React.createElement("div", { className: `${prefixCls}-body-left` },
            React.createElement("div", { className: `${prefixCls}-body-left-title` }, i18n.iconLib),
            React.createElement(Input, { value: searchText, placeholder: i18n.searchIcon, prefixIcon: "search", onChange: handleIconSearchChange }),
            React.createElement("div", { className: `${prefixCls}-body-left-list` },
                React.createElement("div", { className: `${prefixCls}-body-left-list-sub-title` }, i18n.customIcon),
                React.createElement(SortList, { list: list, onChange: handleLeftListChange, renderItem: renderLeftListItem, valueKey: "name" }),
                React.createElement("div", { className: `${prefixCls}-body-left-list-sub-title` }, i18n.defaultIcon),
                (searchText
                    ? defaultIconList.filter((i) => i.includes(searchText))
                    : defaultIconList).map((i) => (React.createElement("div", { key: i }, rowRenderer({ name: i, label: i }, 'default')))))));
    }, [
        customIconList,
        defaultIconList,
        handleIconSearchChange,
        handleLeftListChange,
        renderLeftListItem,
        rowRenderer,
        searchText,
    ]);
    const renderRightSettings = useCallback(({ showHeader = false, showApplyButton = true, nameDisabled = false, }) => {
        const closeEditPanel = () => {
            setIconName('');
            setCurIconSrc('');
            setOriginalColor(false);
            setShowEditPanel(false);
        };
        return (React.createElement(React.Fragment, null,
            showHeader && (React.createElement("div", { className: `${prefixCls}-edit-header` },
                React.createElement(IconButton, { icon: "close", type: "only-icon", onClick: closeEditPanel }),
                React.createElement("span", null, i18n.changeIcon),
                React.createElement(Button, { onClick: closeEditPanel }, i18n.cancelText),
                React.createElement(Button, { type: "primary", onClick: () => handleEditItem(IconAction.update) }, i18n.saveChanges))),
            React.createElement("div", { className: classNames(`${prefixCls}-body-right`, {
                    'center-flex-item': uploading,
                }) }, uploading ? (React.createElement("div", { className: "uploading" },
                React.createElement(Icon, { icon: "loading" }),
                React.createElement("span", null,
                    i18n.uploadingIcon,
                    "\uFF081/1\uFF09..."))) : (React.createElement(React.Fragment, null,
                React.createElement("div", { className: `${prefixCls}-body-right-title` },
                    React.createElement("span", null, i18n.iconName),
                    React.createElement(Input, { value: iconName, onChange: (e) => setIconName(e.target.value), onBlur: handleChangeIconName, placeholder: i18n.iconNameInputHint, disabled: nameDisabled, status: iconName && !iconNameValid ? 'error' : undefined }),
                    React.createElement("span", { className: "icon-name-hint" }, i18n.iconNameLimit)),
                React.createElement("div", { className: `${prefixCls}-upload-and-preview` },
                    React.createElement(Dropzone, { ref: dropZoneRef, accept: 'image/*', tip: i18n.dragImageHint, desc: i18n.imageSuffixSupport, onDropAccepted: ([file]) => {
                            if (file.type === 'image/svg+xml') {
                                if (file.size > 102400) {
                                    toastApi.warning(`${i18n.localImgRequirementHint2}100KB`);
                                    return;
                                }
                                const { name } = file;
                                const objUrl = URL.createObjectURL(file);
                                const noIconName = iconName === '';
                                const noSuffixFileName = formatIconName({
                                    name: iconName || name,
                                    convertToLowerCase: true,
                                });
                                setFile(file);
                                setCurIconSrc(objUrl);
                                processIconName(noSuffixFileName);
                                // 更新文件不需要覆盖名称
                                if (!showEditPanel && noIconName) {
                                    setIconName(noSuffixFileName);
                                }
                            }
                            else {
                                toastApi.warning(i18n.invalidFileType);
                            }
                        } }),
                    curIconSrc && (React.createElement("div", { className: `${prefixCls}-preview`, onClick: () => {
                            var _a;
                            (_a = dropZoneRef.current) === null || _a === void 0 ? void 0 : _a.click();
                        } },
                        React.createElement("div", { className: "image-container" }, curIconSrc && (React.createElement("img", { src: curIconSrc, alt: "Icon here" }))),
                        React.createElement("div", { className: "mask-and-btn" },
                            React.createElement(Button, { size: "compact" }, i18n.replaceIcon))))),
                React.createElement(Checkbox, { className: "color-changeable", checked: originalColor, disabled: !iconName || !curIconSrc, onChange: (checked) => setOriginalColor(checked) }, i18n.originalColor),
                showApplyButton && (React.createElement(Button, { disabled: !file || !iconName || !iconNameValid || !iconSizeValid, onClick: () => handleEditItem(IconAction.create) }, i18n.uploadIcon)),
                React.createElement("div", { className: `${prefixCls}-body-right-hint` },
                    i18n.localImgRequirement,
                    React.createElement("div", { className: `${prefixCls}-body-right-hint-detail` },
                        React.createElement("span", null,
                            "1\u3001",
                            i18n.localImgRequirementHint,
                            ";"),
                        React.createElement("span", null,
                            "2\u3001",
                            i18n.localImgRequirementHint2,
                            "100KB;"),
                        React.createElement("span", null,
                            "3\u3001",
                            i18n.localImgRequirementHint3,
                            ";"),
                        React.createElement("span", null,
                            "4\u3001",
                            i18n.localImgRequirementHint4))))))));
    }, [
        curIconSrc,
        file,
        handleChangeIconName,
        handleEditItem,
        iconName,
        iconNameValid,
        iconSizeValid,
        originalColor,
        processIconName,
        showEditPanel,
        uploading,
    ]);
    useEffect(() => {
        if (!visible) {
            handleClearState();
            setSearchText('');
        }
    }, [handleClearState, visible]);
    useEffect(() => {
        setVisible(showCustomIconSetting);
    }, [showCustomIconSetting]);
    useEffect(() => {
        // 初始化
        if (isInitialized[appId]) {
            setIconList(Object.assign(Object.assign({}, iconCache), { customIconList: getOrderCustomIconList(orderPreferenceCache, iconCache.customIconList) }));
            setLoading(false);
        }
    }, [appId, iconCache, isInitialized, orderPreferenceCache]);
    useEffect(() => {
        var _a;
        if (needRefresh) {
            const key = v4();
            (_a = toastApi.notification) === null || _a === void 0 ? void 0 : _a.notice({
                key,
                content: (React.createElement(ToastContainer, { type: "warning", message: i18n.refreshTip, buttonText: i18n.refresh, onClose: () => {
                        setNeedRefresh(false);
                        setRefreshList(true);
                        toastApi.notification.removeNotice(key);
                    } })),
                closable: true,
                duration: null,
            });
        }
    }, [needRefresh, setNeedRefresh]);
    useEffect(() => {
        if (refreshList) {
            setRefreshList(false);
            (() => __awaiter(this, void 0, void 0, function* () {
                try {
                    const now = new Date().getTime();
                    setLoading(true);
                    yield iconsUtil.initCustomIconData();
                    const costTime = +new Date() - now;
                    setTimeout(() => {
                        setLoading(false);
                        setNeedRefresh(false);
                    }, costTime > 500 ? 0 : 500 - costTime);
                }
                catch (_a) {
                    setNeedRefresh(true);
                }
            }))();
        }
    }, [refreshList, setNeedRefresh]);
    return (React.createElement(React.Fragment, null,
        React.createElement(Drawer, { level: null, handler: false, open: visible, onClose: handleVisibleChange, width: '566px', className: `${prefixCls}-drawer`, ref: customIconSettingDrawerRef, wrapperClassName: `${prefixCls}-drawer-wrapper` },
            React.createElement(Spin, { tip: i18n.loadingText, spinning: loading },
                React.createElement("div", { className: `${prefixCls}` },
                    React.createElement("div", { className: `${prefixCls}-header` },
                        React.createElement(IconButton, { icon: "close", type: "only-icon", onClick: handleVisibleChange }),
                        React.createElement("span", null, i18n.customIcon)),
                    React.createElement("div", { className: `${prefixCls}-body` },
                        renderLeftList(),
                        renderRightSettings({}))))),
        React.createElement(Drawer, { level: null, handler: false, open: showEditPanel, onClose: handleClearState, width: '356px', className: `${prefixCls}-drawer ${prefixCls}-edit-drawer` }, renderRightSettings({ showHeader: true, showApplyButton: false, nameDisabled: true })),
        React.createElement("a", { href: "#", ref: downloadAnchor, className: "hidden-anchor" })));
});
var CustomIconManager$1 = CustomIconManager;

export { CustomIconManager$1 as default };
