import $i18n from '../../../../../../locales/i18n.js';
import React, { useState, useCallback, useMemo, useEffect } from 'react';
import { createPortal } from 'react-dom';
import classNames from 'classnames';
import { CnButton, CnIcon, CnInput, CnMessage, CnTooltip } from '@cainiaofe/cn-ui';
import { DndContext, closestCenter, KeyboardSensor, MouseSensor, TouchSensor, useSensor, useSensors, DragOverlay, } from '@dnd-kit/core';
import { arrayMove, SortableContext, sortableKeyboardCoordinates, useSortable, verticalListSortingStrategy, } from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import { event as eventBus } from '@ice/stark-data';
import { useModel } from '../../../../../../utils/mobx-react-simpler/index.js';
import { Popup } from '@cainiaofe/cn-domain-popup';
import { getPopupContainer } from '../../../../../../utils/floating-layer.js';
import { shouldKeepCol } from '../../../../../../utils/data/get-column-meta-data.js';
import { ToolbarDivider } from '../toolbar-divider';
import { getFieldComponentType, useFieldIcon, } from '../../../../../../cn-ai-table/view/utils/field-icon-utils';
import { useAiTableIcons } from '../../../../../../cn-ai-table/view/hooks/use-ai-table-icons';
import { FieldSelector } from '../../../../../../cn-ai-table/view/components/selectors/field-selector/field-selector';
import { getFieldSystem, } from '../../../../../../cn-ai-table/view/field-system';
import { useAiColumns } from '../../../../../../cn-ai-table/view/hooks';
import { useCnAiListEventNames } from '../../../../../../cn-ai-agent/context/cn-ai-list-event-context';
import { pickLookupCallbacks } from '../../../../../../cn-ai-table/types';
import { SvgIcon } from '../../../icons';
import { armsHottagLog } from '../../../../../../utils/arms/arms-hot-tag-log.js';
import './field-management-button.scss';
const FormulaIcon = CnIcon.createFromIconfontCN({
    scriptUrl: '//at.alicdn.com/t/a/font_4448706_i4lwtal07u.js',
});
// 最大固定列数量
const MAX_PINNED_COLUMNS = 3;
// 可拖拽的字段项组件
const SortableFieldItem = ({ field, onToggleVisible, onMoveToTop, onTogglePin, isFirst, canPin, canUnpin, }) => {
    const icons = useAiTableIcons();
    const getIcon = useFieldIcon();
    const [moreVisible, setMoreVisible] = useState(false);
    const isDragDisabled = field.isOnlyPinned;
    const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
        id: field.dataIndex,
        disabled: isDragDisabled,
    });
    const style = {
        transform: CSS.Transform.toString(transform),
        transition,
    };
    const handleToggleVisible = (e) => {
        e.stopPropagation();
        onToggleVisible(field.dataIndex);
    };
    const handleMoveToTop = () => {
        setMoreVisible(false);
        onMoveToTop(field.dataIndex);
    };
    const handleTogglePin = () => {
        setMoreVisible(false);
        onTogglePin(field.dataIndex);
    };
    // 判断是否可以显示固定按钮：非固定字段且可以添加固定，或者固定字段且可以取消固定
    const showPinOption = field.isPinned ? canUnpin : canPin;
    return (React.createElement("div", { ref: setNodeRef, style: style, className: classNames('field-management-item', {
            'field-management-item-dragging': isDragging,
            'field-management-item-pinned': field.isPinned,
            'field-management-item-only-pinned': field.isOnlyPinned,
            'field-management-item-hidden': !field.visible,
        }) },
        React.createElement("div", { className: classNames('field-management-item-drag-handle', {
                'field-management-item-drag-handle-disabled': isDragDisabled,
            }), ...(isDragDisabled ? {} : { ...attributes, ...listeners }) },
            React.createElement(CnIcon, { type: "bar", size: "medium" })),
        React.createElement("div", { className: "field-management-item-icon" }, field.isAiColumn ? (React.createElement("img", { src: icons.FIELD_AI, alt: $i18n.get({ id: 'AIField', dm: 'AI字段' }), style: { width: '16px', height: '16px' } })) : field.isFormulaColumn ? (React.createElement(FormulaIcon, { type: "icon-formula", style: { fontSize: '16px' } })) : (React.createElement("img", { src: getIcon(field.fieldType), alt: field.title, style: { width: '16px', height: '16px' } }))),
        React.createElement("div", { className: "field-management-item-name" }, field.title),
        field.isOnlyPinned && (React.createElement("div", { className: "field-management-item-lock" },
            React.createElement(CnIcon, { type: "lock", size: 16, color: "#999" }))),
        !field.isOnlyPinned && (React.createElement("div", { className: "field-management-item-actions" },
            React.createElement("div", { className: classNames('field-management-item-visibility', {
                    'field-management-item-visibility-off': !field.visible,
                }), onClick: handleToggleVisible },
                React.createElement(SvgIcon, { name: field.visible ? 'eye' : 'eyeClose', size: 16, color: "#333" })),
            React.createElement(Popup, { triggerType: "click", visible: moreVisible, onVisibleChange: setMoreVisible, trigger: React.createElement("div", { className: "field-management-item-more" },
                    React.createElement(CnIcon, { type: "menu", size: "medium" })), align: "bl", container: getPopupContainer },
                React.createElement("div", { className: "field-management-more-menu" },
                    !isFirst && !field.isPinned && (React.createElement("div", { className: "field-management-more-menu-item", onClick: handleMoveToTop },
                        React.createElement(CnIcon, { type: "arrow-up", size: "medium" }),
                        React.createElement("span", null, $i18n.get({ id: 'MoveToTop', dm: '移动到顶部' })))),
                    showPinOption && (React.createElement("div", { className: "field-management-more-menu-item", onClick: handleTogglePin },
                        React.createElement(CnIcon, { type: field.isPinned ? 'unlock' : 'pin', size: "medium" }),
                        React.createElement("span", null, field.isPinned
                            ? $i18n.get({ id: 'Unfreeze', dm: '取消固定' })
                            : $i18n.get({ id: 'FixedField', dm: '固定字段' }))))))))));
};
// 固定列区域的 droppable 组件
const PinnedDropArea = (props) => {
    const { children } = props;
    return (React.createElement("div", { className: "field-management-pinned-area", "data-droppable": "pinned" }, children));
};
export function FieldManagementButton({ viewId, onFieldVisibilityChange, onFieldOrderChange, isCompact = false, enableAiFields = true, enableLookup = true, enableFormula = true, }) {
    var _a, _b, _c, _d, _e;
    const cnAiListEventNames = useCnAiListEventNames();
    const icons = useAiTableIcons();
    const getIcon = useFieldIcon();
    const dataModel = useModel('dataModel');
    const [fieldVisible, setFieldVisible] = useState(false);
    const [searchValue, setSearchValue] = useState('');
    const [activeId, setActiveId] = useState(null);
    const [overPinnedArea, setOverPinnedArea] = useState(false);
    // 添加字段：选择器与配置面板状态
    const [selectorVisible, setSelectorVisible] = useState(false);
    const [activeDriverType, setActiveDriverType] = useState(null);
    const [selectedFieldLabel, setSelectedFieldLabel] = useState('');
    const viewConfig = dataModel.getViewConfig(viewId);
    // 固定字段ID集合（从 viewConfig 中获取）
    const [pinnedFieldIds, setPinnedFieldIds] = useState(() => {
        var _a, _b, _c;
        const savedPinnedIds = (_a = viewConfig.custom) === null || _a === void 0 ? void 0 : _a.pinnedFieldIds;
        if (Array.isArray(savedPinnedIds) && savedPinnedIds.length > 0) {
            return savedPinnedIds;
        }
        // 兼容旧数据：如果有 pinnedColumnsCount，根据 columnOrder 推断固定字段
        const legacyCount = (_c = (_b = viewConfig.custom) === null || _b === void 0 ? void 0 : _b.pinnedColumnsCount) !== null && _c !== void 0 ? _c : 1;
        const order = viewConfig.columnOrder || [];
        return order.slice(0, legacyCount);
    });
    // 同步 viewConfig 中的 pinnedFieldIds
    useEffect(() => {
        var _a, _b, _c;
        const savedPinnedIds = (_a = viewConfig.custom) === null || _a === void 0 ? void 0 : _a.pinnedFieldIds;
        if (Array.isArray(savedPinnedIds) && savedPinnedIds.length > 0) {
            setPinnedFieldIds(savedPinnedIds);
        }
        else {
            // 兼容旧数据
            const legacyCount = (_c = (_b = viewConfig.custom) === null || _b === void 0 ? void 0 : _b.pinnedColumnsCount) !== null && _c !== void 0 ? _c : 1;
            const order = viewConfig.columnOrder || [];
            if (order.length > 0) {
                setPinnedFieldIds(order.slice(0, legacyCount));
            }
        }
    }, [
        (_a = viewConfig.custom) === null || _a === void 0 ? void 0 : _a.pinnedFieldIds,
        (_b = viewConfig.custom) === null || _b === void 0 ? void 0 : _b.pinnedColumnsCount,
        viewConfig.columnOrder,
    ]);
    // 使用 AI 列管理 hook（只用于保存列配置）
    const { saveAiColumn, savingAiColumn, executingColumnTask } = useAiColumns({
        tableId: dataModel.tableId,
        enabled: enableAiFields,
        bizRequestConfig: {
            aiColumn: (_c = dataModel.bizRequestConfig) === null || _c === void 0 ? void 0 : _c.aiColumn,
            cubePlatform: (_d = dataModel.bizRequestConfig) === null || _d === void 0 ? void 0 : _d.cubePlatform,
        },
    });
    const { registry, orchestrator } = useMemo(() => getFieldSystem(), []);
    const buildContext = useCallback(() => {
        var _a;
        return {
            dataModel,
            viewId,
            bizRequestConfig: dataModel.bizRequestConfig,
            lookupFieldConfig: (_a = dataModel.lookupFieldConfig) !== null && _a !== void 0 ? _a : undefined,
            eventBus: { emit: (event, payload) => eventBus.emit(event, payload) },
            cnAiListEventNames,
            services: {
                aiColumn: {
                    saveAiColumn,
                    savingAiColumn,
                    executingColumnTask,
                },
                lookup: pickLookupCallbacks(dataModel.lookupFieldConfig),
            },
        };
    }, [dataModel, viewId, cnAiListEventNames, saveAiColumn, savingAiColumn, executingColumnTask]);
    const selectorItems = useMemo(() => {
        let items = registry.getSelectorItems();
        if (!enableAiFields) {
            items = items.filter((item) => item.category !== 'ai' && item.category !== 'agent');
        }
        if (!enableLookup) {
            items = items.filter((item) => item.type !== 'lookup');
        }
        if (!enableFormula) {
            items = items.filter((item) => item.type !== 'formula');
        }
        return items;
    }, [registry, enableAiFields, enableLookup, enableFormula]);
    const addFieldActive = selectorVisible || activeDriverType !== null;
    const resetSelection = useCallback(() => {
        setActiveDriverType(null);
        setSelectedFieldLabel('');
    }, []);
    const closeAddField = useCallback(() => {
        setSelectorVisible(false);
        resetSelection();
    }, [resetSelection]);
    // 获取所有过滤后的字段ID列表（与 getViewColumns 保持一致）
    // 改造后：AI 列使用表级 customFields.aiColumns 判断，不再依赖视图级 aiColumns
    const filteredFieldIds = useMemo(() => {
        var _a, _b;
        const aiColumnSet = new Set(dataModel.aiColumns.map((col) => col.columnCode));
        const customAiColumnSet = new Set(((_a = dataModel.customFields) === null || _a === void 0 ? void 0 : _a.aiColumns) || []);
        const newFilteredFieldIds = (_b = dataModel === null || dataModel === void 0 ? void 0 : dataModel.columnDefinitions) === null || _b === void 0 ? void 0 : _b.filter((col) => {
            if (col.isAiColumn || aiColumnSet.has(col.dataIndex)) {
                return customAiColumnSet.has(col.dataIndex);
            }
            return shouldKeepCol(col);
        }).map((col) => col.dataIndex);
        return newFilteredFieldIds;
    }, [dataModel.columnDefinitions, dataModel.aiColumns, dataModel.customFields]);
    // 字段顺序状态
    const [fieldOrder, setFieldOrder] = useState(() => {
        var _a;
        if (((_a = viewConfig.columnOrder) === null || _a === void 0 ? void 0 : _a.length) > 0) {
            // 只保留在 filteredFieldIds 中的字段（与 getViewColumns 保持一致）
            const order = viewConfig.columnOrder.filter((colId) => filteredFieldIds === null || filteredFieldIds === void 0 ? void 0 : filteredFieldIds.includes(colId));
            // 添加不在 columnOrder 中但在 filteredFieldIds 中的字段
            filteredFieldIds === null || filteredFieldIds === void 0 ? void 0 : filteredFieldIds.forEach((id) => {
                if (!order.includes(id)) {
                    order.push(id);
                }
            });
            return order;
        }
        return filteredFieldIds || [];
    });
    // 可见字段状态
    const [visibleFields, setVisibleFields] = useState(() => {
        var _a;
        // 使用 filteredFieldIds（已经过滤了未启用的 AI 列）
        const fullOrder = ((_a = viewConfig.columnOrder) === null || _a === void 0 ? void 0 : _a.length) > 0
            ? viewConfig.columnOrder.filter((colId) => filteredFieldIds === null || filteredFieldIds === void 0 ? void 0 : filteredFieldIds.includes(colId))
            : filteredFieldIds || [];
        if (viewConfig.hiddenColumns && viewConfig.hiddenColumns.length > 0) {
            return fullOrder.filter((colId) => !viewConfig.hiddenColumns.includes(colId));
        }
        return fullOrder;
    });
    // 同步 viewConfig 变化
    useEffect(() => {
        var _a;
        // 使用 filteredFieldIds（已经过滤了未启用的 AI 列）
        const order = ((_a = viewConfig.columnOrder) === null || _a === void 0 ? void 0 : _a.length) > 0
            ? viewConfig.columnOrder.filter((colId) => filteredFieldIds === null || filteredFieldIds === void 0 ? void 0 : filteredFieldIds.includes(colId))
            : filteredFieldIds || [];
        const fullOrder = [...order];
        filteredFieldIds === null || filteredFieldIds === void 0 ? void 0 : filteredFieldIds.forEach((id) => {
            if (!fullOrder.includes(id)) {
                fullOrder.push(id);
            }
        });
        setFieldOrder(fullOrder);
        if (viewConfig.hiddenColumns && viewConfig.hiddenColumns.length > 0) {
            const visible = fullOrder.filter((colId) => !viewConfig.hiddenColumns.includes(colId));
            setVisibleFields(visible);
        }
        else {
            setVisibleFields(fullOrder);
        }
    }, [viewConfig.columnOrder, viewConfig.hiddenColumns, filteredFieldIds, dataModel, viewId]);
    // 构建字段列表
    const fieldList = useMemo(() => {
        // 计算可见的固定字段数量（页面必须至少有一个可见的固定字段）
        const visiblePinnedCount = pinnedFieldIds.filter((id) => visibleFields.includes(id)).length;
        const hasOnlyOneVisiblePinned = visiblePinnedCount === 1;
        const newFieldList = fieldOrder.map((dataIndex) => {
            var _a;
            const col = (_a = dataModel.columnDefinitions) === null || _a === void 0 ? void 0 : _a.find((c) => c.dataIndex === dataIndex);
            const isPinned = pinnedFieldIds.includes(dataIndex);
            const isVisible = visibleFields.includes(dataIndex);
            // 使用 getFieldComponentType 统一获取字段类型（支持系统字段）
            const fieldType = getFieldComponentType(dataModel.fieldMap, dataIndex, col === null || col === void 0 ? void 0 : col.format);
            return {
                dataIndex,
                title: (col === null || col === void 0 ? void 0 : col.title) || dataIndex,
                visible: isVisible,
                isPinned, // 基于字段ID判断是否固定
                // 唯一可见固定字段标识：当这是唯一可见的固定字段时，不能隐藏它
                isOnlyPinned: isPinned && isVisible && hasOnlyOneVisiblePinned,
                fieldType,
                isAiColumn: (col === null || col === void 0 ? void 0 : col.isAiColumn) || false,
                isFormulaColumn: (col === null || col === void 0 ? void 0 : col.format) === 'formula',
            };
        });
        return newFieldList;
    }, [fieldOrder, visibleFields, pinnedFieldIds, dataModel.columnDefinitions, dataModel.fieldMap]);
    // 分离固定列和非固定列
    const { pinnedFields, unpinnedFields } = useMemo(() => {
        const pinned = fieldList.filter((f) => f.isPinned);
        const unpinned = fieldList.filter((f) => !f.isPinned);
        return { pinnedFields: pinned, unpinnedFields: unpinned };
    }, [fieldList]);
    // 过滤后的字段列表（搜索）
    const filteredPinnedFields = useMemo(() => {
        if (!searchValue) {
            return pinnedFields;
        }
        return pinnedFields.filter((field) => {
            var _a, _b;
            return ((_a = field.title) === null || _a === void 0 ? void 0 : _a.toLowerCase().includes(searchValue === null || searchValue === void 0 ? void 0 : searchValue.toLowerCase())) ||
                ((_b = field.dataIndex) === null || _b === void 0 ? void 0 : _b.toLowerCase().includes(searchValue === null || searchValue === void 0 ? void 0 : searchValue.toLowerCase()));
        });
    }, [pinnedFields, searchValue]);
    const filteredUnpinnedFields = useMemo(() => {
        if (!searchValue) {
            return unpinnedFields;
        }
        return unpinnedFields.filter((field) => {
            var _a, _b;
            return ((_a = field.title) === null || _a === void 0 ? void 0 : _a.toLowerCase().includes(searchValue === null || searchValue === void 0 ? void 0 : searchValue.toLowerCase())) ||
                ((_b = field.dataIndex) === null || _b === void 0 ? void 0 : _b.toLowerCase().includes(searchValue === null || searchValue === void 0 ? void 0 : searchValue.toLowerCase()));
        });
    }, [unpinnedFields, searchValue]);
    // 拖拽传感器
    const sensors = useSensors(useSensor(MouseSensor, { activationConstraint: { distance: 5 } }), useSensor(TouchSensor, { activationConstraint: { distance: 5 } }), useSensor(KeyboardSensor, {
        coordinateGetter: sortableKeyboardCoordinates,
    }));
    // 保存配置
    const saveConfig = useCallback((newFieldOrder, newVisibleFields, newPinnedIds) => {
        const hiddenColumns = newFieldOrder.filter((id) => !newVisibleFields.includes(id));
        // 使用当前的 pinnedFieldIds 或新传入的
        const effectivePinnedIds = newPinnedIds !== null && newPinnedIds !== void 0 ? newPinnedIds : pinnedFieldIds;
        // 计算可见的固定字段数量（表格组件使用这个值来固定列）
        const visiblePinnedCount = effectivePinnedIds.filter((id) => newVisibleFields.includes(id)).length;
        const configUpdate = {
            columnOrder: newFieldOrder,
            hiddenColumns,
            custom: {
                ...viewConfig.custom,
                pinnedFieldIds: effectivePinnedIds,
                // pinnedColumnsCount 表示可见的固定列数量，供表格组件使用
                pinnedColumnsCount: visiblePinnedCount,
            },
        };
        dataModel.setViewConfig(viewId, configUpdate, true);
        onFieldVisibilityChange === null || onFieldVisibilityChange === void 0 ? void 0 : onFieldVisibilityChange(newVisibleFields);
        onFieldOrderChange === null || onFieldOrderChange === void 0 ? void 0 : onFieldOrderChange(newFieldOrder);
    }, [
        viewId,
        dataModel,
        viewConfig.custom,
        pinnedFieldIds,
        onFieldVisibilityChange,
        onFieldOrderChange,
    ]);
    // 处理拖拽开始
    const handleDragStart = (event) => {
        setActiveId(event.active.id);
    };
    // 处理拖拽过程
    const handleDragOver = (event) => {
        const { over } = event;
        if (!over) {
            setOverPinnedArea(false);
            return;
        }
        // 检查是否拖拽到固定区域（基于字段ID判断）
        const overId = over.id;
        const isOverPinned = pinnedFieldIds.includes(overId);
        setOverPinnedArea(isOverPinned);
    };
    // 处理拖拽结束
    const handleDragEnd = (event) => {
        const { active, over } = event;
        setActiveId(null);
        setOverPinnedArea(false);
        if (!active || !over || active.id === over.id) {
            return;
        }
        const dragActiveId = active.id;
        const dragOverId = over.id;
        const activeIndex = fieldOrder.indexOf(dragActiveId);
        const overIndex = fieldOrder.indexOf(dragOverId);
        if (activeIndex === -1 || overIndex === -1) {
            return;
        }
        // 基于字段ID判断是否在固定区域
        const isActiveInPinned = pinnedFieldIds.includes(dragActiveId);
        const isOverInPinned = pinnedFieldIds.includes(dragOverId);
        let newOrder = [...fieldOrder];
        let newPinnedIds = [...pinnedFieldIds];
        let dragAction = '';
        if (!isActiveInPinned && isOverInPinned) {
            // 从非固定区拖到固定区 - 固定该字段
            dragAction = 'pin';
            if (pinnedFieldIds.length >= MAX_PINNED_COLUMNS) {
                // 已达到最大固定数（3个），将新字段加入固定，移除最老的固定字段
                newPinnedIds = newPinnedIds.slice(1); // 移除第一个（最老的）
                newPinnedIds.push(dragActiveId);
                newOrder = arrayMove(newOrder, activeIndex, overIndex);
            }
            else {
                // 未达到最大固定数，增加固定列
                newPinnedIds.push(dragActiveId);
                newOrder = arrayMove(newOrder, activeIndex, overIndex);
            }
        }
        else if (isActiveInPinned && !isOverInPinned) {
            // 从固定区拖到非固定区 - 取消固定
            if (pinnedFieldIds.length <= 1) {
                // 至少保留一个固定字段
                CnMessage.warning($i18n.get({ id: 'AtLeastOneFixedFieldNeedsToBe', dm: '至少需要保留一个固定字段' }));
                return;
            }
            dragAction = 'unpin';
            // 从固定列表中移除
            newPinnedIds = newPinnedIds.filter((id) => id !== dragActiveId);
            newOrder = arrayMove(newOrder, activeIndex, overIndex);
        }
        else {
            // 同区域内拖拽 - 只改变顺序，不改变固定状态
            dragAction = 'reorder';
            newOrder = arrayMove(newOrder, activeIndex, overIndex);
        }
        const dragActionNameMap = {
            pin: $i18n.get({ id: 'DragAndDropAFixedField', dm: '拖拽固定字段' }),
            unpin: $i18n.get({ id: 'DragToUnfix', dm: '拖拽取消固定' }),
            reorder: $i18n.get({ id: 'DraganddropSortField', dm: '拖拽排序字段' }),
        };
        armsHottagLog({
            hottag: `cn-ai-table.fieldManagement.${dragAction}`,
            name: dragActionNameMap[dragAction] || $i18n.get({ id: 'DragField', dm: '拖拽字段' }),
            c6: dragActiveId,
            c7: dragOverId,
        });
        setFieldOrder(newOrder);
        setPinnedFieldIds(newPinnedIds);
        saveConfig(newOrder, visibleFields, newPinnedIds);
    };
    // 切换字段可见性
    const handleToggleFieldVisible = useCallback((dataIndex) => {
        const isVisible = visibleFields.includes(dataIndex);
        armsHottagLog({
            hottag: 'cn-ai-table.fieldManagement.toggleVisible',
            name: isVisible
                ? $i18n.get({ id: 'HideField', dm: '隐藏字段' })
                : $i18n.get({ id: 'DisplayFields', dm: '显示字段' }),
            c6: dataIndex,
        });
        const newVisibleFields = isVisible
            ? visibleFields.filter((id) => id !== dataIndex)
            : [...visibleFields, dataIndex];
        setVisibleFields(newVisibleFields);
        saveConfig(fieldOrder, newVisibleFields);
    }, [visibleFields, fieldOrder, saveConfig]);
    // 移动到顶部（非固定区的顶部）
    const handleMoveToTop = useCallback((dataIndex) => {
        // 非固定字段才能移动到顶部
        if (pinnedFieldIds.includes(dataIndex))
            return;
        armsHottagLog({
            hottag: 'cn-ai-table.fieldManagement.moveToTop',
            name: $i18n.get({ id: 'MoveToTop', dm: '移动到顶部' }),
            c6: dataIndex,
        });
        const currentIndex = fieldOrder.indexOf(dataIndex);
        // 找到第一个非固定字段的位置
        const firstUnpinnedIndex = fieldOrder.findIndex((id) => !pinnedFieldIds.includes(id));
        if (currentIndex > firstUnpinnedIndex) {
            const newOrder = arrayMove(fieldOrder, currentIndex, firstUnpinnedIndex);
            setFieldOrder(newOrder);
            saveConfig(newOrder, visibleFields);
        }
    }, [fieldOrder, pinnedFieldIds, visibleFields, saveConfig]);
    // 切换固定状态
    const handleTogglePin = useCallback((dataIndex) => {
        const isPinned = pinnedFieldIds.includes(dataIndex);
        let newPinnedIds = [...pinnedFieldIds];
        let newFieldOrder = [...fieldOrder];
        if (isPinned) {
            // 取消固定
            if (pinnedFieldIds.length <= 1) {
                CnMessage.warning($i18n.get({ id: 'AtLeastOneFixedFieldNeedsToBe', dm: '至少需要保留一个固定字段' }));
                return;
            }
            armsHottagLog({
                hottag: 'cn-ai-table.fieldManagement.unpin',
                name: $i18n.get({ id: 'Unfreeze', dm: '取消固定' }),
                c6: dataIndex,
            });
            newPinnedIds = newPinnedIds.filter((id) => id !== dataIndex);
            // 重新排列 columnOrder，确保固定字段在前面
            // 1. 获取所有固定字段（保持在 fieldOrder 中的相对顺序）
            const pinnedColumns = fieldOrder.filter((id) => newPinnedIds.includes(id));
            // 2. 获取所有非固定字段（保持在 fieldOrder 中的相对顺序）
            const unpinnedColumns = fieldOrder.filter((id) => !newPinnedIds.includes(id));
            // 3. 固定字段在前，非固定字段在后
            newFieldOrder = [...pinnedColumns, ...unpinnedColumns];
        }
        else {
            // 固定
            if (pinnedFieldIds.length >= MAX_PINNED_COLUMNS) {
                CnMessage.warning($i18n.get({
                    id: 'AMaximumOfMAXPINNEDCOLUMNSFields_28532551',
                    dm: '最多只能固定 {MAXPINNEDCOLUMNS} 个字段',
                }, { MAXPINNEDCOLUMNS: MAX_PINNED_COLUMNS }));
                return;
            }
            armsHottagLog({
                hottag: 'cn-ai-table.fieldManagement.pin',
                name: $i18n.get({ id: 'FixedField', dm: '固定字段' }),
                c6: dataIndex,
            });
            newPinnedIds.push(dataIndex);
            // 重新排列 columnOrder，确保固定字段在前面
            // 1. 获取所有固定字段（保持在 fieldOrder 中的相对顺序）
            const pinnedColumns = fieldOrder.filter((id) => newPinnedIds.includes(id));
            // 2. 获取所有非固定字段（保持在 fieldOrder 中的相对顺序）
            const unpinnedColumns = fieldOrder.filter((id) => !newPinnedIds.includes(id));
            // 3. 固定字段在前，非固定字段在后
            newFieldOrder = [...pinnedColumns, ...unpinnedColumns];
        }
        setPinnedFieldIds(newPinnedIds);
        setFieldOrder(newFieldOrder);
        saveConfig(newFieldOrder, visibleFields, newPinnedIds);
    }, [fieldOrder, pinnedFieldIds, visibleFields, saveConfig]);
    // 获取正在拖拽的字段
    const activeField = useMemo(() => {
        if (!activeId)
            return null;
        return fieldList.find((f) => f.dataIndex === activeId);
    }, [activeId, fieldList]);
    // 计算隐藏字段数量
    const hiddenCount = useMemo(() => {
        var _a;
        return ((_a = viewConfig.hiddenColumns) === null || _a === void 0 ? void 0 : _a.length) || 0;
    }, [viewConfig.hiddenColumns]);
    // 是否可以添加更多固定列
    const canAddPinnedColumn = pinnedFieldIds.length < MAX_PINNED_COLUMNS;
    // 是否可以取消固定（至少保留一个固定字段）
    const canUnpinColumn = pinnedFieldIds.length > 1;
    const handleFieldSelect = useCallback(async (fieldType) => {
        const driver = registry.get(fieldType);
        if (!driver)
            return;
        const meta = driver.getMeta();
        const ui = driver.getUiContribution();
        armsHottagLog({
            hottag: 'cn-ai-table.addField.selectField',
            name: $i18n.get({ id: 'SelectField', dm: '选择字段' }),
            c6: fieldType,
        });
        if (ui.panelKind === 'inline' && ui.createPanel) {
            setActiveDriverType(fieldType);
            setSelectedFieldLabel(meta.label);
            setSelectorVisible(false);
        }
        else {
            const result = await orchestrator.createField(fieldType, {}, buildContext());
            if (result.success) {
                closeAddField();
            }
        }
    }, [registry, orchestrator, buildContext, closeAddField]);
    const handleDriverPanelSave = useCallback(async (config) => {
        if (!activeDriverType)
            return;
        const result = await orchestrator.createField(activeDriverType, config, buildContext());
        if (result.success) {
            closeAddField();
            setFieldVisible(false);
        }
    }, [activeDriverType, orchestrator, buildContext, closeAddField]);
    const handleDriverPanelCancel = useCallback(() => {
        if (activeDriverType) {
            const driver = registry.get(activeDriverType);
            const meta = driver === null || driver === void 0 ? void 0 : driver.getMeta();
            if ((meta === null || meta === void 0 ? void 0 : meta.category) === 'ai' || (meta === null || meta === void 0 ? void 0 : meta.category) === 'agent') {
                armsHottagLog({
                    hottag: 'cn-ai-table.fieldManagement.cancelAddAiField',
                    name: $i18n.get({ id: 'UnaddAIField', dm: '取消添加AI字段' }),
                });
            }
            if ((meta === null || meta === void 0 ? void 0 : meta.type) === 'lookup') {
                armsHottagLog({
                    hottag: 'cn-ai-table.addField.cancelLookupField',
                    name: $i18n.get({ id: 'RemoveAddedCitationField', dm: '取消添加引用字段' }),
                });
            }
            if ((meta === null || meta === void 0 ? void 0 : meta.type) === 'formula') {
                armsHottagLog({
                    hottag: 'cn-ai-table.fieldManagement.cancelAddFormulaField',
                    name: $i18n.get({ id: 'CancelAddingFormulaField', dm: '取消添加公式字段' }),
                });
            }
        }
        closeAddField();
    }, [activeDriverType, registry, closeAddField]);
    const handleOpenSelector = useCallback((e) => {
        e.stopPropagation();
        if (activeDriverType) {
            closeAddField();
            return;
        }
        armsHottagLog({
            hottag: 'cn-ai-table.fieldManagement.addFieldClick',
            name: $i18n.get({ id: 'AddField', dm: '添加字段' }),
        });
        setSelectorVisible((visible) => !visible);
    }, [activeDriverType, closeAddField]);
    const activeDriver = activeDriverType ? registry.get(activeDriverType) : null;
    const ActivePanel = (_e = activeDriver === null || activeDriver === void 0 ? void 0 : activeDriver.getUiContribution().createPanel) !== null && _e !== void 0 ? _e : null;
    const handleFieldVisibleChange = useCallback((nextOpen) => {
        if (!nextOpen && addFieldActive) {
            return;
        }
        if (nextOpen) {
            armsHottagLog({
                hottag: 'cn-ai-table.fieldManagement.open',
                name: $i18n.get({ id: 'FieldManagement', dm: '字段管理' }),
            });
        }
        setFieldVisible(nextOpen);
    }, [addFieldActive]);
    // 所有字段的 ID 列表（用于 SortableContext）
    const allFieldIds = useMemo(() => {
        return [...filteredPinnedFields, ...filteredUnpinnedFields].map((f) => f.dataIndex);
    }, [filteredPinnedFields, filteredUnpinnedFields]);
    const buttonElement = (React.createElement(CnButton, { text: true, className: classNames('toolbar-btn', {
            'toolbar-btn-active': hiddenCount > 0,
        }) },
        React.createElement("img", { src: icons.TOOLBAR_FIELD_MANAGEMENT, alt: $i18n.get({ id: 'FieldManagement', dm: '字段管理' }) }),
        React.createElement("span", null,
            $i18n.get({ id: 'FieldManagement', dm: '字段管理' }),
            hiddenCount > 0
                ? $i18n.get({
                    id: 'HiddenCountHidden',
                    dm: '({hiddenCount}隐藏)',
                }, { hiddenCount })
                : '')));
    return (React.createElement(React.Fragment, null,
        React.createElement(Popup, { triggerType: "click", visible: fieldVisible, onVisibleChange: handleFieldVisibleChange, trigger: isCompact ? (React.createElement(CnTooltip, { trigger: buttonElement, triggerType: "hover", align: "b", popupProps: fieldVisible ? { visible: false } : undefined }, $i18n.get({ id: 'FieldManagement', dm: '字段管理' }))) : (buttonElement), align: "bl", offset: { mainAxis: 10 }, container: getPopupContainer },
            React.createElement("div", { className: "field-management-popup" },
                React.createElement("div", { className: "field-management-search" },
                    React.createElement(CnIcon, { type: "search", size: "medium", className: "field-management-search-icon" }),
                    React.createElement(CnInput, { value: searchValue, onChange: setSearchValue, placeholder: $i18n.get({ id: 'Search', dm: '搜索' }), hasClear: true, className: "field-management-search-input" })),
                React.createElement("div", { className: "field-management-list" },
                    React.createElement(DndContext, { sensors: sensors, collisionDetection: closestCenter, onDragStart: handleDragStart, onDragOver: handleDragOver, onDragEnd: handleDragEnd },
                        React.createElement(SortableContext, { items: allFieldIds.filter((item) => item !== null), strategy: verticalListSortingStrategy },
                            React.createElement(PinnedDropArea, null, filteredPinnedFields.map((field, index) => (React.createElement(SortableFieldItem, { key: field.dataIndex, field: field, onToggleVisible: handleToggleFieldVisible, onMoveToTop: handleMoveToTop, onTogglePin: handleTogglePin, isFirst: index === 0, canPin: canAddPinnedColumn, canUnpin: canUnpinColumn })))),
                            React.createElement("div", { className: classNames('field-management-unpinned-area', {
                                    'field-management-unpinned-area-highlight': overPinnedArea,
                                }) }, filteredUnpinnedFields.map((field) => (React.createElement(SortableFieldItem, { key: field.dataIndex, field: field, onToggleVisible: handleToggleFieldVisible, onMoveToTop: handleMoveToTop, onTogglePin: handleTogglePin, isFirst: false, canPin: canAddPinnedColumn, canUnpin: canUnpinColumn }))))),
                        createPortal(React.createElement(DragOverlay, null, activeField ? (React.createElement("div", { className: classNames('field-management-drag-overlay', {
                                'field-management-drag-overlay-pin': overPinnedArea && !activeField.isPinned,
                            }) },
                            React.createElement("div", { className: "field-management-item-icon" }, activeField.isAiColumn ? (React.createElement("img", { src: icons.FIELD_AI, alt: $i18n.get({ id: 'AIField', dm: 'AI字段' }), style: { width: '16px', height: '16px' } })) : activeField.isFormulaColumn ? (React.createElement(FormulaIcon, { type: "icon-formula", style: { fontSize: '16px' } })) : (React.createElement("img", { src: getIcon(activeField.fieldType), alt: activeField.title }))),
                            React.createElement("div", { className: "field-management-item-name" }, activeField.title),
                            overPinnedArea && !activeField.isPinned && (React.createElement(CnIcon, { type: "pin", size: "small", className: "field-management-drag-overlay-pin-hint" })))) : null), document.body))),
                React.createElement("div", { className: "field-management-footer" },
                    React.createElement(Popup, { visible: addFieldActive, onVisibleChange: (visible) => {
                            if (!visible) {
                                closeAddField();
                            }
                        }, trigger: React.createElement("div", { className: "field-management-add-field", onClick: handleOpenSelector },
                            React.createElement(CnIcon, { type: "add", size: "medium" }),
                            React.createElement("span", null, $i18n.get({ id: 'AddField', dm: '添加字段' }))), align: "rb", offset: { mainAxis: 20 }, container: getPopupContainer },
                        selectorVisible ? (React.createElement(FieldSelector, { enableAiFields: enableAiFields, items: selectorItems, onSelect: handleFieldSelect })) : null,
                        ActivePanel && activeDriverType ? (React.createElement(ActivePanel, { fieldType: activeDriverType, fieldLabel: selectedFieldLabel, context: buildContext(), onSave: handleDriverPanelSave, onCancel: handleDriverPanelCancel })) : null)))),
        React.createElement(ToolbarDivider, null)));
}
