<template>
    <el-card class="right-card">
        <div class="card-header">
            <span>营养数据分析</span>
            <el-button link>收起</el-button>
        </div>
        <div class="nutrition-analysis">
            <!-- 营养设定 -->
            <div class="nutrition-setting">
                <span>营养设定：</span>
                <span class="value">{{ nutritionSettings }}kcal/d</span>
            </div>

            <!-- 三大营养素表格 -->
            <div class="nutrition-table">
                <el-table :data="nutritionData" border size="small">
                    <el-table-column width="95" prop="name" label="营养素" align="center" />
                    <el-table-column width="70" prop="enteralNutrition" label="肠内营养" align="center" />
                    <el-table-column width="70" prop="parenteralNutrition" label="肠外营养" align="center" />
                    <el-table-column prop="dietTherapy" label="膳食治疗" width="70" align="center" />
                    <el-table-column prop="total" label="汇总" width="50" align="center" />
                    <el-table-column prop="nutritionSettings" label="营养设定" width="70" align="center" />
                </el-table>
                <!-- <div class="total-amount">
          <span>含量：</span>
          <span class="value">{{ nutritionCalculation.totalWeight }}g/天</span>
        </div> -->
            </div>

            <!-- 营养素占比图表 -->
            <div class="nutrition-chart">
                <div class="chart-title">三大营养元素质量占比</div>
                <div class="chart-content">
                    <div ref="chartRef" class="pie-chart"></div>
                    <div class="chart-legend">
                        <div class="legend-item">
                            <span class="color-block protein"></span>
                            <span>蛋白质</span>
                            <span class="percentage">{{ nutritionCalculation.proteinPercentage }}%</span>
                        </div>
                        <div class="legend-item">
                            <span class="color-block fat"></span>
                            <span>脂肪</span>
                            <span class="percentage">{{ nutritionCalculation.fatPercentage }}%</span>
                        </div>
                        <div class="legend-item">
                            <span class="color-block carbs"></span>
                            <span>碳水化合物</span>
                            <span class="percentage">{{ nutritionCalculation.carbohydratePercentage }}%</span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 产品列表 -->
            <div class="product-list">
                <el-table :data="productData" border size="small" v-loading="loading">
                    <el-table-column prop="name" label="属性名" width="100" show-overflow-tooltip />
                    <el-table-column prop="enteralNutrition" label="肠内营养" width="70" align="center" />
                    <el-table-column prop="parenteralNutrition" label="肠外营养" width="70" align="center" />
                    <el-table-column prop="dietTherapy" label="膳食治疗" width="70" align="center" />
                    <el-table-column prop="total" label="汇总" width="50" align="center" />
                    <el-table-column prop="nutritionSettings" label="营养设定" width="70" align="center" />
                    <!-- <template #empty>
                        <el-empty description="暂无营养产品数据" :image-size="60" />
                    </template> -->
                </el-table>
            </div>
        </div>
    </el-card>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, computed } from 'vue';
import { listByType } from '@/api/system/dict/data/index.ts';
import { DictDataVO } from '@/api/system/dict/data/types.ts';
import { listAllNutrition } from '@/api/warehouse/productNutrition';
import { NutritionVO } from '@/api/warehouse/productNutrition/types';
import * as echarts from 'echarts';

const nutritionVOList = ref<NutritionVO[]>(null);

// onMounted(async () => {
//     const data = await listAllNutrition();
//     nutritionVOList.value = data.rows;
// });

// Props定义
const props = defineProps<{
    nutritionProducts?: Array<{
        id?: string | number,
        name: string,
        productCode: string,
        type: string,
        protein?: number,
        fat?: number,
        carbohydrate?: number,
        calorie?: number,
        dosePerTime?: number,
        dosePerDay?: number,
        quantity?: number,
        // // 微量元素信息
        // ca?: number,  // 钙
        // p?: number,   // 磷
        // k?: number,   // 钾
        // na?: number,  // 钠
        // mg?: number,  // 镁
        // cl?: number,  // 氯
        // fe?: number,  // 铁
        // zn?: number,  // 锌
        // se?: number,  // 硒
        // cu?: number,  // 铜
        // mn?: number,  // 锰
        // i?: number,   // 碘
        // f?: number,   // 氟
        // cr?: number,  // 铬
        // mo?: number,  // 钼
        // // 氨基酸信息
        // isoleucine?: number,          // 异亮氨酸
        // tryptophan?: number,          // 色氨酸
        // sulfurAminoAcid?: string | number,     // 含硫氨基酸
        // histidine?: string | number,           // 组氨酸
        // aromaticAminoAcid?: string | number,   // 芳香族氨基酸
        // glutamicAcid?: string | number,        // 谷氨酸
        // threonine?: number,           // 苏氨酸
        // serine?: number,              // 丝氨酸
        // arginine?: number,            // 精氨酸
        // lysine?: number,              // 赖氨酸
        // asparticAcid?: string | number,        // 天冬氨酸
        // cysteine?: number,            // 胱氨酸
        // proline?: number,             // 脯氨酸
        // tyrosine?: number,            // 酪氨酸
        // leucine?: number,             // 亮氨酸
        // valine?: number,              // 缬氨酸
        // methionine?: number,          // 蛋氨酸
        // alanine?: number,             // 丙氨酸
        // phenylalanine?: number,       // 苯丙氨酸
        // glycine?: number,             // 甘氨酸
        // // 脂肪酸信息
        // fattyAcid?: string | number,           // 脂肪酸
        // saturatedFattyAcid?: string | number,  // 饱和脂肪酸
        // monounsaturatedFattyAcid?: string | number,  // 单不饱和脂肪酸
        // polyunsaturatedFattyAcid?: string | number,  // 多不饱和脂肪酸
        // // 维生素信息
        // vitaminA?: number,            // 维生素A
        // vitaminACarotene?: number,    // 维生素A(胡萝卜素)
        // vitaminAAlcohol?: number,     // 维生素A醇
        // vitaminD?: number,            // 维生素D
        // vitaminE?: number,            // 维生素E
        // vitaminETocopherol?: number,  // 维生素E（生育酚）
        // vitaminK?: number,            // 维生素K
        // vitaminBOne?: number,         // 维生素B1
        // vitaminBTwo?: number,         // 维生素B2
        // vitaminBSix?: number,         // 维生素B6
        // vitaminBTwelve?: number,      // 维生素B12
        // niacin?: number,              // 烟酸（尼克酸）
        // vitaminC?: number,            // 维生素C
        // folicAcid?: string | number,  // 叶酸
        // choline?: number,             // 胆碱
        // biotin?: number,              // 生物素
        // pantothenicAcid?: string | number,     // 泛酸
        // // 其他营养信息
        // cholesterol?: number,         // 胆固醇
        // bloodGlucoseIndex?: number,   // 血糖生成指数
        // insolubleDietaryFiber?: number,        // 不可溶性膳食纤维
        // dietaryFiber?: number,        // 膳食纤维
        // ash?: number,                 // 灰分
        // solubleDietaryFiber?: number, // 可溶性膳食纤维
        // osmoticPressure?: number,     // 渗透压
        // moisture?: number             // 水分
    }>
}>();

