import * as React from 'react';
import { observer } from 'mobx-react-lite';
import { useModel } from '../../../../../../../utils/mobx-react-simpler/index.js';
import { NormalTableView } from '../normal-table-view';
import { useCellFormat } from '../../../../../../../cn-ai-table/hooks/useCellFormat';
import { useGroupValueFormatter } from '../../../../../../../cn-ai-table/hooks/useGroupValueFormatter';
import { GroupedHeaderRow } from './components/grouped-header-row';
import { GroupedSpacerRow } from './components/grouped-spacer-row';
import { useExpandOnGroupingChange } from './hooks/use-expand-on-grouping';
import { useGroupRowDragEnd } from './hooks/use-group-row-drag-end';
import { buildGroupedVirtualRows } from './utils/build-virtual-rows';
import { createGetGroupInfo } from './utils/group-info';
import './styles/grouped-table-view.scss';
/**
 * 有分组配置时：用虚拟行（间隔 + 分组头 + 数据）驱动 NormalTableView，并处理跨组拖拽。
 * 无分组时不渲染表格，仅外层容器。
 */
export const GroupedTableView = 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 = useModel('dataModel');
    const { processedColumnMap } = useCellFormat(dataModel.columnDefinitions);
    const formatGroupValue = 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]);
    useExpandOnGroupingChange({
        table,
        groupingFieldsKey,
        groupingLength: grouping.length,
        dataSource: dataModel.rawData,
    });
    // 解析分组行 → 表头文案、格式化值、条数
    const getGroupInfo = React.useMemo(() => createGetGroupInfo({ grouping, table, formatGroupValue }), [grouping, table, formatGroupValue]);
    // 拍平分组树为虚拟列表项；依赖 expanded 以免折叠时引用不变不重算
    const { expanded } = table.getState();
    const customRows = React.useMemo(() => buildGroupedVirtualRows(table), 
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [table.getRowModel().rows, grouping, expanded]);
    // 同组排序 rawData；跨组调接口改分组字段
    const handleRowDragEnd = 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(GroupedSpacerRow, { key: `spacer-${virtualRow.index}`, totalColSpan: totalColSpan });
        }
        if (type === 'group' && row) {
            return (React.createElement(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(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));
});
