"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.List = void 0;
const i18n_1 = __importDefault(require("../../../../../locales/i18n.js"));
/**
 * @deprecated 看板视图组件 - 暂时未使用
 * 用于展示看板视图，以卡片形式展示数据，支持分组和虚拟滚动
 * 当前功能尚未启用，保留代码以备后续使用
 */
const cn_ui_1 = require("@cainiaofe/cn-ui");
const react_1 = __importDefault(require("react"));
const mobx_react_lite_1 = require("mobx-react-lite");
const toolbar_1 = require("../../toolbar/toolbar");
const mobx_react_simpler_1 = require("../../../../../utils/mobx-react-simpler/index.js");
const useCellFormat_1 = require("../../../../hooks/useCellFormat");
const useGroupValueFormatter_1 = require("../../../../hooks/useGroupValueFormatter");
const card_config_1 = require("../../configs/card-config/card-config");
const react_virtual_1 = require("../../../../../cn-ai-table/react-virtual");
const use_ai_table_icons_1 = require("../../../../../cn-ai-table/view/hooks/use-ai-table-icons");
const primary_key_1 = require("../../../../../cn-ai-table/view/utils/primary-key");
require("./list-view.scss");
const ListItem = (0, mobx_react_lite_1.observer)(({ groupTitle, data, displayColumns, groupingFields, processedColumnMap, showFieldTitle, primaryKey, onItemClick, }) => {
    const fieldsToShow = react_1.default.useMemo(() => {
        return displayColumns.filter((col) => !groupingFields.includes(col.dataIndex));
    }, [displayColumns, groupingFields]);
    // 渲染单元格内容（使用与表格视图相同的格式化方式）
    const renderCellValue = (col, value, rowIndex, rowData) => {
        const processedCol = processedColumnMap.get(col.dataIndex);
        // 优先使用预处理后的 cell 渲染函数
        if (processedCol === null || processedCol === void 0 ? void 0 : processedCol.cell) {
            return processedCol.cell(value, rowIndex, rowData);
        }
        // 如果有 render 函数，也使用它
        if (processedCol === null || processedCol === void 0 ? void 0 : processedCol.render) {
            return processedCol.render(value, rowIndex, rowData);
        }
        // fallback: 直接显示值
        return value !== null && value !== void 0 ? value : '- -';
    };
    // 渲染卡片内容
    const renderCardContent = (item, rowIndex) => {
        return (react_1.default.createElement("div", { className: "list-description" }, fieldsToShow.map((col) => {
            const value = item[col.dataIndex];
            const displayValue = renderCellValue(col, value, rowIndex, item);
            const hasTitle = showFieldTitle;
            return (react_1.default.createElement("div", { key: col.dataIndex, className: `list-description-item ${hasTitle ? 'list-description-item-with-title' : 'list-description-item-no-title'}` },
                hasTitle && react_1.default.createElement("div", { className: "list-description-label" }, col.title),
                react_1.default.createElement("div", { className: `list-description-value ${hasTitle
                        ? 'list-description-value-with-title'
                        : 'list-description-value-no-title'}` }, displayValue)));
        })));
    };
    // 渲染卡片标题
    const renderCardTitle = (item, rowIndex) => {
        // 尝试获取第一个可显示字段作为标题
        const titleField = displayColumns.find((col) => {
            const value = item[col.dataIndex];
            return value !== null && value !== undefined && value !== '';
        });
        if (!titleField) {
            return i18n_1.default.get({ id: 'Untitled', dm: '无标题' });
        }
        const titleValue = item[titleField.dataIndex];
        return renderCellValue(titleField, titleValue, rowIndex, item);
    };
    return (react_1.default.createElement("div", null,
        react_1.default.createElement("div", { className: "list-tag" },
            react_1.default.createElement("span", { className: "list-tag-text" }, groupTitle),
            react_1.default.createElement("span", { className: "list-tag-count" }, data.length)),
        react_1.default.createElement(VirtualizedCardList, { data: data, renderCardContent: renderCardContent, renderCardTitle: renderCardTitle, showFieldTitle: showFieldTitle, onItemClick: onItemClick, visibleFieldCount: fieldsToShow.length, primaryKey: primaryKey })));
});
const VirtualizedCardList = ({ data, renderCardContent, renderCardTitle, showFieldTitle, onItemClick, visibleFieldCount, primaryKey, }) => {
    const scrollContainerRef = react_1.default.useRef(null);
    const estimatedCardHeight = react_1.default.useMemo(() => {
        const base = showFieldTitle ? 140 : 120;
        const perField = 28;
        return base + visibleFieldCount * perField;
    }, [showFieldTitle, visibleFieldCount]);
    const virtualizer = (0, react_virtual_1.useVirtualizer)({
        count: data.length,
        getScrollElement: () => scrollContainerRef.current,
        estimateSize: () => estimatedCardHeight,
        overscan: 5,
    });
    const virtualItems = virtualizer.getVirtualItems();
    const paddingTop = virtualItems.length > 0 ? virtualItems[0].start : 0;
    const paddingBottom = virtualItems.length > 0
        ? virtualizer.getTotalSize() - virtualItems[virtualItems.length - 1].end
        : 0;
    const virtualizedData = virtualItems
        .map((virtualItem) => ({
        virtualItem,
        record: data[virtualItem.index],
    }))
        .filter((item) => item.record);
    return (react_1.default.createElement("div", { className: "list-item-scroll", ref: scrollContainerRef },
        react_1.default.createElement("div", { style: { height: paddingTop } }),
        react_1.default.createElement(cn_ui_1.CnListPro, { shape: "card", grid: {
                column: 1,
                wrap: true,
            }, dataSource: virtualizedData, renderItem: (item) => {
                const { virtualItem, record } = item;
                if (!record) {
                    return null;
                }
                const rowKey = (0, primary_key_1.safeGetRowKey)(record, primaryKey, virtualItem.index);
                return (react_1.default.createElement("div", { key: rowKey, "data-index": virtualItem.index, ref: virtualizer.measureElement },
                    react_1.default.createElement(cn_ui_1.CnListProItem, { className: "list-item", onClick: () => onItemClick === null || onItemClick === void 0 ? void 0 : onItemClick(record), style: { cursor: 'pointer' }, title: renderCardTitle(record, virtualItem.index), description: renderCardContent(record, virtualItem.index) })));
            } }),
        react_1.default.createElement("div", { style: { height: paddingBottom } })));
};
/**
 * 看板视图
 */
