"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.selectRowForPageConfig = selectRowForPageConfig;
exports.findComponentIndex = findComponentIndex;
exports.readTableViewFromComponents = readTableViewFromComponents;
exports.readAiColumnsConfigFromComponents = readAiColumnsConfigFromComponents;
exports.mergeAiColumnsConfigIntoComponents = mergeAiColumnsConfigIntoComponents;
exports.upsertAiColumnInComponents = upsertAiColumnInComponents;
exports.removeAiColumnFromComponents = removeAiColumnFromComponents;
exports.mergeTableViewIntoComponents = mergeTableViewIntoComponents;
exports.loadUserCubeConfigFromPlatform = loadUserCubeConfigFromPlatform;
const get_list_from_cube_1 = require("./get-list-from-cube");
const EMPTY_USER_CUBE = { components: [] };
/**
 * 选用哪一行解析「整页」userCubeConfig。勿按 tableId 在 components 里筛行，避免首存新表丢同页其它表。
 * 单行 = 与魔方 `tableData[0]` 一致；多行 = 取 gmtModified 最新。
 */
function selectRowForPageConfig(tableData) {
    if (!tableData.length) {
        return null;
    }
    if (tableData.length === 1) {
        return tableData[0];
    }
    return [...tableData].sort((a, b) => (Number(b.gmtModified) || 0) - (Number(a.gmtModified) || 0))[0];
}
function findComponentIndex(components, tableId, nodeId) {
    return components.findIndex((item) => item.tableId === tableId || (!!nodeId && item.nodeId === nodeId));
}
function readTableViewFromComponents(components, tableId) {
    var _a, _b, _c;
    if (!tableId || !(components === null || components === void 0 ? void 0 : components.length)) {
        return null;
    }
    const i = findComponentIndex(components, tableId);
    return i >= 0 ? ((_c = (_b = (_a = components[i]) === null || _a === void 0 ? void 0 : _a.config) === null || _b === void 0 ? void 0 : _b.tableView) !== null && _c !== void 0 ? _c : null) : null;
}
/** 对齐魔方 `__AI_Field_Fun__.getAiColumn`：`components[].config.columns.config` */
function readAiColumnsConfigFromComponents(components, tableId) {
    var _a, _b;
    if (!tableId || !(components === null || components === void 0 ? void 0 : components.length)) {
        return [];
    }
    const i = findComponentIndex(components, tableId);
    if (i < 0) {
        return [];
    }
    const wrap = (_b = (_a = components[i]) === null || _a === void 0 ? void 0 : _a.config) === null || _b === void 0 ? void 0 : _b.columns;
    return Array.isArray(wrap === null || wrap === void 0 ? void 0 : wrap.config) ? wrap.config : [];
}
/** 对齐魔方：整表替换该 `tableId` 下的 `columns.config` 数组 */
function mergeAiColumnsConfigIntoComponents(components, payload) {
    const { tableId, nodeId, columns } = payload;
    const next = (components || []).slice();
    const index = findComponentIndex(next, tableId, nodeId);
    if (index > -1) {
        const prev = next[index];
        next[index] = {
            ...prev,
            config: { ...(prev.config || {}), columns: { config: columns } },
        };
    }
    else {
        next.push({
            nodeId,
            tableId,
            componentName: 'CnTable',
            config: { columns: { config: columns } },
        });
    }
    return next;
}
function upsertAiColumnInComponents(components, payload) {
    var _a;
    const { tableId, nodeId, column } = payload;
    const existing = readAiColumnsConfigFromComponents(components, tableId);
    const columnCode = String((_a = column.columnCode) !== null && _a !== void 0 ? _a : '');
    const idx = existing.findIndex((c) => {
        const o = c;
        return o && String(o.columnCode) === columnCode;
    });
    const nextCols = [...existing];
    if (idx > -1) {
        nextCols[idx] = column;
    }
    else {
        nextCols.push(column);
    }
    return mergeAiColumnsConfigIntoComponents(components, { tableId, nodeId, columns: nextCols });
}
function removeAiColumnFromComponents(components, payload) {
    const { tableId, nodeId, columnCode } = payload;
    const existing = readAiColumnsConfigFromComponents(components, tableId);
    const nextCols = existing.filter((c) => {
        const o = c;
        return !o || String(o.columnCode) !== columnCode;
    });
    return mergeAiColumnsConfigIntoComponents(components, { tableId, nodeId, columns: nextCols });
}
/** 对齐 funcMap.setTableView：命中则改 tableView，否则 push CnTable。 */
function mergeTableViewIntoComponents(components, payload) {
    const { tableId, viewsData, nodeId } = payload;
    const next = (components || []).slice();
    const index = findComponentIndex(next, tableId, nodeId);
    if (index > -1) {
        const prev = next[index];
        next[index] = {
            ...prev,
            config: { ...(prev.config || {}), tableView: viewsData },
        };
    }
    else {
        next.push({
            nodeId,
            tableId,
            componentName: 'CnTable',
            config: { tableView: viewsData },
        });
    }
    return next;
}
/**
 * getList → 解析一行 content → userCubeConfig；行 id 写入根级 id（配置行主键）。
 */
async function loadUserCubeConfigFromPlatform(meta, bizRequestConfig) {
    var _a;
    try {
        const tableData = await (0, get_list_from_cube_1.fetchUserCubeTableRows)(meta, bizRequestConfig);
        if (!tableData.length) {
            return {
                userCubeConfig: { ...EMPTY_USER_CUBE, id: '', components: [] },
                userCubeConfigRowId: '',
            };
        }
        const row = selectRowForPageConfig(tableData);
        if (!(row === null || row === void 0 ? void 0 : row.content)) {
            return {
                userCubeConfig: { ...EMPTY_USER_CUBE, id: '', components: [] },
                userCubeConfigRowId: '',
            };
        }
        const parsed = JSON.parse(row.content);
        const userCubeConfigRowId = String((_a = row.id) !== null && _a !== void 0 ? _a : '');
        if (userCubeConfigRowId) {
            parsed.id = userCubeConfigRowId;
        }
        if (!Array.isArray(parsed.components)) {
            parsed.components = [];
        }
        return { userCubeConfig: parsed, userCubeConfigRowId };
    }
    catch {
        return {
            userCubeConfig: { ...EMPTY_USER_CUBE, id: '', components: [] },
            userCubeConfigRowId: '',
        };
    }
}