// 图表相关
const chartRef = ref<HTMLElement | null>(null);
const dictData = ref<DictDataVO[] | null>(null);
let myChart: echarts.ECharts | null = null;

// 加载状态
const loading = ref(false);

// 完整的营养产品基础数据列表（从后端获取的所有营养产品信息）
const allNutritionProducts = ref<NutritionVO[]>([]);

// 获取所有营养产品列表
const fetchAllNutritionProducts = async () => {
    try {
        console.log('RightCard: 开始获取所有营养产品列表...');
        const response = await listAllNutrition();
        console.log("营养产品列表 :", response);
        if (response.rows) {
            allNutritionProducts.value = response.rows;
            console.log('RightCard: 获取到营养产品列表:', response.rows);
            console.log('RightCard: 营养产品列表长度:', response.rows.length);
            if (response.rows.length > 0) {
                console.log('RightCard: 前3个产品ID:', response.rows.slice(0, 3).map(p => ({ id: p.id, productName: p.productName, productCode: p.productCode })));
            }
        }
    } catch (error) {
        console.error('RightCard: 获取营养产品列表失败:', error);
        allNutritionProducts.value = [];
    }
};

// 营养分析数据 - 基于计算结果动态生成
const nutritionData = computed(() => {
    if (!props.nutritionProducts || props.nutritionProducts.length === 0) {
        return [
            {
                name: '蛋白质',
                enteralNutrition: 0,
                parenteralNutrition: 0,
                dietTherapy: 0,
                total: 0,
                nutritionSettings: 0
            },
            {
                name: '脂肪',
                enteralNutrition: 0,
                parenteralNutrition: 0,
                dietTherapy: 0,
                total: 0,
                nutritionSettings: 0
            },
            {
                name: '碳水化合物',
                enteralNutrition: 0,
                parenteralNutrition: 0,
                dietTherapy: 0,
                total: 0,
                nutritionSettings: 0
            }
        ];
    }

    // 计算三大营养素总和
    let totalProtein = 0;
    let totalFat = 0;
    let totalCarbohydrate = 0;

    props.nutritionProducts.forEach(product => {
        const dosePerTime = product.dosePerTime || 0;
        const quantity = product.quantity || 1;
        const multiplier = dosePerTime * quantity;

        if (product.protein && multiplier > 0) {
            totalProtein += (product.protein / 100) * multiplier;
        }
        if (product.fat && multiplier > 0) {
            totalFat += (product.fat / 100) * multiplier;
        }
        if (product.carbohydrate && multiplier > 0) {
            totalCarbohydrate += (product.carbohydrate / 100) * multiplier;
        }
    });

    return [
        {
            name: '蛋白质',
            enteralNutrition: Number(totalProtein.toFixed(2)),
            parenteralNutrition: 0,
            dietTherapy: 0,
            total: Number(totalProtein.toFixed(2)),
            nutritionSettings: 0
        },
        {
            name: '脂肪',
            enteralNutrition: Number(totalFat.toFixed(2)),
            parenteralNutrition: 0,
            dietTherapy: 0,
            total: Number(totalFat.toFixed(2)),
            nutritionSettings: 0
        },
        {
            name: '碳水化合物',
            enteralNutrition: Number(totalCarbohydrate.toFixed(2)),
            parenteralNutrition: 0,
            dietTherapy: 0,
            total: Number(totalCarbohydrate.toFixed(2)),
            nutritionSettings: 0
        }
    ];
});

