/**
 * amis-ui v6.12.0-beta.0
 * Copyright 2018-2025 fex
 */

import { __read, __assign } from 'tslib';
import React__default from 'react';
import { themeable, mapTree, filterTree } from 'amis-core';
import GroupedSelection from '../GroupedSelection.js';
import ThemedTabs, { Tab } from '../Tabs.js';
import TreeSelection from '../TreeSelection.js';
import SearchBox from '../SearchBox.js';
import { Icon } from '../icons.js';
import { Badge } from '../Badge.js';
import { PopOverContainer } from '../PopOverContainer.js';
import { matchSorter } from 'match-sorter';
import TooltipWrapper from '../TooltipWrapper.js';

// 数组成员读取
var memberOpers = [
    {
        label: '取列值',
        value: 'ARRAYMAP(${arr}, item => item.${member})',
        description: '取当前列的所有值（数组）'
    },
    {
        label: '取条件值',
        value: 'ARRAYFILTER(ARRAYMAP(${arr}, item => item.${member}), item => item === 条件)',
        description: '取当前列中符合配置条件的值（数组）'
    },
    {
        label: '取表值',
        value: 'ARRAYFILTER(${arr}, item => item.${member} === 条件)',
        description: '取列表中符合配置条件的值（数组）'
    },
    {
        label: '计数',
        value: 'COUNT(ARRAYFILTER(${arr}, item => item.${member} === 条件))',
        description: '统计表中符合配置条件的值的总数'
    },
    {
        label: '去重计数',
        value: 'COUNT(UNIQ(${arr}, item.${member}))',
        description: '对表中当前值进行去重，并统计去重后的值的数量',
        simple: true
    },
    {
        label: '求和',
        value: 'SUM(ARRAYMAP(${arr}, item => item.${member}))',
        description: '求当前列的所有值之和',
        simple: true
    },
    {
        label: '平均值',
        value: 'AVG(ARRAYMAP(${arr}, item => item.${member}))',
        description: '求当前列的平均值',
        simple: true
    },
    {
        label: '最大值',
        value: 'MAX(ARRAYMAP(${arr}, item => item.${member}))',
        description: '取当前列的最大值',
        simple: true
    },
    {
        label: '最小值',
        value: 'MIN(ARRAYMAP(${arr}, item => item.${member}))',
        description: '取当前列的最小值',
        simple: true
    }
];
function VariableList(props) {
    var variableListRef = React__default.useRef(null);
    var className = props.className, cx = props.classnames, _a = props.tabsMode, tabsMode = _a === void 0 ? 'line' : _a, themePrefix = props.classPrefix, itemClassName = props.itemClassName, selectMode = props.selectMode, onSelect = props.onSelect, placeholderRender = props.placeholderRender, selfVariableName = props.selfVariableName, expandTree = props.expandTree, simplifyMemberOprs = props.simplifyMemberOprs, popOverContainer = props.popOverContainer;
    var _b = __read(React__default.useState([]), 2), variables = _b[0], setVariables = _b[1];
    var _c = __read(React__default.useState([]), 2), filterVars = _c[0], setFilterVars = _c[1];
    var classPrefix = "".concat(themePrefix, "FormulaEditor-VariableList");
    React__default.useEffect(function () {
        // 追加path，用于分级高亮
        var list = mapTree(props.data, function (item, key, level, paths) {
            var _a;
            var path = paths === null || paths === void 0 ? void 0 : paths.reduce(function (prev, item) {
                var _a;
                return !item.value
                    ? prev
                    : "".concat(prev).concat(prev ? '.' : '').concat((_a = item.label) !== null && _a !== void 0 ? _a : item.value);
            }, '');
            return __assign(__assign(__assign({}, item), { path: "".concat(path).concat(path ? '.' : '').concat(item.label) }), (item.isMember || paths.some(function (item) { return item.isMember; })
                ? {
                    memberDepth: (_a = paths === null || paths === void 0 ? void 0 : paths.filter(function (item) { return item.type === 'array'; })) === null || _a === void 0 ? void 0 : _a.length
                }
                : {}));
        });
        setVariables(list);
        setFilterVars(list);
    }, [props.data]);
    var itemRender = props.itemRender && typeof props.itemRender === 'function'
        ? props.itemRender
        : function (option, states) {
            var _a;
            return (React__default.createElement("div", { key: states.index },
                React__default.createElement("div", { className: cx("".concat(classPrefix, "-item"), itemClassName) },
                    option.label &&
                        selfVariableName &&
                        option.value === selfVariableName && (React__default.createElement(Badge, { classnames: cx, badge: {
                            mode: 'text',
                            text: 'self',
                            offset: [15, 2]
                        } },
                        React__default.createElement("label", null, option.label))),
                    option.memberDepth === undefined &&
                        option.label &&
                        (!selfVariableName || option.value !== selfVariableName) && (React__default.createElement(TooltipWrapper, { tooltip: (_a = option.description) !== null && _a !== void 0 ? _a : option.label, tooltipTheme: "dark" },
                        React__default.createElement("label", null, option.label))),
                    option.memberDepth !== undefined &&
                        option.label &&
                        (!selfVariableName || option.value !== selfVariableName) ? (option.memberDepth < 2 ? (React__default.createElement(PopOverContainer, { popOverContainer: popOverContainer ||
                            (function () {
                                return document.querySelector(".".concat(cx('FormulaPicker-Modal')));
                            }), popOverRender: function (_a) {
                            var onClose = _a.onClose;
                            return (React__default.createElement("ul", { className: cx("".concat(classPrefix, "-item-oper")) }, memberOpers
                                .filter(function (item) { return !simplifyMemberOprs || item.simple; })
                                .map(function (item, i) {
                                return (React__default.createElement(TooltipWrapper, { key: i, tooltip: item.description, tooltipTheme: "dark" },
                                    React__default.createElement("li", { key: i, onClick: function () {
                                            return handleMemberClick(__assign(__assign({}, item), { isMember: true }), option, onClose);
                                        } },
                                        React__default.createElement("span", null, item.label))));
                            })));
                        } }, function (_a) {
                        var _b;
                        var onClick = _a.onClick; _a.ref; _a.isOpened;
                        return (React__default.createElement(TooltipWrapper, { tooltip: (_b = option.description) !== null && _b !== void 0 ? _b : option.label, tooltipTheme: "dark" },
                            React__default.createElement(React__default.Fragment, null,
                                React__default.createElement("label", { onClick: onClick }, option.label),
                                React__default.createElement(Icon, { onClick: onClick, icon: "ellipsis-v", className: "icon" }))));
                    })) : (React__default.createElement("label", null, option.label))) : null,
                    (option === null || option === void 0 ? void 0 : option.tag) ? (React__default.createElement("span", { className: cx("".concat(classPrefix, "-item-tag")) }, option.tag)) : null)));
        };
    function handleMemberClick(item, option, onClose) {
        // todo：暂时只提供一层的快捷操作
        var lastPointIdx = option.value.lastIndexOf('.');
        // const firstPointIdx = option.value.indexOf('.');
        var arr = option.value.substring(0, lastPointIdx);
        var member = option.value.substring(lastPointIdx + 1);
        var value = item.value
            .replace('${arr}', arr)
            .replace('${member}', member);
        onClose === null || onClose === void 0 ? void 0 : onClose();
        onSelect === null || onSelect === void 0 ? void 0 : onSelect(__assign(__assign({}, item), { label: value, value: value }));
    }
    function onSearch(term) {
        var tree = filterTree(variables, function (i, key, level, paths) {
            return !!((Array.isArray(i.children) && i.children.length) ||
                !!matchSorter([i].concat(paths), term, {
                    keys: ['label', 'value'],
                    threshold: matchSorter.rankings.CONTAINS
                }).length);
        }, 1, true);
        setFilterVars(!term ? variables : tree);
    }
    function renderSearchBox() {
        return (React__default.createElement("div", { className: cx('FormulaEditor-VariableList-searchBox') },
            React__default.createElement(SearchBox, { mini: false, onSearch: onSearch, mobileUI: props.mobileUI })));
    }
    function handleChange(item) {
        if (item.isMember || item.memberDepth !== undefined) {
            return;
        }
        onSelect === null || onSelect === void 0 ? void 0 : onSelect(item);
    }
    return (React__default.createElement("div", { className: cx(className, 'FormulaEditor-VariableList', selectMode && "FormulaEditor-VariableList-".concat(selectMode)), ref: variableListRef }, selectMode === 'tabs' ? (React__default.createElement(ThemedTabs, { tabsMode: tabsMode, className: cx("".concat(classPrefix, "-base ").concat(classPrefix, "-tabs")) }, filterVars.map(function (item, index) { return (React__default.createElement(Tab, { className: cx("".concat(classPrefix, "-tab")), eventKey: index, key: index, title: item.label },
        React__default.createElement(VariableList, { classnames: cx, classPrefix: "".concat(classPrefix, "-sub-"), className: cx("".concat(classPrefix, "-sub")), itemRender: itemRender, placeholderRender: placeholderRender, selectMode: item.selectMode, data: item.children, onSelect: handleChange, selfVariableName: selfVariableName }))); }))) : selectMode === 'tree' ? (React__default.createElement("div", { className: cx('FormulaEditor-VariableList-body') },
        renderSearchBox(),
        React__default.createElement(TreeSelection, { itemRender: itemRender, placeholderRender: placeholderRender, className: cx("".concat(classPrefix, "-base"), 'is-scrollable'), multiple: false, expand: expandTree ? 'all' : 'none', options: filterVars, onChange: function (item) { return handleChange(item); } }))) : (React__default.createElement("div", { className: cx('FormulaEditor-VariableList-body') },
        renderSearchBox(),
        React__default.createElement(GroupedSelection, { itemRender: itemRender, placeholderRender: placeholderRender, className: cx("".concat(classPrefix, "-base"), 'is-scrollable'), multiple: false, options: filterVars, onChange: function (item) { return handleChange(item); } })))));
}
var VariableList$1 = themeable(VariableList);

export { VariableList$1 as default };
