<template>
    <div class="product-route-example">
        <div class="page-header">
            <h2>多产品多线路表单配置示例</h2>
            <p class="description">
                支持选择多个产品、多个线路，为每个组合生成独立的表单组（性能优化：只渲染可见表单）
            </p>
        </div>

        <!-- 产品选择区域 -->
        <el-card class="product-section">
            <h3>已选择的产品</h3>
            <div class="product-tags">
                <el-tag
                    v-for="(product, index) in selectedProducts"
                    :key="product.code"
                    :type="activeProduct === product.code ? 'primary' : 'info'"
                    :class="{ 'has-error': hasProductError(product.code) }"
                    closable
                    class="product-tag"
                    @close="removeProduct(index)"
                    @click="setActiveProduct(product.code)"
                >
                    <span class="product-name">{{ product.name }}</span>
                    <span class="product-code">({{ product.code }})</span>
                    <el-tag :type="getProductTypeTag(product.productType)" size="small" class="product-type-tag">
                        {{ product.productType }}
                    </el-tag>
                </el-tag>
            </div>
            <div class="action-row">
                <el-button type="primary" size="small" @click="addProduct">添加产品</el-button>
            </div>
        </el-card>

        <!-- 线路选择区域 -->
        <el-card class="line-section">
            <h3>已选择的线路</h3>
            <div class="line-tags">
                <el-tag
                    v-for="(route, index) in currentProductRoutes"
                    :key="route.code"
                    :type="currentActiveRoute === route.code ? 'primary' : 'info'"
                    :class="{ 'has-error': hasRouteError(route.code) }"
                    closable
                    class="line-tag"
                    @close="removeRoute(index)"
                    @click="setActiveRoute(route.code)"
                >
                    <span class="route-name">{{ route.name }}</span>
                    <span class="route-code">({{ route.code }})</span>
                </el-tag>
            </div>
            <div class="action-row">
                <el-button type="primary" size="small" @click="addRoute">添加线路</el-button>
            </div>
        </el-card>

        <!-- 表单区域 - 优化后的实现 -->
        <div v-if="allFormPairs.length > 0" class="forms-container">
            <h3>表单列表（优化后）</h3>
            <div class="performance-info">
                <el-alert
                    :title="`性能优化：只渲染 ${visibleFormPairs.length} 个可见表单，保留 ${allFormPairs.length} 个表单的数据`"
                    type="success"
                    :closable="false"
                />
            </div>

            <!-- 使用 keep-alive 缓存已渲染的表单组件 -->
            <template v-for="pair in visibleFormPairs" :key="getPairKey(pair)">
                <el-card class="form-item-card" shadow="hover">
                    <template #header>
                        <div class="form-header">
                            <span class="form-title"> {{ pair.productName }} - {{ pair.routeName }} </span>
                            <span class="form-key">Key: {{ getPairKey(pair) }}</span>
                        </div>
                    </template>

                    <pro-form
                        :id="getPairKey(pair)"
                        :ref="el => setFormRef(getPairKey(pair), el)"
                        :columns="getFormColumns(pair.product, pair.route)"
                        :initial-values="getInitialValues(pair)"
                        :rules="formRules"
                        :label-width="'120px'"
                        :cols="3"
                        @values-change="values => handleFormValuesChange(pair, values)"
                    />

                    <div class="form-footer">
                        <el-text type="info" size="small"> 数据已自动保存，切换产品/线路后返回仍会保留 </el-text>
                    </div>
                </el-card>
            </template>

            <!-- 隐藏的表单数据提示 -->
            <div v-if="hiddenFormsCount > 0" class="hidden-forms-info">
                <el-alert
                    :title="`还有 ${hiddenFormsCount} 个表单的数据已保存，切换产品/线路时会自动恢复`"
                    type="info"
                    :closable="false"
                />
            </div>
        </div>

        <!-- 数据展示区域 -->
        <el-card class="data-preview">
            <h3>所有表单数据预览（用于验证数据保留）</h3>
            <div class="preview-actions">
                <el-button type="primary" @click="handleSubmitAll">统一提交</el-button>
                <el-button type="success" @click="handleSaveData">暂存数据</el-button>
                <el-button type="text" @click="showAllData = !showAllData">
                    {{ showAllData ? '隐藏' : '显示' }}所有数据
                </el-button>
            </div>
            <pre v-if="showAllData" class="data-json">{{ JSON.stringify(formDataMap, null, 2) }}</pre>
        </el-card>
    </div>
</template>