// 营养产品列表数据 - 基于props.nutritionProducts计算各种微量元素的总和
const productData = computed(() => {
    console.log('=== productData计算开始 ===');
    console.log('props.nutritionProducts:', props.nutritionProducts);

    if (!props.nutritionProducts || props.nutritionProducts.length === 0) {
        console.log('营养产品列表为空，返回默认数据');
        return [
            { name: '维生素A', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '维生素A(胡萝卜素)', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '维生素A醇', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '维生素D', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '维生素E', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '维生素E(生育酚)', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '维生素K', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '维生素B1', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '维生素B2', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '维生素B6', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '维生素B12', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '烟酸(尼克酸)', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '维生素C', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '叶酸', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '胆碱', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '生物素', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '泛酸', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '铁', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '锌', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '硒', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '铜', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '锰', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '碘', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '氟', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '铬', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '钼', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '钙', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '磷', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '钾', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '钠', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '镁', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '氯', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '胆固醇', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '异亮氨酸', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '色氨酸', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '含硫氨基酸', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '组氨酸', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '芳香族氨基酸', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '谷氨酸', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '苏氨酸', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '丝氨酸', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '精氨酸', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '赖氨酸', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '天冬氨酸', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '胱氨酸', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '脯氨酸', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '酪氨酸', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '亮氨酸', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '缬氨酸', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '蛋氨酸', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '丙氨酸', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '苯丙氨酸', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '甘氨酸', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '脂肪酸', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '饱和脂肪酸', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '单不饱和脂肪酸', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '多不饱和脂肪酸', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '血糖生成指数', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '不可溶性膳食纤维', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '膳食纤维', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 },
            { name: '可溶性膳食纤维', enteralNutrition: 0, parenteralNutrition: 0, dietTherapy: 0, total: 0, nutritionSettings: 0 }
        ];
    }

    // 计算各种营养素的总和
    const totals = {
        vitaminA: 0,
        vitaminACarotene: 0,
        vitaminAAlcohol: 0,
        vitaminD: 0,
        vitaminE: 0,
        vitaminETocopherol: 0,
        vitaminK: 0,
        vitaminBOne: 0,
        vitaminBTwo: 0,
        vitaminBSix: 0,
        vitaminBTwelve: 0,
        niacin: 0,
        vitaminC: 0,
        folicAcid: 0,
        choline: 0,
        biotin: 0,
        pantothenicAcid: 0,
        fe: 0,
        zn: 0,
        se: 0,
        cu: 0,
        mn: 0,
        i: 0,
        f: 0,
        cr: 0,
        mo: 0,
        ca: 0,
        p: 0,
        k: 0,
        na: 0,
        mg: 0,
        cl: 0,
        cholesterol: 0,
        isoleucine: 0,
        tryptophan: 0,
        sulfurAminoAcid: 0,
        histidine: 0,
        aromaticAminoAcid: 0,
        glutamicAcid: 0,
        threonine: 0,
        serine: 0,
        arginine: 0,
        lysine: 0,
        asparticAcid: 0,
        cysteine: 0,
        proline: 0,
        tyrosine: 0,
        leucine: 0,
        valine: 0,
        methionine: 0,
        alanine: 0,
        phenylalanine: 0,
        glycine: 0,
        fattyAcid: 0,
        saturatedFattyAcid: 0,
        monounsaturatedFattyAcid: 0,
        polyunsaturatedFattyAcid: 0,
        bloodGlucoseIndex: 0,
        insolubleDietaryFiber: 0,
        dietaryFiber: 0,
        solubleDietaryFiber: 0
    };

    console.log('开始遍历营养产品，产品数量:', props.nutritionProducts.length);

    // 遍历所有营养产品，累加各种营养素
    props.nutritionProducts.forEach((product, index) => {
        const dosePerTime = product.dosePerTime || 0;
        const quantity = product.quantity || 1;
        const multiplier = dosePerTime * quantity;

        console.log(`=== 产品 ${index + 1}: ${product.name} ===`);
        console.log('产品详细信息:', product);
        console.log('dosePerTime:', dosePerTime, 'quantity:', quantity, 'multiplier:', multiplier);

        // 优先从完整营养产品列表中获取详细营养信息
        const detailedNutrition = getNutritionDetailsFromAll(product.id);
        console.log('从完整列表获取的详细营养信息:', detailedNutrition);

        if (multiplier > 0) {
            console.log('开始计算微量元素...');

            // 获取营养素数据：优先使用完整列表中的数据，其次使用产品自带的数据
            const getNutrientValue = (nutrientName: string) => {
                const detailedValue = detailedNutrition?.[nutrientName];
                const productValue = product[nutrientName];
                const finalValue = detailedValue !== undefined && detailedValue !== null ? detailedValue : productValue;

                if (detailedValue !== undefined && detailedValue !== null && productValue !== undefined && productValue !== null) {
                    console.log(`${nutrientName}: 使用完整列表数据 ${detailedValue} (产品数据: ${productValue})`);
                } else if (detailedValue !== undefined && detailedValue !== null) {
                    console.log(`${nutrientName}: 使用完整列表数据 ${detailedValue}`);
                } else if (productValue !== undefined && productValue !== null) {
                    console.log(`${nutrientName}: 使用产品数据 ${productValue}`);
                }

                return finalValue || 0;
            };

            // 维生素类
            const vitaminA = getNutrientValue('vitaminA');
            if (vitaminA) {
                const oldValue = totals.vitaminA;
                totals.vitaminA += (vitaminA / 100) * multiplier;
                console.log(`维生素A: ${oldValue} + (${vitaminA}/100) * ${multiplier} = ${totals.vitaminA}`);
            }

            // 其他维生素
            const vitaminACarotene = getNutrientValue('vitaminACarotene');
            if (vitaminACarotene) totals.vitaminACarotene += (vitaminACarotene / 100) * multiplier;

            const vitaminAAlcohol = getNutrientValue('vitaminAAlcohol');
            if (vitaminAAlcohol) totals.vitaminAAlcohol += (vitaminAAlcohol / 100) * multiplier;

            const vitaminD = getNutrientValue('vitaminD');
            if (vitaminD) totals.vitaminD += (vitaminD / 100) * multiplier;

            const vitaminE = getNutrientValue('vitaminE');
            if (vitaminE) totals.vitaminE += (vitaminE / 100) * multiplier;

            const vitaminETocopherol = getNutrientValue('vitaminETocopherol');
            if (vitaminETocopherol) totals.vitaminETocopherol += (vitaminETocopherol / 100) * multiplier;

            const vitaminK = getNutrientValue('vitaminK');
            if (vitaminK) totals.vitaminK += (vitaminK / 100) * multiplier;

            const vitaminBOne = getNutrientValue('vitaminBOne');
            if (vitaminBOne) totals.vitaminBOne += (vitaminBOne / 100) * multiplier;

            const vitaminBTwo = getNutrientValue('vitaminBTwo');
            if (vitaminBTwo) totals.vitaminBTwo += (vitaminBTwo / 100) * multiplier;

            const vitaminBSix = getNutrientValue('vitaminBSix');
            if (vitaminBSix) totals.vitaminBSix += (vitaminBSix / 100) * multiplier;

            const vitaminBTwelve = getNutrientValue('vitaminBTwelve');
            if (vitaminBTwelve) totals.vitaminBTwelve += (vitaminBTwelve / 100) * multiplier;

            const niacin = getNutrientValue('niacin');
            if (niacin) totals.niacin += (niacin / 100) * multiplier;

            const vitaminC = getNutrientValue('vitaminC');
            if (vitaminC) {
                const oldValue = totals.vitaminC;
                totals.vitaminC += (vitaminC / 100) * multiplier;
                console.log(`维生素C: ${oldValue} + (${vitaminC}/100) * ${multiplier} = ${totals.vitaminC}`);
            }

            const folicAcid = getNutrientValue('folicAcid');
            if (folicAcid) totals.folicAcid += (Number(folicAcid) / 100) * multiplier;

            const choline = getNutrientValue('choline');
            if (choline) totals.choline += (choline / 100) * multiplier;

            const biotin = getNutrientValue('biotin');
            if (biotin) totals.biotin += (biotin / 100) * multiplier;

            const pantothenicAcid = getNutrientValue('pantothenicAcid');
            if (pantothenicAcid) totals.pantothenicAcid += (Number(pantothenicAcid) / 100) * multiplier;

            // 矿物质类
            const fe = getNutrientValue('fe');
            if (fe) {
                const oldValue = totals.fe;
                totals.fe += (fe / 100) * multiplier;
                console.log(`铁: ${oldValue} + (${fe}/100) * ${multiplier} = ${totals.fe}`);
            }

            const zn = getNutrientValue('zn');
            if (zn) totals.zn += (zn / 100) * multiplier;

            const se = getNutrientValue('se');
            if (se) totals.se += (se / 100) * multiplier;

            const cu = getNutrientValue('cu');
            if (cu) totals.cu += (cu / 100) * multiplier;

            const mn = getNutrientValue('mn');
            if (mn) totals.mn += (mn / 100) * multiplier;

            const i = getNutrientValue('i');
            if (i) totals.i += (i / 100) * multiplier;

            const f = getNutrientValue('f');
            if (f) totals.f += (f / 100) * multiplier;

            const cr = getNutrientValue('cr');
            if (cr) totals.cr += (cr / 100) * multiplier;

            const mo = getNutrientValue('mo');
            if (mo) totals.mo += (mo / 100) * multiplier;

            const ca = getNutrientValue('ca');
            if (ca) {
                const oldValue = totals.ca;
                totals.ca += (ca / 100) * multiplier;
                console.log(`钙: ${oldValue} + (${ca}/100) * ${multiplier} = ${totals.ca}`);
            }

            const p = getNutrientValue('p');
            if (p) totals.p += (p / 100) * multiplier;

            const k = getNutrientValue('k');
            if (k) totals.k += (k / 100) * multiplier;

            const na = getNutrientValue('na');
            if (na) totals.na += (na / 100) * multiplier;

            const mg = getNutrientValue('mg');
            if (mg) totals.mg += (mg / 100) * multiplier;

            const cl = getNutrientValue('cl');
            if (cl) totals.cl += (cl / 100) * multiplier;

            // 其他类
            const cholesterol = getNutrientValue('cholesterol');
            if (cholesterol) totals.cholesterol += (cholesterol / 100) * multiplier;

            // 氨基酸类
            const isoleucine = getNutrientValue('isoleucine');
            if (isoleucine) totals.isoleucine += (isoleucine / 100) * multiplier;

            const tryptophan = getNutrientValue('tryptophan');
            if (tryptophan) totals.tryptophan += (tryptophan / 100) * multiplier;

            const sulfurAminoAcid = getNutrientValue('sulfurAminoAcid');
            if (sulfurAminoAcid) totals.sulfurAminoAcid += (Number(sulfurAminoAcid) / 100) * multiplier;

            const histidine = getNutrientValue('histidine');
            if (histidine) totals.histidine += (Number(histidine) / 100) * multiplier;

            const aromaticAminoAcid = getNutrientValue('aromaticAminoAcid');
            if (aromaticAminoAcid) totals.aromaticAminoAcid += (Number(aromaticAminoAcid) / 100) * multiplier;

            const glutamicAcid = getNutrientValue('glutamicAcid');
            if (glutamicAcid) totals.glutamicAcid += (Number(glutamicAcid) / 100) * multiplier;

            const threonine = getNutrientValue('threonine');
            if (threonine) totals.threonine += (threonine / 100) * multiplier;

            const serine = getNutrientValue('serine');
            if (serine) totals.serine += (serine / 100) * multiplier;

            const arginine = getNutrientValue('arginine');
            if (arginine) totals.arginine += (arginine / 100) * multiplier;

            const lysine = getNutrientValue('lysine');
            if (lysine) totals.lysine += (lysine / 100) * multiplier;

            const asparticAcid = getNutrientValue('asparticAcid');
            if (asparticAcid) totals.asparticAcid += (Number(asparticAcid) / 100) * multiplier;

            const cysteine = getNutrientValue('cysteine');
            if (cysteine) totals.cysteine += (cysteine / 100) * multiplier;

            const proline = getNutrientValue('proline');
            if (proline) totals.proline += (proline / 100) * multiplier;

            const tyrosine = getNutrientValue('tyrosine');
            if (tyrosine) totals.tyrosine += (tyrosine / 100) * multiplier;

            const leucine = getNutrientValue('leucine');
            if (leucine) totals.leucine += (leucine / 100) * multiplier;

            const valine = getNutrientValue('valine');
            if (valine) totals.valine += (valine / 100) * multiplier;

            const methionine = getNutrientValue('methionine');
            if (methionine) totals.methionine += (methionine / 100) * multiplier;

            const alanine = getNutrientValue('alanine');
            if (alanine) totals.alanine += (alanine / 100) * multiplier;

            const phenylalanine = getNutrientValue('phenylalanine');
            if (phenylalanine) totals.phenylalanine += (phenylalanine / 100) * multiplier;

            const glycine = getNutrientValue('glycine');
            if (glycine) totals.glycine += (glycine / 100) * multiplier;

            // 脂肪酸类
            const fattyAcid = getNutrientValue('fattyAcid');
            if (fattyAcid) totals.fattyAcid += (Number(fattyAcid) / 100) * multiplier;

            const saturatedFattyAcid = getNutrientValue('saturatedFattyAcid');
            if (saturatedFattyAcid) totals.saturatedFattyAcid += (Number(saturatedFattyAcid) / 100) * multiplier;

            const monounsaturatedFattyAcid = getNutrientValue('monounsaturatedFattyAcid');
            if (monounsaturatedFattyAcid) totals.monounsaturatedFattyAcid += (Number(monounsaturatedFattyAcid) / 100) * multiplier;

            const polyunsaturatedFattyAcid = getNutrientValue('polyunsaturatedFattyAcid');
            if (polyunsaturatedFattyAcid) totals.polyunsaturatedFattyAcid += (Number(polyunsaturatedFattyAcid) / 100) * multiplier;

            // 其他营养信息
            const bloodGlucoseIndex = getNutrientValue('bloodGlucoseIndex');
            if (bloodGlucoseIndex) totals.bloodGlucoseIndex += (bloodGlucoseIndex / 100) * multiplier;

            const insolubleDietaryFiber = getNutrientValue('insolubleDietaryFiber');
            if (insolubleDietaryFiber) totals.insolubleDietaryFiber += (insolubleDietaryFiber / 100) * multiplier;

            const dietaryFiber = getNutrientValue('dietaryFiber');
            if (dietaryFiber) totals.dietaryFiber += (dietaryFiber / 100) * multiplier;

            const solubleDietaryFiber = getNutrientValue('solubleDietaryFiber');
            if (solubleDietaryFiber) totals.solubleDietaryFiber += (solubleDietaryFiber / 100) * multiplier;
        } else {
            console.log('multiplier <= 0，跳过计算');
        }
    });

    console.log('计算完成后的totals:', totals);

    // 格式化结果并返回
    const result = [
        { name: '维生素A', enteralNutrition: Number(totals.vitaminA.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.vitaminA.toFixed(2)), nutritionSettings: 0 },
        { name: '维生素A(胡萝卜素)', enteralNutrition: Number(totals.vitaminACarotene.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.vitaminACarotene.toFixed(2)), nutritionSettings: 0 },
        { name: '维生素A醇', enteralNutrition: Number(totals.vitaminAAlcohol.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.vitaminAAlcohol.toFixed(2)), nutritionSettings: 0 },
        { name: '维生素D', enteralNutrition: Number(totals.vitaminD.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.vitaminD.toFixed(2)), nutritionSettings: 0 },
        { name: '维生素E', enteralNutrition: Number(totals.vitaminE.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.vitaminE.toFixed(2)), nutritionSettings: 0 },
        { name: '维生素E(生育酚)', enteralNutrition: Number(totals.vitaminETocopherol.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.vitaminETocopherol.toFixed(2)), nutritionSettings: 0 },
        { name: '维生素K', enteralNutrition: Number(totals.vitaminK.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.vitaminK.toFixed(2)), nutritionSettings: 0 },
        { name: '维生素B1', enteralNutrition: Number(totals.vitaminBOne.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.vitaminBOne.toFixed(2)), nutritionSettings: 0 },
        { name: '维生素B2', enteralNutrition: Number(totals.vitaminBTwo.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.vitaminBTwo.toFixed(2)), nutritionSettings: 0 },
        { name: '维生素B6', enteralNutrition: Number(totals.vitaminBSix.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.vitaminBSix.toFixed(2)), nutritionSettings: 0 },
        { name: '维生素B12', enteralNutrition: Number(totals.vitaminBTwelve.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.vitaminBTwelve.toFixed(2)), nutritionSettings: 0 },
        { name: '烟酸(尼克酸)', enteralNutrition: Number(totals.niacin.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.niacin.toFixed(2)), nutritionSettings: 0 },
        { name: '维生素C', enteralNutrition: Number(totals.vitaminC.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.vitaminC.toFixed(2)), nutritionSettings: 0 },
        { name: '叶酸', enteralNutrition: Number(totals.folicAcid.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.folicAcid.toFixed(2)), nutritionSettings: 0 },
        { name: '胆碱', enteralNutrition: Number(totals.choline.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.choline.toFixed(2)), nutritionSettings: 0 },
        { name: '生物素', enteralNutrition: Number(totals.biotin.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.biotin.toFixed(2)), nutritionSettings: 0 },
        { name: '泛酸', enteralNutrition: Number(totals.pantothenicAcid.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.pantothenicAcid.toFixed(2)), nutritionSettings: 0 },
        { name: '铁', enteralNutrition: Number(totals.fe.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.fe.toFixed(2)), nutritionSettings: 0 },
        { name: '锌', enteralNutrition: Number(totals.zn.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.zn.toFixed(2)), nutritionSettings: 0 },
        { name: '硒', enteralNutrition: Number(totals.se.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.se.toFixed(2)), nutritionSettings: 0 },
        { name: '铜', enteralNutrition: Number(totals.cu.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.cu.toFixed(2)), nutritionSettings: 0 },
        { name: '锰', enteralNutrition: Number(totals.mn.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.mn.toFixed(2)), nutritionSettings: 0 },
        { name: '碘', enteralNutrition: Number(totals.i.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.i.toFixed(2)), nutritionSettings: 0 },
        { name: '氟', enteralNutrition: Number(totals.f.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.f.toFixed(2)), nutritionSettings: 0 },
        { name: '铬', enteralNutrition: Number(totals.cr.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.cr.toFixed(2)), nutritionSettings: 0 },
        { name: '钼', enteralNutrition: Number(totals.mo.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.mo.toFixed(2)), nutritionSettings: 0 },
        { name: '钙', enteralNutrition: Number(totals.ca.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.ca.toFixed(2)), nutritionSettings: 0 },
        { name: '磷', enteralNutrition: Number(totals.p.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.p.toFixed(2)), nutritionSettings: 0 },
        { name: '钾', enteralNutrition: Number(totals.k.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.k.toFixed(2)), nutritionSettings: 0 },
        { name: '钠', enteralNutrition: Number(totals.na.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.na.toFixed(2)), nutritionSettings: 0 },
        { name: '镁', enteralNutrition: Number(totals.mg.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.mg.toFixed(2)), nutritionSettings: 0 },
        { name: '氯', enteralNutrition: Number(totals.cl.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.cl.toFixed(2)), nutritionSettings: 0 },
        { name: '胆固醇', enteralNutrition: Number(totals.cholesterol.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.cholesterol.toFixed(2)), nutritionSettings: 0 },
        { name: '异亮氨酸', enteralNutrition: Number(totals.isoleucine.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.isoleucine.toFixed(2)), nutritionSettings: 0 },
        { name: '色氨酸', enteralNutrition: Number(totals.tryptophan.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.tryptophan.toFixed(2)), nutritionSettings: 0 },
        { name: '含硫氨基酸', enteralNutrition: Number(totals.sulfurAminoAcid.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.sulfurAminoAcid.toFixed(2)), nutritionSettings: 0 },
        { name: '组氨酸', enteralNutrition: Number(totals.histidine.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.histidine.toFixed(2)), nutritionSettings: 0 },
        { name: '芳香族氨基酸', enteralNutrition: Number(totals.aromaticAminoAcid.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.aromaticAminoAcid.toFixed(2)), nutritionSettings: 0 },
        { name: '谷氨酸', enteralNutrition: Number(totals.glutamicAcid.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.glutamicAcid.toFixed(2)), nutritionSettings: 0 },
        { name: '苏氨酸', enteralNutrition: Number(totals.threonine.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.threonine.toFixed(2)), nutritionSettings: 0 },
        { name: '丝氨酸', enteralNutrition: Number(totals.serine.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.serine.toFixed(2)), nutritionSettings: 0 },
        { name: '精氨酸', enteralNutrition: Number(totals.arginine.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.arginine.toFixed(2)), nutritionSettings: 0 },
        { name: '赖氨酸', enteralNutrition: Number(totals.lysine.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.lysine.toFixed(2)), nutritionSettings: 0 },
        { name: '天冬氨酸', enteralNutrition: Number(totals.asparticAcid.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.asparticAcid.toFixed(2)), nutritionSettings: 0 },
        { name: '胱氨酸', enteralNutrition: Number(totals.cysteine.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.cysteine.toFixed(2)), nutritionSettings: 0 },
        { name: '脯氨酸', enteralNutrition: Number(totals.proline.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.proline.toFixed(2)), nutritionSettings: 0 },
        { name: '酪氨酸', enteralNutrition: Number(totals.tyrosine.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.tyrosine.toFixed(2)), nutritionSettings: 0 },
        { name: '亮氨酸', enteralNutrition: Number(totals.leucine.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.leucine.toFixed(2)), nutritionSettings: 0 },
        { name: '缬氨酸', enteralNutrition: Number(totals.valine.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.valine.toFixed(2)), nutritionSettings: 0 },
        { name: '蛋氨酸', enteralNutrition: Number(totals.methionine.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.methionine.toFixed(2)), nutritionSettings: 0 },
        { name: '丙氨酸', enteralNutrition: Number(totals.alanine.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.alanine.toFixed(2)), nutritionSettings: 0 },
        { name: '苯丙氨酸', enteralNutrition: Number(totals.phenylalanine.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.phenylalanine.toFixed(2)), nutritionSettings: 0 },
        { name: '甘氨酸', enteralNutrition: Number(totals.glycine.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.glycine.toFixed(2)), nutritionSettings: 0 },
        { name: '脂肪酸', enteralNutrition: Number(totals.fattyAcid.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.fattyAcid.toFixed(2)), nutritionSettings: 0 },
        { name: '饱和脂肪酸', enteralNutrition: Number(totals.saturatedFattyAcid.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.saturatedFattyAcid.toFixed(2)), nutritionSettings: 0 },
        { name: '单不饱和脂肪酸', enteralNutrition: Number(totals.monounsaturatedFattyAcid.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.monounsaturatedFattyAcid.toFixed(2)), nutritionSettings: 0 },
        { name: '多不饱和脂肪酸', enteralNutrition: Number(totals.polyunsaturatedFattyAcid.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.polyunsaturatedFattyAcid.toFixed(2)), nutritionSettings: 0 },
        { name: '血糖生成指数', enteralNutrition: Number(totals.bloodGlucoseIndex.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.bloodGlucoseIndex.toFixed(2)), nutritionSettings: 0 },
        { name: '不可溶性膳食纤维', enteralNutrition: Number(totals.insolubleDietaryFiber.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.insolubleDietaryFiber.toFixed(2)), nutritionSettings: 0 },
        { name: '膳食纤维', enteralNutrition: Number(totals.dietaryFiber.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.dietaryFiber.toFixed(2)), nutritionSettings: 0 },
        { name: '可溶性膳食纤维', enteralNutrition: Number(totals.solubleDietaryFiber.toFixed(2)), parenteralNutrition: 0, dietTherapy: 0, total: Number(totals.solubleDietaryFiber.toFixed(2)), nutritionSettings: 0 }
    ];

    console.log('=== productData计算结果 ===', result);
    return result;
});

