import $i18n from '../../../../../../locales/i18n.js';
/**
 * @file NormalTableView 组件
 * @description 普通表格视图组件，支持虚拟滚动、列/行拖拽、单元格编辑、AI字段等功能
 *
 * 主要功能：
 * - 虚拟滚动：使用 padding 方式实现大数据量渲染，避免 transform 影响边框
 * - 拖拽排序：支持列拖拽重排和行拖拽排序
 * - 单元格编辑：支持普通字段和AI字段的编辑
 * - 行选择：支持单选/多选模式，包含全选功能
 * - 固定列：支持左侧固定列（sticky）
 * - 操作列：支持右侧固定操作列
 * - AI列：支持AI字段的生成、编辑和重新生成
 *
 * 组件结构：
 * - DraggableRow：可拖拽的数据行组件
 * - EditFieldPanelPopup：字段编辑配置弹窗组件（由 driver.editPanel 驱动）
 * - NormalTableView：主表格视图组件
 */
import * as React from 'react';
import { observer } from 'mobx-react-lite';
// classNames 已移至 DraggableRow 组件
import { event as eventBus } from '@ice/stark-data';
import { useCnAiListEventNames, useCnAiListInstanceKey, } from '../../../../../../cn-ai-agent/context/cn-ai-list-event-context';
import { CN_AI_LIST_INSTANCE_KEY_DATA_ATTR } from '../../../../../../cn-ai-agent/constants/event-constants';
import { DEFAULT_PRIMARY_KEY, safeGetRowKey, } from '../../../../../../cn-ai-table/view/utils/primary-key';
import '../table-view.scss';
import './normal-table-view.scss';
// import { flexRender } from '../../../../../../cn-ai-table/react-table'; // 用于 tfoot（已注释）
// ColumnDef 和 Table 类型已移至 ../types/normal-table-view.ts
import { useCellFormat } from '../../../../../hooks/useCellFormat';
import { useCellEditing } from '../../../../../hooks/useCellEditing';
// useVirtualizer 已移至 useVirtualScroll Hook
import { formilyCore, CnMessage, CnCheckbox, CnTooltip } from '@cainiaofe/cn-ui';
import { useModel } from '../../../../../../utils/mobx-react-simpler/index.js';
import { updateRecord, queryRecord } from '../../../../../../plugins/cn-ai-table-plugin/service/birda-request.js';
import { ADDRESS_SELECT_COMPONENT_TYPES, DEPARTMENT_SELECT_COMPONENT_TYPES, } from '../../../../../../cn-ai-table/view/constants/component-types';
// getCellColorFill, componentAdapterMap, DropdownFormItem 已移至 DraggableRow 组件
import { ColumnHeaderMenuPopup } from './column-header-menu/column-header-menu';
import { useColumnHeaderMenu } from './column-header-menu/useColumnHeaderMenu';
import { handleSortAsc, handleSortDesc, handleFillColor, handleGroupBy, handleFilterBy, handleFreezeToColumn, handleUnfreezeColumn, deleteFieldViaSystem, getEditConfigViaSystem, } from '../utils/columnHeaderMenuUtils';
import { getFieldSystem } from '../../../../../../cn-ai-table/view/field-system';
import { pickLookupCallbacks } from '../../../../../../cn-ai-table/types';
import { armsHottagLog } from '../../../../../../utils/arms/arms-hot-tag-log.js';
import { useAiColumns } from '../../../../../../cn-ai-table/view/hooks';
import { parsePromptVariables, buildPromptParamsWithExtractor, } from '../../../../../../cn-ai-table/view/components/toolbar/components/add-field/utils/prompt-utils';
import { updateAiCellData } from '../../../../../../cn-ai-table/view/services/ai-column-service';
import { AI_GENERATING_MARKER } from '../../../../../../cn-ai-table/view/constants/ai-cell-constants';
import { emitCellSelectEvent } from '../utils/cell-event-utils';
// 拖拽相关 - 使用封装的工具
import { DRAG_HANDLE_WIDTH, getActionColumnWidth, DraggableColumnHeader, ColumnDragPreview, RowDragPreview, useDragAndDrop, useDragModifiers, DndContext, SortableContext, verticalListSortingStrategy, horizontalListSortingStrategy, closestCenter, buildPinnedModel, resolvePinnedFieldIds, commitColumnOrder, commitRowOrderLocal, } from '../drag-utils';
// Pipeline 相关导入
import { usePipeline, runPlugins } from '../pipeline';
// 插件注册已移至 runPlugins() 内部的 ensurePluginsRegistered()，不再依赖 side-effect import
// AI 单元格操作按钮（包含内容弹窗）
import { AiCellActions } from './ai-cell-actions/ai-cell-actions';
import { useAiTableIcons } from '../../../../../../cn-ai-table/view/hooks/use-ai-table-icons';
// DraggableRow 组件已提取到独立文件
import { DraggableRow } from './draggable-row';
// 通用字段编辑面板弹窗（由 driver.editPanel 驱动）
import { EditFieldPanelPopup } from './edit-field-panel-popup';
// 自定义 Hooks
import { useVirtualScroll, useColumnResizeGuideLine } from './hooks';
const { createForm } = formilyCore;
// ================== 主组件 ==================
/**
 * 普通表格视图组件
 * @description 功能丰富的表格组件，支持虚拟滚动、拖拽、编辑、选择等功能
 */