<script setup>
import { ref, computed, watch, nextTick, onMounted } from 'vue';
import { ProForm } from '@deppon/deppon-template';
import { ElCard, ElButton, ElMessage, ElTag, ElText, ElAlert } from '@deppon/deppon-ui';

// localStorage 键名
const STORAGE_KEY = 'productRouteFormData';

// 产品列表
const productList = ref([
    { code: 'FLF', disable: false, name: '精准卡航', productType: 'LTT' },
    { code: 'LRF', disable: false, name: '精准汽运', productType: 'LTT' },
    { code: 'EXP_BZKD', disable: false, name: '标准快递/大件快递3.60', productType: 'EXPRESS' },
    { code: 'NZBRH', disable: false, name: '精准泡货', productType: 'EXPRESS' },
    { code: 'WXJTH', disable: false, name: '微小件特惠', productType: 'EXPRESS' },
    { code: 'DSZH', disable: false, name: '重货特惠', productType: 'EXPRESS' },
    { code: 'HKDJC', disable: false, name: '特快次日', productType: 'EXPRESS' },
    { code: 'HKDJG', disable: false, name: '特快隔日', productType: 'EXPRESS' },
    { code: 'DEAP', disable: false, name: '特快冷链', productType: 'EXPRESS' },
    { code: 'TZKJC', disable: false, name: '特快专递', productType: 'EXPRESS' },
    { code: 'CITYPIECE', disable: false, name: '同城当日达', productType: 'EXPRESS' },
    { code: 'JZZH', disable: false, name: '精准重货', productType: 'LTT' },
    { code: 'ZYSCZD', disable: false, name: '泡货特惠', productType: 'EXPRESS' },
    { code: 'DPTL', disable: false, name: '德邦联运', productType: 'EXPRESS' },
    { code: 'NFLF', disable: false, name: '精准卡航(新)', productType: 'EXPRESS' },
    { code: 'NJZZH', disable: false, name: '精准重货(新)', productType: 'EXPRESS' },
    { code: 'NLRF', disable: false, name: '精准汽运(新)', productType: 'EXPRESS' },
    { code: 'YTY', disable: false, name: '精准大票', productType: 'LTT' },
    { code: 'YTYDS', disable: false, name: '精准大票(电商)', productType: 'EXPRESS' },
]);

// 线路列表
const routeList = ref([
    { code: 'BJ_SH', name: '北京-上海', origin: '北京', destination: '上海' },
    { code: 'BJ_GZ', name: '北京-广州', origin: '北京', destination: '广州' },
    { code: 'SH_SZ', name: '上海-深圳', origin: '上海', destination: '深圳' },
    { code: 'GZ_HZ', name: '广州-杭州', origin: '广州', destination: '杭州' },
    { code: 'CD_BJ', name: '成都-北京', origin: '成都', destination: '北京' },
    { code: 'WH_SH', name: '武汉-上海', origin: '武汉', destination: '上海' },
    { code: 'XA_GZ', name: '西安-广州', origin: '西安', destination: '广州' },
    { code: 'NJ_SZ', name: '南京-深圳', origin: '南京', destination: '深圳' },
]);

// 状态管理
const selectedProducts = ref([]);
// 每个产品对应的线路列表（key: productCode, value: route[]）
const productRoutesMap = ref({});
const activeProduct = ref(null);
// 每个产品对应的激活线路（key: productCode, value: routeCode）
const productActiveRouteMap = ref({});
const showAllData = ref(false);

// 表单数据存储（独立于组件实例）
const formDataMap = ref({});

// 表单 ref 存储
const formRefs = ref({});

// 校验错误状态存储（key: productCode_routeCode, value: true表示有错误）
const validationErrors = ref({});

// 设置表单 ref
const setFormRef = (key, el) => {
    if (el) {
        formRefs.value[key] = el;
    }
};

// 表单组合
const getPairKey = pair => {
    return `${pair.productCode}_${pair.routeCode}`;
};

// 计算所有表单组合（用于保留数据）
const allFormPairs = computed(() => {
    const pairs = [];

    selectedProducts.value.forEach(product => {
        const routes = productRoutesMap.value[product.code] || [];
        routes.forEach(route => {
            pairs.push({
                productCode: product.code,
                productName: product.name,
                product: product,
                routeCode: route.code,
                routeName: route.name,
                route: route,
            });
        });
    });

    return pairs;
});

