"use strict";
/**
 * 行选择插件
 *
 * 作为行选择的**单一来源**，提供全部选择能力：
 * - 单选 / 多选
 * - 全选 / 半选态
 * - 跨页保留选中
 * - 事件总线通知（ROW_SELECT / CELL_CLEAR）
 *
 * 数据源口径统一为当前**可见数据**（筛选后），由调用方通过
 * pipeline.setContext('visibleData', ...) 预注入。
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.rowSelectionPlugin = rowSelectionPlugin;
const stark_data_1 = require("@ice/stark-data");
const primary_key_1 = require("../../../../../../../cn-ai-table/view/utils/primary-key");
function rowSelectionPlugin(options) {
    return (pipeline) => {
        const { enabled, selectionType, selectedKeys, primaryKey, dataSource, setSelectKeys, disabledRowKeys, eventNames, } = options;
        if (!enabled) {
            return pipeline;
        }
        // ---------- 派生状态 ----------
        const selectableRowKeys = dataSource
            .filter((record, index) => {
            const recordKey = (0, primary_key_1.safeGetRowKey)(record, primaryKey, index);
            for (const key of disabledRowKeys) {
                if ((0, primary_key_1.isSameRowKey)(key, recordKey))
                    return false;
            }
            return true;
        })
            .map((record, index) => (0, primary_key_1.safeGetRowKey)(record, primaryKey, index));
        let selectAllState = { checked: false, indeterminate: false };
        if (selectableRowKeys.length > 0) {
            const selectedCount = selectableRowKeys.filter((key) => selectedKeys.some((sk) => (0, primary_key_1.isSameRowKey)(sk, key))).length;
            const allSelected = selectedCount === selectableRowKeys.length;
            selectAllState = {
                checked: allSelected,
                indeterminate: selectedCount > 0 && !allSelected,
            };
        }
        // ---------- Handlers ----------
        const handlers = {
            handleRowSelectChange: (rowId, selected) => {
                if (!setSelectKeys)
                    return;
                let newSelectedKeys;
                if (selectionType === 'single') {
                    newSelectedKeys = selected ? [rowId] : [];
                }
                else {
                    newSelectedKeys = selected
                        ? [...selectedKeys, rowId]
                        : selectedKeys.filter((key) => !(0, primary_key_1.isSameRowKey)(key, rowId));
                }
                const selectedRows = dataSource.filter((row, idx) => newSelectedKeys.some((key) => (0, primary_key_1.isSameRowKey)(key, (0, primary_key_1.safeGetRowKey)(row, primaryKey, idx))));
                setSelectKeys(newSelectedKeys, selectedRows);
                if (newSelectedKeys.length > 0) {
                    stark_data_1.event.emit(eventNames.ROW_SELECT, {
                        type: 'row',
                        selectedRowKeys: newSelectedKeys,
                        selectedRows,
                    });
                }
                else {
                    stark_data_1.event.emit(eventNames.CELL_CLEAR);
                }
            },
            isRowSelected: (rowId) => {
                return selectedKeys.some((key) => (0, primary_key_1.isSameRowKey)(key, rowId));
            },
            isRowDisabled: (record, index) => {
                const recordKey = (0, primary_key_1.safeGetRowKey)(record, primaryKey, index);
                for (const key of disabledRowKeys) {
                    if ((0, primary_key_1.isSameRowKey)(key, recordKey))
                        return true;
                }
                return false;
            },
            selectableRowKeys,
            selectAllState,
            handleSelectAll: (checked) => {
                if (!setSelectKeys)
                    return;
                const currentPageKeys = dataSource.map((r, idx) => (0, primary_key_1.safeGetRowKey)(r, primaryKey, idx));
                const isInCurrentPage = (key) => currentPageKeys.some((pk) => (0, primary_key_1.isSameRowKey)(pk, key));
                if (checked) {
                    const crossPage = selectedKeys.filter((key) => !isInCurrentPage(key));
                    const merged = [...crossPage, ...selectableRowKeys];
                    const unique = [];
                    for (const key of merged) {
                        if (!unique.some((k) => (0, primary_key_1.isSameRowKey)(k, key))) {
                            unique.push(key);
                        }
                    }
                    const selectedRows = dataSource.filter((r, idx) => unique.some((key) => (0, primary_key_1.isSameRowKey)(key, (0, primary_key_1.safeGetRowKey)(r, primaryKey, idx))));
                    setSelectKeys(unique, selectedRows);
                    stark_data_1.event.emit(eventNames.ROW_SELECT, {
                        type: 'row',
                        selectedRowKeys: unique,
                        selectedRows,
                    });
                }
                else {
                    const crossPage = selectedKeys.filter((key) => !isInCurrentPage(key));
                    setSelectKeys(crossPage, []);
                    if (crossPage.length > 0) {
                        stark_data_1.event.emit(eventNames.ROW_SELECT, {
                            type: 'row',
                            selectedRowKeys: crossPage,
                            selectedRows: [],
                        });
                    }
                    else {
                        stark_data_1.event.emit(eventNames.CELL_CLEAR);
                    }
                }
            },
            handleClearSelection: () => {
                if (!setSelectKeys)
                    return;
                setSelectKeys([], []);
                stark_data_1.event.emit(eventNames.CELL_CLEAR);
            },
        };
        pipeline.setContext('rowSelectionHandlers', handlers);
        pipeline.setConfig({
            rowSelection: {
                enabled,
                selectionType,
                selectedKeys,
                primaryKey,
                dataSource,
            },
        });
        return pipeline;
    };
}
