import $i18n from '../../../../../locales/i18n.js';
import * as React from 'react';
import { observer } from 'mobx-react-lite';
import { useModel } from '../../../../../utils/mobx-react-simpler/index.js';
import { useReactTable } from '../../../../../cn-ai-table/react-table';
import { getCoreRowModel, getGroupedRowModel, getExpandedRowModel, getSortedRowModel, getFilteredRowModel, } from '../../../../../cn-ai-table/table-core';
import { customFilterFn } from './utils/filters/customFilterFns';
import { NormalTableView } from './components/normal-table-view';
import { GroupedTableView } from './components/grouped-table-view';
import { Toolbar } from '../../toolbar/toolbar';
import { useSelect } from './hooks/useSelect';
import { useLowcodeConfig } from '../../../../../hooks/index.js';
import { extractDataFromModelWithFormat } from './utils/extract-table-data';
import { useCellFormat } from '../../../../hooks/useCellFormat';
import { useSmartFollow } from '../../../hooks';
import { useStableArray, useStableMap } from '../../../hooks/use-stable-value';
import { calculateOperateColumnWidth, collectColumnFixedWidths, useAutoColumnWidth } from './hooks/use-auto-column-width';
import { getActionColumnWidth } from './drag-utils';
import { DEFAULT_PRIMARY_KEY } from '../../../../../cn-ai-table/view/utils/primary-key';
import { event as eventBus } from '@ice/stark-data';
import { useCnAiListEventNames } from '../../../../../cn-ai-agent/context/cn-ai-list-event-context';
import { CnLoading } from '@cainiaofe/cn-ui';
export const TableView = observer(({ viewId, showIndex: showIndexFromProps, showSelect: showSelectFromProps, rowSelection: rowSelectionFromProps, onSelectChange: onSelectChangeFromProps, operateColumn: operateColumnFromProps, toolbar: toolbarFromProps, groupMaxLevels: groupMaxLevelsFromProps, columnsAutoWidth = true, columnsAutoWidthOpt, enableAiFields: enableAiFieldsFromProps, enableSmartFollow: enableSmartFollowFromProps, enableLookup: enableLookupFromProps, enableFormula: enableFormulaFromProps, toolbarVisible: toolbarVisibleFromProps, toolbarPermissions: toolbarPermissionsFromProps, }) => {
    var _a, _b;
    const enableAiFields = enableAiFieldsFromProps !== false;
    const enableSmartFollow = enableSmartFollowFromProps !== false;
    const enableLookup = enableLookupFromProps !== false;
    const enableFormula = enableFormulaFromProps !== false;
    const toolbarVisible = toolbarVisibleFromProps !== false;
    const toolbarPermissions = toolbarPermissionsFromProps;
    const groupMaxLevels = groupMaxLevelsFromProps !== null && groupMaxLevelsFromProps !== void 0 ? groupMaxLevelsFromProps : 1;
    const cnAiListEventNames = useCnAiListEventNames();
    const dataModel = useModel('dataModel');
    const contentAreaRef = React.useRef(null);
    const [contentWidth, setContentWidth] = React.useState(0);
    // 低码插件通过 setLowcodeConfig 写入全局；与 CnAiTable 直连 props 合并，props 优先
    const { showIndex: showIndexLc, showSelect: showSelectLc, rowSelection: rowSelectionLc, onSelectChange: onSelectChangeLc, operateColumn: operateColumnLc, toolbar: toolbarLc, } = useLowcodeConfig();
    const { showIndex, showSelect, rowSelection, onSelectChange, operateColumn, toolbar } = {
        showIndex: showIndexFromProps !== null && showIndexFromProps !== void 0 ? showIndexFromProps : showIndexLc,
        showSelect: showSelectFromProps !== null && showSelectFromProps !== void 0 ? showSelectFromProps : showSelectLc,
        rowSelection: rowSelectionFromProps !== null && rowSelectionFromProps !== void 0 ? rowSelectionFromProps : rowSelectionLc,
        onSelectChange: onSelectChangeFromProps !== null && onSelectChangeFromProps !== void 0 ? onSelectChangeFromProps : onSelectChangeLc,
        operateColumn: operateColumnFromProps !== null && operateColumnFromProps !== void 0 ? operateColumnFromProps : operateColumnLc,
        toolbar: toolbarFromProps !== null && toolbarFromProps !== void 0 ? toolbarFromProps : toolbarLc,
    };
    // primaryKey 由 CnAiTable 统一同步进 dataModel（已合并 props / lowcode / 默认值），此处直接消费
    const primaryKey = dataModel.primaryKey || DEFAULT_PRIMARY_KEY;
    // 处理 toolbar 可能为 null 或 undefined 的情况
    const { batchArea, toolArea, buttonSize } = toolbar !== null && toolbar !== void 0 ? toolbar : {};
    // 使用 useSelect hook 处理行选择状态
    const { hasSelect, selectKeys, setSelectKeys, storeSelectInfo } = useSelect({
        showSelect,
        rowSelection,
        onSelectChange,
        primaryKey,
    });
    // 规范化 selectKeys 为数组
    const normalizedSelectKeys = React.useMemo(() => {
        if (Array.isArray(selectKeys)) {
            return selectKeys;
        }
        if (selectKeys) {
            return [selectKeys];
        }
        return [];
    }, [selectKeys]);
    // 构建传递给 NormalTableView 的行选择 props
    const rowSelectionProps = React.useMemo(() => ({
        hasSelect,
        selectKeys: normalizedSelectKeys,
        setSelectKeys,
        selectionType: (rowSelection === null || rowSelection === void 0 ? void 0 : rowSelection.type) || 'multiple',
        isDisabled: rowSelection === null || rowSelection === void 0 ? void 0 : rowSelection.isDisabled,
        primaryKey,
    }), [
        hasSelect,
        normalizedSelectKeys,
        setSelectKeys,
        rowSelection === null || rowSelection === void 0 ? void 0 : rowSelection.type,
        rowSelection === null || rowSelection === void 0 ? void 0 : rowSelection.isDisabled,
        primaryKey,
    ]);
    // 同步选择信息到 DataModel，以便在分页栏中显示
    React.useEffect(() => {
        let normalizedKeys = [];
        if (Array.isArray(selectKeys)) {
            normalizedKeys = selectKeys;
        }
        else if (selectKeys) {
            normalizedKeys = [selectKeys];
        }
        dataModel.setSelectionInfo(normalizedKeys, (storeSelectInfo === null || storeSelectInfo === void 0 ? void 0 : storeSelectInfo.current) || [], !!(showSelect || rowSelection));
    }, [selectKeys, storeSelectInfo, showSelect, rowSelection, dataModel]);
    // 监听 refresh/getList、AIFilter 搜索 等触发的 PAGINATION_CHANGE，清空选中项
    React.useEffect(() => {
        const handlePaginationChange = () => {
            if (hasSelect && setSelectKeys) {
                setSelectKeys([], []);
                eventBus.emit(cnAiListEventNames.CELL_CLEAR);
            }
        };
        eventBus.on(cnAiListEventNames.PAGINATION_CHANGE, handlePaginationChange);
        return () => eventBus.off(cnAiListEventNames.PAGINATION_CHANGE, handlePaginationChange);
    }, [hasSelect, setSelectKeys, cnAiListEventNames]);
    // 用于触发显示各种条件设置面板的状态
    const [showFilterPanelTrigger, setShowFilterPanelTrigger] = React.useState(0);
    const [showSortPanelTrigger, setShowSortPanelTrigger] = React.useState(0);
    const [showGroupPanelTrigger, setShowGroupPanelTrigger] = React.useState(0);
    const [showColorFillPanelTrigger, setShowColorFillPanelTrigger] = React.useState(0);
    // 触发显示各种面板的函数
    const handleShowFilterPanel = React.useCallback(() => {
        setShowFilterPanelTrigger((prev) => prev + 1);
    }, []);
    const handleShowSortPanel = React.useCallback(() => {
        setShowSortPanelTrigger((prev) => prev + 1);
    }, []);
    const handleShowGroupPanel = React.useCallback(() => {
        setShowGroupPanelTrigger((prev) => prev + 1);
    }, []);
    const handleShowColorFillPanel = React.useCallback(() => {
        setShowColorFillPanelTrigger((prev) => prev + 1);
    }, []);
    // 使用 useMemo 确保当 rawData 变化时，viewData 引用也会更新
    // 表格视图使用 rawData，因为筛选和排序由表格组件的 getFilteredRowModel 和 getSortedRowModel 处理
    const viewData = React.useMemo(() => {
        return dataModel.getDisplayData();
    }, [dataModel === null || dataModel === void 0 ? void 0 : dataModel.rawData, dataModel === null || dataModel === void 0 ? void 0 : dataModel.aiCellData]);
    const viewColumns = dataModel.getViewColumns(viewId);
    const viewConfig = dataModel.getViewConfig(viewId);
    const viewColumnMetaData = dataModel.getViewColumnMetaData(viewId);
    // 筛选/排序/分组变化时保留选中项；「选中 x 项」显示为当前视图（筛选后）结果集中被选中的条数
    const filteredViewData = React.useMemo(() => dataModel.getViewData(viewId), [
        dataModel,
        viewId,
        dataModel.rawData,
        viewConfig === null || viewConfig === void 0 ? void 0 : viewConfig.filter,
        viewConfig === null || viewConfig === void 0 ? void 0 : viewConfig.sort,
        viewConfig === null || viewConfig === void 0 ? void 0 : viewConfig.group,
    ]);
    const selectedCountInCurrentView = React.useMemo(() => {
        if (!normalizedSelectKeys.length)
            return 0;
        const keySet = new Set(normalizedSelectKeys.map(String));
        return filteredViewData.filter((row, idx) => keySet.has(dataModel.getRowKeyId(row, idx))).length;
    }, [filteredViewData, normalizedSelectKeys, primaryKey]);
    React.useEffect(() => {
        dataModel.setSelectedCountInCurrentView(selectedCountInCurrentView);
        return () => dataModel.setSelectedCountInCurrentView(null);
    }, [dataModel, selectedCountInCurrentView]);
    // 创建字段类型映射，用于快速查找字段的组件类型
    // 使用 useStableMap 确保只有内容变化时才返回新引用
    const fieldTypeMap = useStableMap(() => {
        const map = new Map();
        viewColumnMetaData === null || viewColumnMetaData === void 0 ? void 0 : viewColumnMetaData.forEach((meta) => {
            map.set(meta.entityKey, meta.entityType || '');
        });
        return map;
    }, [viewColumnMetaData]);
    // 筛选配置的稳定引用，只比较关键字段 field/operator/value
    const stableFilterConfig = useStableArray(viewConfig.filter, ['field', 'operator', 'value']);
    // 构建列定义
    const columns = React.useMemo(() => {
        return viewColumns.map((col) => {
            const columnDef = {
                header: col.title,
                accessorKey: col.dataIndex || col.columnCode,
                filterFn: 'custom', // 使用自定义筛选函数
                ...col,
            };
            return columnDef;
        });
    }, [viewColumns]);
    // 获取分组状态
    const grouping = React.useMemo(() => {
        if (viewConfig.group && viewConfig.group.length > 0) {
            return viewConfig.group.map((g) => g.field).filter(Boolean);
        }
        return [];
    }, [viewConfig.group]);
    // 获取筛选状态
    // 将视图配置中的筛选规则转换为表格组件需要的格式
    const columnFilters = React.useMemo(() => {
        if (stableFilterConfig.length > 0) {
            return stableFilterConfig.map((f) => {
                // 获取字段的组件类型，传递给筛选函数进行判断
                const componentType = fieldTypeMap.get(f.field) || '';
                return {
                    id: f.field,
                    value: {
                        operator: f.operator,
                        value: f.value,
                        componentType,
                        fieldId: f.field,
                        fieldMap: dataModel.fieldMap,
                    },
                };
            });
        }
        return [];
    }, [stableFilterConfig, fieldTypeMap, dataModel.fieldMap]);
    // 获取排序状态
    // 将视图配置中的排序规则转换为表格组件需要的格式
    // 保持排序规则的顺序，确保多条件排序按正确顺序生效
    const sorting = React.useMemo(() => {
        if (viewConfig.sort && viewConfig.sort.length > 0) {
            return viewConfig.sort.map((s) => ({
                id: s.field,
                desc: s.order === 'desc',
            }));
        }
        return [];
    }, [viewConfig.sort]);
    const hasGrouping = grouping.length > 0;
    React.useEffect(() => {
        const element = contentAreaRef.current;
        if (!element || typeof window === 'undefined')
            return;
        const updateContentWidth = () => {
            const style = window.getComputedStyle(element);
            const paddingLeft = parseFloat(style.paddingLeft) || 0;
            const paddingRight = parseFloat(style.paddingRight) || 0;
            const nextWidth = Math.max(0, Math.floor(element.clientWidth - paddingLeft - paddingRight));
            setContentWidth((prev) => (prev === nextWidth ? prev : nextWidth));
        };
        updateContentWidth();
        if (typeof ResizeObserver !== 'undefined') {
            const resizeObserver = new ResizeObserver(updateContentWidth);
            resizeObserver.observe(element);
            return () => resizeObserver.disconnect();
        }
        window.addEventListener('resize', updateContentWidth);
        return () => window.removeEventListener('resize', updateContentWidth);
    }, []);
    // 用户拖拽/远端持久化列宽（从 viewConfig.custom.widthMap 读取），useMemo 避免每次渲染产生新引用
    const persistedWidthMap = React.useMemo(() => { var _a; return ((_a = viewConfig.custom) === null || _a === void 0 ? void 0 : _a.widthMap) || {}; }, [(_a = viewConfig.custom) === null || _a === void 0 ? void 0 : _a.widthMap]);
    const operateColumnWidth = React.useMemo(() => {
        if (!Array.isArray(operateColumn === null || operateColumn === void 0 ? void 0 : operateColumn.buttons) || operateColumn.buttons.length === 0) {
            return 0;
        }
        if (columnsAutoWidth === false) {
            return Number(operateColumn.width) || 150;
        }
        return calculateOperateColumnWidth({
            operateColumn,
            dataSource: viewData,
            options: columnsAutoWidthOpt,
        });
    }, [columnsAutoWidth, operateColumn, viewData, columnsAutoWidthOpt]);
    const autoSizedOperateColumn = React.useMemo(() => {
        if (!operateColumnWidth) {
            return operateColumn;
        }
        return {
            ...operateColumn,
            width: operateColumnWidth,
        };
    }, [operateColumn, operateColumnWidth]);
    const reservedWidth = React.useMemo(() => {
        const actionColumnWidth = getActionColumnWidth(!!showIndex, !!rowSelectionProps.hasSelect);
        return actionColumnWidth + operateColumnWidth;
    }, [operateColumnWidth, rowSelectionProps.hasSelect, showIndex]);
    const autoWidthMap = useAutoColumnWidth({
        enabled: columnsAutoWidth !== false,
        columns,
        dataSource: viewData,
        persistedWidthMap,
        options: columnsAutoWidthOpt,
        containerWidth: contentWidth,
        reservedWidth,
    });
    // 从列配置中收集所有显式设置了 width 的列，作为最低优先级底层。
    // 确保 columnsAutoWidth=false 时 column.width 也能生效，不被 200px 兜底覆盖。
    const columnFixedWidthMap = React.useMemo(() => collectColumnFixedWidths(columns), [columns]);
    const widthMap = React.useMemo(() => ({
        ...columnFixedWidthMap, // 最低优先级：列配置中的固定 width
        ...autoWidthMap, // 自动测宽（含固定列，两者值一致；disabled 时为 {}）
        ...persistedWidthMap, // 最高优先级：用户拖拽持久化
    }), [columnFixedWidthMap, autoWidthMap, persistedWidthMap]);
    // 受控 columnSizing 状态，与 widthMap 保持同步
    const columnSizing = React.useMemo(() => {
        return { ...widthMap };
    }, [widthMap]);
    const defaultSizingInfo = React.useMemo(() => ({
        startOffset: null,
        startSize: null,
        deltaOffset: null,
        deltaPercentage: null,
        isResizingColumn: false,
        columnSizingStart: [],
    }), []);
    // Ref-based columnSizingInfo: stores every mousemove delta without triggering React re-renders.
    // TanStack Table's default behaviour calls setState on each mousemove, causing a full table
    // re-render even though column widths don't change until mouseup (columnResizeMode='onEnd').
    // By redirecting updates to a ref we eliminate those intermediate renders entirely.
    const columnSizingInfoRef = React.useRef(defaultSizingInfo);
    const handleColumnSizingInfoChange = React.useCallback((updater) => {
        const prev = columnSizingInfoRef.current;
        columnSizingInfoRef.current = typeof updater === 'function' ? updater(prev) : updater;
    }, []);
    // 列宽拖拽结束时写回 widthMap（columnResizeMode='onEnd' 下只在松手时触发）
    const handleColumnSizingChange = React.useCallback((updater) => {
        var _a;
        const MIN_COL_WIDTH = 80;
        // With ref-based columnSizingInfo, the updater from TanStack reads stale state,
        // so we compute the final sizing directly from our ref.
        const info = columnSizingInfoRef.current;
        const startEntries = (info === null || info === void 0 ? void 0 : info.columnSizingStart) || [];
        const delta = (_a = info === null || info === void 0 ? void 0 : info.deltaOffset) !== null && _a !== void 0 ? _a : 0;
        let clampedSizing;
        let hasChanges = false;
        if (startEntries.length > 0) {
            clampedSizing = { ...persistedWidthMap };
            for (const [colId, startSize] of startEntries) {
                const clamped = Math.max(Math.round(startSize + delta), MIN_COL_WIDTH);
                if (persistedWidthMap[colId] !== clamped) {
                    hasChanges = true;
                }
                clampedSizing[colId] = clamped;
            }
        }
        else {
            // Fallback: standard TanStack updater (e.g. programmatic resize)
            const newSizing = typeof updater === 'function' ? updater(columnSizing) : updater;
            clampedSizing = { ...persistedWidthMap };
            for (const [key, value] of Object.entries(newSizing)) {
                const clamped = Math.max(value, MIN_COL_WIDTH);
                if (columnSizing[key] === clamped) {
                    continue;
                }
                clampedSizing[key] = clamped;
                if (persistedWidthMap[key] !== clamped) {
                    hasChanges = true;
                }
            }
        }
        if (!hasChanges)
            return;
        columnSizingInfoRef.current = defaultSizingInfo;
        dataModel.setViewConfig(viewId, {
            custom: {
                ...viewConfig.custom,
                widthMap: clampedSizing,
            },
        }, true);
    }, [columnSizing, persistedWidthMap, viewConfig.custom, dataModel, viewId, defaultSizingInfo]);
    // 创建表格实例（根据是否有分组来决定配置）
    // 注意：useReactTable 返回的是同一个实例，但会在每次渲染时调用 setOptions 更新配置
    // 关键：每次 viewData 变化时，需要确保 table.options.data 也更新，这样 memo 才能检测到变化
    const table = useReactTable({
        data: viewData, // 确保每次 viewData 引用变化时，这里也会传入新的引用
        columns,
        getCoreRowModel: getCoreRowModel(),
        getFilteredRowModel: getFilteredRowModel(),
        getSortedRowModel: getSortedRowModel(),
        filterFns: {
            custom: customFilterFn,
        },
        enableColumnResizing: true,
        columnResizeMode: 'onEnd',
        onColumnSizingChange: handleColumnSizingChange,
        onColumnSizingInfoChange: handleColumnSizingInfoChange,
        defaultColumn: {
            size: 200,
            minSize: 80,
        },
        ...(hasGrouping
            ? {
                getGroupedRowModel: getGroupedRowModel(),
                getExpandedRowModel: getExpandedRowModel(),
                enableGrouping: true,
                groupedColumnMode: false,
                // 默认 paginateExpandedRows=true 时会把分组树拍平到 getRowModel().rows，
                // buildGroupedVirtualRows 误把每层分组都当顶层渲染，出现重复组头；分组场景下保持树形。
                paginateExpandedRows: false,
                // 分组模型在 data 变化时会重算并触发 _autoResetExpanded；行拖拽/刷新数据不应清空展开态
                autoResetExpanded: false,
                state: {
                    grouping,
                    sorting,
                    columnFilters,
                    columnSizing,
                    columnSizingInfo: defaultSizingInfo,
                },
            }
            : {
                state: {
                    sorting,
                    columnFilters,
                    columnSizing,
                    columnSizingInfo: defaultSizingInfo,
                },
            }),
    });
    const rowHeight = 'low';
    // 处理排序变化的通用函数
    const handleSortChange = (fields, order) => {
        if (!fields) {
            // 如果字段为空，清除所有排序
            dataModel.setViewConfig(viewId, {
                sort: [],
            });
            return;
        }
        // 如果 fields 是逗号分隔的字符串，转换为数组
        const fieldArray = typeof fields === 'string' ? fields.split(',').filter(Boolean) : [fields];
        const sortRules = fieldArray.map((field) => ({
            field: field.trim(),
            order: order || 'asc',
        }));
        dataModel.setViewConfig(viewId, {
            sort: sortRules,
        });
    };
    // 使用 useCellFormat 获取格式化函数
    const { processedColumnMap } = useCellFormat(dataModel.columnDefinitions);
    // 判断是否为主视图（只有主视图才启用跟单任务逻辑）
    const isPrimaryView = dataModel.isPrimaryView(viewId);
    // 提取表格数据为 AI 可消费的格式（包含格式化后的文本，推荐用于获取显示值）
    const formattedTableData = React.useMemo(() => {
        // 使用全量列定义，而不是可见的 viewColumns
        return extractDataFromModelWithFormat(viewData, dataModel.columnDefinitions, processedColumnMap, dataModel.primaryKey);
    }, [viewData, dataModel.columnDefinitions, processedColumnMap, dataModel.primaryKey]);
    // 智能跟单任务：页面进入时提交跟单任务，并轮询查询状态
    // 只在主视图中启用，新增的表格视图不触发跟单任务
    // 注意：只保存 needAttentionRowIds，不保存全表返回的 jobOutput
    const { loading: smartFollowLoading, needAttentionRowIds: smartFollowNeedAttentionRowIds, runningTasks: smartFollowRunningTasks, conversationId, respMessageId, refresh: smartFollowRefresh, } = useSmartFollow({
        tableId: dataModel.tableId,
        formattedTableData,
        columnDefinitions: dataModel.columnDefinitions,
        enabled: enableSmartFollow && isPrimaryView && !!dataModel.tableId && formattedTableData.length > 0,
    });
    // 表格展示专用延迟态：轮询期间不回显高亮，所有任务完成后一次性写入。 TODO: 后续优化标识，不做表格重新渲染
    // 仅影响主表格行高亮输入；dataModel.setSmartFollowState 和事件总线仍消费实时值。
    // 使用 useMemo 同步派生，确保渲染过程中即可决定是否回显，不存在 useEffect 的一帧延迟。
    const EMPTY_ROW_IDS = React.useMemo(() => [], []);
    const deferredNeedAttentionRowIds = React.useMemo(() => {
        if (!enableSmartFollow || !isPrimaryView)
            return EMPTY_ROW_IDS;
        // 轮询中（loading 或仍有 runningTasks）：不回显，返回稳定空数组引用避免子组件重渲染
        if (smartFollowLoading || smartFollowRunningTasks.length > 0)
            return EMPTY_ROW_IDS;
        // 轮询结束：一次性回显全部结果
        return smartFollowNeedAttentionRowIds;
    }, [
        EMPTY_ROW_IDS,
        enableSmartFollow,
        isPrimaryView,
        smartFollowLoading,
        smartFollowRunningTasks.length,
        smartFollowNeedAttentionRowIds,
    ]);
    // 将智能跟单状态同步到 dataModel（供跟单视图使用）
    // 只在主视图中同步，只同步 needAttentionRowIds，不同步 jobOutput
    React.useEffect(() => {
        var _a;
        if (!enableSmartFollow || !isPrimaryView)
            return;
        (_a = dataModel.setSmartFollowState) === null || _a === void 0 ? void 0 : _a.call(dataModel, {
            loading: smartFollowLoading,
            needAttentionRowIds: smartFollowNeedAttentionRowIds,
            runningTasks: smartFollowRunningTasks,
            conversationId,
            refresh: smartFollowRefresh,
        });
    }, [
        enableSmartFollow,
        isPrimaryView,
        dataModel,
        smartFollowLoading,
        smartFollowNeedAttentionRowIds,
        smartFollowRunningTasks,
        conversationId,
        smartFollowRefresh,
    ]);
    // 向 AI 助理同步跟单任务状态：queryFollowOrderTasks.do 轮询的 loading、finishedTasks 数量、以及 submitOrderFollowRequests 返回的 conversationId / respMessageId（供 queryTaskFollowSummary 使用）
    // 只在主视图中同步
    const followOrderEnabled = enableSmartFollow &&
        isPrimaryView &&
        !!dataModel.tableId &&
        ((_b = formattedTableData === null || formattedTableData === void 0 ? void 0 : formattedTableData.length) !== null && _b !== void 0 ? _b : 0) > 0;
    React.useEffect(() => {
        var _a;
        if (!followOrderEnabled)
            return;
        eventBus.emit(cnAiListEventNames.FOLLOW_ORDER_TASKS_UPDATE, {
            loading: smartFollowLoading,
            finishedCount: (_a = smartFollowNeedAttentionRowIds === null || smartFollowNeedAttentionRowIds === void 0 ? void 0 : smartFollowNeedAttentionRowIds.length) !== null && _a !== void 0 ? _a : 0,
            conversationId: conversationId !== null && conversationId !== void 0 ? conversationId : null,
            respMessageId: respMessageId !== null && respMessageId !== void 0 ? respMessageId : null,
        });
    }, [
        followOrderEnabled,
        smartFollowLoading,
        smartFollowNeedAttentionRowIds,
        conversationId,
        respMessageId,
        cnAiListEventNames,
    ]);
    // 将方法暴露到 window 对象，方便调试和外部调用
    const getTableDataForAIWithFormat = React.useCallback(() => {
        return formattedTableData;
    }, [formattedTableData]);
    // 将列定义暴露到 window 对象，方便调试和外部调用
    const getColumnDefinitions = React.useCallback(() => {
        return dataModel.columnDefinitions;
    }, [dataModel.columnDefinitions]);
    React.useEffect(() => {
        if (typeof window !== 'undefined') {
            window.__getTableDataForAIWithFormat = getTableDataForAIWithFormat;
            window.__getColumnDefinitions = getColumnDefinitions;
            // 智能跟单会话信息，供后续 Agent 使用
            window.__smartFollowConversationId = conversationId;
            window.__smartFollowRespMessageId = respMessageId;
        }
    }, [getTableDataForAIWithFormat, getColumnDefinitions, conversationId, respMessageId]);
    // 当格式化后的数据变化时，通过事件总线通知外部组件
    React.useEffect(() => {
        eventBus.emit(cnAiListEventNames.TABLE_DATA_UPDATE);
    }, [formattedTableData, cnAiListEventNames]);
    // 当列定义变化时，通过事件总线通知外部组件
    React.useEffect(() => {
        eventBus.emit(cnAiListEventNames.TABLE_DATA_UPDATE);
    }, [dataModel.columnDefinitions, cnAiListEventNames]);
    const renderToolbar = () => {
        var _a, _b, _c, _d, _e;
        const perms = toolbarPermissions;
        return (React.createElement("div", { className: "ai-table-toolbar-sticky" },
            React.createElement(Toolbar, { toolbarVisible: toolbarVisible, permissions: {
                    addRecord: true,
                    fieldManagement: (_a = perms === null || perms === void 0 ? void 0 : perms.fieldManagement) !== null && _a !== void 0 ? _a : true,
                    filter: (_b = perms === null || perms === void 0 ? void 0 : perms.filter) !== null && _b !== void 0 ? _b : true,
                    sort: (_c = perms === null || perms === void 0 ? void 0 : perms.sort) !== null && _c !== void 0 ? _c : true,
                    group: (_d = perms === null || perms === void 0 ? void 0 : perms.group) !== null && _d !== void 0 ? _d : true,
                    colorFill: (_e = perms === null || perms === void 0 ? void 0 : perms.colorFill) !== null && _e !== void 0 ? _e : true,
                    component: false,
                }, enableAiFields: enableAiFields, enableLookup: enableLookup, enableFormula: enableFormula, viewId: viewId, onSortChange: handleSortChange, showFilterPanelTrigger: showFilterPanelTrigger, showSortPanelTrigger: showSortPanelTrigger, showGroupPanelTrigger: showGroupPanelTrigger, showColorFillPanelTrigger: showColorFillPanelTrigger, groupMaxLevels: groupMaxLevels, batchArea: batchArea, toolArea: toolArea, buttonSize: buttonSize, selectKeys: selectKeys, storeSelectInfo: storeSelectInfo })));
    };
    if (hasGrouping) {
        return (React.createElement("div", { className: "ai-table-content-area", ref: contentAreaRef },
            renderToolbar(),
            React.createElement(CnLoading, { tip: $i18n.get({ id: 'Loading', dm: '加载中...' }), inline: false, visible: dataModel.loading },
                React.createElement(GroupedTableView, { viewId: viewId, table: table, columns: columns, viewColumnMetaData: viewColumnMetaData, showIndex: !!showIndex, rowSelectionProps: rowSelectionProps, operateColumn: autoSizedOperateColumn, widthMap: widthMap, onShowFilterPanel: handleShowFilterPanel, onShowSortPanel: handleShowSortPanel, onShowGroupPanel: handleShowGroupPanel, onShowColorFillPanel: handleShowColorFillPanel, enableAiFields: enableAiFields }))));
    }
    return (React.createElement("div", { className: "ai-table-content-area", ref: contentAreaRef },
        renderToolbar(),
        React.createElement(CnLoading, { tip: $i18n.get({ id: 'Loading', dm: '加载中...' }), inline: false, visible: dataModel.loading },
            React.createElement(NormalTableView, { viewId: viewId, table: table, columns: columns, viewColumnMetaData: viewColumnMetaData, rowHeight: rowHeight, showIndex: !!showIndex, rowSelectionProps: rowSelectionProps, widthMap: widthMap, onShowFilterPanel: handleShowFilterPanel, onShowSortPanel: handleShowSortPanel, onShowGroupPanel: handleShowGroupPanel, onShowColorFillPanel: handleShowColorFillPanel, operateColumn: autoSizedOperateColumn, maxGroupLevels: groupMaxLevels, enableAiFields: enableAiFields, 
                // 只在主视图中显示跟单相关的 UI（使用延迟态，轮询结束后一次性回显）
                // deferredNeedAttentionRowIds 在 !isPrimaryView 时已返回稳定空数组，无需额外三元
                smartFollowNeedAttentionRowIds: deferredNeedAttentionRowIds }))));
});