// 计算可见的表单组合（只渲染这些）
const visibleFormPairs = computed(() => {
    const pairs = [];

    // 只显示激活的产品和线路
    if (!activeProduct.value || !currentActiveRoute.value) {
        return pairs;
    }

    const activeProductObj = selectedProducts.value.find(p => p.code === activeProduct.value);
    const routes = productRoutesMap.value[activeProduct.value] || [];
    const activeRouteObj = routes.find(r => r.code === currentActiveRoute.value);

    if (activeProductObj && activeRouteObj) {
        pairs.push({
            productCode: activeProductObj.code,
            productName: activeProductObj.name,
            product: activeProductObj,
            routeCode: activeRouteObj.code,
            routeName: activeRouteObj.name,
            route: activeRouteObj,
        });
    }

    return pairs;
});

// 隐藏的表单数量
const hiddenFormsCount = computed(() => {
    return allFormPairs.value.length - visibleFormPairs.value.length;
});

// 当前激活产品对应的线路列表
const currentProductRoutes = computed(() => {
    if (!activeProduct.value) {
        return [];
    }
    return productRoutesMap.value[activeProduct.value] || [];
});

// 当前激活产品对应的激活线路
const currentActiveRoute = computed(() => {
    if (!activeProduct.value) {
        return null;
    }
    return productActiveRouteMap.value[activeProduct.value] || null;
});

// 获取产品类型标签类型
const getProductTypeTag = productType => {
    return productType === 'LTT' ? 'success' : 'primary';
};

// 检查产品是否有校验错误（该产品对应的所有线路的表单中是否有校验失败）
const hasProductError = productCode => {
    const routes = productRoutesMap.value[productCode] || [];
    return routes.some(route => {
        const key = `${productCode}_${route.code}`;
        return validationErrors.value[key] === true;
    });
};

