import { bs as isSymbol_1, b1 as getDefaultExportFromCjs, bt as identity_1, aj as LazyLoad, w as appContext, bu as getColumnStat, bv as MapUIStyleTypeSet, v as i18n, T as THEME_COLOR, bw as CreateFilter, bx as RadioGroup, am as LinkButton, h as __spreadArray, i as __read, b6 as splitColors, b as __awaiter, c as __generator, t as toastApi, b7 as setCustomColorSchemePref, b8 as getCustomColorSchemeRef, by as _baseTimes, bz as toInteger_1, bA as _castFunction, a3 as Input, y as IconButton, U as map$1, $ as getTheme, a0 as ThemeEnum, bB as isNumber_1, aT as uniq, bC as size$1, az as Select } from './MapEditView-67426f04.js';
import * as React from 'react';
import { useRef as useRef$2, useCallback as useCallback$2, useEffect as useEffect$1 } from 'react';
import classNames from 'classnames';
import { C as ColorList } from './MapVisualGeoIcon-606acf2a.js';
import { useMount, useDebounceFn } from 'ahooks';
import { size, map, forEach, set, slice, find, get } from 'lodash';
import { T as Transfer } from './Transfer-20410a61.js';
import { observer, useLocalStore } from 'mobx-react';
import { useKey, useMeasure } from 'react-use';
import { u as useDataValue } from './useDataValue-bfcabd04.js';
import { ckmeans } from 'simple-statistics';
import { init } from 'echarts';
import { S as Slider } from './Slider-6a70ba99.js';

var isSymbol = isSymbol_1;

/**
 * The base implementation of methods like `_.max` and `_.min` which accepts a
 * `comparator` to determine the extremum value.
 *
 * @private
 * @param {Array} array The array to iterate over.
 * @param {Function} iteratee The iteratee invoked per iteration.
 * @param {Function} comparator The comparator used to compare values.
 * @returns {*} Returns the extremum value.
 */
function baseExtremum$2(array, iteratee, comparator) {
  var index = -1,
      length = array.length;

  while (++index < length) {
    var value = array[index],
        current = iteratee(value);

    if (current != null && (computed === undefined
          ? (current === current && !isSymbol(current))
          : comparator(current, computed)
        )) {
      var computed = current,
          result = value;
    }
  }
  return result;
}

var _baseExtremum = baseExtremum$2;

/**
 * The base implementation of `_.gt` which doesn't coerce arguments.
 *
 * @private
 * @param {*} value The value to compare.
 * @param {*} other The other value to compare.
 * @returns {boolean} Returns `true` if `value` is greater than `other`,
 *  else `false`.
 */

function baseGt$1(value, other) {
  return value > other;
}

var _baseGt = baseGt$1;

var baseExtremum$1 = _baseExtremum,
    baseGt = _baseGt,
    identity$1 = identity_1;

/**
 * Computes the maximum value of `array`. If `array` is empty or falsey,
 * `undefined` is returned.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Math
 * @param {Array} array The array to iterate over.
 * @returns {*} Returns the maximum value.
 * @example
 *
 * _.max([4, 2, 8, 6]);
 * // => 8
 *
 * _.max([]);
 * // => undefined
 */
function max(array) {
  return (array && array.length)
    ? baseExtremum$1(array, identity$1, baseGt)
    : undefined;
}

var max_1 = max;

var max$1 = /*@__PURE__*/getDefaultExportFromCjs(max_1);

/**
 * The base implementation of `_.lt` which doesn't coerce arguments.
 *
 * @private
 * @param {*} value The value to compare.
 * @param {*} other The other value to compare.
 * @returns {boolean} Returns `true` if `value` is less than `other`,
 *  else `false`.
 */

function baseLt$1(value, other) {
  return value < other;
}

var _baseLt = baseLt$1;

var baseExtremum = _baseExtremum,
    baseLt = _baseLt,
    identity = identity_1;

/**
 * Computes the minimum value of `array`. If `array` is empty or falsey,
 * `undefined` is returned.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Math
 * @param {Array} array The array to iterate over.
 * @returns {*} Returns the minimum value.
 * @example
 *
 * _.min([4, 2, 8, 6]);
 * // => 2
 *
 * _.min([]);
 * // => undefined
 */
function min(array) {
  return (array && array.length)
    ? baseExtremum(array, identity, baseLt)
    : undefined;
}

var min_1 = min;

var min$1 = /*@__PURE__*/getDefaultExportFromCjs(min_1);

