<template>
  <div class="crop-cd-dashboard p-4 bg-white min-h-screen">
    <div class="flex justify-between items-center mb-6">
      <h1 class="text-xl font-bold text-gray-800">作物态 Cd 数据统计分析</h1>
      <div class="flex items-center">
        <div class="stat-card inline-block px-3 py-2">
          <div class="stat-value text-lg">样本数量{{ stats.samples }}</div>
        </div>
      </div>
    </div>
    
    <!-- 加载状态 -->
    <div v-if="isLoading" class="loading-overlay">
      <span class="spinner"></span>
      <span class="ml-3 text-gray-700">数据加载中...</span>
    </div>
    
    <!-- 错误提示 -->
    <div v-if="error" class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-6">
      <p>数据加载失败: {{ error.message }}</p>
      <button class="mt-2 px-3 py-1 bg-red-500 text-white rounded" @click="initCharts">重试</button>
    </div>
    
    
    <!-- 1️⃣ 作物态Cd指标 -->
    <section class="mb-4 chart-container">
      <h3 class="section-title text-base font-semibold">作物态Cd主要指标</h3>
      <div ref="cdBarChart" style="width: 100%; height: 415px;"></div>
    </section>

    <!-- 2️⃣ 养分元素 -->
    <section class="mb-4 chart-container">
      <h3 class="section-title text-base font-semibold">主要养分元素</h3>
      <div ref="nutrientBoxChart" style="width: 100%; height: 400px;"></div>
    </section>

    <!-- 3️⃣ 其他理化性质 -->
    <section class="chart-container">
      <div class="flex justify-between items-center mb-3">
        <h3 class="section-title text-base font-semibold">其他理化性质</h3>
      </div>
      <div ref="extraBoxChart" style="width: 100%; height: 400px;"></div>
    </section>

  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick } from 'vue';
import * as echarts from 'echarts';
import axios from 'axios';


// 图表实例引用
const cdBarChart = ref(null);
const nutrientBoxChart = ref(null);
const extraBoxChart = ref(null);


// 图表实例变量
let chartInstanceCd = null;
let chartInstanceNutrient = null;
let chartInstanceExtra = null;


// 响应式状态
const showDialog = ref(false);
const dialogTitle = ref("");

const isLoading = ref(true);
const error = ref(null);
const lastUpdate = ref("");
const stats = ref({
  cd002Avg: 0,
  cd02Avg: 0,
  cd2Avg: 0,
  samples: 0
});

// 按类别缓存统计数据（与x轴顺序对应）
const pollutionStats = ref([]);
const nutrientStats = ref([]);
const extraStats = ref([]);

// 字段配置（根据接口返回的作物态Cd数据结构定义）
const fieldConfig = {
 pollution: [
    { 
      key: '002_0002IDW', 
      name: '粉粒组分质量占比',  // 横坐标保持原标识
      color: '#5470c6' ,
      unit:"%",
      convert: false
    },
    { 
      key: '02_002IDW', 
      name: '砂粒组分质量占比',  // 横坐标保持原标识
      color: '#91cc75' ,
      unit:"%",
      convert: false
    },
    { 
      key: '2_02IDW', 
      name: '石砾组分质量占比',  // 横坐标保持原标识
      color: '#fac858' ,
      unit:"%",
      convert: false
    }
  ],
  nutrient: [
    { key: 'AvaK_IDW', name: '速效钾', color: '#ee6666',unit:'mg/kg' ,convert: false},
    { key: 'SAvaK_IDW', name: '交换性速效钾', color: '#ee6666' ,unit:'mg/kg' ,convert: false},
    { key: 'AvaP_IDW', name: '速效磷', color: '#ee6666' ,unit:'mg/kg' ,convert: false},
    { key: 'TMn_IDW', name: '全锰', color: '#73c0de' ,unit:'mg/kg' ,convert: false},
    { key: 'TN_IDW', name: '全氮', color: '#ee6666' ,unit:'mg/kg' ,convert: true,conversionFactor:1000},
    { key: 'TS_IDW', name: '全硫', color: '#ee6666',unit:'mg/kg' ,convert: true,conversionFactor:1000}
  ],
  extra: [
    { key: 'TAl_IDW', name: '全铝', color: '#73c0de' ,unit:'%',convert: false },
    { key: 'TCa_IDW', name: '全钙', color: '#73c0de' ,unit:'%',convert: false},
    { key: 'TFe_IDW', name: '全铁', color: '#73c0de' ,unit:'%',convert: false},
    { key: 'TMg_IDW', name: '全镁', color: '#73c0de' ,unit:'%',convert: false},
  ]
};


