import { aD as jsxRuntimeExports, s as __assign$2, aP as createI18n, aQ as LANGUAGE, n as iconsUtil, i as __read, t as toastApi, b as __awaiter, c as __generator, ar as Tooltip, I as Icon, aR as dialogApi, aS as IconAction, a6 as Input, C as SortList, y as IconButton, aq as Button, au as Checkbox, aT as ToastContainer, av as Drawer, ac as Spin, aU as IconsUtil, aV as reduce, aW as uniq, $ as find, h as __spreadArray, Z as filter, aX as findIndex, aY as uploadCustomIcon, aZ as deleteCustomIcon, a_ as PreferenceError, a$ as CUSTOM_ICON_PREFIX, b0 as CUSTOM_ICON_SUFFIX } from './MapEditView-24782753.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 'perf-request';
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';

var 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: '当前图标数据缓存已过时，继续操作会导致数据丢失，建议刷新',
    },
};

var cn = __assign$2({}, cn$1);

var 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',
    },
};

var us = __assign$2({}, us$1);

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

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