var JsonCodeEditor = LazyLoad(function () { return import('./index-181ce188.js'); });
var defOkProps = {
    doSaveColor: true,
    restoreReserveColorStatus: true,
};
var prefixCls$2 = 'dm-map-type-setting';
var MapTypeSetting = observer(function (props) {
    var _a = React.useContext(appContext.getContext()).routeStore, mapInstanceCanvas = _a.mapInstanceCanvas, getPopupContainer = _a.getPopupContainer, interfaceStyle = _a.MapSettingStore.interfaceStyle;
    var children = props.children, className = props.className, visual = props.visual, col = props.col, packageInfo = props.packageInfo, breaks = props.breaks, changeTypeVisual = props.changeTypeVisual;
    var unmounted = useRef$2(false);
    var store = useLocalStore(function () {
        return {
            col: col,
            tempColors: undefined,
            loading: false,
            list: [],
            icons: visual === null || visual === void 0 ? void 0 : visual.icons,
            breaks: breaks,
            values: breaks || [],
            colors: (visual === null || visual === void 0 ? void 0 : visual.colors) || [],
            sourceColors: (visual === null || visual === void 0 ? void 0 : visual.colors) || [],
            curSelectColors: (visual === null || visual === void 0 ? void 0 : visual.colors) || [],
            saveColor: false,
            reserveColorStatus: false,
            sourceStops: [],
            codeMode: false,
            originList: [], // break icon 初始化对应关系
        };
    });
    var tempColors = store.tempColors, list = store.list, icons = store.icons, values = store.values, loading = store.loading, saveColor = store.saveColor, colors = store.colors, sourceColors = store.sourceColors, curSelectColors = store.curSelectColors, reserveColorStatus = store.reserveColorStatus, sourceStops = store.sourceStops, codeMode = store.codeMode;
    var _onOk = function (_a) {
        var _b = _a === void 0 ? defOkProps : _a, doSaveColor = _b.doSaveColor, restoreReserveColorStatus = _b.restoreReserveColorStatus, highPriorityColors = _b.highPriorityColors;
        if (restoreReserveColorStatus && reserveColorStatus) {
            store.reserveColorStatus = false;
        }
        // 当前渐变色
        var curColors = highPriorityColors
            ? highPriorityColors
            : sourceStops.length
                ? __spreadArray([], __read(sourceStops), false).sort(function (a, b) { return a.offset - b.offset; }).map(function (i) { return i.color; })
                : sourceColors;
        _changeColors(curColors);
        var valueLen = size(values);
        var _colors = valueLen > size(curColors)
            ? splitColors(curColors, valueLen)
            : slice(curColors, 0, valueLen);
        var _icons = map(values, function (value) {
            var item = find(store.originList, { value: value });
            return (item === null || item === void 0 ? void 0 : item.icon) || 'marker';
        });
        changeTypeVisual && changeTypeVisual({ colors: _colors, breaks: values, icons: _icons });
        if (doSaveColor && saveColor) {
            (function () { return __awaiter(void 0, void 0, void 0, function () {
                var _customColorScheme;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4 /*yield*/, getCustomColorSchemeRef()];
                        case 1:
                            _customColorScheme = _a.sent();
                            if (curColors.length) {
                                setCustomColorSchemePref(__spreadArray(__spreadArray([], __read(_customColorScheme), false), [curColors], false));
                            }
                            return [2 /*return*/];
                    }
                });
            }); })();
        }
    };
    // 预览样式
    var handlePreviewStyle = function () {
        if (size(store.values) === 0) {
            toastApi.warning(i18n.mapEdit.previewHelp);
            return;
        }
        // 存储当前颜色，以备恢复
        if (!tempColors) {
            store.tempColors = colors;
        }
        if (!reserveColorStatus) {
            store.reserveColorStatus = true;
        }
        _onOk({
            doSaveColor: false,
            restoreReserveColorStatus: false,
        });
    };
    // 恢复样式和状态
    var handleResetStatusAndColor = function () {
        handleResetState();
        if (tempColors) {
            store.colors = tempColors || [];
            _onOk({
                doSaveColor: true,
                restoreReserveColorStatus: true,
                highPriorityColors: tempColors,
            });
            store.tempColors = undefined;
        }
    };
    var handleResetState = useCallback$2(function () {
        store['colors'] = (visual === null || visual === void 0 ? void 0 : visual.colors) || [];
        store['sourceStops'] = [];
        store['curSelectColors'] = (visual === null || visual === void 0 ? void 0 : visual.colors) || [];
        store['values'] = breaks || [];
        store['icons'] = visual === null || visual === void 0 ? void 0 : visual.icons;
        store['saveColor'] = false;
    }, [breaks, store, visual]);
    var _changeColors = function (colors) {
        var valueLen = size(values);
        var _colors = valueLen > size(colors)
            ? splitColors(colors, valueLen)
            : slice(colors, 0, valueLen);
        store.colors = _colors;
    };
    var _changeSaveColor = function (checked) {
        store.saveColor = checked;
    };
    var _changeGradientStop = function (newStop) {
        var _sourceColors = newStop.map(function (i) { return i.color; });
        store.sourceStops = newStop;
        store.sourceColors = _sourceColors;
    };
    var getStatistics = useCallback$2(function (col) {
        var _a;
        store['loading'] = true;
        unmounted.current = false;
        var columnName = col || props.col + '';
        if (size(store.list) > 0 && store.col === columnName) {
            store.loading = false;
            return;
        }
        var _b = packageInfo || {}, packageUuid = _b.packageUuid, source = _b.source, geometryType = _b.geometryType;
        if (!columnName) {
            return;
        }
        var body = (_a = {},
            _a["geometry_type"] = geometryType,
            _a["column_name"] = columnName,
            _a["column_type"] = 'str',
            _a.filters = [],
            _a);
        getColumnStat({
            packageUuid: packageUuid,
            source: source,
            dbType: 'str',
            column: columnName,
            body: body,
        }).then(function (resp) {
            if (!unmounted.current) {
                store.loading = false;
                store.col = columnName;
                store.list = map(resp.values, function (i) {
                    return { title: i, key: i };
                });
            }
        });
    }, [packageInfo, props.col, store]);
    useMount(function () {
        getStatistics(col);
        var list = [];
        forEach(breaks, function (value, index) {
            console.log(123);
            list.push({
                value: value,
                icon: icons[index],
            });
        });
        store.originList = list;
    });
    useEffect$1(function () {
        getStatistics(col);
    }, [col, getStatistics]);
    useEffect$1(function () {
        return function () {
            unmounted.current = true;
        };
    }, []);
    var _onChange = function (selected) {
        store.values = selected;
    };
    var _changeQuotes = function (_values) {
        // todo 改变icons
        var _icons = [];
        var _colors = [];
        _values.forEach(function (a) {
            var i = breaks === null || breaks === void 0 ? void 0 : breaks.indexOf(a);
            if (i !== undefined && i !== -1) {
                var _color = get(curSelectColors, [i]);
                var _icon = get(visual === null || visual === void 0 ? void 0 : visual.icons, [i]);
                if (_icon)
                    _icons.push(_icon);
                if (_color)
                    _colors.push(_color);
            }
        });
        if (size(_icons) > 0) {
            store.icons = _icons;
        }
        else {
            store.icons = (visual === null || visual === void 0 ? void 0 : visual.icons) || [];
        }
        if (size(_colors) > 0) {
            store.colors = _colors;
        }
        else {
            store.colors = curSelectColors;
        }
        store.values = _values;
    };
    useEffect$1(function () {
        if (visual) {
            handleResetState();
        }
    }, [handleResetState, visual]);
    useEffect$1(function () {
        store['sourceColors'] = colors || [];
    }, [colors, store]);
    // const codeJson = {};
    // forEach(values, (v, i) => {
    //   set(codeJson, v, colors[i]);
    // });
    var codeJsonStr = React.useMemo(function () {
        var codeJson = {};
        forEach(values, function (v, i) {
            set(codeJson, v, colors[i] || '-');
        });
        return JSON.stringify(codeJson, null, '\t');
    }, [colors, values]);
    var run = useDebounceFn(function (value) {
        console.log(value, 'value');
        try {
            var _values_1 = [];
            var _colors_1 = [];
            var obj = JSON.parse(value);
            forEach(obj, function (v, k) {
                _values_1.push(k);
                _colors_1.push(v);
            });
            store.values = _values_1;
            store.colors = _colors_1;
        }
        catch (_a) {
            console.log('error');
        }
    }, { wait: 300 }).run;
    var codeOverLay = React.useMemo(function () {
        return (React.createElement(JsonCodeEditor, { height: "300px", width: "400px", onChange: run, theme: interfaceStyle === MapUIStyleTypeSet.dark ? undefined : 'chaos', 
            // onValidate={onValidate}
            value: codeJsonStr, className: "mb20" }));
    }, [codeJsonStr, interfaceStyle, run]);
    var overlay = (React.createElement("div", { className: "".concat(prefixCls$2, "-content") }, codeMode ? (codeOverLay) : (React.createElement(React.Fragment, null,
        React.createElement(Transfer, { allowClearText: i18n.mapEdit.clear, allowClear: true, visibleUpDown: true, options: list, value: values, onChange: _onChange, onRemove: _changeQuotes, sortable: true, allSelectLabel: i18n.mapEdit.selectAll, sortListVirtualized: true }),
        React.createElement(ColorList, { saveColor: saveColor, themeColor: THEME_COLOR, colors: colors, reserveColorStatus: reserveColorStatus, handlePreviewStyle: handlePreviewStyle, changeColors: function (colors) {
                store.sourceColors = colors || [];
                store.curSelectColors = colors;
            }, changeGradientStop: _changeGradientStop, changeSaveColor: _changeSaveColor, pickColorFromMap: true, toMeasureCanvas: mapInstanceCanvas })))));
    return (React.createElement(CreateFilter, { onOk: _onOk, onClose: handleResetStatusAndColor, okButtonLabel: i18n.mapEdit.okText, cancelButtonLabel: i18n.mapEdit.cancelText, loading: loading, overlay: overlay, footerClassName: "".concat(prefixCls$2, "-footer"), className: classNames(prefixCls$2, className), placement: "rightTop", getPopupContainer: getPopupContainer, footerPrefixEl: function () { return (React.createElement("div", { style: { display: 'flex', alignItems: 'center' } },
            React.createElement(RadioGroup, { radioType: 'button', onChange: function () { return (store.codeMode = !store.codeMode); }, value: codeMode ? 'code' : 'pointer', options: [
                    { label: 'pointer', value: 'pointer', onlyIcon: 'pointer' },
                    { label: 'code', value: 'code', onlyIcon: 'code' },
                ] }),
            React.createElement(LinkButton, { className: "ml10", onClick: handlePreviewStyle }, i18n.mapEdit.previewStyle))); } }, children));
});
MapTypeSetting.defaultProps = {
    breaks: [],
};