// 数据请求（作物态Cd接口）
const fetchData = async () => {
  try {
    const apiUrl = 'http://localhost:8000/api/vector/stats/CropCd_input_data';
    const response = await axios.get(apiUrl);
    console.log("接口原始返回：", response.data);
    return response.data.data;
  } catch (err) {
    throw new Error('数据加载失败: ' + err.message);
  }
};

// 构建箱线图数据
const buildBoxplotData = (statsArray) => {
  return statsArray.map(stat => {
    if (!stat.min) return [null, null, null, null, null];
    return [stat.min, stat.q1, stat.median, stat.q3, stat.max];
  });
};

// 初始化作物态Cd指标图表
const initPollutionChart = () => {
  nextTick(() => {
    // 若图表实例已存在，先销毁避免内存泄漏
    if (chartInstanceCd) chartInstanceCd.dispose();
    // 校验 DOM 存在性（防止 ref 未关联到有效 DOM）
    if (!cdBarChart.value) return;
    // 初始化 ECharts 实例
    chartInstanceCd = echarts.init(cdBarChart.value);
    
    const xAxisData = fieldConfig.pollution.map(f => f.name);
    const barData = pollutionStats.value.map(stat => stat.avg || 0);
    
    chartInstanceCd.setOption({
      title: {},
      tooltip: {
        trigger: 'axis',
        formatter: (params) => `${params[0].name}<br/>平均值: ${params[0].value.toFixed(4)}`
      },
      grid: { top: 40, right: 15, bottom: '18%', left: '10%' },
      xAxis: { type: "category", data: xAxisData, axisLabel: { fontSize: 12, rotate: 30 } },
      yAxis: { type: "value", name: '%', nameTextStyle: { fontSize: 12 }, axisLabel: { fontSize: 11 } },
      series: [{
        name: '平均值', type: "bar",
        itemStyle: { color: (p) => fieldConfig.pollution[p.dataIndex].color },
        data: barData
      }]
    });
  });
};

// 初始化养分元素图表
const initNutrientChart = () => {
  nextTick(() => {
    if (chartInstanceNutrient) chartInstanceNutrient.dispose();
    if (!nutrientBoxChart.value) return;
    chartInstanceNutrient = echarts.init(nutrientBoxChart.value);
    
    const xAxisData = fieldConfig.nutrient.map(f => f.name);
    const boxData = buildBoxplotData(nutrientStats.value);
    
    chartInstanceNutrient.setOption({
      title: { text: "主要养分元素分布", left: 'center', textStyle: { fontSize: 14 } },
      tooltip: {
        trigger: "item",
        formatter: (params) => {
          const stat = nutrientStats.value[params.dataIndex];
          const fieldConfigItem = fieldConfig.nutrient.find(f => f.key === stat.key);
          return formatTooltip(stat, fieldConfigItem?.unit);
        }
      },
      grid: { top: 40, right: 15, bottom: 45, left: 40 },
      xAxis: { 
        type: "category", 
        data: xAxisData, 
        axisLabel: { fontSize: 11, rotate: 30 } 
      },
      yAxis: { 
        type: "value", 
        name: 'mg/kg', 
        nameTextStyle: { fontSize: 12 }, 
        axisLabel: { fontSize: 11 } 
      },
      series: [{
        name: '养分元素', 
        type: "boxplot",
        itemStyle: { color: '#ee6666', borderColor: '#fac858' },
        data: boxData
      }]
    });
  });
};

