"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.FilterButton = FilterButton;
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 table_column_feature_utils_1 = require("../../../../../../cn-ai-table/view/utils/table-column-feature-utils");
const env_1 = require("../../../../../../utils/env/index.js");
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-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");
/**
 * 筛选功能不支持的字段类型
 */
const UNSUPPORTED_FILTER_FIELD_TYPES = ['CnCurrencyAmountNumberPickerPro'];
function FilterButton({ viewId, onFilterChange, onAddCondition, onConditionCleared, keepVisible = false, 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) => {
            var _a, _b;
            const field = dataModel.fieldMap[col.dataIndex];
            if (!(0, table_column_feature_utils_1.canUseInToolbar)(field, col))
                return false;
            const componentType = (_b = (_a = effectiveFieldMap[col.dataIndex]) === null || _a === void 0 ? void 0 : _a['x-component']) !== null && _b !== void 0 ? _b : field === null || field === void 0 ? void 0 : field['x-component'];
            if (UNSUPPORTED_FILTER_FIELD_TYPES.includes(componentType)) {
                return false;
            }
            return true;
        }).map((col) => col.dataIndex);
    }, [dataModel.columnDefinitions, dataModel.fieldMap, effectiveFieldMap]);
    // 字段选项：只包含过滤后的字段
    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 defaultField = react_1.default.useMemo(() => {
        return filteredFieldIds && filteredFieldIds.length > 0 ? filteredFieldIds[0] : '';
    }, [filteredFieldIds]);
    // 筛选相关
    const currentFilter = viewConfig.filter || [];
    // 筛选条件列表，每个条件包含字段、操作符和值
    const [filterConditions, setFilterConditions] = (0, react_1.useState)(currentFilter.length > 0
        ? currentFilter
            .map((f) => ({
            field: f.field || '',
            operator: f.operator || 'eq',
            value: f.value || '',
        }))
            // 过滤掉字段为空的筛选条件
            .filter((f) => f.field)
        : []);
    const filterCount = filterConditions.length; // 筛选规则数量
    // 同步 viewConfig.filter 的变化到内部状态
    react_1.default.useEffect(() => {
        const filterFromConfig = viewConfig.filter || [];
        const newConditions = filterFromConfig.length > 0
            ? filterFromConfig
                .map((f) => ({
                field: f.field || '',
                operator: f.operator || 'eq',
                value: f.value || '',
            }))
                .filter((f) => f.field)
            : [];
        setFilterConditions(newConditions);
    }, [viewConfig.filter]);
    // 添加筛选条件
    const handleAddFilterCondition = () => {
        (0, arms_hot_tag_log_1.armsHottagLog)({
            hottag: 'cn-ai-table.filter.addCondition',
            name: i18n_1.default.get({ id: 'AddCondition', dm: '添加条件' }),
        });
        const newConditions = [
            ...filterConditions,
            { field: defaultField, operator: 'eq', value: '' },
        ];
        setFilterConditions(newConditions);
        dataModel.setViewConfig(viewId, { filter: newConditions });
        onFilterChange === null || onFilterChange === void 0 ? void 0 : onFilterChange(newConditions.length > 0 ? 'custom' : '');
        onAddCondition === null || onAddCondition === void 0 ? void 0 : onAddCondition();
    };
    // 删除筛选条件
    const handleRemoveFilterCondition = (index) => {
        (0, arms_hot_tag_log_1.armsHottagLog)({
            hottag: 'cn-ai-table.filter.removeCondition',
            name: i18n_1.default.get({ id: 'DeleteCondition', dm: '删除条件' }),
            c7: index,
        });
        const newConditions = filterConditions.filter((_, i) => i !== index);
        setFilterConditions(newConditions);
        onAddCondition === null || onAddCondition === void 0 ? void 0 : onAddCondition();
        // 更新视图配置
        dataModel.setViewConfig(viewId, {
            filter: newConditions,
        });
        onFilterChange === null || onFilterChange === void 0 ? void 0 : onFilterChange(newConditions.length > 0 ? 'custom' : '');
        // 如果条件被清空，通知工具栏隐藏通知栏
        if (newConditions.length === 0) {
            onConditionCleared === null || onConditionCleared === void 0 ? void 0 : onConditionCleared();
        }
    };
    // 更新筛选条件的字段
    const handleUpdateFilterField = (index, field) => {
        (0, arms_hot_tag_log_1.armsHottagLog)({
            hottag: 'cn-ai-table.filter.updateField',
            name: i18n_1.default.get({ id: 'UpdateField', dm: '更新字段' }),
            c6: field,
            c7: index,
        });
        const newConditions = [...filterConditions];
        // 切换字段时重置操作符为默认值 'eq'，并清空值
        newConditions[index] = { ...newConditions[index], field, operator: 'eq', value: '' };
        setFilterConditions(newConditions);
        // 更新视图配置并触发筛选
        dataModel.setViewConfig(viewId, {
            filter: newConditions,
        });
        onFilterChange === null || onFilterChange === void 0 ? void 0 : onFilterChange('custom');
        // 切换字段时触发通知提示
        onAddCondition === null || onAddCondition === void 0 ? void 0 : onAddCondition();
    };
    // 更新筛选条件的操作符
    const handleUpdateFilterOperator = (index, operator) => {
        (0, arms_hot_tag_log_1.armsHottagLog)({
            hottag: 'cn-ai-table.filter.updateOperator',
            name: i18n_1.default.get({ id: 'UpdateOperator', dm: '更新操作符' }),
            c6: operator,
            c7: index,
        });
        const newConditions = [...filterConditions];
        newConditions[index] = { ...newConditions[index], operator };
        // 如果切换为 empty 或 notEmpty，确保值为空字符串
        if (operator === 'empty' || operator === 'notEmpty') {
            newConditions[index] = { ...newConditions[index], value: '' };
        }
        setFilterConditions(newConditions);
        // 更新视图配置并触发筛选
        dataModel.setViewConfig(viewId, {
            filter: newConditions,
        });
        onFilterChange === null || onFilterChange === void 0 ? void 0 : onFilterChange('custom');
        // 切换操作符时触发通知提示
        onAddCondition === null || onAddCondition === void 0 ? void 0 : onAddCondition();
    };
    // 更新筛选条件的值
    const handleUpdateFilterValue = (index, value) => {
        (0, arms_hot_tag_log_1.armsHottagLog)({
            hottag: 'cn-ai-table.filter.updateValue',
            name: i18n_1.default.get({ id: 'UpdateValue', dm: '更新值' }),
            c6: value,
            c7: index,
        });
        const newConditions = [...filterConditions];
        // 如果是数组（多选），转换为逗号分隔的字符串
        const valueStr = Array.isArray(value) ? value.join(',') : String(value);
        newConditions[index] = { ...newConditions[index], value: valueStr };
        setFilterConditions(newConditions);
        // 更新视图配置并触发筛选
        dataModel.setViewConfig(viewId, {
            filter: newConditions,
        });
        onFilterChange === null || onFilterChange === void 0 ? void 0 : onFilterChange('custom');
        // 修改值时触发通知提示
        onAddCondition === null || onAddCondition === void 0 ? void 0 : onAddCondition();
    };
    // 处理点击筛选按钮（仅打点，不自动添加条件，与图2面板一致：先展示空面板，由用户点击「添加筛选条件」再添加）
    const handleFilterButtonClick = () => {
        (0, arms_hot_tag_log_1.armsHottagLog)({
            hottag: 'cn-ai-table.filter',
            name: i18n_1.default.get({ id: 'Filter', dm: '筛选' }),
        });
    };
    // 响应式紧凑模式下由按钮 onClick 控制面板开关（CnTooltip 包裹时 CnPopup 的 trigger 点击不触发）
    const [panelVisible, setPanelVisible] = (0, react_1.useState)(false);
    const handleTriggerClick = () => {
        if (isCompact)
            setPanelVisible((prev) => !prev);
        handleFilterButtonClick();
    };
    const buttonElement = (react_1.default.createElement(cn_ui_1.CnButton, { text: true, className: (0, classnames_1.default)('toolbar-btn', {
            'toolbar-btn-active': filterCount > 0,
        }), onClick: handleTriggerClick },
        react_1.default.createElement("img", { src: icons.TOOLBAR_FILTER, alt: i18n_1.default.get({ id: 'Filter', dm: '筛选' }) }),
        react_1.default.createElement("span", null,
            i18n_1.default.get({ id: 'Filter', dm: '筛选' }),
            filterCount > 0 ? `(${filterCount})` : '')));
    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: 'Filter', dm: '筛选' }), disableTooltip: panelVisible }, buttonElement)) : (buttonElement), title: i18n_1.default.get({ id: 'FilterByTheFollowingCriteria', dm: '按以下条件筛选' }), conditions: filterConditions, conditionCount: filterCount, addButtonText: i18n_1.default.get({ id: 'AddFilterCondition', dm: '添加筛选条件' }), onAdd: handleAddFilterCondition, onRemove: handleRemoveFilterCondition, renderConditionItem: (condition, index) => {
            var _a;
            return (react_1.default.createElement(react_1.default.Fragment, null,
                react_1.default.createElement(cn_ui_1.CnAsyncSelect, { dataSource: fieldOptions, value: condition.field, onChange: (value) => handleUpdateFilterField(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) }),
                react_1.default.createElement(cn_ui_1.CnAsyncSelect, { dataSource: (0, operator_options_1.getOperatorOptions)((_a = effectiveFieldMap[condition.field]) === null || _a === void 0 ? void 0 : _a['x-component']), value: condition.operator, onChange: (value) => handleUpdateFilterOperator(index, value), placeholder: i18n_1.default.get({ id: 'SelectOperator', dm: '选择操作符' }), className: "operator-select" }),
                react_1.default.createElement(filter_condition_value_input_1.FilterConditionValueInput, { fieldId: condition.field, operator: condition.operator, value: condition.value, onChange: (val) => handleUpdateFilterValue(index, val), fieldMap: effectiveFieldMap })));
        }, keepVisible: keepVisible, active: filterCount > 0, currentPageHintText: i18n_1.default.get({ id: 'Filter', dm: '筛选' }), showAndBeforeCondition: true, viewId: viewId, shouldOpen: () => !((0, env_1.isBirda)() === false && (0, isEmpty_1.default)(dataModel.fieldMap)), popupClassName: "condition-popup-filter" }));
}