var baseTimes = _baseTimes,
    castFunction = _castFunction,
    toInteger = toInteger_1;

/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;

/** Used as references for the maximum length and index of an array. */
var MAX_ARRAY_LENGTH = 4294967295;

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMin = Math.min;

/**
 * Invokes the iteratee `n` times, returning an array of the results of
 * each invocation. The iteratee is invoked with one argument; (index).
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Util
 * @param {number} n The number of times to invoke `iteratee`.
 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
 * @returns {Array} Returns the array of results.
 * @example
 *
 * _.times(3, String);
 * // => ['0', '1', '2']
 *
 *  _.times(4, _.constant(0));
 * // => [0, 0, 0, 0]
 */
function times(n, iteratee) {
  n = toInteger(n);
  if (n < 1 || n > MAX_SAFE_INTEGER) {
    return [];
  }
  var index = MAX_ARRAY_LENGTH,
      length = nativeMin(n, MAX_ARRAY_LENGTH);

  iteratee = castFunction(iteratee);
  n -= MAX_ARRAY_LENGTH;

  var result = baseTimes(length, iteratee);
  while (++index < n) {
    iteratee(index);
  }
  return result;
}

var times_1 = times;

var times$1 = /*@__PURE__*/getDefaultExportFromCjs(times_1);