// 初始化其他理化性质图表
const initExtraChart = () => {
  const xAxisData = fieldConfig.extra.map(f => f.name);
  const boxData = buildBoxplotData(extraStats.value);
  
    nextTick(() => {
      if (chartInstanceExtra) chartInstanceExtra.dispose();
      chartInstanceExtra = echarts.init(extraBoxChart.value);
      chartInstanceExtra.setOption({
         title: { text: "其他理化性质分布", left: 'center', textStyle: { fontSize: 14 } },
         tooltip: {
           trigger: "item",
           formatter: (params) => formatTooltip(extraStats.value[params.dataIndex])
        },
         grid: { top: 40, right: 15, bottom: 40, left: 40 },
         xAxis: { type: "category", data: xAxisData, axisLabel: { fontSize: 11} },
        yAxis: { type: "value", name: '%', nameTextStyle: { fontSize: 12 }, axisLabel: { fontSize: 11 } },
        series: [{
          name: '理化性质', type: "boxplot",
           itemStyle: { color: '#73c0de', borderColor: '#5470c6' },
           data: boxData
        }]
        });
      });
};


// 格式化Tooltip
const formatTooltip = (stat , unit ='') => {
  if (!stat || !stat.min) {
    return `<div style="font-weight:bold;color:#f56c6c">${stat?.name || '未知'}</div><div>无有效数据</div>`;
  }
  return `<div style="font-weight:bold">${stat.name}</div>
    <div style="margin-top:8px">
      <div>最小值：<span style="color:#5a5;">${stat.min.toFixed(4)}</span></div>
      <div>下四分位：<span style="color:#d87a80;">${stat.q1.toFixed(4)}</span></div>
      <div>中位数：<span style="color:#f56c6c;font-weight:bold;">${stat.median.toFixed(4)}</span></div>
      <div>上四分位：<span style="color:#d87a80;">${stat.q3.toFixed(4)}</span></div>
      <div>最大值：<span style="color:#5a5;">${stat.max.toFixed(4)}</span></div>
    </div>`;
};

// 初始化图表主流程
const initCharts = async () => {
  try {
    isLoading.value = true;
    error.value = null;
    
    const statsData = await fetchData(); // 新接口返回的统计数据
    
    // -------- 1. 处理「作物态Cd指标」统计 --------
    pollutionStats.value = fieldConfig.pollution.map(field => {
      const fieldStats = statsData[field.key]; // 从接口数据中取对应字段的统计
      if (!fieldStats) {
        return { 
          key: field.key, 
          name: field.name, 
          min: null, 
          q1: null, 
          median: null, 
          q3: null, 
          max: null, 
          avg: null 
        };
      }
      // （可选）单位转换：若接口返回原始值，需按fieldConfig的convert规则转换
      let min = fieldStats.min;
      let q1 = fieldStats.q1;
      let median = fieldStats.median;
      let q3 = fieldStats.q3;
      let max = fieldStats.max;
      let avg = fieldStats.mean;
      if (field.convert && field.conversionFactor) {
        min *= field.conversionFactor;
        q1 *= field.conversionFactor;
        median *= field.conversionFactor;
        q3 *= field.conversionFactor;
        max *= field.conversionFactor;
        avg *= field.conversionFactor;
      }
      return {
        key: field.key,
        name: field.name,
        min,
        q1,
        median,
        q3,
        max,
        avg
      };
    });

    // -------- 2. 处理「主要养分元素」统计 --------
    nutrientStats.value = fieldConfig.nutrient.map(field => {
      const fieldStats = statsData[field.key];
      if (!fieldStats) {
        return { 
          key: field.key, 
          name: field.name, 
          min: null, 
          q1: null, 
          median: null, 
          q3: null, 
          max: null, 
          avg: null 
        };
      }
      // （可选）单位转换
      let min = fieldStats.min;
      let q1 = fieldStats.q1;
      let median = fieldStats.median;
      let q3 = fieldStats.q3;
      let max = fieldStats.max;
      let avg = fieldStats.mean;
      if (field.convert && field.conversionFactor) {
        min *= field.conversionFactor;
        q1 *= field.conversionFactor;
        median *= field.conversionFactor;
        q3 *= field.conversionFactor;
        max *= field.conversionFactor;
        avg *= field.conversionFactor;
      }
      return {
        key: field.key,
        name: field.name,
        min,
        q1,
        median,
        q3,
        max,
        avg
      };
    });

    // -------- 3. 处理「其他理化性质」统计 --------
    extraStats.value = fieldConfig.extra.map(field => {
      const fieldStats = statsData[field.key];
      if (!fieldStats) {
        return { 
          key: field.key, 
          name: field.name, 
          min: null, 
          q1: null, 
          median: null, 
          q3: null, 
          max: null, 
          avg: null 
        };
      }
      // （可选）单位转换
      let min = fieldStats.min;
      let q1 = fieldStats.q1;
      let median = fieldStats.median;
      let q3 = fieldStats.q3;
      let max = fieldStats.max;
      let avg = fieldStats.mean;
      if (field.convert && field.conversionFactor) {
        min *= field.conversionFactor;
        q1 *= field.conversionFactor;
        median *= field.conversionFactor;
        q3 *= field.conversionFactor;
        max *= field.conversionFactor;
        avg *= field.conversionFactor;
      }
      return {
        key: field.key,
        name: field.name,
        min,
        q1,
        median,
        q3,
        max,
        avg
      };
    });

    // -------- 更新「样本数量」等汇总统计 --------
    const firstFieldKey = fieldConfig.pollution[0]?.key;
    stats.value = {
      cd002Avg: pollutionStats.value.find(s => s.key === '002_0002IDW')?.avg || 0,
      cd02Avg: pollutionStats.value.find(s => s.key === '02_002IDW')?.avg || 0,
      cd2Avg: pollutionStats.value.find(s => s.key === '2_02IDW')?.avg || 0,
      samples: statsData[firstFieldKey]?.count || 0 // 从接口的count字段取样本数
    };

    // 初始化图表
    initPollutionChart();
    initNutrientChart();
    initExtraChart();
    
    isLoading.value = false;
  } catch (err) {
    isLoading.value = false;
    error.value = err;
    console.error('初始化失败:', err);
  }
};

