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 { buildEffectiveFieldMap, canUseInToolbar, getToolbarFieldSchema, } from '../../../../../../cn-ai-table/view/utils/table-column-feature-utils';
import { isBirda } from '../../../../../../utils/env/index.js';
import { ConditionPanel } from '../condition-panel';
import { TriggerWithTooltip } from '../condition-panel/trigger-with-tooltip';
import { FilterConditionValueInput } from './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';
/**
 * 筛选功能不支持的字段类型
 */
const UNSUPPORTED_FILTER_FIELD_TYPES = ['CnCurrencyAmountNumberPickerPro'];
export function FilterButton({ viewId, onFilterChange, onAddCondition, onConditionCleared, keepVisible = false, 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) => {
            var _a, _b;
            const field = dataModel.fieldMap[col.dataIndex];
            if (!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.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 defaultField = React.useMemo(() => {
        return filteredFieldIds && filteredFieldIds.length > 0 ? filteredFieldIds[0] : '';
    }, [filteredFieldIds]);
    // 筛选相关
    const currentFilter = viewConfig.filter || [];
    // 筛选条件列表，每个条件包含字段、操作符和值
    const [filterConditions, setFilterConditions] = 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.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 = () => {
        armsHottagLog({
            hottag: 'cn-ai-table.filter.addCondition',
            name: $i18n.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) => {
        armsHottagLog({
            hottag: 'cn-ai-table.filter.removeCondition',
            name: $i18n.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) => {
        armsHottagLog({
            hottag: 'cn-ai-table.filter.updateField',
            name: $i18n.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) => {
        armsHottagLog({
            hottag: 'cn-ai-table.filter.updateOperator',
            name: $i18n.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) => {
        armsHottagLog({
            hottag: 'cn-ai-table.filter.updateValue',
            name: $i18n.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 = () => {
        armsHottagLog({
            hottag: 'cn-ai-table.filter',
            name: $i18n.get({ id: 'Filter', dm: '筛选' }),
        });
    };
    // 响应式紧凑模式下由按钮 onClick 控制面板开关（CnTooltip 包裹时 CnPopup 的 trigger 点击不触发）
    const [panelVisible, setPanelVisible] = useState(false);
    const handleTriggerClick = () => {
        if (isCompact)
            setPanelVisible((prev) => !prev);
        handleFilterButtonClick();
    };
    const buttonElement = (React.createElement(CnButton, { text: true, className: classNames('toolbar-btn', {
            'toolbar-btn-active': filterCount > 0,
        }), onClick: handleTriggerClick },
        React.createElement("img", { src: icons.TOOLBAR_FILTER, alt: $i18n.get({ id: 'Filter', dm: '筛选' }) }),
        React.createElement("span", null,
            $i18n.get({ id: 'Filter', dm: '筛选' }),
            filterCount > 0 ? `(${filterCount})` : '')));
    return (React.createElement(ConditionPanel, { visible: isCompact ? panelVisible : undefined, onVisibleChange: isCompact ? setPanelVisible : undefined, trigger: isCompact ? (React.createElement(TriggerWithTooltip, { tooltipContent: $i18n.get({ id: 'Filter', dm: '筛选' }), disableTooltip: panelVisible }, buttonElement)) : (buttonElement), title: $i18n.get({ id: 'FilterByTheFollowingCriteria', dm: '按以下条件筛选' }), conditions: filterConditions, conditionCount: filterCount, addButtonText: $i18n.get({ id: 'AddFilterCondition', dm: '添加筛选条件' }), onAdd: handleAddFilterCondition, onRemove: handleRemoveFilterCondition, renderConditionItem: (condition, index) => {
            var _a;
            return (React.createElement(React.Fragment, null,
                React.createElement(CnAsyncSelect, { dataSource: fieldOptions, value: condition.field, onChange: (value) => handleUpdateFilterField(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) }),
                React.createElement(CnAsyncSelect, { dataSource: getOperatorOptions((_a = effectiveFieldMap[condition.field]) === null || _a === void 0 ? void 0 : _a['x-component']), value: condition.operator, onChange: (value) => handleUpdateFilterOperator(index, value), placeholder: $i18n.get({ id: 'SelectOperator', dm: '选择操作符' }), className: "operator-select" }),
                React.createElement(FilterConditionValueInput, { fieldId: condition.field, operator: condition.operator, value: condition.value, onChange: (val) => handleUpdateFilterValue(index, val), fieldMap: effectiveFieldMap })));
        }, keepVisible: keepVisible, active: filterCount > 0, currentPageHintText: $i18n.get({ id: 'Filter', dm: '筛选' }), showAndBeforeCondition: true, viewId: viewId, shouldOpen: () => !(isBirda() === false && isEmpty(dataModel.fieldMap)), popupClassName: "condition-popup-filter" }));
}