// 监听props变化更新产品列表
watch(() => props.nutritionProducts, (newProducts) => {
    console.log("RightCard接收到营养产品更新:", newProducts);
}, { immediate: true });

// 根据产品ID从完整营养产品列表中获取详细营养信息
const getNutritionDetailsFromAll = (productId: string | number): NutritionVO | null => {
    console.log('=== getNutritionDetailsFromAll 开始 ===');
    console.log('查找产品ID:', productId);
    console.log('完整营养产品列表长度:', allNutritionProducts.value?.length || 0);

    if (!productId || !allNutritionProducts.value || allNutritionProducts.value.length === 0) {
        console.log('产品ID为空或完整营养产品列表为空');
        return null;
    }

    // 提取实际的产品ID（去除可能的后缀，如 1954733747963371521_0_0 -> 1954733747963371521）
    let actualProductId = productId;
    if (typeof productId === 'string' && productId.includes('_')) {
        actualProductId = productId.split('_')[0];
        console.log('提取实际产品ID:', actualProductId, '原始ID:', productId);
    }

    // 在完整营养产品列表中查找对应的产品
    const foundProduct = allNutritionProducts.value.find(product => {
        // 可能的匹配方式：直接ID匹配、字符串ID匹配、产品编码匹配
        const match = product.id === actualProductId ||
            product.id === actualProductId.toString() ||
            product.productCode === actualProductId ||
            product.id?.toString() === actualProductId.toString();

        if (match) {
            console.log('找到匹配的产品:', product);
        }

        return match;
    });

    console.log('查找结果:', foundProduct ? '找到产品' : '未找到产品');
    console.log('=== getNutritionDetailsFromAll 结束 ===');

    return foundProduct || null;
};