var useState$1 = React.useState, useEffect = React.useEffect, useReducer = React.useReducer, useCallback$1 = React.useCallback, useRef$1 = React.useRef;
var prefixCls$1 = 'dmc-number-list-edit';
var strToNumber = function (val) {
    return typeof val === 'number' ? val : parseFloat(val);
};
var checkNumber = function (value) {
    var val = strToNumber(value);
    return typeof val === 'number' && isFinite(val);
};
var initialState = [];
var InAddEle = React.memo(function (props) {
    var addInputEnter = props.addInputEnter, addInputBlur = props.addInputBlur;
    return (React.createElement("div", { className: "".concat(prefixCls$1, "-list-li") },
        React.createElement(Input, { type: "menu-bg", size: "compact", block: true, allowClear: false, autoFocus: true, onPressEnter: addInputEnter, className: "".concat(prefixCls$1, "-list-add-input"), onBlur: addInputBlur })));
});
InAddEle.whyDidYouRender = true;
InAddEle.displayName = 'NumberListEditInAddEle';
var BtnEle = React.memo(function (props) {
    var onDelete = props.onDelete, onAdd = props.onAdd, disabled = props.disabled;
    return (React.createElement("div", { className: "".concat(prefixCls$1, "-handle") },
        React.createElement(IconButton, { icon: "add", ghost: true, disabled: disabled, onClick: onAdd }),
        React.createElement("div", { className: "".concat(prefixCls$1, "-handle-division") }),
        React.createElement(IconButton, { icon: "remove", ghost: true, disabled: disabled, onClick: onDelete })));
});
BtnEle.whyDidYouRender = true;
BtnEle.displayName = 'NumberListEditBtnEle';
var Item = React.memo(function (props) {
    var _a;
    var selected = props.selected, index = props.index, onDBClick = props.onDBClick, equalIndex = props.equalIndex, item = props.item, editInputEnter = props.editInputEnter, editInputBlur = props.editInputBlur, selectedLi = props.selectedLi;
    var _onDBClick = useDataValue(onDBClick);
    var _selectedLi = useDataValue(selectedLi);
    return (React.createElement("div", { "data-value": index, className: classNames("".concat(prefixCls$1, "-list-li"), (_a = {},
            _a["".concat(prefixCls$1, "-list-li-select")] = selected,
            _a)), onDoubleClick: _onDBClick },
        !equalIndex && (React.createElement("div", { className: classNames("".concat(prefixCls$1, "-list-li-text")), "data-value": index, onClick: _selectedLi }, item)),
        equalIndex && (React.createElement(Input, { type: "menu-bg", size: "compact", block: true, allowClear: false, autoFocus: true, onPressEnter: editInputEnter, defaultValue: item + '', onBlur: editInputBlur, className: "".concat(prefixCls$1, "-list-li-input") }))));
});
Item.whyDidYouRender = true;
Item.displayName = 'NumberListEditItem';
var reducer = function (state, action) {
    state = state || [];
    var selectedIndexs = action.selectedIndexs, changePropsList = action.changePropsList, type = action.type, list = action.list, value = action.value, activeIndex = action.activeIndex;
    var newState;
    switch (type) {
        case 'init':
            newState = list;
            break;
        case 'add':
            newState = __spreadArray(__spreadArray([], __read(state), false), [value], false);
            break;
        case 'delete':
            state = state.filter(function (current, index) {
                // @ts-ignore
                if ((selectedIndexs === null || selectedIndexs === void 0 ? void 0 : selectedIndexs.indexOf(index)) > -1) {
                    return false;
                }
                return true;
            });
            newState = __spreadArray([], __read(state), false);
            break;
        case 'edit':
            state[activeIndex] = value;
            newState = __spreadArray([], __read(state), false);
            break;
        default:
            newState = __spreadArray([], __read(state), false);
    }
    // 去重
    newState = Array.from(new Set(newState));
    // 排序
    newState.sort(function (a, b) {
        return a - b;
    });
    changePropsList && changePropsList(newState);
    return newState;
};
var NumberListEdit = React.memo(function (props) {
    var _a = props || {}, list = _a.list, width = _a.width, height = _a.height, valueCheck = _a.valueCheck, changePropsList = _a.changePropsList, noContent = _a.noContent, disabled = _a.disabled;
    // 渲染list
    var _b = __read(useReducer(reducer, list || initialState), 2), renderList = _b[0], setRenderList = _b[1];
    // 活动下标
    var _c = __read(useState$1(null), 2), activeIndex = _c[0], setActiveIndex = _c[1];
    // 选中下标 可以多个下标
    var _d = __read(useState$1([]), 2), selectedIndex = _d[0], setSelectedIndex = _d[1];
    // 选中多个下标
    var _e = __read(useState$1(false), 2), shift = _e[0], setShift = _e[1];
    // 是否添加状态
    var _f = __read(useState$1(false), 2), inAdd = _f[0], setInAdd = _f[1];
    var wrapperRef = useRef$1(null);
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    var stateRef = useRef$1({});
    stateRef.current = { selectedIndex: selectedIndex, activeIndex: activeIndex, shift: shift };
    var editInputBlur = useCallback$1(function (e) {
        var activeIndex = stateRef.current.activeIndex;
        var target = e.target;
        var str = target.value;
        var value = Number(str);
        var canAdd = true;
        if (valueCheck) {
            canAdd = valueCheck(value);
        }
        if (canAdd && str.length > 0) {
            setRenderList({ type: 'edit', value: value, activeIndex: activeIndex, changePropsList: changePropsList });
        }
        setActiveIndexNull();
        setSelectedIndexNull();
    }, [changePropsList, valueCheck]);
    var onShiftDown = useCallback$1(function () {
        setShift(true);
    }, []);
    var onShiftUp = useCallback$1(function () {
        setShift(false);
    }, []);
    useKey('Shift', onShiftDown, { event: 'keydown' }, [onShiftDown]);
    useKey('Shift', onShiftUp, { event: 'keyup' }, [onShiftUp]);
    var addInputBlur = useCallback$1(function (e) {
        var target = e.target;
        var str = target.value;
        var value = Number(str);
        var canAdd = true;
        if (valueCheck) {
            canAdd = valueCheck(value);
        }
        if (canAdd && str.length > 0) {
            setRenderList({ type: 'add', value: value, changePropsList: changePropsList });
        }
        setInAdd(false);
        setActiveIndexNull();
        setSelectedIndexNull();
    }, [changePropsList, valueCheck]);
    useEffect(function () {
        setRenderList({ type: 'init', list: list });
    }, [list]);
    // 添加按钮触发
    var onAdd = useCallback$1(function () {
        setInAdd(true);
    }, []);
    // 删除按钮触发
    var onDelete = useCallback$1(function () {
        var arr = [];
        var selectedIndex = stateRef.current.selectedIndex;
        selectedIndex === null || selectedIndex === void 0 ? void 0 : selectedIndex.forEach(function (current) {
            if (typeof current === 'number' && isFinite(current)) {
                arr.push(current);
            }
        });
        setRenderList({ type: 'delete', selectedIndexs: arr, changePropsList: changePropsList });
        setSelectedIndexNull();
    }, [changePropsList]);
    // 双击
    var onDBClick = useCallback$1(function (index) {
        var idx = Number(index);
        setActiveIndex(idx);
        setInAdd(false);
    }, []);
    var selectedLi = useCallback$1(function (index) {
        var idx = Number(index);
        var _a = stateRef.current, selectedIndex = _a.selectedIndex, shift = _a.shift;
        var subscript = selectedIndex.indexOf(idx);
        if (subscript > -1) {
            selectedIndex.splice(subscript, 1);
            var arr = Array.from(new Set(selectedIndex));
            setSelectedIndex(arr);
            return;
        }
        if (shift) {
            selectedIndex.push(idx);
            var arr = Array.from(new Set(selectedIndex));
            setSelectedIndex(arr);
        }
        else {
            setSelectedIndex([Number(idx)]);
        }
        setInAdd(false);
    }, []);
    // setActiveIndexNull input blur事件
    var setActiveIndexNull = function () {
        setActiveIndex(null);
    };
    // setSelectedIndexNull input blur事件
    var setSelectedIndexNull = function () {
        setSelectedIndex([]);
    };
    // 编辑input Enter
    var editInputEnter = useCallback$1(function (e) {
        var activeIndex = stateRef.current.activeIndex;
        var target = e.target;
        var value = Number(target.value);
        var canAdd = true;
        if (valueCheck) {
            canAdd = valueCheck(value);
        }
        if (canAdd) {
            setRenderList({ type: 'edit', value: value, activeIndex: activeIndex, changePropsList: changePropsList });
        }
        setActiveIndexNull();
    }, [changePropsList, valueCheck]);
    // add input Enter
    var addInputEnter = useCallback$1(function (e) {
        var target = e.target;
        var value = Number(target.value);
        var canAdd = true;
        if (valueCheck) {
            canAdd = valueCheck(value);
        }
        if (canAdd) {
            setRenderList({ type: 'add', value: value, changePropsList: changePropsList });
            setInAdd(false);
            requestAnimationFrame(function () {
                setInAdd(true);
            });
        }
    }, [changePropsList, valueCheck]);
    var noListEle = React.createElement("div", { className: "".concat(prefixCls$1, "-list-none") }, noContent);
    var rowRenderer = useCallback$1(function (params) {
        var item = params.item, index = params.index;
        var equalIndex = activeIndex === index;
        var selected = selectedIndex.indexOf(index) > -1;
        return (React.createElement(Item, { item: item, key: index, index: index, equalIndex: equalIndex, selected: selected, onDBClick: onDBClick, editInputEnter: editInputEnter, editInputBlur: editInputBlur, selectedLi: selectedLi }));
    }, [activeIndex, editInputBlur, editInputEnter, onDBClick, selectedIndex, selectedLi]);
    return (React.createElement("div", { className: prefixCls$1, style: { width: width, height: height }, ref: wrapperRef },
        React.createElement("div", { className: "".concat(prefixCls$1, "-list") },
            map$1(renderList, function (item, index) {
                // @ts-ignore
                return rowRenderer({ item: item, index: index });
            }),
            (renderList === null || renderList === void 0 ? void 0 : renderList.length) === 0 && noListEle,
            inAdd && React.createElement(InAddEle, { addInputEnter: addInputEnter, addInputBlur: addInputBlur })),
        React.createElement(BtnEle, { disabled: disabled, onAdd: onAdd, onDelete: onDelete })));
});
NumberListEdit.defaultProps = {
    className: '',
    list: [],
    valueCheck: checkNumber,
    noContent: '无',
};
NumberListEdit.whyDidYouRender = true;
NumberListEdit.displayName = 'NumberListEdit';

