import { br as isSymbol_1, A as getDefaultExportFromCjs, bs as identity_1, ah as LazyLoad, q as appContext, bt as getColumnStat, bu as MapUIStyleTypeSet, p as i18n, T as THEME_COLOR, bv as CreateFilter, b4 as RadioGroup, ak as LinkButton, b3 as splitColors, a as __awaiter, b5 as getCustomColorSchemeRef, b6 as setCustomColorSchemePref, t as toastApi, bw as _baseTimes, bx as toInteger_1, by as _castFunction, a1 as Input, s as IconButton, O as map$1, Y as getTheme, Z as ThemeEnum, be as Slider, bz as size$1, aw as Select } from './MapEditView-f6381866.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-2a18409b.js';
import { useMount, useDebounceFn, useCreation } from 'ahooks';
import { map, size, forEach, set, slice, find, get } from 'lodash';
import { T as Transfer } from './Transfer-b219601e.js';
import { observer, useLocalStore } from 'mobx-react';
import { useKey, useMeasure } from 'react-use';
import { u as useDataValue } from './useDataValue-6bd3790f.js';
import { ckmeans } from 'simple-statistics';
import { init } from 'echarts';

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);

const JsonCodeEditor$1 = LazyLoad(() => import('./index-5d31e445.js'));
const defOkProps = {
    doSaveColor: true,
    restoreReserveColorStatus: true,
};
const prefixCls$2 = 'dm-map-type-setting';
const MapTypeSetting = observer((props) => {
    const { routeStore: { mapInstanceCanvas, getPopupContainer, MapSettingStore: { interfaceStyle }, }, } = React.useContext(appContext.getContext());
    const { children, className, visual, col, packageInfo, breaks, changeTypeVisual } = props;
    const unmounted = useRef$2(false);
    const store = useLocalStore(() => {
        return {
            col,
            tempColors: undefined,
            loading: false,
            list: [],
            icons: visual === null || visual === void 0 ? void 0 : visual.icons,
            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 初始化对应关系
        };
    });
    const { tempColors, list, icons, values, loading, saveColor, colors, sourceColors, curSelectColors, reserveColorStatus, sourceStops, codeMode, } = store;
    const _onOk = ({ doSaveColor, restoreReserveColorStatus, highPriorityColors, } = defOkProps) => {
        if (restoreReserveColorStatus && reserveColorStatus) {
            store.reserveColorStatus = false;
        }
        // 当前渐变色
        const curColors = highPriorityColors
            ? highPriorityColors
            : sourceStops.length
                ? [...sourceStops].sort((a, b) => a.offset - b.offset).map((i) => i.color)
                : sourceColors;
        _changeColors(curColors);
        const valueLen = size(values);
        const _colors = valueLen > size(curColors)
            ? splitColors(curColors, valueLen)
            : slice(curColors, 0, valueLen);
        const _icons = map(values, (value) => {
            const item = find(store.originList, { value });
            return (item === null || item === void 0 ? void 0 : item.icon) || 'marker';
        });
        changeTypeVisual && changeTypeVisual({ colors: _colors, breaks: values, icons: _icons });
        if (doSaveColor && saveColor) {
            (() => __awaiter(void 0, void 0, void 0, function* () {
                const _customColorScheme = yield getCustomColorSchemeRef();
                if (curColors.length) {
                    setCustomColorSchemePref([..._customColorScheme, curColors]);
                }
            }))();
        }
    };
    // 预览样式
    const handlePreviewStyle = () => {
        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,
        });
    };
    // 恢复样式和状态
    const handleResetStatusAndColor = () => {
        handleResetState();
        if (tempColors) {
            store.colors = tempColors || [];
            _onOk({
                doSaveColor: true,
                restoreReserveColorStatus: true,
                highPriorityColors: tempColors,
            });
            store.tempColors = undefined;
        }
    };
    const handleResetState = useCallback$2(() => {
        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'] = map(breaks || [], (t) => t + '');
        store['icons'] = visual === null || visual === void 0 ? void 0 : visual.icons;
        store['saveColor'] = false;
    }, [breaks, store, visual]);
    const _changeColors = (colors) => {
        const valueLen = size(values);
        const _colors = valueLen > size(colors)
            ? splitColors(colors, valueLen)
            : slice(colors, 0, valueLen);
        store.colors = _colors;
    };
    const _changeSaveColor = (checked) => {
        store.saveColor = checked;
    };
    const _changeGradientStop = (newStop) => {
        const _sourceColors = newStop.map((i) => i.color);
        store.sourceStops = newStop;
        store.sourceColors = _sourceColors;
    };
    const getStatistics = useCallback$2((col) => {
        store['loading'] = true;
        unmounted.current = false;
        const columnName = col || props.col + '';
        if (size(store.list) > 0 && store.col === columnName) {
            store.loading = false;
            return;
        }
        const { packageUuid, source, geometryType } = packageInfo || {};
        if (!columnName) {
            return;
        }
        const body = {
            [`geometry_type`]: geometryType,
            [`column_name`]: columnName,
            [`column_type`]: 'str',
            filters: [],
        };
        getColumnStat({
            packageUuid,
            source,
            dbType: 'str',
            column: columnName,
            body,
        }).then((resp) => {
            if (!unmounted.current) {
                store.loading = false;
                store.col = columnName;
                store.list = map(resp.values, (i) => {
                    return { title: i + '', key: i + '' };
                });
            }
        });
    }, [packageInfo, props.col, store]);
    useMount(() => {
        getStatistics(col);
        const list = [];
        forEach(breaks, (value, index) => {
            console.log(123);
            list.push({
                value: value + '',
                icon: icons === null || icons === void 0 ? void 0 : icons[index],
            });
        });
        store.originList = list;
    });
    useEffect$1(() => {
        getStatistics(col);
    }, [col, getStatistics]);
    useEffect$1(() => {
        return () => {
            unmounted.current = true;
        };
    }, []);
    const _onChange = (selected) => {
        store.values = selected;
    };
    const _changeQuotes = (_values) => {
        // todo 改变icons
        const _icons = [];
        const _colors = [];
        _values.forEach((a) => {
            const i = breaks === null || breaks === void 0 ? void 0 : breaks.indexOf(a);
            if (i !== undefined && i !== -1) {
                const _color = get(curSelectColors, [i]);
                const _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 = map(_values, (t) => t + '');
    };
    useEffect$1(() => {
        if (visual) {
            handleResetState();
        }
    }, [handleResetState, visual]);
    useEffect$1(() => {
        store['sourceColors'] = colors || [];
    }, [colors, store]);
    // const codeJson = {};
    // forEach(values, (v, i) => {
    //   set(codeJson, v, colors[i]);
    // });
    const codeJsonStr = React.useMemo(() => {
        const codeJson = {};
        forEach(values, (v, i) => {
            set(codeJson, v, colors[i] || '-');
        });
        return JSON.stringify(codeJson, null, '\t');
    }, [colors, values]);
    const { run } = useDebounceFn((value) => {
        console.log(value, 'value');
        try {
            const _values = [];
            const _colors = [];
            const obj = JSON.parse(value);
            forEach(obj, (v, k) => {
                _values.push(k);
                _colors.push(v);
            });
            store.values = map(_values, (t) => t + '');
            store.colors = _colors;
        }
        catch (_a) {
            console.log('error');
        }
    }, { wait: 300 });
    const codeOverLay = React.useMemo(() => {
        return (React.createElement(JsonCodeEditor$1, { height: `300px`, width: `400px`, onChange: run, theme: interfaceStyle === MapUIStyleTypeSet.dark ? undefined : 'chaos', 
            // onValidate={onValidate}
            value: codeJsonStr, className: "mb20" }));
    }, [codeJsonStr, interfaceStyle, run]);
    console.log('list..', list, values);
    const overlay = (React.createElement("div", { className: `${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: (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: `${prefixCls$2}-footer`, className: classNames(prefixCls$2, className), placement: "rightTop", getPopupContainer: getPopupContainer, footerPrefixEl: () => (React.createElement("div", { style: { display: 'flex', alignItems: 'center' } },
            React.createElement(RadioGroup, { radioType: 'button', onChange: () => (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.displayName = 'MapTypeSetting';
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);

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

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

const DataSegment = ({ min, max, data = [], values = [], onChange, }) => {
    const [ref, { width, height }] = useMeasure();
    const step = max - min <= 1 ? 0.1 : 1;
    return (React.createElement("div", { className: `${prefixCls}-chart-wrap` },
        React.createElement("div", { ref: ref, className: `${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: `${prefixCls}-slider`, getTooltipPopupContainer: (node) => node === null || node === void 0 ? void 0 : node.closest('.dm-page-framewrap') })),
        React.createElement("div", { className: `${prefixCls}-min-max` },
            React.createElement("span", null, min),
            React.createElement("span", null, max))));
};
DataSegment.whyDidYouRender = true;
DataSegment.displayName = 'DataSegment';

// export const calculateAverageBreaks = function (min: number, max: number, breakLen: number) {
//   // min = Math.floor(min);
//   // max = Math.ceil(max);
//   max = Math.abs(max) < 1 ? Number(Number(max).toExponential(2)) : Math.ceil(max) * 1;
//   let vals = [max];
//   const radio = (max - min) / breakLen;
//   for (let i = breakLen - 1; i > 0; i--) {
//     let 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(val)) {
//       vals.push(val);
//     }
//   }
//   if (isNaN(max) || max === -Infinity) {
//     vals[0] = Infinity;
//   }
//   if (!isNaN(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, max };
// };
const calculateAverageBreaks = (min, max, segmentCount) => {
    // 首先检查分段数量是否合法
    if (segmentCount < 1) {
        throw new Error('Segment count must be at least 1.');
    }
    // 计算每一段的宽度，注意使用Math.abs确保步长为正
    const step = Math.abs((max - min) / segmentCount);
    // 初始化结果数组，并添加第一个值（最小值）
    const segments = [min];
    // 生成剩余的分段值
    for (let i = 1; i < segmentCount; i++) {
        // 计算当前段的值，通过累加步长到前一段的值
        const currentValue = segments[i - 1] + step;
        // 确保最后一段直接为最大值，以处理浮点数运算的不精确性
        if (i === segmentCount - 1) {
            segments.push(max);
        }
        else {
            segments.push(Number(currentValue.toFixed(2)));
        }
    }
    return { values: segments, min, max };
};
const calculateNBC = (max, data, breakLen) => {
    if (breakLen > size$1(data) || !data || !breakLen) {
        return [];
    }
    const breaks = ckmeans(data, breakLen).map((cluster) => {
        return cluster[0];
    });
    // 自然分段中,最后一个数据集可能出现全为最大值情况,这种情况下,直接返回breaks
    if (breaks[breaks.length - 1] === max) {
        return breaks;
    }
    breaks.push(max);
    return breaks;
};

const JsonCodeEditor = LazyLoad(() => import('./index-5d31e445.js'));
var GroupByType;
(function (GroupByType) {
    GroupByType["default"] = "default";
    GroupByType["average"] = "average";
    GroupByType["equidistant"] = "equidistant";
    GroupByType["custom"] = "custom";
})(GroupByType || (GroupByType = {}));
const prefixCls = 'dmc-data-groupby';
const defaultLocale = {
    [GroupByType.default]: '不聚合',
    [GroupByType.average]: '平均分段',
    [GroupByType.equidistant]: '自然断点',
    [GroupByType.custom]: '自定义',
    noContent: '无',
};
const { useState, useCallback, useRef } = React;
const emptyArray = [];
const DataGroupBy = ({ onOk, onClose, loading, children, className, breakLen, data = emptyArray, min: minV, max: maxV, breaks = emptyArray, colors, type = breaks.length ? GroupByType.custom : undefined, extra, segLabel, okButtonLabel, cancelButtonLabel, locale = defaultLocale, placement, clickAway = false, handleBreaksChange, handleColorsChange, footerPrefixEl, getContainer, codeMode, interfaceStyle, }) => {
    const ref = React.useRef(null);
    const getPopupContainer = React.useCallback(() => ref.current, []);
    // const minValue = minV === undefined ? min(data) || 0 : minV;
    // const maxValue = maxV === undefined ? max(data) || 1 : maxV;
    const [minValue, setMinValue] = useState(0);
    const [maxValue, setMaxValue] = useState(1);
    React.useEffect(() => {
        setMinValue(minV === undefined ? min$1(data) || 0 : minV);
    }, [minV, data]);
    React.useEffect(() => {
        setMaxValue(maxV === undefined ? max$1(data) || 1 : maxV);
    }, [maxV, data]);
    const [list, setList] = useState(breaks);
    const [activeType, setActiveType] = useState(type || GroupByType.default);
    const [activeBreakLen, setActiveBreakLen] = useState(breakLen);
    const stateRef = useRef({});
    stateRef.current = { breaks: list, type: activeType, breakLen: activeBreakLen };
    const segOptions = times$1(7, (i) => ({ value: `${i + 1}`, label: `${i + 1}${segLabel}` }));
    const typeOptions = [
        GroupByType.default,
        GroupByType.average,
        GroupByType.equidistant,
        GroupByType.custom,
    ].map((t) => ({ label: locale[t], value: t }));
    // props.breaks 变化需要更新内部状态
    React.useEffect(() => {
        var _a;
        const list = ((_a = stateRef === null || stateRef === void 0 ? void 0 : stateRef.current) === null || _a === void 0 ? void 0 : _a.breaks) || [];
        const arr = Array.from(new Set([...breaks, ...list]));
        if (arr.length !== breaks.length || arr.length !== list.length) {
            setList(breaks);
            stateRef.current.breaks = breaks;
        }
    }, [breaks]);
    const handleConfirm = useCallback(() => {
        if (onOk) {
            onOk(stateRef.current);
        }
    }, [onOk]);
    const handleClose = useCallback(() => {
        if (onClose) {
            onClose();
        }
        setList(breaks);
        setActiveType(type || GroupByType.default);
        setActiveBreakLen(breakLen);
    }, [breaks, onClose, type, breakLen]);
    const setListByBreaks = useCallback((bks, activeType) => {
        if (activeType === GroupByType.average) {
            const { values, min, max } = calculateAverageBreaks(minValue, maxValue, bks);
            setList(values);
            setMinValue(min);
            setMaxValue(max);
        }
        else if (activeType === GroupByType.equidistant) {
            const values = calculateNBC(maxValue, data, bks);
            setList(values);
        }
    }, [maxValue, minValue, data]);
    const changeBreakLen = useCallback((item) => {
        setActiveBreakLen(item);
        setListByBreaks(item, activeType);
    }, [setListByBreaks, activeType]);
    const changePropsList = useCallback((list) => {
        if (size$1(list) > 1) {
            setMinValue(list[0]);
            setMaxValue(list[list.length - 1]);
        }
        setList(list);
        setActiveType(GroupByType.custom);
    }, []);
    const changeType = useCallback((item) => {
        setList([]);
        setActiveType(item);
        setListByBreaks(activeBreakLen, item);
    }, [activeBreakLen, setListByBreaks]);
    useEffect$1(() => {
        handleBreaksChange === null || handleBreaksChange === void 0 ? void 0 : handleBreaksChange(list);
    }, [handleBreaksChange, list]);
    const codeJsonStr = useCreation(() => {
        if (!codeMode) {
            return '';
        }
        const codeJson = {
            breaks: breaks,
            colors: colors,
        };
        return JSON.stringify(codeJson, null, '\t');
    }, [breaks, colors, codeMode]);
    const { run } = useDebounceFn((value) => {
        console.log(value);
        try {
            const obj = JSON.parse(value);
            const { breaks, colors } = obj;
            if (breaks && colors) {
                handleBreaksChange(breaks);
                handleColorsChange(colors);
            }
        }
        catch (e) {
            console.log(e);
        }
    }, {
        wait: 300,
    });
    const codeOverLay = useCreation(() => {
        if (!codeMode) {
            return null;
        }
        return (React.createElement(JsonCodeEditor, { height: `300px`, width: `400px`, onChange: run, theme: interfaceStyle === MapUIStyleTypeSet.dark ? undefined : 'chaos', value: codeJsonStr, className: "mb20" }));
    }, [codeJsonStr, interfaceStyle, run, codeMode]);
    const overlay = codeMode ? (codeOverLay) : (React.createElement("div", { ref: ref, className: `${prefixCls}` },
        React.createElement("div", { className: `${prefixCls}-top` },
            React.createElement(Select, { type: "menu-bg", onChange: changeType, value: activeType, options: typeOptions, getPopupContainer: getPopupContainer, className: `${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: `${prefixCls}-breaklen-select` }))),
        React.createElement("div", { className: `${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: `${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 };
