import $i18n from '../../../../../../locales/i18n.js';
import React, { useState } from 'react';
import classNames from 'classnames';
import isEmpty from 'lodash/isEmpty';
import { CnButton, CnPopup, CnAsyncSelect } from '@cainiaofe/cn-ui';
import { useModel } from '../../../../../../utils/mobx-react-simpler/index.js';
import { isBirda } from '../../../../../../utils/env/index.js';
import { presetColors } from '../../utils/presetColor';
import { buildEffectiveFieldMap, canUseInToolbar, getToolbarFieldSchema, } from '../../../../../../cn-ai-table/view/utils/table-column-feature-utils';
import { ConditionPanel } from '../condition-panel';
import { TriggerWithTooltip } from '../condition-panel/trigger-with-tooltip';
import { FilterConditionValueInput } from '../filter/filter-condition-value-input';
import { useAiTableIcons } from '../../../../../../cn-ai-table/view/hooks/use-ai-table-icons';
import { useFieldIcon } from '../../../../../../cn-ai-table/view/utils/field-icon-utils';
import { getOperatorOptions } from '../../utils/operator-options';
import { armsHottagLog } from '../../../../../../utils/arms/arms-hot-tag-log.js';
export function ColorFillButton({ viewId, onColorFillChange, onAddCondition, onConditionCleared, keepVisible = false, showDivider = true, isCompact = false, }) {
    const icons = useAiTableIcons();
    const getIcon = useFieldIcon();
    const dataModel = useModel('dataModel');
    const viewConfig = dataModel.getViewConfig(viewId);
    const effectiveFieldMap = React.useMemo(() => buildEffectiveFieldMap(dataModel.fieldMap, dataModel.columnDefinitions), [dataModel.fieldMap, dataModel.columnDefinitions]);
    // 获取所有过滤后的字段ID列表
    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) => canUseInToolbar(dataModel.fieldMap[col.dataIndex], col)).map((col) => col.dataIndex);
    }, [dataModel.columnDefinitions, dataModel.fieldMap]);
    // 字段选项：只包含过滤后的字段
    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)));
    };
    // 颜色选择器展开状态（为每个条件维护一个状态）
    const [colorPickerVisible, setColorPickerVisible] = useState({});
    const colorFillIdCounter = React.useRef(0);
    const genColorFillId = () => `color-fill-${colorFillIdCounter.current++}`;
    const stripColorFillId = (list) => list.map(({ _id, ...rest }) => rest);
    const normalizeColorFillFromConfig = (raw) => raw.map((c) => ({
        field: c.field || '',
        operator: c.operator || 'eq',
        value: c.value || '',
        color: c.color || '#FEEDD9',
        scope: c.scope || 'cell',
    }));
    const currentColorFill = viewConfig.colorFill || [];
    // 填色条件列表，每个条件包含字段、操作符、值、颜色和范围
    const [colorFillConditions, setColorFillConditions] = useState(normalizeColorFillFromConfig(currentColorFill).map((c) => ({
        ...c,
        _id: genColorFillId(),
    })));
    const colorFillCount = colorFillConditions.filter((c) => c.field).length; // 填色规则数量
    // 同步 viewConfig.colorFill 的变化到内部状态;按 index + 内容比对复用旧 _id,
    // 自身 update/remove/reorder 触发的回流不会让条件项整体重新挂载。
    React.useEffect(() => {
        const normalized = normalizeColorFillFromConfig(viewConfig.colorFill || []);
        setColorFillConditions((prev) => normalized.map((c, i) => {
            const old = prev[i];
            const same = old &&
                old.field === c.field &&
                old.operator === c.operator &&
                old.value === c.value &&
                old.color === c.color &&
                old.scope === c.scope;
            return { ...c, _id: same ? old._id : genColorFillId() };
        }));
    }, [viewConfig.colorFill]);
    // 添加填色条件
    const handleAddColorFillCondition = () => {
        armsHottagLog({
            hottag: 'cn-ai-table.colorFill.addCondition',
            name: $i18n.get({ id: 'AddCondition', dm: '添加条件' }),
        });
        // 默认选择第一个字段
        const defaultField = fieldOptions.length > 0 ? fieldOptions[0].value : '';
        const newConditions = [
            ...colorFillConditions,
            {
                field: defaultField,
                operator: 'eq',
                value: '',
                color: '#FEEDD9',
                scope: 'cell',
                _id: genColorFillId(),
            },
        ];
        setColorFillConditions(newConditions);
        onAddCondition === null || onAddCondition === void 0 ? void 0 : onAddCondition();
        // 如果有默认字段，立即保存配置
        if (defaultField) {
            const persisted = stripColorFillId(newConditions);
            dataModel.setViewConfig(viewId, {
                colorFill: persisted,
            });
            onColorFillChange === null || onColorFillChange === void 0 ? void 0 : onColorFillChange(persisted);
        }
    };
    // 删除填色条件
    const handleRemoveColorFillCondition = (index) => {
        armsHottagLog({
            hottag: 'cn-ai-table.colorFill.removeCondition',
            name: $i18n.get({ id: 'DeleteCondition', dm: '删除条件' }),
            c7: index,
        });
        const newConditions = colorFillConditions.filter((_, i) => i !== index);
        setColorFillConditions(newConditions);
        onAddCondition === null || onAddCondition === void 0 ? void 0 : onAddCondition();
        // 更新视图配置
        const persisted = stripColorFillId(newConditions);
        dataModel.setViewConfig(viewId, {
            colorFill: persisted,
        });
        onColorFillChange === null || onColorFillChange === void 0 ? void 0 : onColorFillChange(persisted);
        // 如果条件被清空，通知工具栏隐藏通知栏
        if (newConditions.length === 0) {
            onConditionCleared === null || onConditionCleared === void 0 ? void 0 : onConditionCleared();
        }
    };
    // 拖拽重排填色条件
    const handleReorderColorFillCondition = (fromIndex, toIndex) => {
        armsHottagLog({
            hottag: 'cn-ai-table.colorFill.reorderCondition',
            name: $i18n.get({ id: 'AdjustTheOrderOfConditions', dm: '调整条件顺序' }),
            c7: fromIndex,
        });
        const newConditions = [...colorFillConditions];
        const [moved] = newConditions.splice(fromIndex, 1);
        newConditions.splice(toIndex, 0, moved);
        setColorFillConditions(newConditions);
        const persisted = stripColorFillId(newConditions);
        dataModel.setViewConfig(viewId, {
            colorFill: persisted,
        });
        onColorFillChange === null || onColorFillChange === void 0 ? void 0 : onColorFillChange(persisted);
        onAddCondition === null || onAddCondition === void 0 ? void 0 : onAddCondition();
    };
    // 更新填色条件的字段
    const handleUpdateColorFillField = (index, field) => {
        armsHottagLog({
            hottag: 'cn-ai-table.colorFill.updateField',
            name: $i18n.get({ id: 'UpdateField', dm: '更新字段' }),
            c6: field,
            c7: index,
        });
        const newConditions = [...colorFillConditions];
        // 切换字段时重置操作符为默认值 'eq'，并清空值
        newConditions[index] = { ...newConditions[index], field, operator: 'eq', value: '' };
        setColorFillConditions(newConditions);
        // 只要有字段就立即更新配置
        if (field) {
            const persisted = stripColorFillId(newConditions);
            dataModel.setViewConfig(viewId, {
                colorFill: persisted,
            });
            onColorFillChange === null || onColorFillChange === void 0 ? void 0 : onColorFillChange(persisted);
        }
        // 切换字段时触发通知提示
        onAddCondition === null || onAddCondition === void 0 ? void 0 : onAddCondition();
    };
    // 更新填色条件的操作符
    const handleUpdateColorFillOperator = (index, operator) => {
        armsHottagLog({
            hottag: 'cn-ai-table.colorFill.updateOperator',
            name: $i18n.get({ id: 'UpdateOperator', dm: '更新操作符' }),
            c6: operator,
            c7: index,
        });
        const newConditions = [...colorFillConditions];
        newConditions[index] = { ...newConditions[index], operator };
        setColorFillConditions(newConditions);
        // 只要有字段就立即更新配置（"为空"和"不为空"不需要值）
        if (newConditions[index].field) {
            const persisted = stripColorFillId(newConditions);
            dataModel.setViewConfig(viewId, {
                colorFill: persisted,
            });
            onColorFillChange === null || onColorFillChange === void 0 ? void 0 : onColorFillChange(persisted);
        }
        // 切换操作符时触发通知提示
        onAddCondition === null || onAddCondition === void 0 ? void 0 : onAddCondition();
    };
    // 更新填色条件的值
    const handleUpdateColorFillValue = (index, value) => {
        armsHottagLog({
            hottag: 'cn-ai-table.colorFill.updateValue',
            name: $i18n.get({ id: 'UpdateValue', dm: '更新值' }),
            c6: value,
            c7: index,
        });
        const newConditions = [...colorFillConditions];
        newConditions[index] = { ...newConditions[index], value };
        setColorFillConditions(newConditions);
        // 如果字段有值，则更新配置
        if (newConditions[index].field) {
            const persisted = stripColorFillId(newConditions);
            dataModel.setViewConfig(viewId, {
                colorFill: persisted,
            });
            onColorFillChange === null || onColorFillChange === void 0 ? void 0 : onColorFillChange(persisted);
        }
        // 修改值时触发通知提示
        onAddCondition === null || onAddCondition === void 0 ? void 0 : onAddCondition();
    };
    // 更新填色条件的颜色
    const handleUpdateColorFillColor = (index, color) => {
        armsHottagLog({
            hottag: 'cn-ai-table.colorFill.updateColor',
            name: $i18n.get({ id: 'UpdateColor', dm: '更新颜色' }),
            c6: color,
            c7: index,
        });
        const newConditions = [...colorFillConditions];
        newConditions[index] = { ...newConditions[index], color };
        setColorFillConditions(newConditions);
        // 关闭颜色选择器
        setColorPickerVisible({ ...colorPickerVisible, [index]: false });
        // 只要有字段就立即更新配置
        if (newConditions[index].field) {
            const persisted = stripColorFillId(newConditions);
            dataModel.setViewConfig(viewId, {
                colorFill: persisted,
            });
            onColorFillChange === null || onColorFillChange === void 0 ? void 0 : onColorFillChange(persisted);
        }
        // 切换颜色时触发通知提示
        onAddCondition === null || onAddCondition === void 0 ? void 0 : onAddCondition();
    };
    // 切换颜色选择器显示状态
    const toggleColorPicker = (index) => {
        setColorPickerVisible({ ...colorPickerVisible, [index]: !colorPickerVisible[index] });
    };
    // 更新填色条件的范围
    const handleUpdateColorFillScope = (index, scope) => {
        const newConditions = [...colorFillConditions];
        // 如果选择整列模式，清除操作符和值，因为整列只需要字段即可
        if (scope === 'column') {
            newConditions[index] = {
                ...newConditions[index],
                scope,
                operator: 'notEmpty', // 整列模式使用默认操作符
                value: '', // 清空值
            };
        }
        else {
            newConditions[index] = { ...newConditions[index], scope };
        }
        setColorFillConditions(newConditions);
        // 只要有字段就立即更新配置
        if (newConditions[index].field) {
            const persisted = stripColorFillId(newConditions);
            dataModel.setViewConfig(viewId, {
                colorFill: persisted,
            });
            onColorFillChange === null || onColorFillChange === void 0 ? void 0 : onColorFillChange(persisted);
        }
        // 切换范围时触发通知提示
        onAddCondition === null || onAddCondition === void 0 ? void 0 : onAddCondition();
    };
    // 响应式紧凑模式下由按钮 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': colorFillCount > 0,
        }), onClick: isCompact ? handleTriggerClick : undefined },
        React.createElement("img", { src: icons.TOOLBAR_COLOR_FILL, alt: $i18n.get({ id: 'Fill', dm: '填色' }) }),
        React.createElement("span", null,
            $i18n.get({ id: 'Fill', dm: '填色' }),
            colorFillCount > 0 ? `(${colorFillCount})` : '')));
    return (React.createElement(ConditionPanel, { visible: isCompact ? panelVisible : undefined, onVisibleChange: isCompact ? setPanelVisible : undefined, trigger: isCompact ? (React.createElement(TriggerWithTooltip, { tooltipContent: $i18n.get({ id: 'Fill', dm: '填色' }), disableTooltip: panelVisible }, buttonElement)) : (buttonElement), title: $i18n.get({ id: 'FillAccordingToTheFollowingRules', dm: '按以下规则进行填色' }), conditions: colorFillConditions, conditionCount: colorFillCount, addButtonText: $i18n.get({ id: 'AddFillConditions', dm: '添加填色条件' }), onAdd: handleAddColorFillCondition, onRemove: handleRemoveColorFillCondition, onReorder: handleReorderColorFillCondition, getItemId: (condition) => condition._id, renderConditionItem: (condition, index) => {
            var _a;
            return (React.createElement(React.Fragment, null,
                React.createElement(CnPopup, { triggerType: "click", visible: colorPickerVisible[index] || false, onVisibleChange: (visible) => {
                        setColorPickerVisible({ ...colorPickerVisible, [index]: visible });
                    }, trigger: React.createElement("div", { className: "color-picker-trigger", style: { backgroundColor: condition.color }, onClick: () => toggleColorPicker(index) }), offset: [0, 10] },
                    React.createElement("div", { className: "color-picker-popup" },
                        React.createElement("div", { className: "color-picker-grid" },
                            React.createElement("div", { className: "color-picker-empty-cell" }),
                            [
                                $i18n.get({ id: 'Abnormal', dm: '异常' }),
                                $i18n.get({ id: 'Warning', dm: '预警' }),
                                $i18n.get({ id: 'Todo', dm: '待办' }),
                                $i18n.get({ id: 'Normal', dm: '正常' }),
                                $i18n.get({ id: 'Remarks', dm: '备注' }),
                                $i18n.get({ id: 'Special', dm: '特殊' }),
                            ].map((label) => (React.createElement("div", { key: label, className: "color-picker-header-cell" }, label))),
                            presetColors.map((row, rowIndex) => {
                                const rowLabels = [
                                    $i18n.get({ id: 'Strong', dm: '强' }),
                                    $i18n.get({ id: 'Medium', dm: '中' }),
                                    $i18n.get({ id: 'Weak', dm: '弱' }),
                                ];
                                const rowLabel = rowLabels[rowIndex];
                                return (React.createElement(React.Fragment, { key: `color-row-${rowLabel}` },
                                    React.createElement("div", { className: "color-picker-row-header" }, rowLabel),
                                    row.map((color) => (React.createElement("div", { key: color, className: classNames('color-swatch', {
                                            selected: condition.color === color,
                                        }), style: { backgroundColor: color }, onClick: () => handleUpdateColorFillColor(index, color) })))));
                            })))),
                React.createElement(CnAsyncSelect, { dataSource: [
                        { label: $i18n.get({ id: 'Cell', dm: '单元格' }), value: 'cell' },
                        { label: $i18n.get({ id: 'EntireRow', dm: '整行' }), value: 'row' },
                        { label: $i18n.get({ id: 'EntireColumn', dm: '整列' }), value: 'column' },
                    ], value: condition.scope || 'cell', onChange: (value) => handleUpdateColorFillScope(index, value), placeholder: $i18n.get({ id: 'FillRange', dm: '填色范围' }), className: "scope-select" }),
                React.createElement(CnAsyncSelect, { dataSource: fieldOptions, value: condition.field, onChange: (value) => handleUpdateColorFillField(index, value), placeholder: $i18n.get({ id: 'SelectField', dm: '选择字段' }), className: "field-select-color", hasClear: true, autoWidth: false, popupClassName: "field-select-popup", popupStyle: { maxWidth: 300 }, showSearch: true, itemRender: renderFieldOption, valueRender: (item) => renderFieldOption(item) }),
                condition.scope !== 'column' && (React.createElement(CnAsyncSelect, { dataSource: getOperatorOptions((_a = fieldOptions === null || fieldOptions === void 0 ? void 0 : fieldOptions.find((f) => f.value === condition.field)) === null || _a === void 0 ? void 0 : _a.fieldType), value: condition.operator, onChange: (value) => handleUpdateColorFillOperator(index, value), placeholder: $i18n.get({ id: 'SelectOperator', dm: '选择操作符' }), className: "operator-select" })),
                condition.scope !== 'column' && (React.createElement(FilterConditionValueInput, { fieldId: condition.field, operator: condition.operator, value: condition.value, onChange: (value) => handleUpdateColorFillValue(index, value), fieldMap: effectiveFieldMap }))));
        }, keepVisible: keepVisible, active: colorFillCount > 0, viewId: viewId, showDivider: showDivider, shouldOpen: () => !(isBirda() === false && isEmpty(dataModel.fieldMap)) }));
}
