/**
 * amis-ui v6.14.0-beta.1
 * Copyright 2018-2025 fex
 */

'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var tslib = require('tslib');
var React = require('react');
var amisCore = require('amis-core');
var GroupedSelection = require('../GroupedSelection.js');
var Tabs = require('../Tabs.js');
var TreeSelection = require('../TreeSelection.js');
var SearchBox = require('../SearchBox.js');
var icons = require('../icons.js');
var Badge = require('../Badge.js');
var PopOverContainer = require('../PopOverContainer.js');
var matchSorter = require('match-sorter');
var TooltipWrapper = require('../TooltipWrapper.js');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var React__default = /*#__PURE__*/_interopDefaultLegacy(React);

var __react_jsx__ = require('react');
var _J$X_ = (__react_jsx__["default"] || __react_jsx__).createElement;
(__react_jsx__["default"] || __react_jsx__).Fragment;
// 数组成员读取
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["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 = tslib.__read(React__default["default"].useState([]), 2), variables = _b[0], setVariables = _b[1];
    var _c = tslib.__read(React__default["default"].useState([]), 2), filterVars = _c[0], setFilterVars = _c[1];
    var classPrefix = "".concat(themePrefix, "FormulaEditor-VariableList");
    React__default["default"].useEffect(function () {
        // 追加path，用于分级高亮
        var list = amisCore.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 tslib.__assign(tslib.__assign(tslib.__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 (_J$X_("div", { key: states.index },
                _J$X_("div", { className: cx("".concat(classPrefix, "-item"), itemClassName) },
                    option.label &&
                        selfVariableName &&
                        option.value === selfVariableName && (_J$X_(Badge.Badge, { classnames: cx, badge: {
                            mode: 'text',
                            text: 'self',
                            offset: [15, 2]
                        } },
                        _J$X_("label", null, option.label))),
                    option.memberDepth === undefined &&
                        option.label &&
                        (!selfVariableName || option.value !== selfVariableName) && (_J$X_(TooltipWrapper["default"], { tooltip: (_a = option.description) !== null && _a !== void 0 ? _a : option.label, tooltipTheme: "dark" },
                        _J$X_("label", null, option.label))),
                    option.memberDepth !== undefined &&
                        option.label &&
                        (!selfVariableName || option.value !== selfVariableName) ? (option.memberDepth < 2 ? (_J$X_(PopOverContainer.PopOverContainer, { popOverContainer: popOverContainer ||
                            (function () {
                                return document.querySelector(".".concat(cx('FormulaPicker-Modal')));
                            }), popOverRender: function (_a) {
                            var onClose = _a.onClose;
                            return (_J$X_("ul", { className: cx("".concat(classPrefix, "-item-oper")) }, memberOpers
                                .filter(function (item) { return !simplifyMemberOprs || item.simple; })
                                .map(function (item, i) {
                                return (_J$X_(TooltipWrapper["default"], { key: i, tooltip: item.description, tooltipTheme: "dark" },
                                    _J$X_("li", { key: i, onClick: function () {
                                            return handleMemberClick(tslib.__assign(tslib.__assign({}, item), { isMember: true }), option, onClose);
                                        } },
                                        _J$X_("span", null, item.label))));
                            })));
                        } }, function (_a) {
                        var _b;
                        var onClick = _a.onClick; _a.ref; _a.isOpened;
                        return (_J$X_(TooltipWrapper["default"], { tooltip: (_b = option.description) !== null && _b !== void 0 ? _b : option.label, tooltipTheme: "dark" },
                            _J$X_(React__default["default"].Fragment, null,
                                _J$X_("label", { onClick: onClick }, option.label),
                                _J$X_(icons.Icon, { onClick: onClick, icon: "ellipsis-v", className: "icon" }))));
                    })) : (_J$X_("label", null, option.label))) : null,
                    (option === null || option === void 0 ? void 0 : option.tag) ? (_J$X_("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(tslib.__assign(tslib.__assign({}, item), { label: value, value: value }));
    }
    function onSearch(term) {
        term = term.trim();
        var tree = amisCore.filterTree(variables, function (i, key, level, paths) {
            return !!((Array.isArray(i.children) && i.children.length) ||
                !!matchSorter.matchSorter([i].concat(paths), term, {
                    keys: ['label', 'value'],
                    threshold: matchSorter.matchSorter.rankings.CONTAINS
                }).length);
        }, 1, true);
        setFilterVars(!term ? variables : tree);
    }
    function renderSearchBox() {
        return (_J$X_("div", { className: cx('FormulaEditor-VariableList-searchBox') },
            _J$X_(SearchBox["default"], { mini: false, onSearch: onSearch, mobileUI: props.mobileUI })));
    }
    function handleChange(item) {
        // 允许所有有 value 的元素被点击插入
        // 注释掉原来的阻止逻辑，允许 isMember 元素直接点击
        // if (item.isMember || item.memberDepth !== undefined) {
        //   return;
        // }
        onSelect === null || onSelect === void 0 ? void 0 : onSelect(item);
    }
    return (_J$X_("div", { className: cx(className, 'FormulaEditor-VariableList', selectMode && "FormulaEditor-VariableList-".concat(selectMode)), ref: variableListRef }, selectMode === 'tabs' ? (_J$X_(Tabs["default"], { tabsMode: tabsMode, className: cx("".concat(classPrefix, "-base ").concat(classPrefix, "-tabs")) }, filterVars.map(function (item, index) { return (_J$X_(Tabs.Tab, { className: cx("".concat(classPrefix, "-tab")), eventKey: index, key: index, title: item.label },
        _J$X_(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' ? (_J$X_("div", { className: cx('FormulaEditor-VariableList-body') },
        renderSearchBox(),
        _J$X_(TreeSelection["default"], { 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); } }))) : (_J$X_("div", { className: cx('FormulaEditor-VariableList-body') },
        renderSearchBox(),
        _J$X_(GroupedSelection["default"], { itemRender: itemRender, placeholderRender: placeholderRender, className: cx("".concat(classPrefix, "-base"), 'is-scrollable'), multiple: false, options: filterVars, onChange: function (item) { return handleChange(item); } })))));
}
var VariableList$1 = amisCore.themeable(VariableList);

exports["default"] = VariableList$1;