// 组件挂载
onMounted(() => {
  initCharts();
  
  // 窗口resize处理
  const handleResize = () => {
    [chartInstanceCd, chartInstanceNutrient, chartInstanceExtra]
      .forEach(inst => inst && inst.resize());
  };
  window.addEventListener('resize', handleResize);
  
  // 组件卸载清理
  return () => {
    window.removeEventListener('resize', handleResize);
    [chartInstanceCd, chartInstanceNutrient, chartInstanceExtra]
      .forEach(inst => inst && inst.dispose());
  };
});
</script>

<style>
.crop-cd-dashboard {
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
  max-width: 1200px;
  margin: 0 auto;
  font-size: 14px;
}
.chart-container {
  background: white;
  border-radius: 6px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 12px;
  margin-bottom: 16px;
}
.section-title {
  color: #2c3e50;
  border-left: 3px solid #3498db;
  padding-left: 10px;
  margin-bottom: 12px;
}
.toggle-btn {
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  padding: 6px 12px;
  border-radius: 3px;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  transition: all 0.3s;
}
.toggle-btn:hover {
  background: #e9ecef;
}
.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
}
.spinner {
  width: 30px;
  height: 30px;
  border: 3px solid rgba(0, 0, 0, 0.1);
  border-radius: 50%;
  border-left-color: #3498db;
  animation: spin 1s linear infinite;
}
@keyframes spin { to { transform: rotate(360deg); } }
.stat-card {
  background: linear-gradient(135deg, #f5f7fa 0%, #e4edf5 100%);
  border-radius: 6px;
  padding: 8px 12px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.05);
}
.stat-value {
  font-size: 16px;
  font-weight: bold;
  color: #2c3e50;
}
.stat-label {
  font-size: 12px;
  color: #7f8c8d;
}
.legend-item {
  display: flex;
  align-items: center;
  margin-right: 12px;
  font-size: 13px;
  margin-bottom: 8px;
}
.legend-color {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  margin-right: 5px;
}
</style>