"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CnAiTable = void 0;
const i18n_1 = __importDefault(require("../../locales/i18n.js"));
const React = __importStar(require("react"));
const mobx_react_lite_1 = require("mobx-react-lite");
const react_dom_1 = require("react-dom");
const cn_ui_1 = require("@cainiaofe/cn-ui");
const cn_drag_tab_1 = require("../../cn-drag-tab");
const cn_domain_popup_1 = require("@cainiaofe/cn-domain-popup");
require("./cn-ai-table.scss");
const smart_follow_view_1 = require("./components/views/smart-follow-view/smart-follow-view");
const components_1 = require("./components");
const mobx_1 = require("mobx");
const mobx_react_simpler_1 = require("../../utils/mobx-react-simpler/index.js");
const model_1 = require("./model");
const views_window_mirror_1 = require("./utils/views-window-mirror");
const view_type_selector_1 = require("./components/selectors/view-type-selector/view-type-selector");
const view_menu_1 = require("./components/view-menu/view-menu");
const icons_1 = require("./components/icons");
const total_info_1 = require("./components/total-info/total-info");
const primary_key_1 = require("./utils/primary-key");
const use_remote_1 = require("./use-remote");
const hooks_1 = require("./hooks");
const services_1 = require("./services");
const resolve_config_1 = require("./utils/resolve-config");
const isEmpty_1 = __importDefault(require("lodash/isEmpty"));
const isFunction_1 = __importDefault(require("lodash/isFunction"));
const isPlainObject_1 = __importDefault(require("lodash/isPlainObject"));
const isString_1 = __importDefault(require("lodash/isString"));
const isNumber_1 = __importDefault(require("lodash/isNumber"));
const stark_data_1 = require("@ice/stark-data");
const event_constants_1 = require("../../cn-ai-agent/constants/event-constants");
const cn_ai_list_event_context_1 = require("../../cn-ai-agent/context/cn-ai-list-event-context");
const isNil_1 = __importDefault(require("lodash/isNil"));
const arms_hot_tag_log_1 = require("../../utils/arms/arms-hot-tag-log.js");
const floating_layer_1 = require("../../utils/floating-layer.js");
const utils_1 = require("./utils");
const ViewComponent = (0, mobx_react_lite_1.observer)(({ viewId, viewType, fieldTypes, viewTypes, ...tableSelectionProps }) => {
    switch (viewType) {
        case 'Grid':
            return (React.createElement(components_1.CnAiTableView, { viewId: viewId, ...tableSelectionProps, enableAiFields: fieldTypes.ai.enabled, enableSmartFollow: viewTypes.smartFollow.enabled, enableLookup: fieldTypes.lookup.enabled, enableFormula: fieldTypes.formula.enabled, toolbarVisible: viewTypes.grid.toolbarVisible, toolbarPermissions: viewTypes.grid.toolbarPermissions }));
        case 'Task':
            return (React.createElement(components_1.TaskView, { viewId: viewId, enableAiSummary: viewTypes.task.enableSummary, toolbarVisible: viewTypes.task.toolbarVisible, toolbarPermissions: viewTypes.task.toolbarPermissions }));
        case 'SmartFollow':
            return (React.createElement(smart_follow_view_1.SmartFollowView, { viewId: viewId, enableSmartFollow: viewTypes.smartFollow.enableDetailSummary }));
        default:
            return React.createElement("div", null, i18n_1.default.get({ id: 'UnknownViewType', dm: '未知视图类型' }));
    }
});
exports.CnAiTable = (0, mobx_react_lite_1.observer)((props) => {
    const { id, fieldMap, columns, recordOperationRequestConfig, remote, primaryKey, supportBatchEdit, 
    // 行选择与工具栏配置
    showSelect, rowSelection, onSelectChange, showIndex, operateColumn, toolbar, columnsAutoWidth, columnsAutoWidthOpt, bizRequestConfig, groupMaxLevels: groupMaxLevelsFromProps, enabledFieldTypes, fieldTypeOptions, viewTypes: viewTypesProp, showViewTabs = true, hideColumnHeaderMenu = false, } = props;
    const resolvedConfig = React.useMemo(() => (0, resolve_config_1.resolveConfig)(enabledFieldTypes, fieldTypeOptions, viewTypesProp), [enabledFieldTypes, fieldTypeOptions, viewTypesProp]);
    const { fieldTypes: fieldTypeCaps, viewTypes: viewTypeCaps } = resolvedConfig;
    const enableAiFields = fieldTypeCaps.ai.enabled;
    const enableSmartFollow = viewTypeCaps.smartFollow.enabled;
    /** 未传时默认仅允许单层分组 */
    const groupMaxLevels = groupMaxLevelsFromProps !== null && groupMaxLevelsFromProps !== void 0 ? groupMaxLevelsFromProps : 1;
    const tableId = id;
    const instanceKey = React.useMemo(() => (0, event_constants_1.normalizeCnAiListInstanceKey)(tableId), [tableId]);
    const listEventNames = React.useMemo(() => (0, event_constants_1.buildCnAiListEventNames)(instanceKey), [instanceKey]);
    const listEventContextValue = React.useMemo(() => ({ eventNames: listEventNames, instanceKey }), [listEventNames, instanceKey]);
    const dataModel = (0, mobx_react_simpler_1.useModel)(() => new model_1.DataModel());
    const [viewTypeSelectorVisible, setViewTypeSelectorVisible] = React.useState(false);
    const aiColumnsInitializedRef = React.useRef(false);
    const viewsConfigsLoadedRef = React.useRef(false);
    /** 上次 setAllViews 是否为占位空快照；先空后真时需再应用一次真实 ViewsData */
    const viewsAppliedWasPlaceholderRef = React.useRef(false);
    /** 首轮 setAllViews 完成前不露 tab，避免占位 id 替换造成抖动 */
    const [viewsReady, setViewsReady] = React.useState(false);
    const { effectiveViewsConfigs, isLoadingViews } = (0, hooks_1.useViewsConfigs)(tableId, bizRequestConfig);
    /**
     * 组件级首查注入：按已配置引用字段全量生成 joinTableColumns（与 canSearch 解耦）。
     * 仅用于首屏/未显式传入 joinTableColumns 的通用兜底。
     */
    const initialLookupJoinTableColumns = React.useMemo(() => {
        var _a;
        const viewsData = effectiveViewsConfigs && effectiveViewsConfigs.type === 'static'
            ? effectiveViewsConfigs.data
            : undefined;
        return (0, utils_1.buildJoinTableColumnsFromLookupConfig)((_a = viewsData === null || viewsData === void 0 ? void 0 : viewsData.customFields) === null || _a === void 0 ? void 0 : _a.lookupConfig);
    }, [effectiveViewsConfigs]);
    const effectiveRemote = React.useMemo(() => {
        var _a;
        if (!remote)
            return remote;
        const hasBizJoinTableColumns = Boolean((_a = remote === null || remote === void 0 ? void 0 : remote.params) === null || _a === void 0 ? void 0 : _a.joinTableColumns);
        const hasInitialLookupJoinColumns = Object.keys(initialLookupJoinTableColumns).length > 0;
        /**
         * 仅在需要兜底注入 joinTableColumns 时新建 params；否则保持 `remote.params` 引用不变。
         * useRemote 对 `[remote?.url, remote?.params]` 做依赖，无意义的新对象会导致鸟搭等场景反复 getList。
         */
        const nextParams = !hasBizJoinTableColumns && hasInitialLookupJoinColumns
            ? {
                ...(remote.params || {}),
                joinTableColumns: [initialLookupJoinTableColumns],
            }
            : remote.params;
        return {
            ...remote,
            params: nextParams,
            immediate: remote.immediate === false
                ? false
                : !isLoadingViews && viewsReady && effectiveViewsConfigs !== null,
        };
    }, [remote, initialLookupJoinTableColumns, isLoadingViews, effectiveViewsConfigs, viewsReady]);
    /**
     * AI 列管理 hook
     */
    const { runningTasks, loadAiColumns, queryAndPollTableTasks } = (0, hooks_1.useAiColumns)({
        tableId,
        enabled: enableAiFields,
        bizRequestConfig: {
            aiColumn: bizRequestConfig === null || bizRequestConfig === void 0 ? void 0 : bizRequestConfig.aiColumn,
            cubePlatform: bizRequestConfig === null || bizRequestConfig === void 0 ? void 0 : bizRequestConfig.cubePlatform,
        },
        cubePlatformUserConfigRowIdHint: dataModel.cubePlatformUserConfigRowId,
        onCubePlatformUserConfigRowId: (rowId) => dataModel.setCubePlatformUserConfigRowId(rowId),
        onAiColumnsLoaded: (aiColumns) => {
            // 将 AI 列合并到 DataModel 中
            if (aiColumns && aiColumns.length > 0) {
                dataModel.mergeAiColumns(aiColumns);
            }
        },
        onFinishedTasksUpdate: (newFinishedTasks) => {
            dataModel.mergeAiTaskResults(newFinishedTasks);
        },
    });
    React.useEffect(() => {
        dataModel.setRunningTasks(runningTasks || []);
    }, [runningTasks, dataModel]);
    // 初始化基础数据（不包含 viewsConfigs，因为它可能是异步加载的）
    React.useEffect(() => {
        dataModel.setTableId(tableId);
        dataModel.setSupportBatchEdit(supportBatchEdit !== null && supportBatchEdit !== void 0 ? supportBatchEdit : false);
        if (fieldMap) {
            if (fieldMap.type === 'static') {
                dataModel.setFieldMap(fieldMap.data);
            }
        }
        else {
            dataModel.setFieldMap({});
        }
        if (recordOperationRequestConfig) {
            dataModel.setRecordOperationRequestConfig(recordOperationRequestConfig);
        }
        // 保存原始 columns
        dataModel.setOriginColumns(columns || []);
        // props中的columns
        const showedColumns = columns === null || columns === void 0 ? void 0 : columns.filter((col) => !col.hidden);
        dataModel.setColumnDefinitions(showedColumns);
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);
    // 异步加载 AI 列（此时 columnDefinitions 和 viewsConfigs 已设置完成）
    // 先获取动态域名，确保所有后续请求都能使用正确的 host
    const initializeAiColumns = async () => {
        // 0. 预热动态域名（并发安全，后续 service 调用自动读取缓存）
        await (0, services_1.initHostDomainOnce)();
        // 1. 先加载 AI 列定义（触发 onAiColumnsLoaded → mergeAiColumns）
        await loadAiColumns();
        // 2. 再查询任务并回显数据（触发 onFinishedTasksUpdate → mergeAiTaskResults）
        await queryAndPollTableTasks();
    };
    // tableId 变更时重置门闩；effectiveViewsConfigs 异步到达后写入 Model
    React.useEffect(() => {
        viewsConfigsLoadedRef.current = false;
        viewsAppliedWasPlaceholderRef.current = false;
        aiColumnsInitializedRef.current = false;
        setViewsReady(false);
    }, [tableId]);
    // 运行时镜像：把当前 ViewsData 写入 window.__CN_AI_TABLE_VIEWS__[tableId]
    // —— 只读快照，外部消费方不得反向写回；卸载/换 tableId 时清理
    React.useEffect(() => {
        if (!tableId)
            return;
        const dispose = (0, mobx_1.autorun)(() => {
            (0, views_window_mirror_1.setViewsMirror)(tableId, dataModel.toViewsDataSnapshot());
        });
        return () => {
            dispose();
            (0, views_window_mirror_1.clearViewsMirror)(tableId);
        };
    }, [tableId, dataModel]);
    // 异步 ViewsData → Model：占位快照不得锁死；仅非占位应用过一次后不再覆盖（防冲掉会话内改视图）
    React.useEffect(() => {
        var _a;
        if (!effectiveViewsConfigs)
            return;
        const { type, data } = effectiveViewsConfigs;
        if (type !== 'static' || data == null)
            return;
        const vd = data;
        const placeholder = Object.keys(vd.views || {}).length === 0 && !(vd.viewOrder && vd.viewOrder.length > 0);
        const allowApply = !viewsConfigsLoadedRef.current || (viewsAppliedWasPlaceholderRef.current && !placeholder);
        if (!allowApply)
            return;
        dataModel.setAllViews(data, { enableSmartFollow });
        stark_data_1.event.emit(listEventNames.LOOKUP_FIELD_SEARCH_CONFIG_UPDATE, (0, utils_1.createLookupSearchConfigUpdatePayload)((_a = dataModel.customFields) === null || _a === void 0 ? void 0 : _a.lookupConfig, 'hydrate'));
        viewsConfigsLoadedRef.current = true;
        viewsAppliedWasPlaceholderRef.current = placeholder;
        setViewsReady(true);
        if (enableAiFields && !aiColumnsInitializedRef.current && tableId) {
            aiColumnsInitializedRef.current = true;
            initializeAiColumns();
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [effectiveViewsConfigs, tableId, enableSmartFollow]);
    // 初始化 & 监听 props.primaryKey 变化，动态更新主键（支持 string 和 function）
    // 优先级：props.primaryKey > 服务端响应 _primaryKey（见下方 onRequest 钩子） > 默认值
    React.useEffect(() => {
        dataModel.setPrimaryKey(primaryKey || primary_key_1.DEFAULT_PRIMARY_KEY);
    }, [primaryKey, dataModel]);
    React.useEffect(() => {
        dataModel.setBizRequestConfig(bizRequestConfig);
    }, [bizRequestConfig, dataModel]);
    React.useEffect(() => {
        dataModel.setLookupFieldConfig(fieldTypeCaps.lookup);
    }, [fieldTypeCaps.lookup, dataModel]);
    React.useEffect(() => {
        dataModel.setGridToolbarPermissions(viewTypeCaps.grid.toolbarPermissions);
    }, [viewTypeCaps.grid.toolbarPermissions, dataModel]);
    React.useEffect(() => {
        dataModel.setHideColumnHeaderMenu(hideColumnHeaderMenu);
    }, [hideColumnHeaderMenu, dataModel]);
    // 获取所有视图
    const allViews = dataModel.getAllViews();
    // showViewTabs=false 时固定使用的 Grid 视图（优先主视图对应 Grid，其次任意 Grid）
    const gridView = React.useMemo(() => allViews.find((v) => v.type === 'Grid'), [allViews]);
    // showViewTabs=false 时，若当前激活视图不是 Grid，则自动切回 Grid，避免内容区/分页状态不一致
    React.useEffect(() => {
        if (showViewTabs !== false || !viewsReady || !gridView)
            return;
        const activeView = allViews.find((v) => v.id === dataModel.activeViewId);
        if (!activeView || activeView.type !== 'Grid') {
            dataModel.setActiveView(gridView.id);
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [showViewTabs, viewsReady, gridView === null || gridView === void 0 ? void 0 : gridView.id, dataModel.activeViewId]);
    // 使用分页 hook（总数由接口返回的 paging.totalCount 决定）
    const pageRenderInfo = (0, hooks_1.usePage)({
        defaultPageSize: props.defaultPageSize,
        defaultCurrentPage: props.defaultCurrentPage,
        onPageChange: props.onPageChange,
        // pageProps的用处？
        pageProps: props.pageProps,
        pageSizeList: props.pageSizeList,
    });
    // 保存排序等内置参 数
    const innerParams = React.useRef({});
    const [loading, setLoading] = React.useState(false);
    // 同步 loading 状态到 DataModel
    React.useEffect(() => {
        dataModel.setLoading(loading);
    }, [loading, dataModel]);
    // 创建 delegateHub 类似的结构（从 dataModel 和 props 中提取）
    const delegateHub = React.useMemo(() => {
        return {
            dataSource: dataModel.rawData,
            setDataSource: (data) => dataModel.setRawData(data),
            primaryKey: dataModel.primaryKey,
            setPrimaryKey: (key) => dataModel.setPrimaryKey(key),
            sorts: innerParams.current.sorts || [],
            setSorts: (sorts) => {
                innerParams.current.sorts = sorts;
            },
            loading,
            setLoading,
            size: 'medium',
            setSize: () => { }, // cn-ai-table 暂不支持 size 切换
            fullScreen: false,
            setFullScreen: () => { }, // cn-ai-table 暂不支持全屏
            zebra: false,
            setZebra: () => { }, // cn-ai-table 暂不支持斑马线切换
            columns: dataModel.originColumns || [],
            setColumns: (cols) => dataModel.setOriginColumns(cols),
            openKeys: [],
            setOpenKeys: () => { }, // cn-ai-table 暂不支持 openKeys
        };
    }, [dataModel, loading]);
    // 用于跟踪是否已经获取过 tableCount
    const hasTableCountRef = React.useRef(false);
    // 用于跟踪是否是第一次请求（用于判断是否需要触发分批次请求）
    const isFirstRequestRef = React.useRef(true);
    // 用于保存 fetchCall 的引用，确保在回调中能访问到最新的 fetchCall
    const fetchCallRef = React.useRef(null);
    const fetchCall = (0, use_remote_1.useRemote)({
        pageRenderInfo, // 分页信息
        setLoading, // 设置loading状态
        remote: effectiveRemote, // 远程数据源（含 lookup 首查参数兜底）
        innerParams, // 内部参数
        innerInfo: Object.assign({}, delegateHub, {
            // 内部信息
            selectKeys: dataModel.selectKeys,
            setSelectKeys: (keys, info) => dataModel.setSelectionInfo(keys, info),
            treeKeys: [],
            setTreeKeys: () => { },
            pageInfo: pageRenderInfo,
            selectInfo: dataModel.storeSelectInfo,
        }),
    }, (result, clearDataType) => {
        // 使用 ref 中保存的 fetchCall，确保能访问到最新的引用
        const currentFetchCall = fetchCallRef.current; // 请求成功后的回调函数
        (0, react_dom_1.unstable_batchedUpdates)(() => {
            var _a, _b;
            // 确保 result 是正确解析后的数据
            // 如果 result 是 { data: { tableData, paging, ... } } 格式，需要进一步解析
            const finalResult = ((result === null || result === void 0 ? void 0 : result.data) || result);
            const { tableColumns: sourceTableColumns, // 表格列信息
            tableData, // 表格数据
            paging: _paging, // 分页信息
            primaryKey: _primaryKey, // 主键
            tableCount: _tableCount, // 总数据条数（可能在响应根级别）
             } = (() => {
                const emptyObj = {};
                return finalResult || emptyObj;
            })();
            let tableColumns = sourceTableColumns;
            // @ts-ignore 下方为注释掉的远程列逻辑，保留供参考
            // const hasRemoteColumns = isEmpty(props.columns) && !isEmpty(tableColumns);
            // if (hasRemoteColumns) {
            //   // 远程数据源中有列信息
            //   setColumns(tableColumns); // 更新列信息
            // }
            const emptyColumns = !props.columns && (0, isEmpty_1.default)(tableColumns) && (0, isPlainObject_1.default)(tableData === null || tableData === void 0 ? void 0 : tableData[0]);
            if (emptyColumns) {
                // 远程数据源中没有列信息
                // @ts-ignore 远程无列时从首行推断列结构
                const data = ((tableData === null || tableData === void 0 ? void 0 : tableData[0]) || {});
                tableColumns = Object.keys(data)
                    .filter((key) => (0, isString_1.default)(data[key]) || (0, isNumber_1.default)(data[key]))
                    .map((key) => ({
                    name: key,
                    dataIndex: key,
                }));
                // setColumns(tableColumns); // 生成列信息
            }
            // 处理分页信息
            // 优先从响应根级别的 tableCount 获取，如果没有则从 paging 中获取
            const pagingData = _paging;
            const total = (_b = (_a = _tableCount !== null && _tableCount !== void 0 ? _tableCount : pagingData === null || pagingData === void 0 ? void 0 : pagingData.totalCount) !== null && _a !== void 0 ? _a : pagingData === null || pagingData === void 0 ? void 0 : pagingData.total) !== null && _b !== void 0 ? _b : 0;
            // 先获取用户设置的 pageSize 和 currentPage，用于判断是否是分批次请求
            const userPageSize = pageRenderInfo.pageSize;
            const MAX_API_PAGE_SIZE = 100;
            // 判断是否是分批次请求的结果
            // 注意：需要同时满足：
            // 1. 用户设置的 pageSize > 100
            // 2. 已经获取过 tableCount（hasTableCountRef.current === true）
            // 3. 返回的数据量等于用户设置的 pageSize（说明是分批次请求合并后的结果）
            const tableDataLength = Array.isArray(tableData) ? tableData.length : 0;
            const isBatchRequestResult = userPageSize > MAX_API_PAGE_SIZE &&
                hasTableCountRef.current &&
                tableDataLength === userPageSize;
            // 重要：优先使用 API 返回的 currentPage（mergeBatchResponses 中已正确设置为用户点击的页码）
            // 如果 API 返回的 currentPage 存在，使用它；否则使用 pageRenderInfo.currentPage
            // 这样可以避免 React 状态更新异步导致的问题
            const apiCurrentPage = pagingData === null || pagingData === void 0 ? void 0 : pagingData.currentPage;
            const pageRenderInfoCurrentPage = pageRenderInfo.currentPage;
            const userCurrentPage = apiCurrentPage !== null && apiCurrentPage !== void 0 ? apiCurrentPage : pageRenderInfoCurrentPage;
            // 更新总数（即使为0也要更新，确保分页组件能正确显示）
            // 注意：如果用户设置的 pageSize > 100，总数应该基于用户设置的 pageSize 来计算总页数
            // 但实际显示的总数应该是 tableCount（总数据条数）
            if (!(0, isNil_1.default)(total)) {
                pageRenderInfo.setTotal(total);
            }
            if (_paging) {
                // 更新每页数量
                // 注意：如果是分批次请求，不应该更新 pageSize，保持用户设置的 pageSize
                if (!(0, isNil_1.default)(pagingData === null || pagingData === void 0 ? void 0 : pagingData.pageSize) && !isBatchRequestResult) {
                    const currentUserPageSize = pageRenderInfo.pageSize;
                    const apiPageSize = pagingData.pageSize;
                    // 只有当 API 返回的 pageSize 与用户当前设置的 pageSize 一致时，才更新
                    // 或者用户设置的 pageSize <= 100 时，才用 API 返回的值更新
                    if (currentUserPageSize <= 100 || apiPageSize === currentUserPageSize) {
                        pageRenderInfo.setPageSize(apiPageSize);
                    }
                }
                // 更新当前页码（如果接口返回了当前页码）
                // 注意：如果是分批次请求，API 返回的 currentPage 是批次页码（1, 2, 3...），
                // 而不是用户设置的页码，所以不应该更新
                // 重要：分批次请求时，永远不要更新 currentPage，保持用户设置的页码
                if (!(0, isNil_1.default)(pagingData === null || pagingData === void 0 ? void 0 : pagingData.currentPage)) {
                    if (isBatchRequestResult) {
                        // 确保保持用户设置的页码，不更新
                        // 重要：使用 API 返回的 currentPage（mergeBatchResponses 中已正确设置）
                        // 这样可以避免 React 状态更新异步导致的问题
                        const targetCurrentPage = apiCurrentPage !== null && apiCurrentPage !== void 0 ? apiCurrentPage : userCurrentPage;
                        if (pageRenderInfo.currentPage !== targetCurrentPage) {
                            pageRenderInfo.setCurrent(targetCurrentPage);
                        }
                    }
                    else {
                        // 非分批次请求，使用 API 返回的 currentPage
                        pageRenderInfo.setCurrent(pagingData.currentPage);
                    }
                }
            }
            // 处理分批次请求逻辑
            // 如果用户设置的 pageSize > 100，且这是第一次获取到 tableCount，且当前在第一页
            // 需要触发分批次请求来获取完整的第一页数据
            // 注意：isBatchRequestResult 已经在上面定义了，这里不需要重复定义
            // 如果获取到了 tableCount，设置到 fetchCall 中（用于后续分批次请求）
            // 这个设置需要在判断之前完成
            if (!(0, isNil_1.default)(total) && total > 0 && !hasTableCountRef.current) {
                hasTableCountRef.current = true;
                // 设置 tableCount 到 fetchCall，用于后续分批次请求
                if (currentFetchCall && typeof currentFetchCall.setTableCount === 'function') {
                    currentFetchCall.setTableCount(total);
                }
            }
            // 检查是否需要触发分批次请求
            // 只有当 totalCount > 100 时才需要分批次请求
            const shouldTriggerBatch = userPageSize > MAX_API_PAGE_SIZE &&
                hasTableCountRef.current &&
                isFirstRequestRef.current &&
                userCurrentPage === 1 &&
                !(0, isNil_1.default)(total) &&
                total > MAX_API_PAGE_SIZE &&
                !isBatchRequestResult;
            if (shouldTriggerBatch) {
                isFirstRequestRef.current = false;
                // 延迟执行，避免在回调中直接触发请求导致状态混乱
                // 注意：不要传入 currentPage，让分批次请求逻辑自己计算批次页码
                setTimeout(() => {
                    const latestFetchCall = fetchCallRef.current;
                    if (latestFetchCall) {
                        latestFetchCall({});
                    }
                }, 0);
                return; // 提前返回，等待分批次请求完成后再更新数据（不更新 rawData）
            }
            // 只有在不会触发分批次请求时，才更新 rawData
            // 这样可以避免先更新为 100 行，然后再更新为 1000 行的问题
            if (Array.isArray(tableData)) {
                // 更新表格数据 - 创建新数组引用，确保 MobX 能检测到变化
                dataModel.setRawData([...tableData]);
            }
            else {
                dataModel.setRawData([]);
            }
            isFirstRequestRef.current = false;
            // 处理 clearDataType 相关逻辑，进行刷新后的信息清除
            if (clearDataType === 'refresh') {
                // 清空数据
                pageRenderInfo.setCurrent(1);
                isFirstRequestRef.current = true; // 重置首次请求标志
                hasTableCountRef.current = false; // 重置 tableCount 标志
                // 清除若干状态
                // clear(); // TODO: 实现 clear 函数
            }
            if (clearDataType === 'refreshExceptPaging') {
                // 清除若干状态
                // clear(); // TODO: 实现 clear 函数
            } // 如果服务端返回了 primaryKey，则更新主键
            if ((0, isString_1.default)(_primaryKey)) {
                dataModel.setPrimaryKey(_primaryKey);
            }
            // 批量更新
            (0, isFunction_1.default)(effectiveRemote === null || effectiveRemote === void 0 ? void 0 : effectiveRemote.dataChange) && (effectiveRemote === null || effectiveRemote === void 0 ? void 0 : effectiveRemote.dataChange(result)); // 数据变化回调
        });
    });
    // 保存 fetchCall 的引用到 ref，确保在回调中能访问到最新的 fetchCall
    React.useEffect(() => {
        fetchCallRef.current = fetchCall;
    }, [fetchCall]);
    // 公式列计算已下沉到 dataModel.setRawData 内部统一处理，
    // 这里不再需要外置的一次性兜底 effect。
    // 处理新建视图
    const handleCreateView = (viewType, viewName) => {
        (0, arms_hot_tag_log_1.armsHottagLog)({
            hottag: 'cn-ai-table.view.create',
            name: i18n_1.default.get({ id: 'CreateView', dm: '创建视图' }),
            c6: viewType,
            c7: viewName,
        });
        dataModel.createView(viewType, viewName);
        setViewTypeSelectorVisible(false);
    };
    // 处理视图切换
    const handleViewChange = (viewId) => {
        if (viewId !== 'add-view') {
            const view = allViews.find((v) => v.id === viewId);
            (0, arms_hot_tag_log_1.armsHottagLog)({
                hottag: 'cn-ai-table.view.switch',
                name: i18n_1.default.get({ id: 'SwitchView', dm: '切换视图' }),
                c6: viewId,
                c7: (view === null || view === void 0 ? void 0 : view.type) || '',
            });
            dataModel.setActiveView(viewId);
        }
    };
    // 处理新建视图Tab点击
    const handleAddViewClick = () => {
        (0, arms_hot_tag_log_1.armsHottagLog)({
            hottag: 'cn-ai-table.view.addViewClick',
            name: i18n_1.default.get({ id: 'AddView', dm: '添加视图' }),
        });
        setViewTypeSelectorVisible(true);
    };
    // 监听「点击跟单卡片切换至智能跟单」事件（由 AI 助理的 FollowOrderCard 触发）
    React.useEffect(() => {
        const handler = () => {
            if (!enableSmartFollow)
                return;
            // Tab 隐藏模式下不允许切换到非 Grid 视图
            if (showViewTabs === false)
                return;
            const views = dataModel.getAllViews();
            const smartFollow = views.find((v) => v.type === 'SmartFollow');
            if (smartFollow) {
                (0, arms_hot_tag_log_1.armsHottagLog)({
                    hottag: 'cn-ai-table.view.switchToSmartFollow',
                    name: i18n_1.default.get({ id: 'SwitchToSmartMerchandiser', dm: '切换到智能跟单' }),
                    c6: smartFollow.id,
                });
                dataModel.setActiveView(smartFollow.id);
            }
        };
        stark_data_1.event.on(listEventNames.SWITCH_TO_SMART_FOLLOW, handler);
        return () => stark_data_1.event.off(listEventNames.SWITCH_TO_SMART_FOLLOW, handler);
    }, [dataModel, listEventNames, enableSmartFollow]);
    // 根据视图类型获取对应的图标
    const getViewIcon = (viewType) => {
        const viewTypeIconMap = {
            Grid: 'table',
            Task: 'task',
            SmartFollow: 'smartFollow',
        };
        const iconName = viewTypeIconMap[viewType];
        if (!iconName)
            return null;
        return React.createElement(icons_1.SvgIcon, { name: iconName, size: 16 });
    };
    const smartFollowMenuItems = React.useMemo(() => [
        {
            key: 'smart-assistant',
            icon: React.createElement(icons_1.SvgIcon, { name: "aiSparkle", size: 14 }),
            label: i18n_1.default.get({ id: 'EditDocumentaryRequirements', dm: '编辑跟单要求' }),
        },
    ], []);
    const handleSmartFollowMenuClick = React.useCallback((key) => {
        if (key === 'smart-assistant') {
            stark_data_1.event.emit(listEventNames.OPEN_SMART_FOLLOW_ASSISTANT);
        }
    }, [listEventNames]);
    const tableInstanceDataAttr = {
        [event_constants_1.CN_AI_LIST_INSTANCE_KEY_DATA_ATTR]: instanceKey,
    };
    if (isLoadingViews || !viewsReady) {
        return (React.createElement(cn_ai_list_event_context_1.CnAiListEventContext.Provider, { value: listEventContextValue },
            React.createElement(mobx_react_simpler_1.ModelProvider, { dataModel: dataModel },
                React.createElement(cn_ui_1.CnLoading, { tip: i18n_1.default.get({ id: 'Loading', dm: '加载中...' }), inline: false },
                    React.createElement("div", { ...tableInstanceDataAttr })))));
    }
    return (React.createElement(cn_ai_list_event_context_1.CnAiListEventContext.Provider, { value: listEventContextValue },
        React.createElement(mobx_react_simpler_1.ModelProvider, { dataModel: dataModel },
            React.createElement("div", { className: `cn-mutiply-ai-table-container${showViewTabs ? '' : ' cn-mutiply-ai-table-container--no-tabs'}`, ...tableInstanceDataAttr },
                React.createElement("div", { className: "cn-mutiply-ai-table-content" },
                    React.createElement("div", { className: "cn-mutiply-ai-table-main" },
                        !showViewTabs && gridView && (React.createElement(ViewComponent, { viewId: gridView.id, viewType: gridView.type, showIndex: showIndex, showSelect: showSelect, rowSelection: rowSelection, onSelectChange: onSelectChange, operateColumn: operateColumn, toolbar: toolbar, groupMaxLevels: groupMaxLevels, columnsAutoWidth: columnsAutoWidth, columnsAutoWidthOpt: columnsAutoWidthOpt, fieldTypes: fieldTypeCaps, viewTypes: viewTypeCaps })),
                        showViewTabs && (React.createElement("div", { className: "cn-mutiply-ai-table-tab-sticky" },
                            React.createElement(cn_drag_tab_1.CnDragTab, { className: "cn-mutiply-ai-table-tab", activeKey: dataModel.activeViewId || undefined, onChange: handleViewChange, onDragEnd: (info) => {
                                    var _a, _b;
                                    // 获取主视图和 SmartFollow 视图的 ID
                                    const primaryViewId = (_a = allViews.find((v) => dataModel.isPrimaryView(v.id))) === null || _a === void 0 ? void 0 : _a.id;
                                    const smartFollowViewId = (_b = allViews.find((v) => v.type === 'SmartFollow')) === null || _b === void 0 ? void 0 : _b.id;
                                    // 从拖拽结果中过滤掉 add-view 按钮
                                    const draggedViewIds = info.newItems
                                        .filter((item) => item.key !== 'add-view')
                                        .map((item) => item.key);
                                    // 重新构建视图顺序：主视图和 SmartFollow 保持在最前面，其他视图按拖拽顺序排列
                                    const newViewIds = [];
                                    // 先添加主视图（如果存在）
                                    if (primaryViewId) {
                                        newViewIds.push(primaryViewId);
                                    }
                                    // 再添加 SmartFollow 视图（如果存在）
                                    if (smartFollowViewId) {
                                        newViewIds.push(smartFollowViewId);
                                    }
                                    // 最后添加其他视图（按拖拽后的顺序）
                                    draggedViewIds.forEach((viewId) => {
                                        if (viewId !== primaryViewId && viewId !== smartFollowViewId) {
                                            newViewIds.push(viewId);
                                        }
                                    });
                                    (0, arms_hot_tag_log_1.armsHottagLog)({
                                        hottag: 'cn-ai-table.view.reorder',
                                        name: i18n_1.default.get({ id: 'DragAndDropSortView', dm: '拖拽排序视图' }),
                                        c6: newViewIds.join(','),
                                    });
                                    dataModel.reorderViews(newViewIds);
                                }, items: [
                                    // 视图 tabs
                                    ...allViews.map((view) => {
                                        const isActive = view.id === dataModel.activeViewId;
                                        // 主视图和 SmartFollow 视图不能拖拽
                                        const canDrag = dataModel.canDragView(view.id);
                                        return {
                                            key: view.id,
                                            disableDrag: !canDrag,
                                            title: (React.createElement("div", { className: `cn-ai-table-tab-title ${isActive ? 'cn-ai-table-tab-title-active' : ''}` },
                                                React.createElement("span", { className: "cn-ai-table-tab-title-icon" }, getViewIcon(view.type)),
                                                React.createElement("span", { className: "cn-ai-table-tab-title-text" }, view.name),
                                                isActive && view.type === 'SmartFollow' && (React.createElement("span", { onClick: (e) => e.stopPropagation(), onMouseDown: (e) => e.stopPropagation(), onPointerDown: (e) => e.stopPropagation() },
                                                    React.createElement(view_menu_1.ViewMenu, { viewId: view.id, viewName: view.name, customItems: smartFollowMenuItems, onCustomItemClick: handleSmartFollowMenuClick, trigger: React.createElement(cn_ui_1.CnIcon, { type: "arrow-down", size: "large", className: "cn-ai-table-tab-menu-icon" }) }))),
                                                isActive && view.type !== 'SmartFollow' && (React.createElement("span", { onClick: (e) => e.stopPropagation(), onMouseDown: (e) => e.stopPropagation(), onPointerDown: (e) => e.stopPropagation() },
                                                    React.createElement(view_menu_1.ViewMenu, { viewId: view.id, viewName: view.name, trigger: React.createElement(cn_ui_1.CnIcon, { type: "arrow-down", size: "large", className: "cn-ai-table-tab-menu-icon" }) }))))),
                                            // 只渲染当前激活的视图内容，避免所有 TableView 同时渲染导致性能问题
                                            children: (React.createElement(ViewComponent, { viewId: view.id, viewType: view.type, showIndex: showIndex, showSelect: showSelect, rowSelection: rowSelection, onSelectChange: onSelectChange, operateColumn: operateColumn, toolbar: toolbar, groupMaxLevels: groupMaxLevels, columnsAutoWidth: columnsAutoWidth, columnsAutoWidthOpt: columnsAutoWidthOpt, fieldTypes: fieldTypeCaps, viewTypes: viewTypeCaps })),
                                        };
                                    }),
                                    // 添加视图按钮 - 禁用拖拽但允许点击
                                    {
                                        key: 'add-view',
                                        title: '',
                                        disabled: false, // 允许点击
                                        disableDrag: true, // 禁用拖拽
                                        icon: (React.createElement(cn_domain_popup_1.Popup, { visible: viewTypeSelectorVisible, onVisibleChange: setViewTypeSelectorVisible, container: floating_layer_1.getPopupContainer, trigger: React.createElement(cn_ui_1.CnTooltip, { triggerType: "hover", align: "b", popupProps: viewTypeSelectorVisible ? { visible: false } : undefined, trigger: React.createElement("div", null,
                                                    React.createElement(cn_ui_1.CnIcon, { type: "add" })) }, i18n_1.default.get({ id: 'AddView', dm: '添加视图' })), align: "br", offset: 15 },
                                            React.createElement(view_type_selector_1.ViewTypeSelector, { onVisibleChange: setViewTypeSelectorVisible, onSelect: handleCreateView, existingViews: allViews.map((view) => ({
                                                    type: view.type,
                                                    name: view.name,
                                                })), viewTypeCapabilities: viewTypeCaps }))),
                                        tabItemProps: {
                                            onClick: () => {
                                                handleAddViewClick();
                                            },
                                        },
                                    },
                                ] }))))),
                pageRenderInfo &&
                    (() => {
                        var _a;
                        const isGridView = !showViewTabs
                            ? Boolean(gridView)
                            : ((_a = allViews.find((view) => view.id === dataModel.activeViewId)) === null || _a === void 0 ? void 0 : _a.type) === 'Grid';
                        if (!isGridView) {
                            return null;
                        }
                        return (React.createElement("div", { className: "cn-mutiply-ai-table-pagination-wrapper", style: {
                                display: 'flex',
                                justifyContent: 'space-between',
                                alignItems: 'center',
                                flexShrink: 0,
                            } },
                            React.createElement(total_info_1.TotalInfo, { tableInfo: {
                                    showSelectedNum: dataModel.showSelectedNum,
                                    selectKeys: dataModel.selectKeys,
                                    selectedCountInCurrentView: dataModel.selectedCountInCurrentView,
                                    total: pageRenderInfo.total,
                                    storeSelectInfo: dataModel.storeSelectInfo,
                                } }),
                            React.createElement(cn_ui_1.CnPagination, { currentPage: pageRenderInfo.currentPage, pageSize: pageRenderInfo.pageSize, totalCount: pageRenderInfo.total || 0, pageSizeList: pageRenderInfo.pageSizeList, pageSizeSelector: "dropdown", onChange: (page) => {
                                    (0, arms_hot_tag_log_1.armsHottagLog)({
                                        hottag: 'cn-ai-table.pagination.change',
                                        name: i18n_1.default.get({ id: 'SwitchPageNumbers', dm: '切换页码' }),
                                        c6: String(page),
                                    });
                                    pageRenderInfo.setCurrent(page);
                                    // 切换页码保留选中项，支持跨页选中（不发送 PAGINATION_CHANGE）
                                    if (fetchCall) {
                                        fetchCall({ currentPage: page });
                                    }
                                }, onPageSizeChange: (pageSize) => {
                                    (0, arms_hot_tag_log_1.armsHottagLog)({
                                        hottag: 'cn-ai-table.pagination.changePageSize',
                                        name: i18n_1.default.get({ id: 'ToggleAmountPerPage', dm: '切换每页数量' }),
                                        c6: String(pageSize),
                                    });
                                    pageRenderInfo.setPageSize(pageSize);
                                    // 切换 pageSize 保留选中项，支持跨页选中（不发送 PAGINATION_CHANGE）
                                    if (fetchCall) {
                                        fetchCall({ currentPage: 1, pageSize });
                                    }
                                }, size: "small" })));
                    })()))));
});
exports.CnAiTable.displayName = 'CnAiTable';