// 检查线路是否有校验错误（只检查当前激活产品对应的线路错误状态）
const hasRouteError = routeCode => {
    if (!activeProduct.value) {
        return false;
    }
    const key = `${activeProduct.value}_${routeCode}`;
    return validationErrors.value[key] === true;
};
// 获取表单列配置
const getFormColumns = (product, route) => {
    const baseColumns = [
        {
            name: 'productCode',
            label: '产品代码',
            valueType: 'text',
            required: true,
            fieldProps: {
                placeholder: '产品代码',
                disabled: true,
            },
        },
        {
            name: 'productName',
            label: '产品名称',
            valueType: 'text',
            required: true,
            fieldProps: {
                placeholder: '产品名称',
                disabled: true,
            },
        },
        {
            name: 'productType',
            label: '产品类型',
            valueType: 'select',
            required: true,
            fieldProps: {
                options: [
                    { label: 'LTT', value: 'LTT' },
                    { label: 'EXPRESS', value: 'EXPRESS' },
                ],
                placeholder: '产品类型',
                disabled: true,
            },
        },
        {
            name: 'routeCode',
            label: '线路代码',
            valueType: 'text',
            required: true,
            fieldProps: {
                placeholder: '线路代码',
                disabled: true,
            },
        },
        {
            name: 'routeName',
            label: '线路名称',
            valueType: 'text',
            required: true,
            fieldProps: {
                placeholder: '线路名称',
                disabled: true,
            },
        },
        {
            name: 'origin',
            label: '始发地',
            valueType: 'text',
            fieldProps: {
                placeholder: '始发地',
            },
        },
        {
            name: 'destination',
            label: '目的地',
            valueType: 'text',
            fieldProps: {
                placeholder: '目的地',
            },
        },
    ];

    // 价格相关字段
    const priceColumns = [
        {
            name: 'basePrice',
            label: '基础价格',
            valueType: 'text',
            fieldProps: {
                placeholder: '请输入基础价格',
                suffix: '元',
            },
        },
        {
            name: 'discount',
            label: '折扣率',
            valueType: 'text',
            fieldProps: {
                placeholder: '请输入折扣率',
                suffix: '%',
            },
        },
        {
            name: 'discountAmount',
            label: '折扣金额',
            valueType: 'text',
            fieldProps: {
                placeholder: '请输入折扣金额',
                suffix: '元',
            },
        },
        {
            name: 'finalPrice',
            label: '最终价格',
            valueType: 'text',
            fieldProps: {
                placeholder: '最终价格',
                suffix: '元',
            },
        },
    ];

    // 时间相关字段
    const timeColumns = [
        {
            name: 'effectiveDate',
            label: '生效日期',
            valueType: 'date',
            required: true,
            fieldProps: {
                placeholder: '请选择生效日期',
            },
        },
        {
            name: 'expiryDate',
            label: '失效日期',
            valueType: 'date',
            fieldProps: {
                placeholder: '请选择失效日期',
            },
        },
    ];

    // 客户相关字段
    const customerColumns = [
        {
            name: 'customerType',
            label: '客户类型',
            valueType: 'select',
            fieldProps: {
                options: [
                    { label: '个人', value: 'PERSONAL' },
                    { label: '企业', value: 'ENTERPRISE' },
                    { label: '电商', value: 'ECOMMERCE' },
                ],
                placeholder: '请选择客户类型',
            },
        },
        {
            name: 'customerLevel',
            label: '客户等级',
            valueType: 'select',
            fieldProps: {
                options: [
                    { label: '普通', value: 'NORMAL' },
                    { label: '银牌', value: 'SILVER' },
                    { label: '金牌', value: 'GOLD' },
                    { label: '钻石', value: 'DIAMOND' },
                ],
                placeholder: '请选择客户等级',
            },
        },
        {
            name: 'customerCode',
            label: '客户编码',
            valueType: 'text',
            fieldProps: {
                placeholder: '请输入客户编码',
            },
        },
        {
            name: 'customerName',
            label: '客户名称',
            valueType: 'text',
            fieldProps: {
                placeholder: '请输入客户名称',
            },
        },
    ];

    // 重量体积相关字段
    const weightVolumeColumns = [
        {
            name: 'minWeight',
            label: '最小重量',
            valueType: 'text',
            fieldProps: {
                placeholder: '最小重量',
                suffix: 'kg',
            },
        },
        {
            name: 'maxWeight',
            label: '最大重量',
            valueType: 'text',
            fieldProps: {
                placeholder: '最大重量',
                suffix: 'kg',
            },
        },
        {
            name: 'minVolume',
            label: '最小体积',
            valueType: 'text',
            fieldProps: {
                placeholder: '最小体积',
                suffix: 'm³',
            },
        },
        {
            name: 'maxVolume',
            label: '最大体积',
            valueType: 'text',
            fieldProps: {
                placeholder: '最大体积',
                suffix: 'm³',
            },
        },
    ];

    // 费用相关字段
    const feeColumns = [
        {
            name: 'insuranceRate',
            label: '保价费率',
            valueType: 'text',
            fieldProps: {
                placeholder: '保价费率',
                suffix: '%',
            },
        },
        {
            name: 'handlingFee',
            label: '操作费',
            valueType: 'text',
            fieldProps: {
                placeholder: '操作费',
                suffix: '元',
            },
        },
        {
            name: 'fuelSurcharge',
            label: '燃油附加费',
            valueType: 'text',
            fieldProps: {
                placeholder: '燃油附加费',
                suffix: '元',
            },
        },
        {
            name: 'otherFee',
            label: '其他费用',
            valueType: 'text',
            fieldProps: {
                placeholder: '其他费用',
                suffix: '元',
            },
        },
    ];

    // 其他字段
    const otherColumns = [
        {
            name: 'priority',
            label: '优先级',
            valueType: 'select',
            fieldProps: {
                options: [
                    { label: '低', value: 'low' },
                    { label: '中', value: 'medium' },
                    { label: '高', value: 'high' },
                ],
                placeholder: '请选择优先级',
            },
        },
        {
            name: 'status',
            label: '状态',
            valueType: 'select',
            fieldProps: {
                options: [
                    { label: '启用', value: 'active' },
                    { label: '禁用', value: 'inactive' },
                ],
                placeholder: '请选择状态',
            },
        },
        {
            name: 'remark',
            label: '备注',
            valueType: 'text',
            fieldProps: {
                placeholder: '请输入备注信息',
                type: 'textarea',
                rows: 3,
            },
        },
    ];

    return [
        ...baseColumns,
        ...priceColumns,
        ...timeColumns,
        ...customerColumns,
        ...weightVolumeColumns,
        ...feeColumns,
        ...otherColumns,
    ];
};

// 表单校验规则
const formRules = {
    basePrice: [
        {
            validator: (rule, value, callback) => {
                if (value && (isNaN(Number(value)) || Number(value) < 0)) {
                    callback(new Error('请输入有效的价格'));
                } else {
                    callback();
                }
            },
            trigger: 'blur',
        },
    ],
    discount: [
        {
            validator: (rule, value, callback) => {
                if (value) {
                    const num = Number(value);
                    if (isNaN(num) || num < 0 || num > 100) {
                        callback(new Error('折扣率必须在 0-100 之间'));
                    } else {
                        callback();
                    }
                } else {
                    callback();
                }
            },
            trigger: 'blur',
        },
    ],
    effectiveDate: [{ required: true, message: '请选择生效日期', trigger: 'change' }],
    expiryDate: [
        {
            validator: (rule, value, callback, formModel) => {
                if (!value) {
                    callback();
                    return;
                }
                if (formModel.effectiveDate && new Date(value) < new Date(formModel.effectiveDate)) {
                    callback(new Error('失效日期不能早于生效日期'));
                } else {
                    callback();
                }
            },
            trigger: 'change',
        },
    ],
};