exports.List = (0, mobx_react_lite_1.observer)(({ viewId }) => {
    var _a;
    const icons = (0, use_ai_table_icons_1.useAiTableIcons)();
    const dataModel = (0, mobx_react_simpler_1.useModel)('dataModel');
    // 从 dataModel 获取视图数据和配置
    const viewData = dataModel.getViewData(viewId);
    const viewConfig = dataModel.getViewConfig(viewId);
    const viewColumns = dataModel.getViewColumns(viewId);
    // 使用 useCellFormat Hook 进行单元格格式化
    const { processedColumnMap } = (0, useCellFormat_1.useCellFormat)(dataModel.columnDefinitions);
    // 使用 useGroupValueFormatter Hook 格式化分组值
    const formatGroupValue = (0, useGroupValueFormatter_1.useGroupValueFormatter)(processedColumnMap, {
        emptyText: i18n_1.default.get({ id: 'NotGrouped', dm: '未分组' }),
    });
    // 卡片配置
    const [cardConfigVisible, setCardConfigVisible] = react_1.default.useState(false);
    const cardConfig = ((_a = viewConfig.custom) === null || _a === void 0 ? void 0 : _a.cardConfig) || {};
    const showFieldTitle = cardConfig.showFieldTitle !== undefined ? cardConfig.showFieldTitle : true;
    const cardFieldOrder = cardConfig.fieldOrder || viewColumns.map((col) => col.dataIndex);
    const cardVisibleFields = cardConfig.visibleFields || viewColumns.map((col) => col.dataIndex);
    // 根据配置过滤和排序字段
    const displayColumns = react_1.default.useMemo(() => {
        // 先按配置的顺序排序
        const orderedColumns = cardFieldOrder
            .map((dataIndex) => viewColumns.find((col) => col.dataIndex === dataIndex))
            .filter((col) => col && cardVisibleFields.includes(col.dataIndex));
        return orderedColumns;
    }, [viewColumns, cardFieldOrder, cardVisibleFields]);
    // 获取分组字段
    const groupingFields = react_1.default.useMemo(() => {
        if (viewConfig.group && viewConfig.group.length > 0) {
            return viewConfig.group.map((g) => g.field).filter(Boolean);
        }
        return [];
    }, [viewConfig.group]);
    // 根据分组字段对数据进行分组
    const groupedData = react_1.default.useMemo(() => {
        if (groupingFields.length === 0) {
            // 如果没有分组，返回一个包含所有数据的分组
            return [
                {
                    groupValue: null,
                    groupTitle: i18n_1.default.get({ id: 'All', dm: '全部' }),
                    items: viewData,
                },
            ];
        }
        // 获取第一个分组字段（目前只支持单字段分组）
        const groupField = groupingFields[0];
        // 规范化分组值的辅助函数：将数组/对象转换为可比较的字符串
        const normalizeGroupValue = (value) => {
            if (value === null || value === undefined) {
                return '__UNGROUPED__';
            }
            // 如果是数组或对象，使用 JSON.stringify 序列化
            if (Array.isArray(value) || (typeof value === 'object' && value !== null)) {
                // 对数组进行排序，确保相同内容的数组能被正确识别
                if (Array.isArray(value)) {
                    const sortedArray = [...value].sort();
                    return JSON.stringify(sortedArray);
                }
                return JSON.stringify(value);
            }
            // 基本类型直接转换为字符串
            return String(value);
        };
        // 对数据进行分组
        const groupMap = new Map();
        viewData.forEach((item) => {
            const groupValue = item[groupField];
            // 规范化 groupValue 作为 key
            const normalizedKey = normalizeGroupValue(groupValue);
            if (!groupMap.has(normalizedKey)) {
                groupMap.set(normalizedKey, {
                    groupValue: groupValue === null || groupValue === undefined ? null : groupValue,
                    items: [],
                });
            }
            groupMap.get(normalizedKey).items.push(item);
        });
        // 转换为数组格式
        const groups = Array.from(groupMap.values())
            .map(({ groupValue: actualGroupValue, items }) => {
            // 判断是否是未分组
            const isUngrouped = actualGroupValue === null || actualGroupValue === undefined;
            // 格式化分组标题：使用第一个 item 作为样本数据，以便格式化函数能正确工作
            const sampleItem = items.length > 0 ? items[0] : undefined;
            const groupTitle = isUngrouped
                ? i18n_1.default.get({ id: 'NotGrouped', dm: '未分组' })
                : formatGroupValue(groupField, actualGroupValue, sampleItem);
            return {
                groupValue: actualGroupValue,
                groupTitle,
                items,
            };
        })
            .sort((a, b) => {
            // 未分组（groupValue 为 null）始终排在最左侧
            if (a.groupValue === null && b.groupValue !== null) {
                return -1;
            }
            if (a.groupValue !== null && b.groupValue === null) {
                return 1;
            }
            // 其他分组保持原有顺序
            return 0;
        });
        return groups;
    }, [viewData, groupingFields, formatGroupValue]);
    const handleItemClick = (_item) => {
        // no-op: detail drawer removed
    };
    return (react_1.default.createElement(react_1.default.Fragment, null,
        react_1.default.createElement("div", { className: "ai-table-toolbar-sticky" },
            react_1.default.createElement(toolbar_1.Toolbar, { viewId: viewId, permissions: {
                    addRecord: true,
                    fieldManagement: false,
                    viewConfig: true,
                    filter: true,
                    sort: true,
                    group: true,
                }, groupMaxLevels: 1, renderRightContent: () => (react_1.default.createElement(react_1.default.Fragment, null,
                    react_1.default.createElement(card_config_1.CardConfig, { viewId: viewId, visible: cardConfigVisible, onVisibleChange: setCardConfigVisible, trigger: react_1.default.createElement(cn_ui_1.CnButton, { text: true, className: "toolbar-btn" },
                            react_1.default.createElement("img", { src: icons.VIEW_LIST, alt: i18n_1.default.get({ id: 'CardConfiguration', dm: '卡片配置' }) }),
                            react_1.default.createElement("span", null, i18n_1.default.get({ id: 'CardConfiguration', dm: '卡片配置' }))) }))) })),
        react_1.default.createElement("div", { className: "list-wrapper" }, groupedData.map((group, index) => {
            // 生成唯一的 key：使用 groupValue 的字符串形式，如果是对象则使用 JSON.stringify
            let groupKey;
            if (group.groupValue !== null && group.groupValue !== undefined) {
                groupKey =
                    typeof group.groupValue === 'object'
                        ? JSON.stringify(group.groupValue)
                        : String(group.groupValue);
            }
            else {
                groupKey = `ungrouped-${index}`;
            }
            return (react_1.default.createElement(ListItem, { key: groupKey, groupTitle: group.groupTitle, data: group.items, displayColumns: displayColumns, groupingFields: groupingFields, processedColumnMap: processedColumnMap, showFieldTitle: showFieldTitle, primaryKey: dataModel.primaryKey, onItemClick: handleItemClick }));
        }))));
});
