import $i18n from '../../../../../locales/i18n.js';
import React, { useState, useCallback } from 'react';
import { CnIcon, CnInput, CnRadioGroup } from '@cainiaofe/cn-ui';
import { DndContext, closestCenter, KeyboardSensor, MouseSensor, TouchSensor, useSensor, useSensors, } from '@dnd-kit/core';
import { arrayMove, SortableContext, sortableKeyboardCoordinates, verticalListSortingStrategy, } from '@dnd-kit/sortable';
import { Popup } from '@cainiaofe/cn-domain-popup';
import { useModel } from '../../../../../utils/mobx-react-simpler/index.js';
import { shouldKeepCol } from '../../../../../utils/data/get-column-meta-data.js';
import { getFieldComponentType } from '../../../../../cn-ai-table/view/utils/field-icon-utils';
import { SortableFieldItem } from './sortable-field-item';
import { getPopupContainer } from '../../../../../utils/floating-layer.js';
import './card-config.scss';
/**
 * 卡片配置组件
 * 用于配置卡片视图的字段显示顺序、可见性和字段标题显示选项
 * 支持拖拽排序、字段搜索和可见性切换功能
 */
export const CardConfig = (props) => {
    var _a;
    const { viewId, visible, onVisibleChange, trigger, excludeAiColumns } = props;
    // ============================= MISC =============================
    const dataModel = useModel('dataModel');
    const viewConfig = dataModel.getViewConfig(viewId);
    // ============================= Computed =============================
    // 从视图配置中读取卡片配置
    const cardConfig = ((_a = viewConfig.custom) === null || _a === void 0 ? void 0 : _a.cardConfig) || {};
    // 数据源：与字段管理一致，AI 列只展示已启用的（customFields.aiColumns）
    const filteredFieldIds = React.useMemo(() => {
        var _a;
        const aiColumnSet = new Set((dataModel.aiColumns || []).map((ac) => ac.columnCode));
        const customAiColumnSet = excludeAiColumns
            ? new Set(((_a = dataModel.customFields) === null || _a === void 0 ? void 0 : _a.aiColumns) || [])
            : null;
        return dataModel.columnDefinitions
            .filter((col) => {
            if (!shouldKeepCol(col))
                return false;
            if ((col === null || col === void 0 ? void 0 : col.dataIndex) == null || col.dataIndex === '')
                return false;
            if (col.isAiColumn || aiColumnSet.has(col.dataIndex)) {
                return customAiColumnSet ? customAiColumnSet.has(col.dataIndex) : true;
            }
            return true;
        })
            .map((col) => col.dataIndex);
    }, [dataModel.columnDefinitions, dataModel.aiColumns, dataModel.customFields, excludeAiColumns]);
    // ============================= State =============================
    // 字段标题显示/隐藏状态（默认显示）
    const [showFieldTitle, setShowFieldTitle] = useState(cardConfig.showFieldTitle !== undefined ? cardConfig.showFieldTitle : true);
    // 字段顺序状态（支持拖拽排序）
    const [fieldOrder, setFieldOrder] = useState(() => {
        if (cardConfig.fieldOrder && cardConfig.fieldOrder.length > 0) {
            // 合并已保存的顺序和新字段，确保所有字段都在列表中
            const allFields = [...cardConfig.fieldOrder];
            filteredFieldIds.forEach((id) => {
                if (!allFields.includes(id)) {
                    allFields.push(id);
                }
            });
            return allFields;
        }
        return filteredFieldIds;
    });
    // 可见字段列表状态（控制哪些字段在卡片中显示）
    const [visibleFields, setVisibleFields] = useState(() => {
        if (cardConfig.visibleFields && cardConfig.visibleFields.length > 0) {
            // 过滤掉已删除的字段
            return cardConfig.visibleFields.filter((id) => filteredFieldIds.includes(id));
        }
        // 新建视图时，默认只显示前4个字段（如果字段总数少于4个，则显示所有字段）
        return filteredFieldIds.slice(0, 4);
    });
    // 同步 filteredFieldIds 变化：新增字段追加到 fieldOrder，已删除字段从 visibleFields 中移除
    React.useEffect(() => {
        setFieldOrder((prev) => {
            const prevSet = new Set(prev);
            const newIds = filteredFieldIds.filter((id) => !prevSet.has(id));
            if (newIds.length === 0)
                return prev;
            return [...prev, ...newIds];
        });
        setVisibleFields((prev) => {
            return prev.filter((id) => filteredFieldIds.includes(id));
        });
    }, [filteredFieldIds]);
    // 搜索关键词状态
    const [searchValue, setSearchValue] = useState('');
    // ============================= Computed (Dependent) =============================
    /**
     * 构建字段列表（包含可见性信息）
     */
    const fieldList = React.useMemo(() => {
        return fieldOrder
            .filter((dataIndex) => filteredFieldIds.includes(dataIndex))
            .map((dataIndex) => {
            const col = dataModel.columnDefinitions.find((c) => c.dataIndex === dataIndex);
            return {
                dataIndex,
                title: (col === null || col === void 0 ? void 0 : col.title) || dataIndex,
                visible: visibleFields.includes(dataIndex),
                fieldType: getFieldComponentType(dataModel.fieldMap, dataIndex, col === null || col === void 0 ? void 0 : col.format),
                isAiColumn: (col === null || col === void 0 ? void 0 : col.isAiColumn) || false,
                isFormulaColumn: (col === null || col === void 0 ? void 0 : col.format) === 'formula',
            };
        });
    }, [
        fieldOrder,
        visibleFields,
        filteredFieldIds,
        dataModel.columnDefinitions,
        dataModel.fieldMap,
    ]);
    // 过滤后的字段列表（根据搜索关键词）
    const filteredFieldList = React.useMemo(() => {
        if (!searchValue) {
            return fieldList;
        }
        const lowerSearchValue = searchValue === null || searchValue === void 0 ? void 0 : searchValue.toLowerCase();
        return fieldList.filter((field) => {
            var _a, _b;
            return ((_a = field.title) === null || _a === void 0 ? void 0 : _a.toLowerCase().includes(lowerSearchValue)) ||
                ((_b = field.dataIndex) === null || _b === void 0 ? void 0 : _b.toLowerCase().includes(lowerSearchValue));
        });
    }, [fieldList, searchValue]);
    // ============================= Config =============================
    // 拖拽传感器配置（支持鼠标、触摸和键盘操作）
    const sensors = useSensors(useSensor(MouseSensor, {}), useSensor(TouchSensor, {}), useSensor(KeyboardSensor, {
        coordinateGetter: sortableKeyboardCoordinates,
    }));
    // ============================= Events =============================
    /**
     * 保存卡片配置到视图配置中
     * @param config 卡片配置对象，包含字段标题显示、字段顺序和可见字段列表
     */
    const saveConfig = useCallback((config) => {
        const currentViewConfig = dataModel.getViewConfig(viewId);
        dataModel.setViewConfig(viewId, {
            custom: {
                ...currentViewConfig.custom,
                cardConfig: config,
            },
        }, true);
    }, [viewId, dataModel]);
    /**
     * 处理拖拽结束事件
     * 更新字段顺序并保存配置
     */
    const handleDragEnd = useCallback((event) => {
        const { active, over } = event;
        if (active && over && active.id !== over.id) {
            setFieldOrder((currentOrder) => {
                const oldIndex = currentOrder.indexOf(active.id);
                const newIndex = currentOrder.indexOf(over.id);
                if (oldIndex !== -1 && newIndex !== -1) {
                    const newOrder = arrayMove(currentOrder, oldIndex, newIndex);
                    // 立即保存配置
                    saveConfig({
                        showFieldTitle,
                        fieldOrder: newOrder,
                        visibleFields,
                    });
                    return newOrder;
                }
                return currentOrder;
            });
        }
    }, [showFieldTitle, visibleFields, saveConfig]);
    /**
     * 切换字段可见性
     * @param dataIndex 要切换可见性的字段ID
     */
    const handleToggleFieldVisible = useCallback((dataIndex) => {
        setVisibleFields((currentVisibleFields) => {
            const newVisibleFields = currentVisibleFields.includes(dataIndex)
                ? currentVisibleFields.filter((id) => id !== dataIndex)
                : [...currentVisibleFields, dataIndex];
            // 立即保存配置
            saveConfig({
                showFieldTitle,
                fieldOrder,
                visibleFields: newVisibleFields,
            });
            return newVisibleFields;
        });
    }, [showFieldTitle, fieldOrder, saveConfig]);
    /**
     * 处理字段标题显示/隐藏切换
     * @param value 单选组的值（'show' 或 'hide'）
     */
    const handleShowFieldTitleChange = useCallback((value) => {
        const newValue = value === 'show';
        setShowFieldTitle(newValue);
        saveConfig({
            showFieldTitle: newValue,
            fieldOrder,
            visibleFields,
        });
    }, [fieldOrder, visibleFields, saveConfig]);
    // ============================= Effect =============================
    /**
     * 初始化效果：如果配置不存在，自动保存默认配置
     * 默认显示前4个字段（如果字段总数少于4个，则显示所有字段）
     */
    React.useEffect(() => {
        if (!cardConfig.visibleFields || cardConfig.visibleFields.length === 0) {
            const defaultVisibleFields = filteredFieldIds.slice(0, 4);
            setVisibleFields(defaultVisibleFields);
            saveConfig({
                showFieldTitle,
                fieldOrder,
                visibleFields: defaultVisibleFields,
            });
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);
    // ============================= Render =============================
    return (React.createElement(Popup, { visible: visible, onVisibleChange: onVisibleChange, trigger: trigger, container: getPopupContainer, align: "bl", offset: 10 },
        React.createElement("div", { className: "card-config-popup" },
            React.createElement("div", { className: "card-config-header" },
                React.createElement("div", { className: "card-config-header-title" },
                    React.createElement("span", null, $i18n.get({ id: 'CardConfiguration', dm: '卡片配置' }))),
                React.createElement(CnIcon, { type: "question-circle", size: "small", className: "card-config-help-icon" })),
            React.createElement("div", { className: "card-config-section" },
                React.createElement("div", { className: "card-config-section-label" }, $i18n.get({ id: 'FieldTitle', dm: '字段标题' })),
                React.createElement(CnRadioGroup, { value: showFieldTitle ? 'show' : 'hide', onChange: handleShowFieldTitleChange, direction: "hoz", dataSource: [
                        { label: $i18n.get({ id: 'Display', dm: '显示' }), value: 'show' },
                        { label: $i18n.get({ id: 'Hide', dm: '隐藏' }), value: 'hide' },
                    ] })),
            React.createElement("div", { className: "card-config-search" },
                React.createElement(CnIcon, { type: "search", size: "medium", className: "card-config-search-icon" }),
                React.createElement(CnInput, { value: searchValue, onChange: setSearchValue, placeholder: $i18n.get({ id: 'Search', dm: '搜索' }), hasClear: true, className: "card-config-search-input" })),
            React.createElement("div", { className: "card-config-field-list" },
                React.createElement(DndContext, { sensors: sensors, collisionDetection: closestCenter, onDragEnd: handleDragEnd },
                    React.createElement(SortableContext, { items: filteredFieldList.map((f) => f.dataIndex).filter((item) => item !== null), strategy: verticalListSortingStrategy }, filteredFieldList.map((field) => (React.createElement(SortableFieldItem, { key: field.dataIndex, field: field, onToggleVisible: handleToggleFieldVisible })))))))));
};