// 获取表单初始值
const getInitialValues = pair => {
    const key = getPairKey(pair);
    const formData = formDataMap.value[key];
    const product = pair.product;
    const route = pair.route;

    const baseValues = {
        productCode: product.code,
        productName: product.name,
        productType: product.productType,
        routeCode: route.code,
        routeName: route.name,
        origin: route.origin,
        destination: route.destination,
        status: 'active',
    };

    // 如果有保存的数据，合并进去
    if (formData) {
        return { ...baseValues, ...formData };
    }

    return baseValues;
};

// 处理表单值变化事件（实时保存数据）
const handleFormValuesChange = async (pair, values) => {
    const key = getPairKey(pair);
    // values 是完整的表单值对象
    if (values && typeof values === 'object') {
        formDataMap.value[key] = { ...values };
        console.log('表单值已变化并保存:', key, formDataMap.value[key]);
    }

    // 如果该表单之前有错误标记，尝试校验，如果校验通过则清除错误标记
    if (validationErrors.value[key] === true) {
        await nextTick();
        const formRef = formRefs.value[key];
        if (formRef && formRef.validate) {
            try {
                const result = await formRef.validate();
                if (result === true) {
                    // 校验通过，清除错误标记
                    validationErrors.value[key] = false;
                }
            } catch (error) {
                // 校验失败，保持错误标记
            }
        }
    }
};

// 添加产品
const addProduct = () => {
    // 从产品列表中选择第一个未选择的产品
    const unselectedProduct = productList.value.find(p => !selectedProducts.value.find(sp => sp.code === p.code));
    if (!unselectedProduct) {
        ElMessage.warning('所有产品都已选择');
        return;
    }

    selectedProducts.value.push(unselectedProduct);
    // 初始化该产品的线路列表
    if (!productRoutesMap.value[unselectedProduct.code]) {
        productRoutesMap.value[unselectedProduct.code] = [];
    }
    if (!activeProduct.value) {
        activeProduct.value = unselectedProduct.code;
    }

    ElMessage.success(`已添加产品: ${unselectedProduct.name}`);
};

// 移除产品
const removeProduct = index => {
    const product = selectedProducts.value[index];
    selectedProducts.value.splice(index, 1);

    // 清理该产品的所有表单数据
    Object.keys(formDataMap.value).forEach(key => {
        if (key.startsWith(`${product.code}_`)) {
            delete formDataMap.value[key];
        }
    });

    // 清理该产品的线路列表和激活线路
    delete productRoutesMap.value[product.code];
    delete productActiveRouteMap.value[product.code];

    // 如果删除的是激活产品，切换到第一个产品
    if (activeProduct.value === product.code && selectedProducts.value.length > 0) {
        activeProduct.value = selectedProducts.value[0].code;
    } else if (selectedProducts.value.length === 0) {
        activeProduct.value = null;
    }

    ElMessage.success(`已移除产品: ${product.name}`);
};

// 添加线路（添加到当前激活产品的线路列表）
const addRoute = () => {
    if (!activeProduct.value) {
        ElMessage.warning('请先选择产品');
        return;
    }

    const routes = productRoutesMap.value[activeProduct.value] || [];
    // 从线路列表中选择第一个未选择的线路
    const unselectedRoute = routeList.value.find(r => !routes.find(sr => sr.code === r.code));
    if (!unselectedRoute) {
        ElMessage.warning('所有线路都已选择');
        return;
    }

    routes.push(unselectedRoute);
    productRoutesMap.value[activeProduct.value] = routes;
    if (!productActiveRouteMap.value[activeProduct.value]) {
        productActiveRouteMap.value[activeProduct.value] = unselectedRoute.code;
    }

    ElMessage.success(`已添加线路: ${unselectedRoute.name}`);
};

// 移除线路（从当前激活产品的线路列表中移除）
const removeRoute = index => {
    if (!activeProduct.value) {
        return;
    }

    const routes = productRoutesMap.value[activeProduct.value] || [];
    const route = routes[index];
    routes.splice(index, 1);
    productRoutesMap.value[activeProduct.value] = routes;

    // 清理当前产品+该线路的表单数据
    const key = `${activeProduct.value}_${route.code}`;
    delete formDataMap.value[key];

    // 如果删除的是激活线路，切换到第一个线路
    if (productActiveRouteMap.value[activeProduct.value] === route.code && routes.length > 0) {
        productActiveRouteMap.value[activeProduct.value] = routes[0].code;
    } else if (routes.length === 0) {
        delete productActiveRouteMap.value[activeProduct.value];
    }

    ElMessage.success(`已移除线路: ${route.name}`);
};