// 计算营养成分总量和百分比
const nutritionCalculation = computed(() => {
    console.log('开始计算营养成分...', props.nutritionProducts);

    if (!props.nutritionProducts || props.nutritionProducts.length === 0) {
        return {
            totalProtein: 0,
            totalFat: 0,
            totalCarbohydrate: 0,
            totalWeight: 0,
            proteinPercentage: 0,
            fatPercentage: 0,
            carbohydratePercentage: 0
        };
    }

    let totalProtein = 0;
    let totalFat = 0;
    let totalCarbohydrate = 0;

    // 遍历所有营养产品，累加营养成分
    props.nutritionProducts.forEach(product => {
        let dose = product.dosePerTime || 0; // 用量/次 (g)
        let quantity = product.quantity || 1; // 数量
        let multiplier = dose * quantity; // 总用量

        console.log(`产品 ${product.name}:`, {
            protein: product.protein,
            fat: product.fat,
            carbohydrate: product.carbohydrate,
            dose,
            quantity,
            multiplier
        });

        if (product.protein && multiplier > 0) {
            totalProtein += (product.protein / 100) * multiplier; // 按百分比计算实际含量
            console.log("计算蛋白质 :", totalProtein);
        }
        if (product.fat && multiplier > 0) {
            totalFat += (product.fat / 100) * multiplier;
            console.log("计算脂肪 :", totalFat);
        }
        if (product.carbohydrate && multiplier > 0) {
            totalCarbohydrate += (product.carbohydrate / 100) * multiplier;
            console.log("计算碳水化合物 :", totalCarbohydrate);
        }
    });

    const totalWeight = totalProtein + totalFat + totalCarbohydrate;

    // 计算百分比
    const proteinPercentage = totalWeight > 0 ? (totalProtein / totalWeight) * 100 : 0;
    const fatPercentage = totalWeight > 0 ? (totalFat / totalWeight) * 100 : 0;
    const carbohydratePercentage = totalWeight > 0 ? (totalCarbohydrate / totalWeight) * 100 : 0;

    const result = {
        totalProtein: Number(totalProtein.toFixed(2)),
        totalFat: Number(totalFat.toFixed(2)),
        totalCarbohydrate: Number(totalCarbohydrate.toFixed(2)),
        totalWeight: Number(totalWeight.toFixed(2)),
        proteinPercentage: Number(proteinPercentage.toFixed(2)),
        fatPercentage: Number(fatPercentage.toFixed(2)),
        carbohydratePercentage: Number(carbohydratePercentage.toFixed(2))
    };

    console.log('营养成分计算结果:', result);
    return result;
});