var DataChart = function (_a) {
    var _b = _a.data, data = _b === void 0 ? [] : _b, width = _a.width, height = _a.height;
    var refEchart = React.useRef();
    var ref = React.useRef(null);
    var seriesBar = React.useMemo(function () { return ({
        type: 'bar',
        barWidth: 10,
        silent: true,
        data: data,
    }); }, [data]);
    var option = React.useMemo(function () { return ({
        animation: false,
        color: [getTheme('') === ThemeEnum.dark ? '#3f4863' : '#ebecef'],
        tooltip: {
            show: false,
        },
        grid: {
            left: 0,
            right: 0,
            bottom: 0,
            top: 0,
        },
        xAxis: [{ data: data }],
        yAxis: [{ show: false, type: 'value' }],
        series: [seriesBar],
    }); }, [data, seriesBar]);
    React.useEffect(function () {
        if (!ref.current)
            return;
        refEchart.current = init(ref.current);
        refEchart.current.setOption(option);
    }, [ref, option]);
    React.useEffect(function () {
        if (refEchart.current) {
            refEchart.current.resize();
        }
    }, [width, height]);
    return React.createElement("div", { className: "".concat(prefixCls, "-segment-chart"), style: { width: width, height: height }, ref: ref });
};
DataChart.whyDidYouRender = true;
DataChart.displayName = 'DataChart';
var DataChart$1 = React.memo(DataChart);

