<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 prop="name" label="三大营养素" align="center" />
          <el-table-column prop="weight" label="质量(g)" align="center" />
          <el-table-column prop="ratio" label="热量占比" align="center">
            <template #default="{ row }">{{ row.ratio }}%</template>
          </el-table-column>
          <el-table-column prop="reference" label="参考值" 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="产品名称" min-width="180" show-overflow-tooltip />
          <el-table-column prop="productCode" label="产品编码" width="120" align="center" show-overflow-tooltip />
          <el-table-column prop="type" label="产品" width="80" 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 * as echarts from 'echarts';

// Props定义
const props = defineProps<{
  nutritionProducts?: Array<{
    name: string,
    productCode: string,
    type: string,
    protein?: number,
    fat?: number,
    carbohydrate?: number,
    calorie?: number,
    dosePerTime?: number,
    dosePerDay?: number,
    quantity?: number
  }>
}>();

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

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

// 营养分析数据 - 基于计算结果动态生成
const nutritionData = computed(() => {

  const protein = dictData.value && dictData.value.length > 0 ? dictData.value[1].dictValue : '';
  const fat = dictData.value && dictData.value.length > 0 ? dictData.value[2].dictValue : '';
  const carbohydrate = dictData.value && dictData.value.length > 0 ? dictData.value[3].dictValue : '';

  return [
    {
      name: '蛋白质',
      weight: nutritionCalculation.value.totalProtein.toString(),
      ratio: nutritionCalculation.value.proteinPercentage.toString(),
      reference: protein
    },
    {
      name: '脂肪',
      weight: nutritionCalculation.value.totalFat.toString(),
      ratio: nutritionCalculation.value.fatPercentage.toString(),
      reference: fat
    },
    {
      name: '碳水化合物',
      weight: nutritionCalculation.value.totalCarbohydrate.toString(),
      ratio: nutritionCalculation.value.carbohydratePercentage.toString(),
      reference: carbohydrate
    }
  ]
});

// 营养产品列表数据 - 直接使用props传入的数据
const productData = ref<Array<{ name: string, productCode: string, type: string }>>([]);

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

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

  if (!productData.value || productData.value.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;

  // 遍历所有营养产品，累加营养成分
  productData.value.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(() => {
  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>