// 计算营养设定 (所有产品热量的累加)
const nutritionSettings = computed(() => {
    if (!props.nutritionProducts || props.nutritionProducts.length === 0) {
        return 0;
    }

    let totalCalorie = 0;

    // 遍历所有营养产品，累加热量
    props.nutritionProducts.forEach(product => {
        const dosePerDay = product.dosePerTime || 0; // 用量/日
        const calorie = product.calorie || 0; // 产品热量

        if (calorie > 0 && dosePerDay > 0) {
            // 使用公式：calorie / 100 * 用量/日
            totalCalorie += calorie / 100 * dosePerDay;
        }

        console.log(`产品 ${product.name} 热量计算:`, {
            calorie,
            dosePerDay,
            productCalorie: calorie / 100 * dosePerDay
        });
    });

    console.log('营养设定总热量:', totalCalorie);
    return totalCalorie;
});

// 更新图表数据
const updateChart = () => {
    if (!myChart) return;

    const option = {
        series: [
            {
                data: [
                    { value: nutritionCalculation.value.proteinPercentage, name: '蛋白质' },
                    { value: nutritionCalculation.value.fatPercentage, name: '脂肪' },
                    { value: nutritionCalculation.value.carbohydratePercentage, name: '碳水化合物' }
                ]
            }
        ]
    };

    myChart.setOption(option);
    console.log('图表已更新:', option);
};