var DataSegment = function (_a) {
    var min = _a.min, max = _a.max, _b = _a.data, data = _b === void 0 ? [] : _b, _c = _a.values, values = _c === void 0 ? [] : _c, onChange = _a.onChange;
    var _d = __read(useMeasure(), 2), ref = _d[0], _e = _d[1], width = _e.width, height = _e.height;
    var step = max - min <= 1 ? 0.1 : 1;
    return (React.createElement("div", { className: "".concat(prefixCls, "-chart-wrap") },
        React.createElement("div", { ref: ref, className: "".concat(prefixCls, "-segment") },
            React.createElement(DataChart$1, { width: width, height: height, data: data }),
            React.createElement(Slider, { max: max, min: min, step: step, range: true, onChange: onChange, value: values, className: "".concat(prefixCls, "-slider"), getTooltipPopupContainer: function (node) { return node === null || node === void 0 ? void 0 : node.closest('.dm-page-root'); } })),
        React.createElement("div", { className: "".concat(prefixCls, "-min-max") },
            React.createElement("span", null, min),
            React.createElement("span", null, max))));
};
DataSegment.whyDidYouRender = true;
DataSegment.displayName = 'DataSegment';

var isNumber = isNumber_1;

/**
 * Checks if `value` is `NaN`.
 *
 * **Note:** This method is based on
 * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as
 * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for
 * `undefined` and other non-number values.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
 * @example
 *
 * _.isNaN(NaN);
 * // => true
 *
 * _.isNaN(new Number(NaN));
 * // => true
 *
 * isNaN(undefined);
 * // => true
 *
 * _.isNaN(undefined);
 * // => false
 */
