"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;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.GroupedTableView = void 0;
const React = __importStar(require("react"));
const mobx_react_lite_1 = require("mobx-react-lite");
const mobx_react_simpler_1 = require("../../../../../../../utils/mobx-react-simpler/index.js");
const normal_table_view_1 = require("../normal-table-view");
const useCellFormat_1 = require("../../../../../../../cn-ai-table/hooks/useCellFormat");
const useGroupValueFormatter_1 = require("../../../../../../../cn-ai-table/hooks/useGroupValueFormatter");
const grouped_header_row_1 = require("./components/grouped-header-row");
const grouped_spacer_row_1 = require("./components/grouped-spacer-row");
const use_expand_on_grouping_1 = require("./hooks/use-expand-on-grouping");
const use_group_row_drag_end_1 = require("./hooks/use-group-row-drag-end");
const build_virtual_rows_1 = require("./utils/build-virtual-rows");
const group_info_1 = require("./utils/group-info");
require("./styles/grouped-table-view.scss");
/**
 * 有分组配置时：用虚拟行（间隔 + 分组头 + 数据）驱动 NormalTableView，并处理跨组拖拽。
 * 无分组时不渲染表格，仅外层容器。
 */
exports.GroupedTableView = (0, mobx_react_lite_1.observer)(function GroupedTableView(props) {
    var _a;
    const { viewId, table, columns, viewColumnMetaData, showIndex = true, rowSelectionProps, widthMap: widthMapFromProps, operateColumn, onShowFilterPanel, onShowSortPanel, onShowGroupPanel, onShowColorFillPanel, enableAiFields, } = props;
    // 列定义 → 分组列展示格式化
    const dataModel = (0, mobx_react_simpler_1.useModel)('dataModel');
    const { processedColumnMap } = (0, useCellFormat_1.useCellFormat)(dataModel.columnDefinitions);
    const formatGroupValue = (0, useGroupValueFormatter_1.useGroupValueFormatter)(processedColumnMap);
    const viewConfig = dataModel.getViewConfig(viewId);
    // 当前视图分组字段；空则整表不走分组 UI
    const grouping = React.useMemo(() => {
        var _a;
        if (((_a = viewConfig.group) === null || _a === void 0 ? void 0 : _a.length) > 0) {
            return viewConfig.group.map((g) => g.field).filter(Boolean);
        }
        return [];
    }, [viewConfig.group]);
    // 与表体列宽一致，分组头合并单元格用
    const widthMap = React.useMemo(() => { var _a; return widthMapFromProps || ((_a = viewConfig.custom) === null || _a === void 0 ? void 0 : _a.widthMap) || {}; }, [widthMapFromProps, (_a = viewConfig.custom) === null || _a === void 0 ? void 0 : _a.widthMap]);
    // 分组字段变化或 rawData 刷新（新引用）时全展开，不保留折叠
    const groupingFieldsKey = React.useMemo(() => grouping.join('\0'), [grouping]);
    (0, use_expand_on_grouping_1.useExpandOnGroupingChange)({
        table,
        groupingFieldsKey,
        groupingLength: grouping.length,
        dataSource: dataModel.rawData,
    });
    // 解析分组行 → 表头文案、格式化值、条数
    const getGroupInfo = React.useMemo(() => (0, group_info_1.createGetGroupInfo)({ grouping, table, formatGroupValue }), [grouping, table, formatGroupValue]);
    // 拍平分组树为虚拟列表项；依赖 expanded 以免折叠时引用不变不重算
    const { expanded } = table.getState();
    const customRows = React.useMemo(() => (0, build_virtual_rows_1.buildGroupedVirtualRows)(table), 
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [table.getRowModel().rows, grouping, expanded]);
    // 同组排序 rawData；跨组调接口改分组字段
    const handleRowDragEnd = (0, use_group_row_drag_end_1.useGroupRowDragEnd)({
        table,
        dataModel: dataModel,
        grouping,
    });
    // custom 行：spacer / 分组头；数据行仍由 NormalTableView 默认渲染
    const customRowRenderer = React.useCallback((virtualRow, _index, rows) => {
        var _a;
        const rowItem = rows[virtualRow.index];
        if (!rowItem || rowItem.type !== 'custom' || !rowItem.data) {
            return null;
        }
        const { type, row, depth, isFirstGroup } = rowItem.data;
        const headerGroups = table.getHeaderGroups();
        const visibleCells = ((_a = headerGroups[0]) === null || _a === void 0 ? void 0 : _a.headers) || [];
        const totalColSpan = visibleCells.length + 1;
        if (type === 'spacer') {
            return React.createElement(grouped_spacer_row_1.GroupedSpacerRow, { key: `spacer-${virtualRow.index}`, totalColSpan: totalColSpan });
        }
        if (type === 'group' && row) {
            return (React.createElement(grouped_header_row_1.GroupedHeaderRow, { key: row.id, table: table, groupRow: row, virtualRowSize: virtualRow.size, depth: depth !== null && depth !== void 0 ? depth : 0, isFirstGroup: Boolean(isFirstGroup), widthMap: widthMap, getGroupInfo: getGroupInfo, showIndex: showIndex, rowSelectionProps: rowSelectionProps, operateColumn: operateColumn }));
        }
        return null;
    }, [table, widthMap, getGroupInfo, operateColumn, showIndex, rowSelectionProps]);
    return (React.createElement("div", { className: "table-group-content-container" }, grouping.length > 0 ? (React.createElement(normal_table_view_1.NormalTableView, { viewId: viewId, table: table, columns: columns, viewColumnMetaData: viewColumnMetaData, customRows: customRows, customRowRenderer: customRowRenderer, onRowDragEnd: handleRowDragEnd, rowHeight: "low", showIndex: showIndex, rowSelectionProps: rowSelectionProps, widthMap: widthMap, operateColumn: operateColumn, onShowFilterPanel: onShowFilterPanel, onShowSortPanel: onShowSortPanel, onShowGroupPanel: onShowGroupPanel, onShowColorFillPanel: onShowColorFillPanel, enableAiFields: enableAiFields })) : null));
});