// 初始化图表
const initChart = () => {
    if (!chartRef.value) return;

    myChart = echarts.init(chartRef.value);
    const option = {
        tooltip: {
            show: false
        },
        legend: {
            show: false
        },
        color: ['#4B6EFF', '#8592A6', '#8CDFFF'],
        series: [
            {
                name: '营养元素',
                type: 'pie',
                radius: ['65%', '85%'],
                center: ['50%', '50%'],
                startAngle: 90,
                avoidLabelOverlap: false,
                silent: true,
                itemStyle: {
                    borderWidth: 0,
                    borderRadius: 0
                },
                label: {
                    show: false
                },
                emphasis: {
                    disabled: true
                },
                labelLine: {
                    show: false
                },
                data: [
                    { value: nutritionCalculation.value.proteinPercentage, name: '蛋白质' },
                    { value: nutritionCalculation.value.fatPercentage, name: '脂肪' },
                    { value: nutritionCalculation.value.carbohydratePercentage, name: '碳水化合物' }
                ]
            }
        ]
    };

    myChart.setOption(option);
};

// 监听营养计算变化，更新图表
watch(() => nutritionCalculation.value, () => {
    updateChart();
}, { deep: true });

onMounted(async () => {
    // 先获取营养产品数据
    await fetchAllNutritionProducts();

    initChart();
    listByType("nutrient_reference").then(response => {
        dictData.value = response.data.nutrient_reference;
    });
    window.addEventListener('resize', () => {
        myChart?.resize();
    });
});
</script>

