"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.ColorFillButton = ColorFillButton;
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 presetColor_1 = require("../../utils/presetColor");
const table_column_feature_utils_1 = require("../../../../../../cn-ai-table/view/utils/table-column-feature-utils");
const condition_panel_1 = require("../condition-panel");
const trigger_with_tooltip_1 = require("../condition-panel/trigger-with-tooltip");
const filter_condition_value_input_1 = require("../filter/filter-condition-value-input");
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 operator_options_1 = require("../../utils/operator-options");
const arms_hot_tag_log_1 = require("../../../../../../utils/arms/arms-hot-tag-log.js");
function ColorFillButton({ viewId, onColorFillChange, onAddCondition, onConditionCleared, keepVisible = false, showDivider = true, isCompact = false, }) {
    const icons = (0, use_ai_table_icons_1.useAiTableIcons)();
    const getIcon = (0, field_icon_utils_1.useFieldIcon)();
    const dataModel = (0, mobx_react_simpler_1.useModel)('dataModel');
    const viewConfig = dataModel.getViewConfig(viewId);
    const effectiveFieldMap = react_1.default.useMemo(() => (0, table_column_feature_utils_1.buildEffectiveFieldMap)(dataModel.fieldMap, dataModel.columnDefinitions), [dataModel.fieldMap, dataModel.columnDefinitions]);
    // 获取所有过滤后的字段ID列表
    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) => (0, table_column_feature_utils_1.canUseInToolbar)(dataModel.fieldMap[col.dataIndex], col)).map((col) => col.dataIndex);
    }, [dataModel.columnDefinitions, dataModel.fieldMap]);
    // 字段选项：只包含过滤后的字段
    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)));
    };
    // 颜色选择器展开状态（为每个条件维护一个状态）
    const [colorPickerVisible, setColorPickerVisible] = (0, react_1.useState)({});
    const colorFillIdCounter = react_1.default.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] = (0, react_1.useState)(normalizeColorFillFromConfig(currentColorFill).map((c) => ({
        ...c,
        _id: genColorFillId(),
    })));
    const colorFillCount = colorFillConditions.filter((c) => c.field).length; // 填色规则数量
    // 同步 viewConfig.colorFill 的变化到内部状态;按 index + 内容比对复用旧 _id,
    // 自身 update/remove/reorder 触发的回流不会让条件项整体重新挂载。
    react_1.default.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 = () => {
        (0, arms_hot_tag_log_1.armsHottagLog)({
            hottag: 'cn-ai-table.colorFill.addCondition',
            name: i18n_1.default.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) => {
        (0, arms_hot_tag_log_1.armsHottagLog)({
            hottag: 'cn-ai-table.colorFill.removeCondition',
            name: i18n_1.default.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) => {
        (0, arms_hot_tag_log_1.armsHottagLog)({
            hottag: 'cn-ai-table.colorFill.reorderCondition',
            name: i18n_1.default.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) => {
        (0, arms_hot_tag_log_1.armsHottagLog)({
            hottag: 'cn-ai-table.colorFill.updateField',
            name: i18n_1.default.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) => {
        (0, arms_hot_tag_log_1.armsHottagLog)({
            hottag: 'cn-ai-table.colorFill.updateOperator',
            name: i18n_1.default.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) => {
        (0, arms_hot_tag_log_1.armsHottagLog)({
            hottag: 'cn-ai-table.colorFill.updateValue',
            name: i18n_1.default.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) => {
        (0, arms_hot_tag_log_1.armsHottagLog)({
            hottag: 'cn-ai-table.colorFill.updateColor',
            name: i18n_1.default.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] = (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': colorFillCount > 0,
        }), onClick: isCompact ? handleTriggerClick : undefined },
        react_1.default.createElement("img", { src: icons.TOOLBAR_COLOR_FILL, alt: i18n_1.default.get({ id: 'Fill', dm: '填色' }) }),
        react_1.default.createElement("span", null,
            i18n_1.default.get({ id: 'Fill', dm: '填色' }),
            colorFillCount > 0 ? `(${colorFillCount})` : '')));
    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: 'Fill', dm: '填色' }), disableTooltip: panelVisible }, buttonElement)) : (buttonElement), title: i18n_1.default.get({ id: 'FillAccordingToTheFollowingRules', dm: '按以下规则进行填色' }), conditions: colorFillConditions, conditionCount: colorFillCount, addButtonText: i18n_1.default.get({ id: 'AddFillConditions', dm: '添加填色条件' }), onAdd: handleAddColorFillCondition, onRemove: handleRemoveColorFillCondition, onReorder: handleReorderColorFillCondition, getItemId: (condition) => condition._id, renderConditionItem: (condition, index) => {
            var _a;
            return (react_1.default.createElement(react_1.default.Fragment, null,
                react_1.default.createElement(cn_ui_1.CnPopup, { triggerType: "click", visible: colorPickerVisible[index] || false, onVisibleChange: (visible) => {
                        setColorPickerVisible({ ...colorPickerVisible, [index]: visible });
                    }, trigger: react_1.default.createElement("div", { className: "color-picker-trigger", style: { backgroundColor: condition.color }, onClick: () => toggleColorPicker(index) }), offset: [0, 10] },
                    react_1.default.createElement("div", { className: "color-picker-popup" },
                        react_1.default.createElement("div", { className: "color-picker-grid" },
                            react_1.default.createElement("div", { className: "color-picker-empty-cell" }),
                            [
                                i18n_1.default.get({ id: 'Abnormal', dm: '异常' }),
                                i18n_1.default.get({ id: 'Warning', dm: '预警' }),
                                i18n_1.default.get({ id: 'Todo', dm: '待办' }),
                                i18n_1.default.get({ id: 'Normal', dm: '正常' }),
                                i18n_1.default.get({ id: 'Remarks', dm: '备注' }),
                                i18n_1.default.get({ id: 'Special', dm: '特殊' }),
                            ].map((label) => (react_1.default.createElement("div", { key: label, className: "color-picker-header-cell" }, label))),
                            presetColor_1.presetColors.map((row, rowIndex) => {
                                const rowLabels = [
                                    i18n_1.default.get({ id: 'Strong', dm: '强' }),
                                    i18n_1.default.get({ id: 'Medium', dm: '中' }),
                                    i18n_1.default.get({ id: 'Weak', dm: '弱' }),
                                ];
                                const rowLabel = rowLabels[rowIndex];
                                return (react_1.default.createElement(react_1.default.Fragment, { key: `color-row-${rowLabel}` },
                                    react_1.default.createElement("div", { className: "color-picker-row-header" }, rowLabel),
                                    row.map((color) => (react_1.default.createElement("div", { key: color, className: (0, classnames_1.default)('color-swatch', {
                                            selected: condition.color === color,
                                        }), style: { backgroundColor: color }, onClick: () => handleUpdateColorFillColor(index, color) })))));
                            })))),
                react_1.default.createElement(cn_ui_1.CnAsyncSelect, { dataSource: [
                        { label: i18n_1.default.get({ id: 'Cell', dm: '单元格' }), value: 'cell' },
                        { label: i18n_1.default.get({ id: 'EntireRow', dm: '整行' }), value: 'row' },
                        { label: i18n_1.default.get({ id: 'EntireColumn', dm: '整列' }), value: 'column' },
                    ], value: condition.scope || 'cell', onChange: (value) => handleUpdateColorFillScope(index, value), placeholder: i18n_1.default.get({ id: 'FillRange', dm: '填色范围' }), className: "scope-select" }),
                react_1.default.createElement(cn_ui_1.CnAsyncSelect, { dataSource: fieldOptions, value: condition.field, onChange: (value) => handleUpdateColorFillField(index, value), placeholder: i18n_1.default.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_1.default.createElement(cn_ui_1.CnAsyncSelect, { dataSource: (0, operator_options_1.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_1.default.get({ id: 'SelectOperator', dm: '选择操作符' }), className: "operator-select" })),
                condition.scope !== 'column' && (react_1.default.createElement(filter_condition_value_input_1.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: () => !((0, env_1.isBirda)() === false && (0, isEmpty_1.default)(dataModel.fieldMap)) }));
}
