"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createGetGroupInfo = createGetGroupInfo;
const i18n_1 = __importDefault(require("../../../../../../../../locales/i18n.js"));
function resolveGroupRowFromTable(table, groupRow) {
    const rowsById = table.getRowModel().rowsById;
    return (groupRow === null || groupRow === void 0 ? void 0 : groupRow.id) && (rowsById === null || rowsById === void 0 ? void 0 : rowsById[groupRow.id]) ? rowsById[groupRow.id] : groupRow;
}
/**
 * 统计子树中「数据行」条数（不含中间分组行）。
 * 注意：table-core Row.getLeafRows 实现为 flattenBy(subRows)，会把嵌套分组行也算进数组，不能用于条数。
 */
function countDataRowsUnderGroup(groupRow) {
    const walk = (rows) => {
        if (!Array.isArray(rows) || rows.length === 0)
            return 0;
        let n = 0;
        for (const r of rows) {
            const row = r;
            if (typeof row.getIsGrouped === 'function' && row.getIsGrouped()) {
                n += walk(row.subRows);
            }
            else {
                n += 1;
            }
        }
        return n;
    };
    return walk(groupRow.subRows);
}
/**
 * 组内数据行数量：优先使用分组模型上的 leafRows（与 getGroupedRowModel 一致，即真实记录数）。
 * 不再与 getLeafRows().length / subRows.length 取 max，否则多级分组会把中间层行数叠进去，与底栏「共 N 项」不一致。
 */
function resolveSubRowsCount(table, groupRow, resolvedGroupRow) {
    var _a, _b;
    const leafRowsArr = resolvedGroupRow.leafRows;
    if (Array.isArray(leafRowsArr) && leafRowsArr.length > 0) {
        return leafRowsArr.length;
    }
    const fromTree = countDataRowsUnderGroup(resolvedGroupRow);
    if (fromTree > 0) {
        return fromTree;
    }
    if (groupRow === null || groupRow === void 0 ? void 0 : groupRow.id) {
        try {
            const groupedModel = (_a = table.getGroupedRowModel) === null || _a === void 0 ? void 0 : _a.call(table);
            const fromGrouped = (_b = groupedModel === null || groupedModel === void 0 ? void 0 : groupedModel.rowsById) === null || _b === void 0 ? void 0 : _b[groupRow.id];
            if (fromGrouped) {
                const gl = Array.isArray(fromGrouped.leafRows) ? fromGrouped.leafRows.length : 0;
                if (gl > 0)
                    return gl;
                return countDataRowsUnderGroup(fromGrouped);
            }
        }
        catch {
            /* ignore */
        }
    }
    return 0;
}
function pickSampleOriginal(subRowsArr, leafRowsArr) {
    let sampleRow;
    if (Array.isArray(subRowsArr) && subRowsArr.length > 0) {
        sampleRow = subRowsArr[0];
    }
    else if (Array.isArray(leafRowsArr) && leafRowsArr.length > 0) {
        sampleRow = leafRowsArr[0];
    }
    if (sampleRow && typeof sampleRow === 'object' && sampleRow !== null && 'original' in sampleRow) {
        return sampleRow.original;
    }
    return undefined;
}
function columnHeaderText(table, groupingColumnId) {
    const groupingColumn = table.getColumn(groupingColumnId);
    if (!groupingColumn) {
        return i18n_1.default.get({ id: 'Grouping', dm: '分组' });
    }
    const columnHeader = groupingColumn.columnDef.header;
    if (typeof columnHeader === 'string') {
        return columnHeader;
    }
    // 与历史逻辑一致：函数型 header 不落默认「分组」，非函数则 String 化
    if (typeof columnHeader !== 'function') {
        return String(columnHeader);
    }
    return i18n_1.default.get({ id: 'Grouping', dm: '分组' });
}
/**
 * 工厂：返回「根据分组行解析表头展示信息」的函数（支持嵌套分组）
 */
function createGetGroupInfo(props) {
    const { grouping, table, formatGroupValue } = props;
    return (groupRow) => {
        var _a;
        const depth = groupRow.depth || 0;
        const groupingColumnId = grouping[depth];
        if (!groupingColumnId)
            return null;
        const resolvedGroupRow = resolveGroupRowFromTable(table, groupRow);
        const groupValue = (_a = resolvedGroupRow.getValue(groupingColumnId)) !== null && _a !== void 0 ? _a : resolvedGroupRow.groupingValue;
        const leafRowsArr = resolvedGroupRow.leafRows;
        const subRowsArr = resolvedGroupRow.subRows;
        const subRowsCount = resolveSubRowsCount(table, groupRow, resolvedGroupRow);
        const sampleRowData = pickSampleOriginal(subRowsArr, leafRowsArr);
        const formattedGroupValue = formatGroupValue(groupingColumnId, groupValue, sampleRowData);
        return {
            columnHeader: columnHeaderText(table, groupingColumnId),
            groupValue: formattedGroupValue,
            depth,
            subRowsCount,
        };
    };
}