<style lang="scss" scoped>
.right-card {
    width: 400px;

    .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;
        padding: 0 4px;

        span {
            font-size: 16px;
            font-weight: 500;
            color: #303133;
        }
    }

    .nutrition-analysis {
        .nutrition-setting {
            background: #fff;
            padding: 12px;
            margin-bottom: 16px;
            border-radius: 4px;
            display: flex;
            align-items: center;
            gap: 8px;
            color: #606266;

            .value {
                color: var(--el-color-primary);
                font-weight: 500;
            }
        }

        .nutrition-table {
            margin-bottom: 16px;

            :deep(.el-table) {
                margin-bottom: 8px;

                th {
                    background-color: #f5f7fa;
                    color: #606266;
                    font-weight: 500;
                    padding: 8px 0;
                }

                td {
                    padding: 8px;
                }
            }

            .total-amount {
                padding: 8px 12px;
                background: #f5f7fa;
                color: #606266;
                font-size: 14px;
                display: flex;
                align-items: center;
                gap: 8px;

                .value {
                    color: #303133;
                }
            }
        }

        .nutrition-chart {
            margin-bottom: 16px;
            background: #fff;
            border-radius: 4px;
            border: 1px solid #e4e7ed;
            overflow: hidden;

            .chart-title {
                font-size: 14px;
                color: #303133;
                text-align: center;
                padding: 12px 0;
                background-color: #f5f7fa;
                border-bottom: 1px solid #e4e7ed;
                font-weight: 500;
            }

            .chart-content {
                display: flex;
                align-items: center;
                gap: 32px;
                padding: 16px;
                background-color: #fff;

                .pie-chart {
                    flex: none;
                    width: 140px;
                    height: 140px;
                }

                .chart-legend {
                    flex: 1;
                    min-width: 120px;
                    display: flex;
                    flex-direction: column;
                    gap: 12px;

                    .legend-item {
                        display: flex;
                        align-items: center;
                        gap: 8px;
                        font-size: 14px;
                        color: #606266;
                        white-space: nowrap;

                        .color-block {
                            width: 12px;
                            height: 12px;
                            border-radius: 2px;
                            flex-shrink: 0;

                            &.protein {
                                background: #4b6eff;
                            }

                            &.fat {
                                background: #8592a6;
                            }

                            &.carbs {
                                background: #8cdfff;
                            }
                        }

                        .percentage {
                            margin-left: 8px;
                            color: #303133;
                            font-weight: 500;
                        }
                    }
                }
            }
        }

        .product-list {
            :deep(.el-table) {
                th {
                    background-color: #f5f7fa;
                    color: #606266;
                    font-weight: 500;
                    padding: 8px 0;
                }

                td {
                    padding: 8px;
                }
            }
        }
    }
}
</style>