export const NormalTableView = observer(({ viewId, table, rowHeight = 'low', showIndex = true, rowSelectionProps, widthMap: widthMapFromProps, operateColumn, customRowRenderer, customRows, onRowDragEnd, onShowFilterPanel, onShowSortPanel, onShowGroupPanel, onShowColorFillPanel, smartFollowNeedAttentionRowIds = [], maxGroupLevels = 1, enableAiFields = true, }) => {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w;
    const cnAiListEventNames = useCnAiListEventNames();
    const listInstanceKey = useCnAiListInstanceKey();
    const icons = useAiTableIcons();
    // ================== Refs ==================
    /** 表格容器 ref，用于虚拟滚动和拖拽定位 */
    const parentRef = React.useRef(null);
    /** 列宽拖拽参考线（副作用隔离到 useColumnResizeGuideLine） */
    const guideLineRef = useColumnResizeGuideLine(parentRef);
    /** 行选中清空函数 ref，供表头点击时清除行选中态 */
    const clearRowSelectionRef = React.useRef(() => { });
    // ================== 行选择配置解构 ==================
    const { hasSelect: rowSelectionEnabled = false, selectKeys = [], selectionType = 'multiple', isDisabled, primaryKey = DEFAULT_PRIMARY_KEY, } = rowSelectionProps || {};
    const selectedRowKeys = React.useMemo(() => (Array.isArray(selectKeys) ? selectKeys : []), [selectKeys]);
    // 使用 ref 保存最新的 isDisabled 函数，确保闭包中始终使用最新版本
    const isDisabledRef = React.useRef(isDisabled);
    isDisabledRef.current = isDisabled;
    // ================== 数据模型 ==================
    /** 数据模型，包含表格数据、列定义、视图配置等 */
    const dataModel = useModel('dataModel');
    // ================== 状态定义 ==================
    /** 当前选中的列ID，用于列高亮显示 */
    const [selectedColumnId, setSelectedColumnId] = React.useState(null);
    /** 统一字段编辑面板状态（由 driver.editPanel 驱动） */
    const [editFieldState, setEditFieldState] = React.useState({
        visible: false,
        fieldType: '',
        columnId: '',
        columnCode: '',
        fieldLabel: '',
        initialValue: undefined,
        EditPanel: null,
    });
    /**
     * 单元格编辑 hook
     * @description 管理单元格编辑状态和值更新
     */
    const { editingCell, setEditingValue, setEditingCell, handleCellClick, isEditing } = useCellEditing((rowId, columnId, value, originalRow) => {
        dataModel.updateCell(dataModel.getRowKey(originalRow), columnId, value);
    }, dataModel.columnDefinitions);
    /** 专业版（非鸟搭）场景下当前选中的单元格，非编辑态 */
    const [selectedCell, setSelectedCell] = React.useState(null);
    // ================== AI 列操作相关 ==================
    /**
     * 使用 AI 列管理 hook
     * @description 用于编辑时保存 AI 列配置和提交 AI 生成任务
     */
    const { saveAiColumn, savingAiColumn, submitColumnTasks, executingColumnTask } = useAiColumns({
        tableId: dataModel.tableId,
        enabled: enableAiFields,
        bizRequestConfig: {
            aiColumn: (_a = dataModel.bizRequestConfig) === null || _a === void 0 ? void 0 : _a.aiColumn,
            cubePlatform: (_b = dataModel.bizRequestConfig) === null || _b === void 0 ? void 0 : _b.cubePlatform,
        },
        onFinishedTasksUpdate: (newFinishedTasks) => {
            // 将 AI 任务结果批量合并到 AI 单元格数据层，触发表格数据刷新
            dataModel.mergeAiTaskResults(newFinishedTasks);
        },
    });
    const buildFieldSystemContext = React.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]);
    /**
     * 构建 AI 任务请求参数
     * @description 解析 prompt 模板中的变量，提取对应列的值，构建任务请求
     * @param columnCode - AI 列编码
     * @param targetRows - 目标数据行数组
     * @param config - AI 字段配置，包含 targetInfo（prompt 模板）
     * @returns SingleGridTaskSubmitRequest[] 任务请求数组
     */
    const buildTaskRequests = React.useCallback((columnCode, targetRows, config) => {
        const variables = parsePromptVariables(config.targetInfo);
        const allColumns = dataModel.columnDefinitions || [];
        const processedColumnMap = dataModel.processedColumnMap || new Map();
        const requests = [];
        let skippedCount = 0;
        targetRows.forEach((row, rowIndex) => {
            const rowKey = dataModel.getRowKeyStrict(row);
            if (rowKey == null) {
                skippedCount += 1;
                return;
            }
            requests.push({
                columnCode,
                rowId: String(rowKey),
                promptParams: buildPromptParamsWithExtractor(row, variables, allColumns, processedColumnMap, rowIndex),
            });
        });
        if (process.env.NODE_ENV !== 'production' && skippedCount > 0) {
            // eslint-disable-next-line no-console
            console.warn(`[cn-ai-table] buildTaskRequests: ${skippedCount} row(s) skipped because primaryKey value is missing.`);
        }
        return requests;
    }, [dataModel]);
    /**
     * 统一编辑字段配置保存
     * 走 orchestrator.editField()，driver 的 updateMeta / materializeData 承担差异化逻辑。
     */
    const handleEditFieldSave = React.useCallback(async (config) => {
        if (!editFieldState.visible || !editFieldState.fieldType)
            return;
        const { fieldType, columnId } = editFieldState;
        const { orchestrator } = getFieldSystem();
        const ctx = buildFieldSystemContext();
        const result = await orchestrator.editField(fieldType, columnId, config, ctx);
        if (result.success) {
            setEditFieldState((prev) => ({ ...prev, visible: false, EditPanel: null }));
        }
    }, [editFieldState, buildFieldSystemContext]);
    const handleEditFieldCancel = React.useCallback(() => {
        setEditFieldState((prev) => ({ ...prev, visible: false, EditPanel: null }));
    }, []);
    const handleEditFieldPanelVisibleChange = React.useCallback((nextVisible) => {
        if (!nextVisible) {
            setEditFieldState((prev) => ({ ...prev, visible: false, EditPanel: null }));
        }
    }, []);
    // ================== AI 任务事件监听 ==================
    /**
     * 监听 AI 单元格生成任务事件
     * - SUBMIT_SINGLE_CELL_AI_TASK：单个单元格 AI 生成
     * - SUBMIT_BATCH_AI_TASKS：批量 AI 任务提交（用于新建 AI 字段时）
     */
    React.useEffect(() => {
        const handleSubmitSingleCellAiTask = (payload) => {
            if (!enableAiFields)
                return;
            const { columnCode, aiConfig, record, rowIndex } = payload;
            // Resolve rowId using the table's primaryKey (supports custom primary key fields)
            let rowId = payload.rowId || '';
            if (!rowId) {
                const strictKey = dataModel.getRowKeyStrict(record);
                if (strictKey != null) {
                    rowId = String(strictKey);
                }
                else if (process.env.NODE_ENV !== 'production') {
                    // eslint-disable-next-line no-console
                    console.warn('[cn-ai-table] handleSubmitSingleCellAiTask: record lacks a valid primaryKey value; skipping');
                }
            }
            if (!rowId || !columnCode) {
                CnMessage.warning($i18n.get({
                    id: 'UnableToGenerateAIContentMissing_1590906583',
                    dm: '无法生成 AI 内容：缺少必要参数',
                }));
                return;
            }
            const promptTemplate = (aiConfig === null || aiConfig === void 0 ? void 0 : aiConfig.promptTemplate) || (aiConfig === null || aiConfig === void 0 ? void 0 : aiConfig.targetInfo) || '';
            if (!promptTemplate) {
                CnMessage.warning($i18n.get({
                    id: 'UnableToGenerateAIContentMissing_106145886',
                    dm: '无法生成 AI 内容：缺少 prompt 模板',
                }));
                return;
            }
            const variables = parsePromptVariables(promptTemplate);
            const allColumns = dataModel.columnDefinitions || [];
            const processedColumnMap = dataModel.processedColumnMap || new Map();
            const promptParams = buildPromptParamsWithExtractor(record, variables, allColumns, processedColumnMap, rowIndex !== null && rowIndex !== void 0 ? rowIndex : 0);
            const taskRequest = {
                columnCode,
                rowId,
                promptParams,
            };
            dataModel.setAiCellData(rowId, columnCode, AI_GENERATING_MARKER);
            submitColumnTasks(columnCode, [taskRequest]);
        };
        eventBus.on(cnAiListEventNames.SUBMIT_SINGLE_CELL_AI_TASK, handleSubmitSingleCellAiTask);
        // 监听批量 AI 任务提交事件（用于新建 AI 字段时）
        const handleSubmitBatchAiTasks = (payload) => {
            if (!enableAiFields)
                return;
            const { columnCode, taskRequests } = payload;
            if (columnCode && (taskRequests === null || taskRequests === void 0 ? void 0 : taskRequests.length) > 0) {
                submitColumnTasks(columnCode, taskRequests);
            }
        };
        eventBus.on(cnAiListEventNames.SUBMIT_BATCH_AI_TASKS, handleSubmitBatchAiTasks);
        return () => {
            eventBus.off(cnAiListEventNames.SUBMIT_SINGLE_CELL_AI_TASK, handleSubmitSingleCellAiTask);
            eventBus.off(cnAiListEventNames.SUBMIT_BATCH_AI_TASKS, handleSubmitBatchAiTasks);
        };
    }, [dataModel, submitColumnTasks, cnAiListEventNames, enableAiFields]);
    // ================== 表头交互 ==================
    /**
     * 处理表头点击事件
     * @description 切换列选中状态，触发列选择事件
     * @param columnId - 列ID
     */
    const handleHeaderClick = React.useCallback((columnId) => {
        var _a;
        const newSelectedColumnId = selectedColumnId === columnId ? null : columnId;
        setSelectedColumnId(newSelectedColumnId);
        // 选中列时清除行选中态
        if (newSelectedColumnId) {
            clearRowSelectionRef.current();
        }
        // 互斥：清除单元格级选中态（普通单元格 + AI 单元格）
        setSelectedCell(null);
        setEditingCell(null);
        setEditingValue('');
        setAiCellActionsState((prev) => (prev.visible ? { ...prev, visible: false } : prev));
        // 触发列选择事件
        if (newSelectedColumnId) {
            // 从 dataModel 获取列名（优先）
            const columnDef = dataModel.columnDefinitions.find((col) => col.dataIndex === newSelectedColumnId);
            let columnName = columnDef === null || columnDef === void 0 ? void 0 : columnDef.title;
            // 如果 dataModel 中没有，尝试从表头 DOM 获取列名
            if (!columnName) {
                try {
                    const headerRow = document.querySelector('thead tr');
                    if (headerRow) {
                        const headerCells = Array.from(headerRow.children);
                        // 需要考虑序号列和选择列
                        const visibleColumns = table.getVisibleLeafColumns();
                        const columnIndex = visibleColumns.findIndex((col) => col.id === newSelectedColumnId);
                        // 加上序号列和选择列的偏移
                        const offset = (showIndex ? 1 : 0) + (rowSelectionEnabled ? 1 : 0);
                        const actualIndex = columnIndex + offset;
                        if (headerCells[actualIndex]) {
                            columnName = ((_a = headerCells[actualIndex].textContent) === null || _a === void 0 ? void 0 : _a.trim()) || undefined;
                        }
                    }
                }
                catch (error) {
                    // 忽略错误
                }
            }
            eventBus.emit(cnAiListEventNames.COLUMN_SELECT, {
                type: 'column',
                columnId: newSelectedColumnId,
                selectedColumnName: columnName || newSelectedColumnId,
            });
        }
        else {
            // 仅清除列选择，不影响行/单元格选中
            eventBus.emit(cnAiListEventNames.COLUMN_CLEAR);
        }
    }, [
        selectedColumnId,
        dataModel,
        table,
        showIndex,
        rowSelectionEnabled,
        setEditingCell,
        setEditingValue,
        cnAiListEventNames,
    ]);
    /** 点击表头外、且非数据单元格时取消列选中（document 监听）。点击数据单元格时不清除列选中态、不发 COLUMN_CLEAR，由单元格点击逻辑切换为单元格选中，避免 AI 助理选中区先消失再出现。
     * 点击 AI 助理区域（含底部聊天框）时不清除列选中，避免用户输入时选中列被误清。 */
    React.useEffect(() => {
        const onMouseDown = (e) => {
            const target = e.target;
            /** 点击落在其它 AI 列表实例（含其 Filter/Agent/Table）内时不应清本表列选（多实例同页） */
            const scoped = target.closest(`[${CN_AI_LIST_INSTANCE_KEY_DATA_ATTR}]`);
            if (scoped) {
                const hitKey = scoped.getAttribute(CN_AI_LIST_INSTANCE_KEY_DATA_ATTR);
                if (hitKey != null && hitKey !== listInstanceKey) {
                    return;
                }
            }
            const container = parentRef.current;
            if (!container)
                return;
            const isInsideAiAgent = !!target.closest('.cn-ai-agent');
            if (isInsideAiAgent)
                return;
            const isHeaderClick = !!target.closest('.ai-table-header-cell');
            const isDataCellClick = !!target.closest('td.ai-table-data-cell');
            const isInsideTable = container.contains(target);
            const isClickOnHeaderOrDataCell = isHeaderClick || isDataCellClick;
            const isClickOnTableRelevantArea = isInsideTable && isClickOnHeaderOrDataCell;
            if (!isClickOnTableRelevantArea) {
                setSelectedColumnId(null);
                eventBus.emit(cnAiListEventNames.COLUMN_CLEAR);
            }
        };
        document.addEventListener('mousedown', onMouseDown);
        return () => document.removeEventListener('mousedown', onMouseDown);
    }, [cnAiListEventNames, listInstanceKey]);
    // ================== 视图配置 ==================
    /** 当前视图配置 */
    const viewConfig = dataModel.getViewConfig(viewId);
    /** 颜色填充规则 */
    const colorFillRules = viewConfig.colorFill || [];
    /** 列宽映射表 */
    const widthMap = widthMapFromProps || ((_c = viewConfig.custom) === null || _c === void 0 ? void 0 : _c.widthMap) || {};
    /** 列顺序（含所有字段） */
    const columnOrder = React.useMemo(() => {
        var _a;
        if ((viewConfig === null || viewConfig === void 0 ? void 0 : viewConfig.columnOrder) && viewConfig.columnOrder.length > 0) {
            return viewConfig.columnOrder;
        }
        return ((_a = dataModel.columnDefinitions) === null || _a === void 0 ? void 0 : _a.map((col) => col.dataIndex)) || [];
    }, [viewConfig.columnOrder, dataModel.columnDefinitions]);
    /** 固定列 ID 列表（自动兼容旧 pinnedColumnsCount） */
    const pinnedFieldIds = React.useMemo(() => resolvePinnedFieldIds(viewConfig, columnOrder), [(_d = viewConfig.custom) === null || _d === void 0 ? void 0 : _d.pinnedFieldIds, (_e = viewConfig.custom) === null || _e === void 0 ? void 0 : _e.pinnedColumnsCount, columnOrder]);
    /** 固定列模型（偏移、z-index 等派生数据的唯一来源） */
    const pinnedModel = React.useMemo(() => buildPinnedModel(columnOrder, pinnedFieldIds, widthMap, getActionColumnWidth(showIndex, rowSelectionEnabled)), [columnOrder, pinnedFieldIds, widthMap, showIndex, rowSelectionEnabled]);
    const pinnedColumnsCount = pinnedModel.pinnedColumnsCount;
    // ================== 行禁用状态计算 ==================
    /**
     * 预先计算所有被禁用行的 primaryKey 集合
     * @description 基于原始数据执行 isDisabled 函数，确保普通视图和分组视图行为一致
     * 使用 isDisabledRef 确保始终调用最新的函数，同时将 isDisabled 作为依赖保证响应性
     * 注意：保持原始类型，不做 String 转换
     */
    const disabledRowKeys = React.useMemo(() => {
        const disabledKeys = new Set();
        const fn = isDisabledRef.current;
        if (fn) {
            dataModel.rawData.forEach((record, index) => {
                if (fn(record, index)) {
                    disabledKeys.add(dataModel.getRowKey(record, index));
                }
            });
        }
        return disabledKeys;
    }, [dataModel.rawData, primaryKey, isDisabled]);
    // ================== 智能跟单状态 ==================
    /**
     * 预先计算智能跟单需要关注的行 ID 集合
     * @description 用于高效查找，直接使用传入的 rowIds 数组（已在 hook 中增量处理）
     */
    const smartFollowFinishedRowIds = React.useMemo(() => {
        return new Set(smartFollowNeedAttentionRowIds.map((rowId) => String(rowId)));
    }, [smartFollowNeedAttentionRowIds]);
    // ================== 可视数据（供行选择插件消费） ==================
    const visibleData = React.useMemo(() => {
        return dataModel.getViewData(viewId);
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [dataModel, viewId, dataModel.rawData, viewConfig.filter]);
    // ================== Pipeline 初始化与插件执行 ==================
    const pipelineContext = React.useMemo(() => ({ dataModel, table, viewId }), [dataModel, table, viewId]);
    const pipeline = usePipeline();
    // inputAndReset: 清空上一轮 context，注入本轮数据 & 配置
    pipeline.inputAndReset({
        data: {
            rows: table.getRowModel().rows,
            columns: ((_g = (_f = table === null || table === void 0 ? void 0 : table.getHeaderGroups()) === null || _f === void 0 ? void 0 : _f[0]) === null || _g === void 0 ? void 0 : _g.headers) || [],
        },
        config: {
            viewId,
            rowHeight,
            showIndex,
            widthMap,
        },
    });
    // 预注入行选择所需的派生数据，供 row-selection plugin 读取
    pipeline.setContext('visibleData', visibleData);
    pipeline.setContext('disabledRowKeys', disabledRowKeys);
    // 统一执行所有已注册插件（按 priority 排序、错误可观测）
    runPlugins({
        props: {
            viewId,
            table,
            columns: ((_j = (_h = table.getHeaderGroups()[0]) === null || _h === void 0 ? void 0 : _h.headers) === null || _j === void 0 ? void 0 : _j.map((h) => h.column.columnDef)) || [],
            viewColumnMetaData: {},
            rowHeight,
            showIndex,
            rowSelectionProps,
            operateColumn,
            customRowRenderer,
            customRows,
            onRowDragEnd,
            cnAiListEventNames,
        },
        pipeline,
        context: pipelineContext,
    });
    // 读取插件产出的 handlers
    const operateColumnHandlers = pipeline.getContext('operateColumnHandlers');
    const rowSelectionHandlers = pipeline.getContext('rowSelectionHandlers');
    const hasOperateColumn = !!operateColumnHandlers;
    const operateColumnWidth = (operateColumnHandlers === null || operateColumnHandlers === void 0 ? void 0 : operateColumnHandlers.getOperateColumnWidth()) || 150;
    // ================== 列头菜单相关 ==================
    /** 表头元素引用 map，用于弹出层定位 */
    const headerRefsMap = React.useRef({});
    // 获取或创建表头 ref
    const getHeaderRef = React.useCallback((columnId) => {
        if (!headerRefsMap.current[columnId]) {
            headerRefsMap.current[columnId] = React.createRef();
        }
        return headerRefsMap.current[columnId];
    }, []);
    // 使用列头菜单 Hook
    // 先创建一个 ref 来存储关闭菜单的函数，因为需要在回调中使用
    const closeMenuRef = React.useRef(null);
    // 获取当前分组数量
    const currentGroupCount = React.useMemo(() => {
        const group = viewConfig.group || [];
        return group.filter((g) => g.field).length; // 过滤掉空字段的分组
    }, [viewConfig.group]);
    const { contextMenuState, handleContextMenu, handleContextMenuClose, getMenuItems } = useColumnHeaderMenu({
        fieldMap: dataModel.fieldMap,
        columnDefinitions: dataModel.columnDefinitions,
        viewConfig,
        // 所有菜单操作都统一在这里调用 util 函数
        onSortAsc: (columnId) => handleSortAsc(columnId, viewId, dataModel, setSelectedColumnId, onShowSortPanel),
        onSortDesc: (columnId) => handleSortDesc(columnId, viewId, dataModel, setSelectedColumnId, onShowSortPanel),
        onFillColor: (columnId) => handleFillColor(columnId, viewId, dataModel, setSelectedColumnId, onShowColorFillPanel),
        onGroupBy: (columnId) => handleGroupBy(columnId, viewId, dataModel, setSelectedColumnId, onShowGroupPanel),
        onFilterBy: (columnId) => handleFilterBy(columnId, viewId, dataModel, setSelectedColumnId, onShowFilterPanel),
        onFreezeToColumn: (columnId, columnIndex) => {
            var _a;
            // 调用 util 函数处理冻结逻辑
            handleFreezeToColumn(columnId, columnIndex, viewId, dataModel, viewConfig);
            // 关闭菜单（通过 ref 调用）
            (_a = closeMenuRef.current) === null || _a === void 0 ? void 0 : _a.call(closeMenuRef);
        },
        onUnfreezeColumn: (columnId, columnIndex) => {
            var _a;
            // 调用 util 函数处理取消冻结逻辑
            handleUnfreezeColumn(columnId, columnIndex, viewId, dataModel, viewConfig);
            // 关闭菜单（通过 ref 调用）
            (_a = closeMenuRef.current) === null || _a === void 0 ? void 0 : _a.call(closeMenuRef);
        },
        onDeleteField: (columnId) => {
            deleteFieldViaSystem(columnId, buildFieldSystemContext());
        },
        isFieldDeletable: (columnId) => {
            const { store } = getFieldSystem();
            return !!store.getFieldRecord(columnId, dataModel);
        },
        onEditAiColumn: enableAiFields
            ? (columnId) => {
                const ctx = buildFieldSystemContext();
                const editConfig = getEditConfigViaSystem(columnId, ctx);
                if (!editConfig || editConfig.type !== 'ai')
                    return;
                const cfg = editConfig.config;
                const driverType = cfg.fieldType || 'ai-generate';
                const { registry } = getFieldSystem();
                const driver = registry.get(driverType);
                const EditPanel = driver === null || driver === void 0 ? void 0 : driver.getUiContribution().editPanel;
                if (!EditPanel)
                    return;
                setEditFieldState({
                    visible: true,
                    fieldType: driverType,
                    columnId: cfg.columnId,
                    columnCode: cfg.columnCode,
                    fieldLabel: cfg.columnName,
                    initialValue: cfg.promptTemplate,
                    EditPanel,
                });
            }
            : undefined,
        onEditFormulaColumn: (columnId) => {
            var _a;
            const ctx = buildFieldSystemContext();
            const editConfig = getEditConfigViaSystem(columnId, ctx);
            if (!editConfig || editConfig.type !== 'formula')
                return;
            armsHottagLog({
                hottag: 'cn-ai-table.formulaField.openEdit',
                name: $i18n.get({ id: 'EditFormulaField', dm: '编辑公式字段' }),
                c6: columnId,
                c7: String((_a = dataModel.tableId) !== null && _a !== void 0 ? _a : ''),
            });
            const cfg = editConfig.config;
            const { registry } = getFieldSystem();
            const driver = registry.get('formula');
            const EditPanel = driver === null || driver === void 0 ? void 0 : driver.getUiContribution().editPanel;
            if (!EditPanel)
                return;
            setEditFieldState({
                visible: true,
                fieldType: 'formula',
                columnId: cfg.columnId,
                columnCode: cfg.columnCode,
                fieldLabel: cfg.columnName,
                initialValue: cfg.expression,
                EditPanel,
            });
        },
        onEditLookupColumn: (columnId) => {
            var _a;
            const ctx = buildFieldSystemContext();
            const editConfig = getEditConfigViaSystem(columnId, ctx);
            if (!editConfig || editConfig.type !== 'lookup')
                return;
            armsHottagLog({
                hottag: 'cn-ai-table.lookupField.openEdit',
                name: $i18n.get({ id: 'OpenQuoteFieldEditing', dm: '打开引用字段编辑' }),
                c6: columnId,
                c7: String((_a = dataModel.tableId) !== null && _a !== void 0 ? _a : ''),
            });
            const cfg = editConfig.config;
            const { registry } = getFieldSystem();
            const driver = registry.get('lookup');
            const EditPanel = driver === null || driver === void 0 ? void 0 : driver.getUiContribution().editPanel;
            if (!EditPanel)
                return;
            setEditFieldState({
                visible: true,
                fieldType: 'lookup',
                columnId: cfg.columnId,
                columnCode: cfg.columnCode,
                fieldLabel: cfg.columnName,
                initialValue: JSON.stringify(cfg.config || {}),
                EditPanel,
            });
        },
        // 传入当前分组数量和最大分组级别
        currentGroupCount,
        maxGroupLevels,
    });
    // 将关闭菜单的函数存储到 ref 中
    React.useEffect(() => {
        closeMenuRef.current = handleContextMenuClose;
    }, [handleContextMenuClose]);
    // ================== 行选择 handlers（由 row-selection plugin 产出） ==================
    const handleRowSelectChangeRaw = (_k = rowSelectionHandlers === null || rowSelectionHandlers === void 0 ? void 0 : rowSelectionHandlers.handleRowSelectChange) !== null && _k !== void 0 ? _k : (() => { });
    const isRowSelectedFn = (_l = rowSelectionHandlers === null || rowSelectionHandlers === void 0 ? void 0 : rowSelectionHandlers.isRowSelected) !== null && _l !== void 0 ? _l : (() => false);
    const isRowDisabledFn = (_m = rowSelectionHandlers === null || rowSelectionHandlers === void 0 ? void 0 : rowSelectionHandlers.isRowDisabled) !== null && _m !== void 0 ? _m : (() => false);
    const selectableRowKeys = (_o = rowSelectionHandlers === null || rowSelectionHandlers === void 0 ? void 0 : rowSelectionHandlers.selectableRowKeys) !== null && _o !== void 0 ? _o : [];
    const selectAllState = (_p = rowSelectionHandlers === null || rowSelectionHandlers === void 0 ? void 0 : rowSelectionHandlers.selectAllState) !== null && _p !== void 0 ? _p : {
        checked: false,
        indeterminate: false,
    };
    const handleSelectAllRaw = (_q = rowSelectionHandlers === null || rowSelectionHandlers === void 0 ? void 0 : rowSelectionHandlers.handleSelectAll) !== null && _q !== void 0 ? _q : (() => { });
    const handleClearSelection = (_r = rowSelectionHandlers === null || rowSelectionHandlers === void 0 ? void 0 : rowSelectionHandlers.handleClearSelection) !== null && _r !== void 0 ? _r : (() => { });
    /** 行选中时清除列选与单元格选；单元格/列选中不再主动清空行选（避免多行选中后点格被误清） */
    const clearColumnAndCellSelection = React.useCallback(() => {
        setSelectedColumnId(null);
        setSelectedCell(null);
        setEditingCell(null);
        setEditingValue('');
        setAiCellActionsState((prev) => (prev.visible ? { ...prev, visible: false } : prev));
    }, [setEditingCell, setEditingValue]);
    const handleRowSelectChange = React.useCallback((rowId, selected) => {
        clearColumnAndCellSelection();
        handleRowSelectChangeRaw(rowId, selected);
    }, [clearColumnAndCellSelection, handleRowSelectChangeRaw]);
    const handleSelectAll = React.useCallback((checked) => {
        clearColumnAndCellSelection();
        handleSelectAllRaw(checked);
    }, [clearColumnAndCellSelection, handleSelectAllRaw]);
    React.useEffect(() => {
        clearRowSelectionRef.current = handleClearSelection;
    }, [handleClearSelection]);
    /** 监听 AGENT_CLEAR_SELECTION：仅 AI 助理点击关闭按钮时发出，同步清除表格的单元格选中、列选中、行选中。
     * 不监听 CELL_CLEAR，否则行选清空/分页等也会触发，会误清表格选中态。 */
    React.useEffect(() => {
        const handleAgentClearSelection = () => {
            clearColumnAndCellSelection();
            clearRowSelectionRef.current();
        };
        eventBus.on(cnAiListEventNames.AGENT_CLEAR_SELECTION, handleAgentClearSelection);
        return () => eventBus.off(cnAiListEventNames.AGENT_CLEAR_SELECTION, handleAgentClearSelection);
    }, [clearColumnAndCellSelection, cnAiListEventNames]);
    // ================== 拖拽相关 ==================
    // 获取可拖拽的列（排除固定列，固定列不参与拖拽）
    const draggableColumnOrder = React.useMemo(() => {
        return columnOrder.filter((id) => !pinnedModel.isPinned(id));
    }, [columnOrder, pinnedModel]);
    // 使用封装的拖拽 Hook
    const { activeColumnId, activeRowId, currentDragType, sensors, handleDragStart, createDragEndHandler, } = useDragAndDrop();
    // 使用封装的 modifiers
    const { restrictToHorizontalAxis, restrictToVerticalAxis } = useDragModifiers(parentRef);
    // 自动滚动配置
    const autoScrollOptions = React.useMemo(() => ({
        threshold: { x: 0.15, y: 0.15 },
        acceleration: 10,
        interval: 5,
        enabled: true,
    }), []);
    // 获取当前拖拽列的宽度
    const activeColumnWidth = React.useMemo(() => {
        if (!activeColumnId)
            return 0;
        return widthMap[activeColumnId] || 200;
    }, [activeColumnId, widthMap]);
    // 获取表格容器的高度和宽度
    const containerHeight = ((_s = parentRef.current) === null || _s === void 0 ? void 0 : _s.clientHeight) || 0;
    const containerWidth = ((_t = parentRef.current) === null || _t === void 0 ? void 0 : _t.scrollWidth) || 0;
    // 创建拖拽结束处理函数（委托 committers）
    const handleDragEnd = createDragEndHandler({
        onColumnDragEnd: (activeId, overId) => {
            commitColumnOrder({
                dataModel,
                viewId,
                columnOrder,
                activeId,
                overId,
                pinnedColumnIds: pinnedFieldIds,
            });
        },
        onRowDragEnd: (activeId, overId) => {
            if (onRowDragEnd) {
                onRowDragEnd(activeId, overId);
                return;
            }
            commitRowOrderLocal({ dataModel, activeId, overId, primaryKey });
        },
    });
    // ================== AI 字段新增后自动滚动 ==================
    /**
     * 监听 AI_FIELD_ADDED 事件，滚动到新增的 AI 列
     * 使用 requestAnimationFrame 延后执行，确保列已渲染
     * 如果列头尚未挂载，进行有限重试
     *
     * 滚动相关的 RAF / setTimeout 句柄存储在 ref 中，不受 useEffect cleanup 影响。
     * 因为 setRawData 等操作会触发频繁重渲染，如果将句柄放在 useEffect 闭包内，
     * cleanup 中的 cancelAnimationFrame 会在 RAF 回调执行前就取消它。
     */
    const scrollTimersRef = React.useRef({ rafId: null, timeoutIds: [] });
    React.useEffect(() => {
        const handleAiFieldAdded = (payload) => {
            const { viewId: eventViewId, columnCode } = payload;
            // 只处理当前视图的事件
            if (eventViewId !== viewId)
                return;
            const timers = scrollTimersRef.current;
            const scrollToColumn = (retryCount = 0) => {
                const maxRetries = 10;
                const retryDelay = 150;
                timers.rafId = requestAnimationFrame(() => {
                    timers.rafId = null;
                    const container = parentRef.current;
                    if (!container)
                        return;
                    let headerElement = null;
                    const headerRef = headerRefsMap.current[columnCode];
                    if (headerRef === null || headerRef === void 0 ? void 0 : headerRef.current) {
                        headerElement = headerRef.current;
                    }
                    else {
                        headerElement = container.querySelector(`th[data-column-id="${columnCode}"]`);
                    }
                    if (!headerElement) {
                        if (retryCount < maxRetries) {
                            const tid = setTimeout(() => scrollToColumn(retryCount + 1), retryDelay);
                            timers.timeoutIds.push(tid);
                        }
                        return;
                    }
                    const containerRect = container.getBoundingClientRect();
                    const headerRect = headerElement.getBoundingClientRect();
                    const pinnedWidth = pinnedModel.totalPinnedWidth;
                    const rightStickyWidth = hasOperateColumn ? operateColumnWidth : 0;
                    const visibleLeft = containerRect.left + pinnedWidth;
                    const visibleRight = containerRect.right - rightStickyWidth;
                    const isFullyVisible = headerRect.left >= visibleLeft && headerRect.right <= visibleRight;
                    if (!isFullyVisible) {
                        const scrollOffset = headerRect.left - visibleLeft;
                        container.scrollLeft += scrollOffset;
                    }
                });
            };
            scrollToColumn();
        };
        eventBus.on(cnAiListEventNames.AI_FIELD_ADDED, handleAiFieldAdded);
        return () => {
            eventBus.off(cnAiListEventNames.AI_FIELD_ADDED, handleAiFieldAdded);
        };
    }, [
        viewId,
        pinnedModel,
        table,
        hasOperateColumn,
        operateColumnWidth,
        cnAiListEventNames,
    ]);
    // 组件卸载时清理滚动相关的 RAF 和 setTimeout
    React.useEffect(() => {
        const timers = scrollTimersRef.current;
        return () => {
            if (timers.rafId !== null) {
                cancelAnimationFrame(timers.rafId);
            }
            for (const tid of timers.timeoutIds) {
                clearTimeout(tid);
            }
        };
    }, []);
    /** AI 单元格操作按钮状态（包含位置、可见性、关联的列和行信息） */
    const [aiCellActionsState, setAiCellActionsState] = React.useState({
        visible: false,
        position: { top: 0, left: 0 },
        cellLeft: 0,
        columnId: null,
        rowId: null,
    });
    /**
     * 处理 AI 单元格保存
     * @param newValue - 新的单元格值
     */
    const handleAiCellSave = React.useCallback(async (newValue) => {
        if (!enableAiFields)
            return;
        const { columnId, rowId } = aiCellActionsState;
        if (columnId && rowId) {
            // 更新本地数据
            dataModel.setAiCellData(rowId, columnId, newValue);
            // 调用接口更新数据
            try {
                const result = await updateAiCellData({
                    tableId: dataModel.tableId,
                    columnCode: columnId, // 对于 AI 列，columnId 就是 columnCode
                    content: newValue,
                    rowId: String(rowId),
                }, dataModel === null || dataModel === void 0 ? void 0 : dataModel.bizRequestConfig);
                if (!result.success) {
                    CnMessage.error(result.errorMsg ||
                        $i18n.get({ id: 'FailedToUpdateAICellData', dm: '更新 AI 单元格数据失败' }));
                }
            }
            catch (error) {
                CnMessage.error($i18n.get({
                    id: 'ErrorOccurredWhileUpdatingAICell_1007076520',
                    dm: '更新 AI 单元格数据时发生错误',
                }));
            }
        }
    }, [aiCellActionsState, dataModel, enableAiFields]);
    /**
     * 处理 AI 单元格重新生成
     */
    const handleAiCellRegenerate = React.useCallback(() => {
        if (!enableAiFields)
            return;
        const { columnId, rowId } = aiCellActionsState;
        if (!columnId || !rowId)
            return;
        // 0. 取消选中/编辑状态，隐藏操作按钮
        setEditingCell(null);
        setEditingValue('');
        setSelectedColumnId(null);
        setAiCellActionsState((prev) => ({ ...prev, visible: false }));
        // 1. 获取 AI 列配置（从表级 customFields 读取）
        const columnAiConfig = dataModel.getCustomFieldAiConfig(columnId);
        if (!columnAiConfig) {
            CnMessage.error($i18n.get({ id: 'UnableToGetAIColumnConfiguration', dm: '无法获取 AI 列配置' }));
            return;
        }
        // 2. 通过主键值获取当前行数据
        const displayData = dataModel.getDisplayData();
        const row = displayData.find((r, idx) => {
            return dataModel.isSameRowKey(dataModel.getRowKey(r, idx), rowId);
        });
        if (!row) {
            CnMessage.error($i18n.get({ id: 'UnableToGetRowData', dm: '无法获取行数据' }));
            return;
        }
        // 3. 构建 AI 字段配置
        const aiFieldConfig = {
            fieldName: columnAiConfig.fieldName || '',
            aiTaskType: columnAiConfig.aiTaskType || '',
            targetInfo: columnAiConfig.targetInfo || '',
            content: columnAiConfig.content || '',
            model: columnAiConfig.model || '',
            autoUpdate: columnAiConfig.autoUpdate || false,
            allowEmptyField: columnAiConfig.allowEmptyField || false,
            fieldDescription: columnAiConfig.fieldDescription,
            columnCode: columnAiConfig.columnCode || columnId,
        };
        // 4. 构建任务请求（单个单元格）
        const taskRequests = buildTaskRequests(aiFieldConfig.columnCode || columnId, [row], aiFieldConfig);
        // 5. 设置单元格为"生成中"状态并提交任务
        if (taskRequests.length > 0) {
            const cellColumnCode = aiFieldConfig.columnCode || columnId;
            dataModel.setAiCellData(rowId, cellColumnCode, AI_GENERATING_MARKER);
            submitColumnTasks(cellColumnCode, taskRequests);
        }
    }, [
        aiCellActionsState,
        dataModel,
        primaryKey,
        viewId,
        setEditingCell,
        setEditingValue,
        setSelectedColumnId,
        buildTaskRequests,
        submitColumnTasks,
        enableAiFields,
    ]);
    // 辅助函数：提取单元格信息并触发选中事件（使用工具函数）
    const emitCellSelectEventCallback = React.useCallback((columnId, currentValue, originalRow, actualRowId, mouseEvent) => {
        emitCellSelectEvent(columnId, currentValue, originalRow, actualRowId, mouseEvent, dataModel, undefined, cnAiListEventNames);
    }, [dataModel, cnAiListEventNames]);
    // 包装 handleCellClick，处理 AI 单元格操作按钮
    const handleCellClickWithAiActions = React.useCallback((rowId, columnId, currentValue, originalRow, mouseEvent) => {
        // 专业版（非鸟搭）场景：不进入编辑态，普通字段支持选中
        // 只有 AI 字段支持编辑
        if (!dataModel.supportBatchEdit) {
            const isAiColumn = dataModel.isAiColumn(columnId);
            if (!isAiColumn || !enableAiFields) {
                // 非 AI 字段，或关闭 AI 能力时的 AI 列：仅选中，不进入 AI 编辑/操作
                const actualRowId = dataModel.getRowKey(originalRow) || rowId;
                // 互斥：清除 AI 单元格的编辑态和操作按钮
                setEditingCell(null);
                setEditingValue('');
                setAiCellActionsState((prev) => (prev.visible ? { ...prev, visible: false } : prev));
                setSelectedColumnId(null);
                setSelectedCell((prev) => {
                    const newSelectedCell = (prev === null || prev === void 0 ? void 0 : prev.rowId) === actualRowId && (prev === null || prev === void 0 ? void 0 : prev.columnId) === columnId
                        ? null
                        : { rowId: actualRowId, columnId };
                    if (newSelectedCell) {
                        clearRowSelectionRef.current();
                        emitCellSelectEventCallback(columnId, currentValue, originalRow, actualRowId, mouseEvent);
                    }
                    else {
                        eventBus.emit(cnAiListEventNames.CELL_CLEAR);
                    }
                    return newSelectedCell;
                });
                return;
            }
            // AI 字段支持编辑，继续执行后续的编辑逻辑
        }
        // 判断是否是 AI 列
        const isAiColumn = dataModel.isAiColumn(columnId);
        // 如果是生成中的单元格，阻止选中和编辑
        if (currentValue === AI_GENERATING_MARKER) {
            mouseEvent.stopPropagation();
            return;
        }
        // 如果是 AI 列且值为空（显示"立即生成"按钮），阻止选中和编辑 TODO:
        if (enableAiFields &&
            isAiColumn &&
            (currentValue === null || currentValue === undefined || currentValue === '')) {
            mouseEvent.stopPropagation();
            return;
        }
        // 互斥：清除普通单元格的选中态和列选中态（保留行多选，避免点单元格误清行选）
        setSelectedCell(null);
        setSelectedColumnId(null);
        if (isAiColumn && enableAiFields) {
            // 获取点击位置，计算操作按钮显示位置（单元格右侧外部）
            const cellElement = mouseEvent.target.closest('td');
            if (cellElement) {
                // 从 originalRow 中获取实际的主键值，而不是使用 rowId（可能是表格库的虚拟 ID）
                const actualRowId = String(dataModel.getRowKey(originalRow) || rowId);
                const rect = cellElement.getBoundingClientRect();
                setAiCellActionsState({
                    visible: true,
                    position: {
                        top: rect.top,
                        left: rect.right + 4, // 在单元格右侧 4px 处显示
                    },
                    cellLeft: rect.left, // 单元格左边界
                    columnId,
                    rowId: actualRowId,
                });
            }
        }
        else {
            // 非 AI 列，隐藏操作按钮
            setAiCellActionsState((prev) => ({ ...prev, visible: false }));
        }
        // 调用原始的 handleCellClick
        handleCellClick(rowId, columnId, currentValue, originalRow, mouseEvent);
    }, [
        dataModel,
        primaryKey,
        handleCellClick,
        setSelectedCell,
        setEditingCell,
        setEditingValue,
        emitCellSelectEventCallback,
        enableAiFields,
        cnAiListEventNames,
    ]);
    const form = React.useMemo(() => createForm({}), [isEditing]);
    // 如果正在编辑的单元格对应的字段不可编辑，自动退出编辑状态
    React.useEffect(() => {
        if (editingCell) {
            const isEditable = dataModel.isFieldEditable(editingCell.columnId);
            if (!isEditable) {
                setEditingCell(null);
                setEditingValue('');
            }
        }
    }, [editingCell, dataModel, setEditingCell, setEditingValue]);
    // 横向或纵向滚动表格时，关闭所有单元格编辑态和 AI 操作弹层，避免弹层错位或一直悬浮
    React.useEffect(() => {
        const container = parentRef.current;
        if (!container)
            return;
        const closeCellOverlays = () => {
            setEditingCell(null);
            setEditingValue('');
            setAiCellActionsState((prev) => (prev.visible ? { ...prev, visible: false } : prev));
        };
        container.addEventListener('scroll', closeCellOverlays);
        return () => container.removeEventListener('scroll', closeCellOverlays);
    }, [setEditingCell, setEditingValue]);
    const { rows } = table.getRowModel();
    // 使用 useCellFormat Hook 进行单元格格式化
    const { renderCellContent } = useCellFormat(dataModel.columnDefinitions);
    // 如果提供了自定义行列表，使用它；否则使用默认的 rows
    const finalRows = React.useMemo(() => {
        if (customRows) {
            return customRows;
        }
        return rows.map((row) => ({ type: 'data', row }));
    }, [customRows, rows]);
    // 从当前真实渲染的数据行集合推导行 ID，保证 SortableContext items 与渲染列表一致。
    // 行拖拽排序写回仍基于 rawData（本地内存语义）。
    const rowIds = React.useMemo(() => {
        return finalRows
            .filter((item) => item.type === 'data' && item.row)
            .map((item, idx) => safeGetRowKey(item.row.original, primaryKey, idx));
    }, [finalRows, primaryKey]);
    /** 分组视图折叠后没有 data 行，但仍有分组头 custom 行，不能用 rowIds 是否为空当作「整表无数据」 */
    const hasTableBodyContent = finalRows.some((item) => { var _a; return item.type === 'data' || (item.type === 'custom' && ((_a = item.data) === null || _a === void 0 ? void 0 : _a.type) === 'group'); });
    // ================== 同步显示顺序数据到 dataModel ==================
    /**
     * 将当前视图的显示顺序数据同步到 dataModel
     * @description 供其他组件（如 toolbar）获取分组/筛选后的实际显示顺序
     */
    React.useEffect(() => {
        // 从 finalRows 中提取数据行的原始数据
        const displayOrderRows = finalRows
            .filter((item) => { var _a; return item.type === 'data' && ((_a = item.row) === null || _a === void 0 ? void 0 : _a.original); })
            .map((item) => item.row.original);
        // 同步到 dataModel
        dataModel.setDisplayOrderData(viewId, displayOrderRows);
    }, [finalRows, viewId, dataModel]);
    /**
     * 处理单元格编辑提交
     * @description 提交单元格编辑内容，支持普通字段和 AI 字段
     * - 普通字段：调用后端接口更新，然后重新获取完整数据
     * - AI 字段：更新本地数据并调用 AI 单元格更新接口
     * @param columnId - 列ID
     * @param row - 行数据（TanStack Table 的 Row 对象）
     * @returns 是否提交成功
     */
    const handleSubmit = React.useCallback(async (columnId, row) => {
        var _a, _b, _c;
        // 触发表单校验
        const result = await form.validate();
        // 校验成功后，获取对应的值
        if (!result) {
            const newFormValues = form.values;
            // const fieldValue = newFormValues[columnId];
            // console.log('表单校验成功，获取到的值:', fieldValue);
            const rowKey = dataModel.getRowKey(row.original);
            // 判断是否是 AI 列
            const isAiColumn = dataModel.isAiColumn(columnId);
            if (isAiColumn) {
                if (!enableAiFields) {
                    form.clearFormGraph();
                    setEditingCell(null);
                    setEditingValue('');
                    return false;
                }
                // AI 列：更新本地数据并调用后端接口
                const cellValue = newFormValues[columnId];
                dataModel.setAiCellData(rowKey, columnId, cellValue);
                // 调用接口更新数据 TODO: 对比一下数据不一致再触发
                try {
                    const updateResult = await updateAiCellData({
                        tableId: dataModel.tableId,
                        columnCode: columnId, // 对于 AI 列，columnId 就是 columnCode
                        content: cellValue,
                        rowId: String(rowKey),
                    }, dataModel === null || dataModel === void 0 ? void 0 : dataModel.bizRequestConfig);
                    if (!updateResult.success) {
                        CnMessage.error(updateResult.errorMsg ||
                            $i18n.get({ id: 'FailedToUpdateAICellData', dm: '更新 AI 单元格数据失败' }));
                    }
                }
                catch (error) {
                    CnMessage.error($i18n.get({
                        id: 'ErrorOccurredWhileUpdatingAICell_1007076520',
                        dm: '更新 AI 单元格数据时发生错误',
                    }));
                }
                form.clearFormGraph();
                setEditingCell(null);
                setEditingValue('');
                return true;
            }
            // 部门、地址字段不执行 update 和 getOne，仅关闭编辑态
            const fieldItem = dataModel.getFieldItem(columnId);
            const componentType = fieldItem === null || fieldItem === void 0 ? void 0 : fieldItem['x-component'];
            const isDepartmentOrAddress = componentType &&
                (ADDRESS_SELECT_COMPONENT_TYPES.includes(componentType) ||
                    DEPARTMENT_SELECT_COMPONENT_TYPES.includes(componentType));
            if (isDepartmentOrAddress) {
                form.clearFormGraph();
                setEditingCell(null);
                setEditingValue('');
                return true;
            }
            // 普通字段：调用后端接口更新
            const updatedRecord = {
                ...row.original,
                ...newFormValues,
            };
            try {
                // 检查配置是否存在
                const recordConfig = dataModel.recordOperationRequestConfig;
                if (!((_a = recordConfig === null || recordConfig === void 0 ? void 0 : recordConfig.update) === null || _a === void 0 ? void 0 : _a.requestConfig)) {
                    CnMessage.error($i18n.get({
                        id: 'UpdateRecordInterfaceNotConfigur_1395299626',
                        dm: '未配置更新记录接口',
                    }));
                    return false;
                }
                // 调用服务端更新记录
                const updateResponse = await updateRecord({
                    ...recordConfig.update.requestConfig,
                    data: updatedRecord,
                });
                if (!updateResponse) {
                    CnMessage.error($i18n.get({ id: 'FailedToUpdateRecord', dm: '更新记录失败' }));
                    return false;
                }
                // 获取完整数据
                if (!((_b = recordConfig === null || recordConfig === void 0 ? void 0 : recordConfig.getOne) === null || _b === void 0 ? void 0 : _b.requestConfig)) {
                    CnMessage.error($i18n.get({
                        id: 'QueryRecordInterfaceIsNotConfigu_1094541155',
                        dm: '未配置查询记录接口',
                    }));
                    return false;
                }
                const fullRecord = await queryRecord({
                    configs: recordConfig.getOne.requestConfig,
                    id: rowKey,
                });
                const recordData = ((_c = fullRecord === null || fullRecord === void 0 ? void 0 : fullRecord.data) === null || _c === void 0 ? void 0 : _c.data) || (fullRecord === null || fullRecord === void 0 ? void 0 : fullRecord.data) || fullRecord;
                if (!recordData) {
                    CnMessage.error($i18n.get({ id: 'FailedToGetRecordDetails', dm: '获取记录详情失败' }));
                    return false;
                }
                // 更新数据模型
                dataModel.updateRow(rowKey, recordData);
                form.clearFormGraph();
                setEditingCell(null);
                setEditingValue('');
                return true;
            }
            catch (error) {
                CnMessage.error($i18n.get({
                    id: 'AnErrorOccurredWhileUpdatingTheR_827926309',
                    dm: '更新记录时发生错误',
                }));
                return false;
            }
        }
        else {
            // console.log('表单校验失败:', result.errors);
            return false;
        }
    }, [form, dataModel, setEditingCell, setEditingValue, primaryKey, enableAiFields]);
    // ================== 虚拟滚动 ==================
    // 使用提取的 useVirtualScroll Hook
    const { paddingTop, paddingBottom, getRowsToRender } = useVirtualScroll({
        count: finalRows.length,
        parentRef,
        rowHeight,
        overscan: 10,
    });
    // 获取要渲染的行数据（只渲染虚拟项对应的行）
    const rowsToRender = React.useMemo(() => getRowsToRender(finalRows), [getRowsToRender, finalRows]);
    // ================== 渲染函数 ==================
    /**
     * 渲染单行
     * @description 根据行类型选择不同的渲染方式
     * - custom 类型：使用 customRowRenderer 渲染（如分组头部行）
     * - data 类型：使用 DraggableRow 渲染数据行
     */
    const renderRow = ({ virtualRow, rowItem, index, }) => {
        if (!rowItem) {
            return null;
        }
        // 如果是自定义行，使用自定义渲染函数
        if (rowItem.type === 'custom' && customRowRenderer) {
            return customRowRenderer(virtualRow, index, finalRows);
        }
        // 如果是数据行，使用默认的 DraggableRow
        const { row, groupRowIndex, isLastInGroup } = rowItem;
        if (!row) {
            return null;
        }
        const displayRowIndex = groupRowIndex !== null && groupRowIndex !== void 0 ? groupRowIndex : index;
        const rowKey = dataModel.getRowKey(row.original, index);
        return (React.createElement(DraggableRow, { key: rowKey, row: row, virtualRow: virtualRow, rowHeight: rowHeight, selectedColumnId: selectedColumnId, colorFillRules: colorFillRules, widthMap: widthMap, dataModel: dataModel, isEditing: isEditing, handleCellClick: handleCellClickWithAiActions, renderCellContent: renderCellContent, currentDragType: currentDragType, handleSubmit: handleSubmit, form: form, showIndex: showIndex, rowIndex: displayRowIndex, rowSelectionEnabled: rowSelectionEnabled, isRowSelected: isRowSelectedFn(rowKey), isRowDisabled: isRowDisabledFn(row.original), selectionType: selectionType, onRowSelectChange: handleRowSelectChange, pinnedModel: pinnedModel, hasOperateColumn: hasOperateColumn, renderOperateCell: operateColumnHandlers === null || operateColumnHandlers === void 0 ? void 0 : operateColumnHandlers.renderOperateCell, operateColumnWidth: operateColumnWidth, measureElement: virtualRow.measureElement, primaryKey: primaryKey, isLastInGroup: isLastInGroup, isSmartFollowRunning: smartFollowFinishedRowIds.has(String(rowKey)), selectedCell: selectedCell }));
    };
    // ================== JSX 渲染 ==================
    return (React.createElement(DndContext, { sensors: sensors, collisionDetection: closestCenter, onDragStart: handleDragStart, onDragEnd: handleDragEnd, autoScroll: autoScrollOptions },
        React.createElement("div", { className: "ai-table-container", ref: parentRef },
            React.createElement("div", { ref: guideLineRef, className: "ai-table-column-resize-guide-line" }),
            React.createElement("table", { className: "ai-table-table" },
                table.getHeaderGroups().length > 0 && (React.createElement("colgroup", null,
                    React.createElement("col", { style: {
                            width: `${getActionColumnWidth(showIndex, rowSelectionEnabled)}px`,
                            minWidth: `${getActionColumnWidth(showIndex, rowSelectionEnabled)}px`,
                        } }),
                    table.getHeaderGroups()[0].headers.map((header) => {
                        const columnId = header.column.id;
                        const columnWidth = widthMap[columnId] || 200;
                        return (React.createElement("col", { key: header.id, style: {
                                width: `${columnWidth}px`,
                                minWidth: `${columnWidth}px`,
                            } }));
                    }),
                    hasOperateColumn && (React.createElement("col", { style: {
                            width: `${operateColumnWidth}px`,
                            minWidth: `${operateColumnWidth}px`,
                        } })))),
                React.createElement("thead", null, table.getHeaderGroups().map((headerGroup) => (React.createElement("tr", { key: headerGroup.id, className: `ai-table-row-${rowHeight}` },
                    React.createElement("th", { className: "ai-table-header-cell ai-table-sticky-column ai-table-action-column-header", style: {
                            width: getActionColumnWidth(showIndex, rowSelectionEnabled),
                            minWidth: getActionColumnWidth(showIndex, rowSelectionEnabled),
                            maxWidth: getActionColumnWidth(showIndex, rowSelectionEnabled),
                        } }, rowSelectionEnabled && selectionType === 'multiple' && (React.createElement("div", { className: "ai-table-header-select-all", style: { paddingLeft: DRAG_HANDLE_WIDTH } },
                        React.createElement(CnTooltip, { trigger: React.createElement("div", { onDoubleClick: selectedRowKeys.length > 0 ? handleClearSelection : undefined },
                                React.createElement(CnCheckbox, { checked: selectAllState.checked, indeterminate: selectAllState.indeterminate, disabled: selectableRowKeys.length === 0, onChange: (checked) => handleSelectAll(checked) })) }, (() => {
                            // 当全选时，显示可选行数（与表格行数一致）；否则显示实际选中的唯一 key 数量
                            // 这样处理是因为数据中可能存在重复主键，全选时用户期望看到与表格行数一致的数量
                            const displayCount = selectAllState.checked
                                ? selectableRowKeys.length
                                : selectedRowKeys.length;
                            return displayCount > 0
                                ? $i18n.get({
                                    id: 'SelectedRowKeysLengthIsSelectedD_883449064',
                                    dm: '已选 {selectedRowKeysLength} 项，双击清空',
                                }, { selectedRowKeysLength: displayCount })
                                : $i18n.get({ id: 'SelectAll', dm: '全选' });
                        })())))),
                    headerGroup.headers
                        .filter((header) => pinnedModel.isPinned(header.column.id))
                        .map((header, index) => {
                        const isSelected = selectedColumnId === header.column.id;
                        const columnWidth = widthMap[header.column.id] || 200;
                        const columnId = header.column.id;
                        return (React.createElement(DraggableColumnHeader, { key: header.id, header: header, isSelected: isSelected, onHeaderClick: handleHeaderClick, rowHeight: rowHeight, columnWidth: columnWidth, isFirstColumn: index === 0, currentDragType: currentDragType, pinnedLeft: pinnedModel.pinnedOffsets[columnId], pinnedIndex: index, pinnedColumnsCount: pinnedColumnsCount, onContextMenu: handleContextMenu(columnId), headerRef: getHeaderRef(columnId) }));
                    }),
                    React.createElement(SortableContext, { items: draggableColumnOrder.filter((item) => item !== null), strategy: horizontalListSortingStrategy }, headerGroup.headers
                        .filter((header) => !pinnedModel.isPinned(header.column.id))
                        .map((header) => {
                        const isSelected = selectedColumnId === header.column.id;
                        const columnWidth = widthMap[header.column.id] || 200;
                        const columnId = header.column.id;
                        return (React.createElement(DraggableColumnHeader, { key: header.id, header: header, isSelected: isSelected, onHeaderClick: handleHeaderClick, rowHeight: rowHeight, columnWidth: columnWidth, isFirstColumn: false, currentDragType: currentDragType, onContextMenu: handleContextMenu(columnId), headerRef: getHeaderRef(columnId) }));
                    })),
                    hasOperateColumn && (React.createElement("th", { className: "ai-table-header-cell ai-table-operate-column-header", style: {
                            width: operateColumnWidth,
                            minWidth: operateColumnWidth,
                        } },
                        React.createElement("div", { className: "ai-table-header-content" },
                            React.createElement("img", { src: icons.VIEW_TABLE, alt: "" }),
                            React.createElement("span", null, (operateColumnHandlers === null || operateColumnHandlers === void 0 ? void 0 : operateColumnHandlers.getOperateColumnTitle()) ||
                                $i18n.get({ id: 'ActionsOperation', dm: '操作' }))))))))),
                React.createElement("tbody", null, !hasTableBodyContent ? (
                /* 无数据时显示居中「暂无数据」 */
                React.createElement("tr", null,
                    React.createElement("td", { colSpan: 1 +
                            ((_w = (_v = (_u = table.getHeaderGroups()[0]) === null || _u === void 0 ? void 0 : _u.headers) === null || _v === void 0 ? void 0 : _v.length) !== null && _w !== void 0 ? _w : 0) +
                            (hasOperateColumn ? 1 : 0), className: "ai-table-empty-placeholder" },
                        React.createElement("div", { className: "ai-table-empty-placeholder-inner" }, $i18n.get({ id: 'NoData', dm: '暂无数据' }))))) : (React.createElement(React.Fragment, null,
                    React.createElement(SortableContext, { items: rowIds, strategy: verticalListSortingStrategy },
                        paddingTop > 0 && (React.createElement("tr", null,
                            React.createElement("td", { colSpan: 1000, className: "ai-table-virtual-padding-cell", style: { height: `${paddingTop}px` } }))),
                        rowsToRender.map(({ virtualRow, rowItem, index }) => renderRow({ virtualRow, rowItem, index })),
                        paddingBottom > 0 && (React.createElement("tr", null,
                            React.createElement("td", { colSpan: 1000, className: "ai-table-virtual-padding-cell", style: { height: `${paddingBottom}px` } }))))))))),
        React.createElement(ColumnDragPreview, { active: !!activeColumnId, width: activeColumnWidth, height: containerHeight, modifier: restrictToHorizontalAxis }),
        React.createElement(RowDragPreview, { active: !!activeRowId, width: containerWidth, rowHeight: rowHeight, modifier: restrictToVerticalAxis }),
        contextMenuState.visible && contextMenuState.columnId && (React.createElement(ColumnHeaderMenuPopup, { visible: contextMenuState.visible, headerRef: getHeaderRef(contextMenuState.columnId), menuItems: getMenuItems(contextMenuState.columnId, (() => {
                var _a, _b;
                // 获取字段名称
                const allHeaders = ((_a = table.getHeaderGroups()[0]) === null || _a === void 0 ? void 0 : _a.headers) || [];
                const header = allHeaders.find((h) => h.column.id === contextMenuState.columnId);
                // 获取字段名称：优先使用 columnDef.header，如果没有则使用 columnId
                const columnName = ((_b = header === null || header === void 0 ? void 0 : header.column.columnDef) === null || _b === void 0 ? void 0 : _b.header) || contextMenuState.columnId;
                return columnName;
            })(), (() => {
                var _a;
                // 计算列索引
                const allHeaders = ((_a = table.getHeaderGroups()[0]) === null || _a === void 0 ? void 0 : _a.headers) || [];
                return allHeaders.findIndex((h) => h.column.id === contextMenuState.columnId);
            })()), onClose: handleContextMenuClose })),
        React.createElement(AiCellActions, { visible: enableAiFields && aiCellActionsState.visible, position: aiCellActionsState.position, cellLeft: aiCellActionsState.cellLeft, cellValue: (() => {
                var _a;
                const { columnId, rowId } = aiCellActionsState;
                if (!columnId || !rowId)
                    return '';
                // 通过主键值查找行数据
                const displayData = dataModel.getDisplayData();
                const row = displayData.find((r, idx) => {
                    return dataModel.isSameRowKey(dataModel.getRowKey(r, idx), rowId);
                });
                return String((_a = row === null || row === void 0 ? void 0 : row[columnId]) !== null && _a !== void 0 ? _a : '');
            })(), fieldName: (() => {
                const { columnId } = aiCellActionsState;
                if (columnId) {
                    const columnDef = dataModel.columnDefinitions.find((col) => col.dataIndex === columnId);
                    return typeof (columnDef === null || columnDef === void 0 ? void 0 : columnDef.title) === 'string' ? columnDef.title : columnId;
                }
                return '';
            })(), onSave: handleAiCellSave, onRegenerate: handleAiCellRegenerate }),
        editFieldState.visible && editFieldState.EditPanel && (React.createElement(EditFieldPanelPopup, { visible: editFieldState.visible, onVisibleChange: handleEditFieldPanelVisibleChange, headerRef: getHeaderRef(editFieldState.columnId), EditPanel: editFieldState.EditPanel, fieldType: editFieldState.fieldType, fieldLabel: editFieldState.fieldLabel, columnId: editFieldState.columnId, columnCode: editFieldState.columnCode, initialValue: editFieldState.initialValue, context: buildFieldSystemContext(), onSave: handleEditFieldSave, onCancel: handleEditFieldCancel }))));
});