function isNaN(value) {
  // An `NaN` primitive is the only value that is not equal to itself.
  // Perform the `toStringTag` check first to avoid errors with some
  // ActiveX objects in IE.
  return isNumber(value) && value != +value;
}

var _isNaN = isNaN;

var isNaN$1 = /*@__PURE__*/getDefaultExportFromCjs(_isNaN);

var calculateAverageBreaks = function (min, max, breakLen) {
    // min = Math.floor(min);
    // max = Math.ceil(max);
    max = Math.abs(max) < 1 ? Number(max.toExponential(2)) : Math.ceil(max) * 1;
    var vals = [max];
    var radio = (max - min) / breakLen;
    for (var i = breakLen - 1; i > 0; i--) {
        var val = min * 1 + radio * i;
        val =
            Math.abs(val) < 1
                ? Number(val.toExponential(2))
                : Number(val.toFixed(Math.abs(max - min) > 10 ? 0 : 1));
        val = val * 1;
        if (!isNaN$1(val)) {
            vals.push(val);
        }
    }
    if (isNaN$1(max) || max === -Infinity) {
        vals[0] = Infinity;
    }
    if (!isNaN$1(min) && min !== Infinity) {
        vals.push(Math.abs(min) < 1 ? Number(min.toExponential(2)) * 1 : Math.floor(min) * 1);
    }
    else {
        vals.push(-Infinity);
    }
    vals = uniq(vals);
    return { values: vals.reverse(), min: min, max: max };
};
var calculateNBC = function (max, data, breakLen) {
    if (breakLen > size$1(data) || !data || !breakLen) {
        return [];
    }
    var breaks = ckmeans(data, breakLen).map(function (cluster) {
        return cluster[0];
    });
    // 自然分段中,最后一个数据集可能出现全为最大值情况,这种情况下,直接返回breaks
    if (breaks[breaks.length - 1] === max) {
        return breaks;
    }
    breaks.push(max);
    return breaks;
};

var _a;
var GroupbyType;
(function (GroupbyType) {
    GroupbyType["default"] = "default";
    GroupbyType["average"] = "average";
    GroupbyType["equidistant"] = "equidistant";
    GroupbyType["custom"] = "custom";
})(GroupbyType || (GroupbyType = {}));
var prefixCls = 'dmc-data-groupby';
var defaultLocale = (_a = {},
    _a[GroupbyType.default] = '不聚合',
    _a[GroupbyType.average] = '平均分段',
    _a[GroupbyType.equidistant] = '自然断点',
    _a[GroupbyType.custom] = '自定义',
    _a.noContent = '无',
    _a);
