"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.SortButton = SortButton;
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 fieldSortUtils_1 = require("../../utils/fieldSortUtils");
const table_column_feature_utils_1 = require("../../../../../../cn-ai-table/view/utils/table-column-feature-utils");
const component_types_1 = require("../../../../../../cn-ai-table/view/constants/component-types");
const condition_panel_1 = require("../condition-panel");
const trigger_with_tooltip_1 = require("../condition-panel/trigger-with-tooltip");
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 arms_hot_tag_log_1 = require("../../../../../../utils/arms/arms-hot-tag-log.js");
/**
 * 排序按钮组件
 * 支持日期/数值字段排序，以及 AI / 公式 / 引用列按单元格展示值排序
 */
function SortButton(props) {
    const { viewId, onSortChange, onAddCondition, onConditionCleared, keepVisible = false, showDivider = true, isCompact = false, } = props;
    // ============================= Hooks =============================
    const icons = (0, use_ai_table_icons_1.useAiTableIcons)();
    const getIcon = (0, field_icon_utils_1.useFieldIcon)();
    // ============================= Model =============================
    const dataModel = (0, mobx_react_simpler_1.useModel)('dataModel');
    const viewConfig = dataModel.getViewConfig(viewId);
    // ============================= Field Options =============================
    /**
     * 获取所有过滤后的字段ID列表
     * 含日期/数值类字段，以及 AI / 公式 / 引用列（按展示值文本排序）
     */
    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) => {
            const field = dataModel.fieldMap[col.dataIndex];
            if (!(0, table_column_feature_utils_1.canUseInToolbar)(field, col))
                return false;
            const effective = (0, table_column_feature_utils_1.getToolbarFieldSchema)(field, col);
            return (0, fieldSortUtils_1.isSortableField)(effective, col);
        }).map((col) => col.dataIndex);
    }, [dataModel.columnDefinitions, dataModel.fieldMap]);
    /**
     * 字段选项列表（用于下拉选择组件）
     * 将字段ID数组转换为下拉选择组件需要的选项格式
     * @returns {Array<{label: string, value: string, fieldType: string}>} 选项对象数组
     * @description 基于 filteredFieldIds 生成，用于 CnAsyncSelect 组件的 dataSource 属性
     */
    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 getFieldOptionsForIndex = (index) => {
        // 获取其他条件已使用的字段（排除当前行）
        const usedFields = sortConditions
            .map((condition, idx) => (idx !== index ? condition.field : ''))
            .filter((field) => field);
        // 返回所有字段选项，但标记已被其他条件使用的字段为禁用
        return fieldOptions.map((option) => ({
            ...option,
            disabled: usedFields.includes(option.value),
        }));
    };
    const sortIdCounter = react_1.default.useRef(0);
    const genSortId = () => `sort-${sortIdCounter.current++}`;
    const currentSort = viewConfig.sort || [];
    const [sortConditions, setSortConditions] = (0, react_1.useState)(currentSort.length > 0
        ? currentSort
            .map((s) => ({
            field: s.field || '',
            order: s.order || 'asc',
            _id: genSortId(),
        }))
            // 过滤掉字段为空的排序条件
            .filter((s) => s.field)
        : []);
    /**
     * 排序规则数量
     */
    const sortCount = sortConditions.length;
    // ============================= Sync Config =============================
    /**
     * 同步 viewConfig.sort 的变化到内部状态
     * 当外部配置变化时，更新内部状态
     */
    react_1.default.useEffect(() => {
        const sortFromConfig = viewConfig.sort || [];
        setSortConditions((prev) => {
            const filtered = sortFromConfig
                .map((s) => ({
                field: s.field || '',
                order: (s.order || 'asc'),
            }))
                .filter((s) => s.field);
            // 按 index 匹配复用旧 _id:同位置且 (field, order) 一致则保留,
            // 否则视为新增/替换并生成新 _id。这样自身 reorder/remove/update
            // 触发的回流不会让条件项整体重新挂载。
            return filtered.map((s, i) => {
                const old = prev[i];
                const same = old && old.field === s.field && old.order === s.order;
                return { ...s, _id: same ? old._id : genSortId() };
            });
        });
    }, [viewConfig.sort]);
    // ============================= Update Config =============================
    /**
     * 实时更新排序配置
     * 将排序条件同步到 viewConfig 并触发回调
     */
    const updateSortConfig = (conditions) => {
        // 过滤掉字段为空的条件,并剥离仅供本地拖拽使用的 _id
        const validConditions = conditions
            .filter((condition) => condition.field)
            .map(({ field, order }) => ({ field, order }));
        if (validConditions.length > 0) {
            // 直接更新 viewConfig
            dataModel.setViewConfig(viewId, {
                sort: validConditions,
            });
            // 注意：不调用 onSortChange，因为已经直接更新了 viewConfig.sort
            // viewConfig.sort 的变化会通过 useEffect 同步，避免所有字段使用同一个 order
        }
        else {
            // 如果所有条件都无效，清除排序
            dataModel.setViewConfig(viewId, {
                sort: [],
            });
            onSortChange === null || onSortChange === void 0 ? void 0 : onSortChange('', 'asc');
        }
    };
    // ============================= Events =============================
    /**
     * 添加排序条件
     */
    const handleAddSortCondition = () => {
        (0, arms_hot_tag_log_1.armsHottagLog)({
            hottag: 'cn-ai-table.sort.addCondition',
            name: i18n_1.default.get({ id: 'AddCondition', dm: '添加条件' }),
        });
        // 获取当前已使用的字段
        const usedFields = sortConditions.map((c) => c.field).filter(Boolean);
        // 找到第一个未被使用的可用字段
        const firstAvailableField = (filteredFieldIds === null || filteredFieldIds === void 0 ? void 0 : filteredFieldIds.find((fieldId) => !usedFields.includes(fieldId))) || '';
        const newConditions = [
            ...sortConditions,
            { field: firstAvailableField, order: 'asc', _id: genSortId() },
        ];
        setSortConditions(newConditions);
        // 如果选中了字段，立即更新配置
        if (firstAvailableField) {
            updateSortConfig(newConditions);
        }
        onAddCondition === null || onAddCondition === void 0 ? void 0 : onAddCondition();
    };
    /**
     * 删除排序条件
     */
    const handleRemoveSortCondition = (index) => {
        (0, arms_hot_tag_log_1.armsHottagLog)({
            hottag: 'cn-ai-table.sort.removeCondition',
            name: i18n_1.default.get({ id: 'DeleteCondition', dm: '删除条件' }),
            c7: index,
        });
        const newConditions = sortConditions.filter((_, i) => i !== index);
        setSortConditions(newConditions);
        onAddCondition === null || onAddCondition === void 0 ? void 0 : onAddCondition();
        updateSortConfig(newConditions);
        // 如果条件被清空，通知工具栏隐藏通知栏
        if (newConditions.length === 0) {
            onConditionCleared === null || onConditionCleared === void 0 ? void 0 : onConditionCleared();
        }
    };
    /**
     * 拖拽重排排序条件
     */
    const handleReorderSortCondition = (fromIndex, toIndex) => {
        const newConditions = [...sortConditions];
        const [moved] = newConditions.splice(fromIndex, 1);
        newConditions.splice(toIndex, 0, moved);
        setSortConditions(newConditions);
        updateSortConfig(newConditions);
        onAddCondition === null || onAddCondition === void 0 ? void 0 : onAddCondition();
    };
    /**
     * 更新排序条件的字段
     */
    const handleUpdateSortField = (index, field) => {
        (0, arms_hot_tag_log_1.armsHottagLog)({
            hottag: 'cn-ai-table.sort.updateField',
            name: i18n_1.default.get({ id: 'UpdateField', dm: '更新字段' }),
            c6: field,
            c7: index,
        });
        const newConditions = [...sortConditions];
        newConditions[index] = { ...newConditions[index], field };
        setSortConditions(newConditions);
        updateSortConfig(newConditions);
        // 切换字段时触发通知提示
        onAddCondition === null || onAddCondition === void 0 ? void 0 : onAddCondition();
    };
    /**
     * 更新排序条件的排序方式
     */
    const handleUpdateSortOrder = (index, order) => {
        (0, arms_hot_tag_log_1.armsHottagLog)({
            hottag: 'cn-ai-table.sort.updateOrder',
            name: i18n_1.default.get({ id: 'UpdateSortMethod', dm: '更新排序方式' }),
            c6: order,
            c7: index,
        });
        const newConditions = [...sortConditions];
        newConditions[index] = { ...newConditions[index], order };
        setSortConditions(newConditions);
        updateSortConfig(newConditions);
        // 切换排序方式时触发通知提示
        onAddCondition === null || onAddCondition === void 0 ? void 0 : onAddCondition();
    };
    /**
     * 获取字段类型
     * @param fieldId 字段ID
     * @returns 'dateTime' | 'number' | 'text' | 'other'
     */
    const getFieldType = (fieldId) => {
        if (!fieldId)
            return 'other';
        const field = dataModel.fieldMap[fieldId];
        if (!field)
            return 'other';
        const componentType = field['x-component'] || 'Input';
        // 检查是否是日期时间类型
        if (component_types_1.DATE_TIME_COMPONENT_TYPES.includes(componentType)) {
            return 'dateTime';
        }
        // 检查是否是数值类型
        if (component_types_1.NUMBER_COMPONENT_TYPES.includes(componentType)) {
            return 'number';
        }
        // 检查是否是文本类型
        if (component_types_1.TEXT_COMPONENT_TYPES.includes(componentType)) {
            return 'text';
        }
        return 'other';
    };
    /**
     * 根据字段类型和排序方式获取按鈕文本
     * @param fieldId 字段ID
     * @param order 排序方式
     * @returns 按鈕文本
     */
    const getSortButtonText = (fieldId, order) => {
        const fieldType = getFieldType(fieldId);
        if (fieldType === 'dateTime') {
            return order === 'asc'
                ? i18n_1.default.get({ id: 'EarlyLate', dm: '早 → 晚' })
                : i18n_1.default.get({ id: 'LateEarly', dm: '晚 → 早' });
        }
        if (fieldType === 'number') {
            return order === 'asc' ? '0 → 9' : '9 → 0';
        }
        // 文本类型：a-A（升序）/ A-a（降序）
        if (fieldType === 'text') {
            return order === 'asc' ? 'a → A' : 'A → a';
        }
        // 默认文本（其他类型）
        return order === 'asc' ? 'A → Z' : 'Z → A';
    };
    // ============================= Render =============================
    // 响应式紧凑模式下由按钮 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': sortCount > 0,
        }), onClick: isCompact ? handleTriggerClick : undefined },
        react_1.default.createElement("img", { src: icons.TOOLBAR_SORT, alt: i18n_1.default.get({ id: 'Sort', dm: '排序' }) }),
        react_1.default.createElement("span", null,
            i18n_1.default.get({ id: 'Sort', dm: '排序' }),
            sortCount > 0 ? `(${sortCount})` : '')));
    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: 'Sort', dm: '排序' }), disableTooltip: panelVisible }, buttonElement)) : (buttonElement), title: i18n_1.default.get({ id: 'SortByTheFollowingCriteria', dm: '按以下条件排序' }), conditions: sortConditions, conditionCount: sortCount, addButtonText: i18n_1.default.get({ id: 'AddSortCriteria', dm: '添加排序条件' }), onAdd: handleAddSortCondition, onRemove: handleRemoveSortCondition, onReorder: handleReorderSortCondition, getItemId: (condition) => condition._id, renderConditionItem: (condition, index) => (react_1.default.createElement(react_1.default.Fragment, null,
            react_1.default.createElement(cn_ui_1.CnAsyncSelect, { dataSource: getFieldOptionsForIndex(index), value: condition.field, onChange: (value) => handleUpdateSortField(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("div", { className: "sort-buttons-container" }, ['asc', 'desc'].map((order) => {
                const isActive = condition.order === order;
                return (react_1.default.createElement(cn_ui_1.CnButton, { key: order, text: true, type: isActive ? 'primary' : 'normal', onClick: () => handleUpdateSortOrder(index, order), className: (0, classnames_1.default)('sort-btn', {
                        [`sort-btn-${order}`]: isActive,
                        'sort-btn-normal': !isActive,
                    }) }, getSortButtonText(condition.field, order)));
            })))), keepVisible: keepVisible, active: sortCount > 0, viewId: viewId, currentPageHintText: i18n_1.default.get({ id: 'Sort', dm: '排序' }), showDivider: showDivider, shouldOpen: () => !((0, env_1.isBirda)() === false && (0, isEmpty_1.default)(dataModel.fieldMap)), popupClassName: "condition-popup-sort" }));
}
