"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.GroupButton = GroupButton;
const i18n_1 = __importDefault(require("../../../../../../locales/i18n.js"));
const react_1 = __importStar(require("react"));
const classnames_1 = __importDefault(require("classnames"));
const isEmpty_1 = __importDefault(require("lodash/isEmpty"));
const cn_ui_1 = require("@cainiaofe/cn-ui");
const mobx_react_simpler_1 = require("../../../../../../utils/mobx-react-simpler/index.js");
const env_1 = require("../../../../../../utils/env/index.js");
const table_column_feature_utils_1 = require("../../../../../../cn-ai-table/view/utils/table-column-feature-utils");
const constants_1 = require("./constants");
const condition_panel_1 = require("../condition-panel");
const trigger_with_tooltip_1 = require("../condition-panel/trigger-with-tooltip");
const use_ai_table_icons_1 = require("../../../../../../cn-ai-table/view/hooks/use-ai-table-icons");
const field_icon_utils_1 = require("../../../../../../cn-ai-table/view/utils/field-icon-utils");
const arms_hot_tag_log_1 = require("../../../../../../utils/arms/arms-hot-tag-log.js");
/**
 * 分组按钮组件
 */
function GroupButton(props) {
    const { viewId, onGroupChange, onAddCondition, onConditionCleared, keepVisible = false, maxGroupLevels = 1, isCompact = false, } = props;
    // ============================= Hooks =============================
    const icons = (0, use_ai_table_icons_1.useAiTableIcons)();
    const getIcon = (0, field_icon_utils_1.useFieldIcon)();
    // ============================= Model =============================
    const dataModel = (0, mobx_react_simpler_1.useModel)('dataModel');
    const viewConfig = dataModel.getViewConfig(viewId);
    // ============================= Field Options =============================
    /**
     * 获取所有过滤后的字段ID列表
     * 所有视图类型都只支持 GROUP_FIELD_TYPE 中定义的字段类型进行分组
     */
    const filteredFieldIds = react_1.default.useMemo(() => {
        var _a;
        return (_a = dataModel === null || dataModel === void 0 ? void 0 : dataModel.columnDefinitions) === null || _a === void 0 ? void 0 : _a.filter((col) => {
            const field = dataModel.fieldMap[col.dataIndex];
            if (!(0, table_column_feature_utils_1.canUseInToolbar)(field, col))
                return false;
            const effectiveField = (0, table_column_feature_utils_1.getToolbarFieldSchema)(field, col);
            const fieldType = effectiveField === null || effectiveField === void 0 ? void 0 : effectiveField['x-component'];
            return ((0, table_column_feature_utils_1.isAiFormulaOrLookupColumnDef)(col) ||
                !!constants_1.GROUP_FIELD_TYPE[fieldType]);
        }).map((col) => col.dataIndex);
    }, [dataModel.columnDefinitions, dataModel.fieldMap]);
    /**
     * 字段选项列表（用于下拉选择组件）
     * 将字段ID数组转换为下拉选择组件需要的选项格式
     */
    const fieldOptions = react_1.default.useMemo(() => {
        return filteredFieldIds === null || filteredFieldIds === void 0 ? void 0 : filteredFieldIds.map((dataIndex) => {
            var _a;
            const col = dataModel.columnDefinitions.find((c) => c.dataIndex === dataIndex);
            const fieldConfig = (_a = dataModel.fieldMap) === null || _a === void 0 ? void 0 : _a[dataIndex];
            const effectiveField = (0, table_column_feature_utils_1.getToolbarFieldSchema)(fieldConfig, col);
            return {
                label: (col === null || col === void 0 ? void 0 : col.title) || dataIndex,
                value: dataIndex,
                fieldType: effectiveField === null || effectiveField === void 0 ? void 0 : effectiveField['x-component'],
            };
        });
    }, [filteredFieldIds, dataModel.columnDefinitions, dataModel.fieldMap]);
    // 自定义渲染字段选项（带图标）
    const renderFieldOption = (item) => {
        if (!item.fieldType) {
            return (react_1.default.createElement("span", { title: item.label, className: "field-option-label" }, item.label));
        }
        return (react_1.default.createElement("div", { title: item.label, className: "field-option" },
            react_1.default.createElement("img", { src: getIcon(item.fieldType), alt: "" }),
            react_1.default.createElement("span", { className: "field-option-label" }, item.label)));
    };
    // ============================= Group State =============================
    /**
     * 分组条件列表
     * 每个条件包含字段
     */
    const [groupConditions, setGroupConditions] = (0, react_1.useState)(() => {
        const currentGroup = viewConfig.group || [];
        return currentGroup.length > 0
            ? currentGroup
                .map((g) => ({
                field: g.field || '',
            }))
                // 过滤掉字段为空的分组条件
                .filter((g) => g.field)
            : [];
    });
    /**
     * 分组规则数量
     */
    const groupCount = groupConditions.length;
    /**
     * 默认分组字段：表格第一个可分组字段
     */
    const defaultGroupField = react_1.default.useMemo(() => { var _a; return (_a = filteredFieldIds === null || filteredFieldIds === void 0 ? void 0 : filteredFieldIds[0]) !== null && _a !== void 0 ? _a : ''; }, [filteredFieldIds]);
    /**
     * 添加条件时使用的默认字段：第一个未被当前条件占用的可分组字段，否则用表格第一个字段
     */
    const getDefaultFieldForNewCondition = react_1.default.useCallback(() => {
        var _a;
        const used = groupConditions.map((c) => c.field).filter(Boolean);
        return (_a = filteredFieldIds === null || filteredFieldIds === void 0 ? void 0 : filteredFieldIds.find((id) => !used.includes(id))) !== null && _a !== void 0 ? _a : defaultGroupField;
    }, [filteredFieldIds, defaultGroupField, groupConditions]);
    /**
     * 获取指定索引的字段选项
     * 已被其他条件使用的字段会被禁用，避免重复选择
     */
    const getFieldOptionsForIndex = (index) => {
        // 获取其他条件已使用的字段（排除当前行）
        const usedFields = groupConditions
            .map((condition, idx) => (idx !== index ? condition.field : ''))
            .filter((field) => field);
        // 返回所有字段选项，但标记已被其他条件使用的字段为禁用
        return fieldOptions.map((option) => ({
            ...option,
            disabled: usedFields.includes(option.value),
        }));
    };
    // ============================= Sync Config =============================
    /**
     * 同步 viewConfig.group 的变化到内部状态
     * 当外部配置变化时，更新内部状态
     */
    react_1.default.useEffect(() => {
        const groupFromConfig = viewConfig.group || [];
        const newConditions = groupFromConfig.length > 0
            ? groupFromConfig
                .map((g) => ({
                field: g.field || '',
            }))
                .filter((g) => g.field)
            : [];
        setGroupConditions(newConditions);
    }, [viewConfig.group]);
    // ============================= Events =============================
    /**
     * 添加分组条件
     */
    const handleAddGroupCondition = () => {
        if (groupConditions.length >= maxGroupLevels) {
            return;
        }
        (0, arms_hot_tag_log_1.armsHottagLog)({
            hottag: 'cn-ai-table.group.addCondition',
            name: i18n_1.default.get({ id: 'AddCondition', dm: '添加条件' }),
        });
        const defaultField = getDefaultFieldForNewCondition();
        const newConditions = [...groupConditions, { field: defaultField }];
        setGroupConditions(newConditions);
        if (defaultField) {
            dataModel.setViewConfig(viewId, { group: newConditions });
            onGroupChange === null || onGroupChange === void 0 ? void 0 : onGroupChange(defaultField);
        }
        onAddCondition === null || onAddCondition === void 0 ? void 0 : onAddCondition();
    };
    /**
     * 删除分组条件
     */
    const handleRemoveGroupCondition = (index) => {
        (0, arms_hot_tag_log_1.armsHottagLog)({
            hottag: 'cn-ai-table.group.removeCondition',
            name: i18n_1.default.get({ id: 'DeleteCondition', dm: '删除条件' }),
            c7: index,
        });
        const newConditions = groupConditions.filter((_, i) => i !== index);
        setGroupConditions(newConditions);
        onAddCondition === null || onAddCondition === void 0 ? void 0 : onAddCondition();
        // 更新视图配置
        if (newConditions.length > 0) {
            dataModel.setViewConfig(viewId, {
                group: newConditions,
            });
            onGroupChange === null || onGroupChange === void 0 ? void 0 : onGroupChange(newConditions[0].field);
        }
        else {
            dataModel.setViewConfig(viewId, {
                group: [],
            });
            onGroupChange === null || onGroupChange === void 0 ? void 0 : onGroupChange('');
        }
        // 如果条件被清空，通知工具栏隐藏通知栏
        if (newConditions.length === 0) {
            onConditionCleared === null || onConditionCleared === void 0 ? void 0 : onConditionCleared();
        }
    };
    /**
     * 更新分组条件的字段
     */
    const handleUpdateGroupField = (index, field) => {
        (0, arms_hot_tag_log_1.armsHottagLog)({
            hottag: 'cn-ai-table.group.updateField',
            name: i18n_1.default.get({ id: 'UpdateField', dm: '更新字段' }),
            c6: field,
            c7: index,
        });
        const newConditions = [...groupConditions];
        newConditions[index] = { ...newConditions[index], field };
        setGroupConditions(newConditions);
        // 更新视图配置
        dataModel.setViewConfig(viewId, {
            group: newConditions,
        });
        // 切换字段时触发通知提示
        onAddCondition === null || onAddCondition === void 0 ? void 0 : onAddCondition();
        onGroupChange === null || onGroupChange === void 0 ? void 0 : onGroupChange(field);
    };
    // ============================= Render =============================
    // 响应式紧凑模式下由按钮 onClick 控制面板开关（CnTooltip 包裹时 CnPopup 的 trigger 点击不触发）
    const [panelVisible, setPanelVisible] = (0, react_1.useState)(false);
    const handleTriggerClick = () => {
        if (isCompact)
            setPanelVisible((prev) => !prev);
    };
    const buttonElement = (react_1.default.createElement(cn_ui_1.CnButton, { text: true, className: (0, classnames_1.default)('toolbar-btn', {
            'toolbar-btn-active': groupCount > 0,
        }), onClick: isCompact ? handleTriggerClick : undefined },
        react_1.default.createElement("img", { src: icons.TOOLBAR_GROUP, alt: i18n_1.default.get({ id: 'Grouping', dm: '分组' }) }),
        react_1.default.createElement("span", null,
            i18n_1.default.get({ id: 'Grouping', dm: '分组' }),
            groupCount > 0 ? `(${groupCount})` : '')));
    return (react_1.default.createElement(condition_panel_1.ConditionPanel, { visible: isCompact ? panelVisible : undefined, onVisibleChange: isCompact ? setPanelVisible : undefined, trigger: isCompact ? (react_1.default.createElement(trigger_with_tooltip_1.TriggerWithTooltip, { tooltipContent: i18n_1.default.get({ id: 'Grouping', dm: '分组' }), disableTooltip: panelVisible }, buttonElement)) : (buttonElement), title: i18n_1.default.get({ id: 'GroupByTheFollowingConditions', dm: '按以下条件分组' }), conditions: groupConditions, conditionCount: groupCount, addButtonText: i18n_1.default.get({ id: 'AddGroupingCondition', dm: '添加分组条件' }), onAdd: handleAddGroupCondition, onRemove: handleRemoveGroupCondition, renderConditionItem: (condition, index) => (react_1.default.createElement(cn_ui_1.CnAsyncSelect, { dataSource: getFieldOptionsForIndex(index), value: condition.field, onChange: (value) => handleUpdateGroupField(index, value), placeholder: i18n_1.default.get({ id: 'SelectField', dm: '选择字段' }), className: "field-select", hasClear: true, autoWidth: false, popupClassName: "field-select-popup", popupStyle: { maxWidth: 300 }, showSearch: true, itemRender: renderFieldOption, valueRender: (item) => renderFieldOption(item) })), keepVisible: keepVisible, maxConditions: maxGroupLevels, active: groupCount > 0, viewId: viewId, currentPageHintText: i18n_1.default.get({ id: 'Grouping', dm: '分组' }), shouldOpen: () => !((0, env_1.isBirda)() === false && (0, isEmpty_1.default)(dataModel.fieldMap)), popupClassName: "condition-popup-group" }));
}