// 设置激活产品
const setActiveProduct = async productCode => {
    activeProduct.value = productCode;
    // 如果该产品没有激活线路，且该产品有线路，设置第一个线路为激活线路
    if (!productActiveRouteMap.value[productCode]) {
        const routes = productRoutesMap.value[productCode] || [];
        if (routes.length > 0) {
            productActiveRouteMap.value[productCode] = routes[0].code;
        }
    }
    // 如果该产品有错误，切换后自动执行校验
    if (hasProductError(productCode)) {
        await nextTick();
        const visiblePairs = visibleFormPairs.value;
        if (visiblePairs.length > 0) {
            const pair = visiblePairs[0];
            const key = getPairKey(pair);
            const formRef = formRefs.value[key];
            if (formRef && formRef.validate) {
                try {
                    await formRef.validate();
                } catch (error) {
                    // 校验失败，错误信息已经在表单中显示
                }
            }
        }
    }
};

// 设置激活线路（设置当前激活产品的激活线路）
const setActiveRoute = async routeCode => {
    if (!activeProduct.value) {
        return;
    }
    productActiveRouteMap.value[activeProduct.value] = routeCode;
    // 如果该线路有错误，切换后自动执行校验
    if (hasRouteError(routeCode)) {
        await nextTick();
        const visiblePairs = visibleFormPairs.value;
        if (visiblePairs.length > 0) {
            const pair = visiblePairs[0];
            const key = getPairKey(pair);
            const formRef = formRefs.value[key];
            if (formRef && formRef.validate) {
                try {
                    await formRef.validate();
                } catch (error) {
                    // 校验失败，错误信息已经在表单中显示
                }
            }
        }
    }
};

// 统一提交所有表单
const handleSubmitAll = async () => {
    try {
        // 获取可见表单的 formRef（用于调用 validateDataManually）
        let visibleFormRef = null;
        if (visibleFormPairs.value.length > 0) {
            const visibleKey = getPairKey(visibleFormPairs.value[0]);
            visibleFormRef = formRefs.value[visibleKey];
        }
        console.log('visibleFormRef:', visibleFormRef);
        console.log('allFormPairs:', allFormPairs.value);
        console.log('formRefs:', formRefs.value);
        console.log('formDataMap:', formDataMap.value);
        const validationPromises = allFormPairs.value.map(async pair => {
            const key = getPairKey(pair);
            const formRef = formRefs.value[key];
            const formData = formDataMap.value[key];
            const isVisible = visibleFormPairs.value.some(p => getPairKey(p) === key);

            // 如果表单已渲染（可见表单），使用 validate 方法
            if (isVisible && formRef && formRef.validate) {
                try {
                    const result = await formRef.validate();
                    console.log('表单校验结果:', result);
                    return { pair, isValid: result === true, error: null };
                } catch (error) {
                    return { pair, isValid: false, error };
                }
            } else {
                // 如果表单未渲染（不可见表单），使用可见表单的 formRef.validateDataManually
                if (visibleFormRef && visibleFormRef.validateDataManually && formData) {
                    try {
                        const errors = await visibleFormRef.validateDataManually(formData);
                        return { pair, isValid: errors.length === 0, error: errors.length > 0 ? errors : null };
                    } catch (error) {
                        return { pair, isValid: false, error };
                    }
                } else {
                    // 如果没有可见表单的 formRef，跳过校验（视为校验通过）
                    return { pair, isValid: true, error: null };
                }
            }
        });

        // 等待所有表单校验完成
        const validateResults = await Promise.all(validationPromises);

        // 检查校验结果
        const failedForms = [];
        validateResults.forEach(({ pair, isValid, error }) => {
            if (!isValid) {
                const formName = `${pair.productName} - ${pair.routeName}`;
                failedForms.push(formName);
                console.log(`表单 ${formName} 校验失败:`, error);
            }
        });

        // 更新校验错误状态
        validateResults.forEach(({ pair, isValid }) => {
            const key = getPairKey(pair);
            // 如果校验通过，设置为 false；如果校验失败，设置为 true
            validationErrors.value[key] = !isValid;
        });

        if (failedForms.length === 0) {
            ElMessage.success(`所有 ${allFormPairs.value.length} 个表单校验通过！`);
            console.log('所有表单数据:', formDataMap.value);
        } else {
            ElMessage.error(`有 ${failedForms.length} 个表单校验失败：${failedForms.join('、')}`);
        }
    } catch (error) {
        console.error('提交表单时发生错误:', error);
        ElMessage.error('提交表单时发生错误');
    }
};

