import $i18n from '../../../../../../locales/i18n.js';
import React, { useState } from 'react';
import classNames from 'classnames';
import isEmpty from 'lodash/isEmpty';
import { CnButton, CnAsyncSelect } from '@cainiaofe/cn-ui';
import { useModel } from '../../../../../../utils/mobx-react-simpler/index.js';
import { isBirda } from '../../../../../../utils/env/index.js';
import { canUseInToolbar, getToolbarFieldSchema, isAiFormulaOrLookupColumnDef, } from '../../../../../../cn-ai-table/view/utils/table-column-feature-utils';
import { GROUP_FIELD_TYPE } from './constants';
import { ConditionPanel } from '../condition-panel';
import { TriggerWithTooltip } from '../condition-panel/trigger-with-tooltip';
import { useAiTableIcons } from '../../../../../../cn-ai-table/view/hooks/use-ai-table-icons';
import { useFieldIcon } from '../../../../../../cn-ai-table/view/utils/field-icon-utils';
import { armsHottagLog } from '../../../../../../utils/arms/arms-hot-tag-log.js';
/**
 * 分组按钮组件
 */
export function GroupButton(props) {
    const { viewId, onGroupChange, onAddCondition, onConditionCleared, keepVisible = false, maxGroupLevels = 1, isCompact = false, } = props;
    // ============================= Hooks =============================
    const icons = useAiTableIcons();
    const getIcon = useFieldIcon();
    // ============================= Model =============================
    const dataModel = useModel('dataModel');
    const viewConfig = dataModel.getViewConfig(viewId);
    // ============================= Field Options =============================
    /**
     * 获取所有过滤后的字段ID列表
     * 所有视图类型都只支持 GROUP_FIELD_TYPE 中定义的字段类型进行分组
     */
    const filteredFieldIds = React.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 (!canUseInToolbar(field, col))
                return false;
            const effectiveField = getToolbarFieldSchema(field, col);
            const fieldType = effectiveField === null || effectiveField === void 0 ? void 0 : effectiveField['x-component'];
            return (isAiFormulaOrLookupColumnDef(col) ||
                !!GROUP_FIELD_TYPE[fieldType]);
        }).map((col) => col.dataIndex);
    }, [dataModel.columnDefinitions, dataModel.fieldMap]);
    /**
     * 字段选项列表（用于下拉选择组件）
     * 将字段ID数组转换为下拉选择组件需要的选项格式
     */
    const fieldOptions = React.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 = 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.createElement("span", { title: item.label, className: "field-option-label" }, item.label));
        }
        return (React.createElement("div", { title: item.label, className: "field-option" },
            React.createElement("img", { src: getIcon(item.fieldType), alt: "" }),
            React.createElement("span", { className: "field-option-label" }, item.label)));
    };
    // ============================= Group State =============================
    /**
     * 分组条件列表
     * 每个条件包含字段
     */
    const [groupConditions, setGroupConditions] = 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.useMemo(() => { var _a; return (_a = filteredFieldIds === null || filteredFieldIds === void 0 ? void 0 : filteredFieldIds[0]) !== null && _a !== void 0 ? _a : ''; }, [filteredFieldIds]);
    /**
     * 添加条件时使用的默认字段：第一个未被当前条件占用的可分组字段，否则用表格第一个字段
     */
    const getDefaultFieldForNewCondition = React.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.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;
        }
        armsHottagLog({
            hottag: 'cn-ai-table.group.addCondition',
            name: $i18n.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) => {
        armsHottagLog({
            hottag: 'cn-ai-table.group.removeCondition',
            name: $i18n.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) => {
        armsHottagLog({
            hottag: 'cn-ai-table.group.updateField',
            name: $i18n.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] = useState(false);
    const handleTriggerClick = () => {
        if (isCompact)
            setPanelVisible((prev) => !prev);
    };
    const buttonElement = (React.createElement(CnButton, { text: true, className: classNames('toolbar-btn', {
            'toolbar-btn-active': groupCount > 0,
        }), onClick: isCompact ? handleTriggerClick : undefined },
        React.createElement("img", { src: icons.TOOLBAR_GROUP, alt: $i18n.get({ id: 'Grouping', dm: '分组' }) }),
        React.createElement("span", null,
            $i18n.get({ id: 'Grouping', dm: '分组' }),
            groupCount > 0 ? `(${groupCount})` : '')));
    return (React.createElement(ConditionPanel, { visible: isCompact ? panelVisible : undefined, onVisibleChange: isCompact ? setPanelVisible : undefined, trigger: isCompact ? (React.createElement(TriggerWithTooltip, { tooltipContent: $i18n.get({ id: 'Grouping', dm: '分组' }), disableTooltip: panelVisible }, buttonElement)) : (buttonElement), title: $i18n.get({ id: 'GroupByTheFollowingConditions', dm: '按以下条件分组' }), conditions: groupConditions, conditionCount: groupCount, addButtonText: $i18n.get({ id: 'AddGroupingCondition', dm: '添加分组条件' }), onAdd: handleAddGroupCondition, onRemove: handleRemoveGroupCondition, renderConditionItem: (condition, index) => (React.createElement(CnAsyncSelect, { dataSource: getFieldOptionsForIndex(index), value: condition.field, onChange: (value) => handleUpdateGroupField(index, value), placeholder: $i18n.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.get({ id: 'Grouping', dm: '分组' }), shouldOpen: () => !(isBirda() === false && isEmpty(dataModel.fieldMap)), popupClassName: "condition-popup-group" }));
}