var useState = React.useState, useCallback = React.useCallback, useRef = React.useRef;
var emptyArray = [];
var DataGroupby = function (_a) {
    var onOk = _a.onOk, onClose = _a.onClose, loading = _a.loading, children = _a.children, className = _a.className, breakLen = _a.breakLen, _b = _a.data, data = _b === void 0 ? emptyArray : _b, minV = _a.min, maxV = _a.max, _c = _a.breaks, breaks = _c === void 0 ? emptyArray : _c, _d = _a.type, type = _d === void 0 ? breaks.length ? GroupbyType.custom : undefined : _d, extra = _a.extra, segLabel = _a.segLabel, okButtonLabel = _a.okButtonLabel, cancelButtonLabel = _a.cancelButtonLabel, _e = _a.locale, locale = _e === void 0 ? defaultLocale : _e, placement = _a.placement, _f = _a.clickAway, clickAway = _f === void 0 ? false : _f, handleBreaksChange = _a.handleBreaksChange, footerPrefixEl = _a.footerPrefixEl, getContainer = _a.getContainer;
    var ref = React.useRef(null);
    var getPopupContainer = React.useCallback(function () { return ref.current; }, []);
    // const minValue = minV === undefined ? min(data) || 0 : minV;
    // const maxValue = maxV === undefined ? max(data) || 1 : maxV;
    var _g = __read(useState(0), 2), minValue = _g[0], setMinValue = _g[1];
    var _h = __read(useState(1), 2), maxValue = _h[0], setMaxValue = _h[1];
    React.useEffect(function () {
        setMinValue(minV === undefined ? min$1(data) || 0 : minV);
    }, [minV, data]);
    React.useEffect(function () {
        setMaxValue(maxV === undefined ? max$1(data) || 1 : maxV);
    }, [maxV, data]);
    var _j = __read(useState(breaks), 2), list = _j[0], setList = _j[1];
    var _k = __read(useState(type || GroupbyType.default), 2), activeType = _k[0], setActiveType = _k[1];
    var _l = __read(useState(breakLen), 2), activeBreakLen = _l[0], setActiveBreakLen = _l[1];
    var stateRef = useRef({});
    stateRef.current = { breaks: list, type: activeType, breakLen: activeBreakLen };
    var segOptions = times$1(7, function (i) { return ({ value: "".concat(i + 1), label: "".concat(i + 1).concat(segLabel) }); });
    var typeOptions = [
        GroupbyType.default,
        GroupbyType.average,
        GroupbyType.equidistant,
        GroupbyType.custom,
    ].map(function (t) { return ({ label: locale[t], value: t }); });
    // props.breaks 变化需要更新内部状态
    React.useEffect(function () {
        var _a;
        var list = ((_a = stateRef === null || stateRef === void 0 ? void 0 : stateRef.current) === null || _a === void 0 ? void 0 : _a.breaks) || [];
        var arr = Array.from(new Set(__spreadArray(__spreadArray([], __read(breaks), false), __read(list), false)));
        if (arr.length !== breaks.length || arr.length !== list.length) {
            setList(breaks);
            stateRef.current.breaks = breaks;
        }
    }, [breaks]);
    var handleConfirm = useCallback(function () {
        if (onOk) {
            onOk(stateRef.current);
        }
    }, [onOk]);
    var handleClose = useCallback(function () {
        if (onClose) {
            onClose();
        }
        setList(breaks);
        setActiveType(type || GroupbyType.default);
        setActiveBreakLen(breakLen);
    }, [breaks, onClose, type, breakLen]);
    var setListByBreaks = useCallback(function (bks, activeType) {
        if (activeType === GroupbyType.average) {
            var _a = calculateAverageBreaks(minValue, maxValue, bks), values = _a.values, min_1 = _a.min, max_1 = _a.max;
            setList(values);
            setMinValue(min_1);
            setMaxValue(max_1);
        }
        else if (activeType === GroupbyType.equidistant) {
            var values = calculateNBC(maxValue, data, bks);
            setList(values);
        }
    }, [maxValue, minValue, data]);
    var changeBreakLen = useCallback(function (item) {
        setActiveBreakLen(item);
        setListByBreaks(item, activeType);
    }, [setListByBreaks, activeType]);
    var changePropsList = useCallback(function (list) {
        if (size$1(list) > 1) {
            setMinValue(list[0]);
            setMaxValue(list[list.length - 1]);
        }
        setList(list);
        setActiveType(GroupbyType.custom);
    }, []);
    var changeType = useCallback(function (item) {
        setList([]);
        setActiveType(item);
        setListByBreaks(activeBreakLen, item);
    }, [activeBreakLen, setListByBreaks]);
    useEffect$1(function () {
        handleBreaksChange === null || handleBreaksChange === void 0 ? void 0 : handleBreaksChange(list);
    }, [handleBreaksChange, list]);
    var overlay = (React.createElement("div", { ref: ref, className: "".concat(prefixCls) },
        React.createElement("div", { className: "".concat(prefixCls, "-top") },
            React.createElement(Select, { type: "menu-bg", onChange: changeType, value: activeType, options: typeOptions, getPopupContainer: getPopupContainer, className: "".concat(prefixCls, "-type-select") }),
            (activeType === GroupbyType.average || activeType === GroupbyType.equidistant) && (React.createElement(Select, { type: "menu-bg", createAble: true, showSearch: true, options: segOptions, value: activeBreakLen, onChange: changeBreakLen, getPopupContainer: getPopupContainer, className: "".concat(prefixCls, "-breaklen-select") }))),
        React.createElement("div", { className: "".concat(prefixCls, "-main") },
            React.createElement(NumberListEdit, { height: 200, list: list, changePropsList: changePropsList, noContent: locale.noContent, disabled: activeType === GroupbyType.default }),
            React.createElement(DataSegment, { values: list, data: data, min: minValue, max: maxValue, onChange: changePropsList })),
        extra));
    return (React.createElement(CreateFilter, { clickAway: clickAway, overlay: overlay, onClose: handleClose, onOk: handleConfirm, loading: loading, okButtonLabel: okButtonLabel, cancelButtonLabel: cancelButtonLabel, footerClassName: "".concat(prefixCls, "-footer"), className: classNames(prefixCls, className), placement: placement, footerPrefixEl: footerPrefixEl, getPopupContainer: getContainer }, children));
};
DataGroupby.defaultProps = {
    segLabel: '段',
    breakLen: 5,
};
DataGroupby.whyDidYouRender = true;
DataGroupby.displayName = 'DataGroupby';

export { DataGroupby as D, MapTypeSetting as M };