// 暂存数据（保存到 localStorage）
const handleSaveData = () => {
    try {
        const dataToSave = {
            selectedProducts: selectedProducts.value,
            productRoutesMap: productRoutesMap.value,
            activeProduct: activeProduct.value,
            productActiveRouteMap: productActiveRouteMap.value,
            formDataMap: formDataMap.value,
            timestamp: Date.now(),
        };
        localStorage.setItem(STORAGE_KEY, JSON.stringify(dataToSave));
        ElMessage.success('数据已暂存成功！');
        console.log('暂存的数据:', dataToSave);
    } catch (error) {
        console.error('暂存数据失败:', error);
        ElMessage.error('暂存数据失败，请重试');
    }
};

// 加载暂存的数据（从 localStorage 读取）
const loadSavedData = () => {
    try {
        const savedDataStr = localStorage.getItem(STORAGE_KEY);
        if (!savedDataStr) {
            return false;
        }

        const savedData = JSON.parse(savedDataStr);

        // 恢复已选择的产品（需要从产品列表中匹配）
        if (savedData.selectedProducts && Array.isArray(savedData.selectedProducts)) {
            selectedProducts.value = savedData.selectedProducts
                .map(savedProduct => {
                    const product = productList.value.find(p => p.code === savedProduct.code);
                    return product || savedProduct;
                })
                .filter(Boolean);
        }

        // 恢复产品线路映射（需要从线路列表中匹配）
        if (savedData.productRoutesMap && typeof savedData.productRoutesMap === 'object') {
            const restoredMap = {};
            Object.keys(savedData.productRoutesMap).forEach(productCode => {
                const routes = savedData.productRoutesMap[productCode];
                if (Array.isArray(routes)) {
                    restoredMap[productCode] = routes
                        .map(savedRoute => {
                            const route = routeList.value.find(r => r.code === savedRoute.code);
                            return route || savedRoute;
                        })
                        .filter(Boolean);
                }
            });
            productRoutesMap.value = restoredMap;
        } else if (savedData.selectedRoutes && Array.isArray(savedData.selectedRoutes)) {
            // 兼容旧数据格式：如果有 selectedRoutes，将其转换为 productRoutesMap
            const routes = savedData.selectedRoutes
                .map(savedRoute => {
                    const route = routeList.value.find(r => r.code === savedRoute.code);
                    return route || savedRoute;
                })
                .filter(Boolean);
            // 为每个产品分配这些线路
            selectedProducts.value.forEach(product => {
                productRoutesMap.value[product.code] = [...routes];
            });
        }

        // 恢复激活的产品
        if (savedData.activeProduct) {
            activeProduct.value = savedData.activeProduct;
        }

        // 恢复产品激活线路映射
        if (savedData.productActiveRouteMap && typeof savedData.productActiveRouteMap === 'object') {
            productActiveRouteMap.value = savedData.productActiveRouteMap;
        } else if (savedData.activeRoute) {
            // 兼容旧数据格式：如果有 activeRoute，将其转换为 productActiveRouteMap
            if (activeProduct.value) {
                productActiveRouteMap.value[activeProduct.value] = savedData.activeRoute;
            }
        }

        // 恢复表单数据
        if (savedData.formDataMap && typeof savedData.formDataMap === 'object') {
            formDataMap.value = savedData.formDataMap;
        }

        return true;
    } catch (error) {
        console.error('加载暂存数据失败:', error);
        return false;
    }
};

// 初始化 formDataMap（为每个产品×线路组合创建数据）
const initFormDataMap = () => {
    allFormPairs.value.forEach(pair => {
        const key = getPairKey(pair);
        // 如果该组合的数据不存在，初始化基础数据
        if (!formDataMap.value[key]) {
            const baseValues = {
                productCode: pair.product.code,
                productName: pair.product.name,
                productType: pair.product.productType,
                routeCode: pair.route.code,
                routeName: pair.route.name,
                origin: pair.route.origin,
                destination: pair.route.destination,
                status: 'active',
            };
            formDataMap.value[key] = baseValues;
        }
    });
};

// 监听 allFormPairs 变化，自动初始化 formDataMap
watch(
    allFormPairs,
    (newPairs, oldPairs) => {
        initFormDataMap();
    },
    { immediate: true, deep: true },
);

// 页面加载时尝试加载暂存的数据
onMounted(() => {
    const loaded = loadSavedData();
    if (loaded) {
        ElMessage.success('已加载暂存的数据');
        // 加载后再次初始化，确保新增的组合也有数据
        initFormDataMap();
    } else {
        // 如果没有加载暂存数据，初始化 formDataMap
        initFormDataMap();
    }
});

// 监听可见表单变化，确保数据正确恢复
watch(
    visibleFormPairs,
    async newPairs => {
        // 等待 DOM 更新完成，确保 ref 已经设置
        await nextTick();
        // 再等待一个 tick，确保组件完全渲染
        await nextTick();

        // 为每个新显示的表单恢复数据
        newPairs.forEach(pair => {
            const key = getPairKey(pair);
            const formRef = formRefs.value[key];
            const savedData = formDataMap.value[key];

            // 如果表单已渲染且有保存的数据，恢复数据
            if (formRef && formRef.setFieldsValue && savedData) {
                // 确保数据不为空对象
                const hasData = Object.values(savedData).some(v => v !== '' && v !== null && v !== undefined);
                if (hasData) {
                    formRef.setFieldsValue(savedData);
                    console.log('已恢复表单数据:', key, savedData);
                }
            }
        });
    },
    { deep: true, immediate: false },
);
</script>

<style scoped lang="less">
.product-route-example {
    width: 100%;
    height: 100%;
    padding: 15px 0 0 15px;
    box-sizing: border-box;
    overflow-y: auto;

    .page-header {
        margin-bottom: 30px;

        h2 {
            font-size: 24px;
            margin-bottom: 10px;
            color: #303133;
        }

        .description {
            color: #909399;
            font-size: 14px;
        }
    }

    .product-section,
    .line-section {
        margin-bottom: 20px;

        :deep(.el-card__header) {
            padding: 18px 20px;
            border-bottom: 1px solid #ebeef5;
        }

        :deep(.el-card__body) {
            padding: 20px;
        }

        h3 {
            margin: 0 0 16px 0;
            color: #303133;
            font-size: 16px;
            font-weight: 600;
        }

        .product-tags,
        .line-tags {
            display: flex;
            gap: 12px;
            flex-wrap: wrap;
            margin-bottom: 16px;
        }

        .product-tag,
        .line-tag {
            cursor: pointer;
            transition: all 0.3s;

            &:hover {
                transform: translateY(-2px);
                box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            }

            &.has-error {
                border-color: #f56c6c !important;
                background-color: #fef0f0 !important;
                color: #f56c6c !important;
            }

            .product-name,
            .route-name {
                font-weight: 500;
                margin-right: 8px;
            }

            .product-code,
            .route-code {
                color: #909399;
                font-size: 12px;
                margin-right: 8px;
            }

            .product-type-tag {
                margin-left: 8px;
            }
        }

        .action-row {
            margin-top: 16px;
        }
    }

    .forms-container {
        margin-bottom: 20px;

        h3 {
            margin: 0 0 16px 0;
            color: #303133;
            font-size: 18px;
            font-weight: 600;
        }

        .performance-info {
            margin-bottom: 20px;
        }

        .hidden-forms-info {
            margin-top: 20px;
        }

        .form-item-card {
            margin-bottom: 20px;

            .form-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
            }

            .form-title {
                font-weight: bold;
                font-size: 16px;
            }

            .form-key {
                font-size: 12px;
                color: #909399;
                font-family: monospace;
            }

            .form-footer {
                margin-top: 15px;
                padding-top: 15px;
                border-top: 1px solid #ebeef5;
                text-align: center;
            }
        }
    }

    .data-preview {
        margin-bottom: 20px;

        :deep(.el-card__header) {
            padding: 18px 20px;
            border-bottom: 1px solid #ebeef5;
        }

        :deep(.el-card__body) {
            padding: 20px;
        }

        h3 {
            margin: 0 0 16px 0;
            color: #303133;
            font-size: 16px;
            font-weight: 600;
        }

        .preview-actions {
            display: flex;
            gap: 12px;
            align-items: center;
            margin-bottom: 16px;
        }

        .data-json {
            background: #f5f7fa;
            padding: 16px;
            border-radius: 4px;
            overflow-x: auto;
            max-height: 400px;
            overflow-y: auto;
            font-size: 12px;
            line-height: 1.6;
            margin: 0;
            font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace;
        }
    }
}
</style>
