<template>
  <div class="flux-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="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-6 chart-container">
      <h3 class="section-title text-base font-semibold">初始Cd（Initial_Cd）分布箱线图</h3>
      <div ref="initialCdChart" style="width: 100%; height: 400px;"></div>
      <div v-if="isLoading" class="absolute inset-0 bg-white bg-opacity-80 flex items-center justify-center">
        <div class="spinner"></div>
      </div>
      <div v-if="error && !chartInstanceInitial" class="bg-yellow-50 border border-yellow-200 p-4 rounded mt-4">
        <p class="text-yellow-700">图表初始化失败: {{ error.message }}</p>
        <button class="mt-2 px-3 py-1 bg-yellow-500 text-white rounded" @click="initInitialCdChart">
          重新尝试初始化
        </button>
      </div>
    </section>

    <!-- 2. 其他指标 合并箱线图 -->
    <section class="mb-6 chart-container">
      <div class="flex flex-wrap justify-between items-center mb-4">
        <h3 class="section-title text-base font-semibold">其他通量Cd指标分布箱线图</h3>
      </div>
      <div ref="otherIndicatorsChart" style="width: 100%; height: 400px;"></div>
      <!-- 容器内的加载遮罩 -->
      <div v-if="isLoading" class="absolute inset-0 bg-white bg-opacity-80 flex items-center justify-center">
        <div class="spinner"></div>
      </div>
      <!-- 错误提示（保留重试按钮） -->
      <div v-if="error && !chartInstanceOther" class="bg-yellow-50 border border-yellow-200 p-4 rounded mt-4">
        <p class="text-yellow-700">图表初始化失败: {{ error.message }}</p>
        <button class="mt-2 px-3 py-1 bg-yellow-500 text-white rounded" @click="initOtherIndicatorsChart">
          重新尝试初始化
        </button>
      </div>
    </section>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue';
import * as echarts from 'echarts';
import { api8000 } from '@/utils/request'; // 导入 api8000 实例

// 图表容器 & 实例
const initialCdChart = ref(null);   // 初始Cd图表
const otherIndicatorsChart = ref(null); // 其他指标图表
const chartInstanceInitial = ref(null);   // 初始Cd实例
const chartInstanceOther = ref(null);     // 其他指标实例
const chartInstancePopup = ref(null);     // 弹窗实例

// 响应式状态
const isLoading = ref(true);
const error = ref(null);
const stats = ref({ samples: 0 });

// 统计数据（拆分两组）
const initialCdStats = ref([]);     // 初始Cd统计
const otherIndicatorsStats = ref([]); // 其他指标统计

// 字段配置（拆分初始Cd和其他指标）
const fieldConfig = {
  initialCd: [
    { key: 'Initial_Cd', name: '土壤初始Cd总量', color: '#5470c6' }
  ],
  otherIndicators: [
    { key: 'DQCJ_Cd', name: '大气沉降输入Cd', color: '#91cc75' },
    { key: 'GGS_Cd', name: '灌溉水输入Cd', color: '#fac858' },
    { key: 'NCP_Cd', name: '农业投入输入Cd', color: '#ee6666' },
    { key: 'DX_Cd', name: '地下渗漏Cd', color: '#73c0de' },
    { key: 'DB_Cd', name: '地表径流Cd', color: '#38b2ac' },
    { key: 'ZL_Cd', name: '籽粒移除Cd', color: '#4169e1' },
  ]
};

// 数据请求
const fetchData = async () => {
  try {
    const apiUrl = 'http://localhost:8000/api/vector/stats/FluxCd_input_data';
    const response = await axios.get(apiUrl);
    const rawData = response.data.features 
      ? response.data.features.map(f => f.properties) 
      : response.data;
    return rawData;
  } catch (err) {
    throw new Error('数据加载失败: ' + err.message);
  }
};

// 分位数计算（QUARTILE.INC）
const calculatePercentile = (sortedArray, percentile) => {
  const n = sortedArray.length;
  if (n === 0) return null;
  if (percentile <= 0) return sortedArray[0];
  if (percentile >= 100) return sortedArray[n - 1];
  
  const index = (n - 1) * (percentile / 100);
  const lowerIndex = Math.floor(index);
  const upperIndex = lowerIndex + 1;
  const fraction = index - lowerIndex;
  
  if (upperIndex >= n) return sortedArray[lowerIndex];
  return sortedArray[lowerIndex] + fraction * (sortedArray[upperIndex] - sortedArray[lowerIndex]);
};

// 计算单个字段的统计量
const calculateFieldStats = (statsData, fieldKey, fieldName) => {
  // 从接口数据中获取当前字段的统计结果
  const fieldStats = statsData[fieldKey]; 
  if (!fieldStats) {
    return { key: fieldKey, name: fieldName, min: null, q1: null, median: null, q3: null, max: null };
  }

  // 提取预统计值
  let min = fieldStats.min;
  let q1 = fieldStats.q1;
  let median = fieldStats.median;
  let q3 = fieldStats.q3;
  let max = fieldStats.max;

  // 强制校正统计量顺序（确保 min ≤ q1 ≤ median ≤ q3 ≤ max）
  const sortedStats = [min, q1, median, q3, max].sort((a, b) => a - b);
  return {
    key: fieldKey,
    name: fieldName,
    min: sortedStats[0],
    q1: sortedStats[1],
    median: sortedStats[2],
    q3: sortedStats[3],
    max: sortedStats[4]
  };
};

// 计算所有统计数据（拆分两组）
const calculateAllStats = (statsData) => {
  // 1. 初始Cd统计（与配置顺序一致）
  initialCdStats.value = fieldConfig.initialCd.map(indicator => 
    calculateFieldStats(statsData, indicator.key, indicator.name)
  );
  
  // 2. 其他指标统计（与配置顺序一致）
  otherIndicatorsStats.value = fieldConfig.otherIndicators.map(indicator => 
    calculateFieldStats(statsData, indicator.key, indicator.name)
  );
  
  // 3. 更新样本数（从预统计数据中取第一个字段的count）
  const firstFieldKey = fieldConfig.initialCd[0]?.key || fieldConfig.otherIndicators[0]?.key;
  stats.value.samples = statsData[firstFieldKey]?.count || 0;
};

// 构建箱线图数据（通用函数）
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 initInitialCdChart = () => {
  // 容器存在性检查
  if (!initialCdChart.value) {
    console.error('initialCdChart容器未找到');
    error.value = new Error('初始Cd图表容器未找到，请刷新页面重试');
    return;
  }
  
  // 容器尺寸检查
  const { offsetWidth, offsetHeight } = initialCdChart.value;
  if (offsetWidth === 0 || offsetHeight === 0) {
    console.error('initialCdChart容器尺寸异常', { offsetWidth, offsetHeight });
    error.value = new Error('初始Cd图表容器尺寸异常，请检查页面样式');
    return;
  }

  // 销毁旧实例
  if (chartInstanceInitial.value) {
    chartInstanceInitial.value.dispose();
  }
  
  // 初始化图表
  try {
    chartInstanceInitial.value = echarts.init(initialCdChart.value);
    const xAxisData = fieldConfig.initialCd.map(ind => ind.name);
    const boxData = buildBoxplotData(initialCdStats.value);
    
    chartInstanceInitial.value.setOption({
      title: { text: '初始Cd分布箱线图', left: 'center', textStyle: { fontSize: 14 } },
      tooltip: {
        trigger: "item",
        formatter: (params) => formatTooltip(initialCdStats.value[params.dataIndex])
      },
      grid: { top: 60, right: 30, bottom: 25, left: 60 },
      xAxis: { 
        type: "category", 
        data: xAxisData,
        axisLabel: { fontSize: 12 }
      },
      yAxis: { 
        type: "value", 
        name: 'g/ha', 
        nameTextStyle: { fontSize: 12 }, 
        axisLabel: { fontSize: 11 },
        scale: true
      },
      series: [{
        name: '初始Cd', 
        type: "boxplot",
        itemStyle: { 
          color: (p) => fieldConfig.initialCd[p.dataIndex].color,
          borderWidth: 2 
        },
        data: boxData
      }]
    });
  } catch (err) {
    console.error('初始Cd图表初始化失败', err);
    error.value = new Error(`初始Cd图表初始化失败: ${err.message}`);
  }
};

// 初始化【其他指标】合并图表
const initOtherIndicatorsChart = () => {
  // 容器存在性检查
  if (!otherIndicatorsChart.value) {
    console.error('otherIndicatorsChart容器未找到');
    error.value = new Error('其他指标图表容器未找到，请刷新页面重试');
    return;
  }
  
  // 容器尺寸检查
  const { offsetWidth, offsetHeight } = otherIndicatorsChart.value;
  if (offsetWidth === 0 || offsetHeight === 0) {
    console.error('otherIndicatorsChart容器尺寸异常', { offsetWidth, offsetHeight });
    error.value = new Error('其他指标图表容器尺寸异常，请检查页面样式');
    return;
  }

  // 销毁旧实例
  if (chartInstanceOther.value) {
    chartInstanceOther.value.dispose();
  }
  
  // 初始化图表
  try {
    chartInstanceOther.value = echarts.init(otherIndicatorsChart.value);
    const xAxisData = fieldConfig.otherIndicators.map(ind => ind.name);
    const boxData = buildBoxplotData(otherIndicatorsStats.value);
    
    chartInstanceOther.value.setOption({
      title: { text: '其他通量Cd指标分布对比', left: 'center', textStyle: { fontSize: 14 } },
      tooltip: {
        trigger: "item",
        formatter: (params) => formatTooltip(otherIndicatorsStats.value[params.dataIndex])
      },
      grid: { top: 60, right: 30, bottom: 70, left: 60 },
      xAxis: { 
        type: "category", 
        data: xAxisData,
        axisLabel: { 
          fontSize: 11, 
          rotate: 45,
          interval: 0, // 强制显示所有标签
          formatter: (value) => value.length > 8 ? value.substring(0, 8) + '...' : value
        }
      },
      yAxis: { 
        type: "value", 
        name: 'g/ha/a', 
        nameTextStyle: { fontSize: 12 }, 
        axisLabel: { fontSize: 11 }
      },
      series: [{
        name: '其他指标', 
        type: "boxplot",
        itemStyle: { 
          color: (p) => fieldConfig.otherIndicators[p.dataIndex].color,
          borderWidth: 2 
        },
        data: boxData
      }]
    });
  } catch (err) {
    console.error('其他指标图表初始化失败', err);
    error.value = new Error(`其他指标图表初始化失败: ${err.message}`);
  }
};

// Tooltip格式化（通用逻辑）
const formatTooltip = (stat) => {
  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;
    chartInstanceInitial.value = null;
    chartInstanceOther.value = null;
    
    // 1. 获取数据
    const data = await fetchData();
    if (!data || data.length === 0) {
      throw new Error('未获取到有效数据');
    }
    
    // 2. 计算统计数据
    calculateAllStats(data);
    
    // 3. 等待DOM更新
    await nextTick(); 
    
    // 4. 轮询检查容器尺寸（最多等待3秒）
    const checkContainers = () => {
      return new Promise((resolve, reject) => {
        let checkCount = 0;
        const interval = setInterval(() => {
          // 检查两个容器的宽度是否有效
          const initialWidth = initialCdChart.value?.offsetWidth || 0;
          const otherWidth = otherIndicatorsChart.value?.offsetWidth || 0;
          
          if (initialWidth > 0 && otherWidth > 0) {
            clearInterval(interval);
            resolve();
          } else if (checkCount >= 30) { // 30 * 100ms = 3秒
            clearInterval(interval);
            reject(new Error('图表容器尺寸异常，准备超时，请检查样式'));
          }
          checkCount++;
        }, 100);
      });
    };
    
    await checkContainers(); 
    
    // 5. 初始化图表
    initInitialCdChart();
    initOtherIndicatorsChart();
    
    isLoading.value = false;
  } catch (err) {
    isLoading.value = false;
    error.value = err;
    console.error('初始化失败:', err);
  }
};

// 组件挂载 & 销毁
onMounted(() => {
  initCharts();
  
  // 窗口resize响应
  const handleResize = () => {
    if (chartInstanceInitial.value) chartInstanceInitial.value.resize();
    if (chartInstanceOther.value) chartInstanceOther.value.resize();
    if (chartInstancePopup.value) chartInstancePopup.value.resize();
  };
  window.addEventListener('resize', handleResize);
  
  return () => {
    window.removeEventListener('resize', handleResize);
    if (chartInstanceInitial.value) chartInstanceInitial.value.dispose();
    if (chartInstanceOther.value) chartInstanceOther.value.dispose();
    if (chartInstancePopup.value) chartInstancePopup.value.dispose();
  };
});
</script>

<style scoped>
.flux-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: 16px;
  margin-bottom: 16px;
  min-height: 400px;
  position: relative;
}
[ref="initialCdChart"], 
[ref="otherIndicatorsChart"] {
  min-height: 400px;
  background-color: #f9f9f9;
  border: 1px dashed #eee;
}

.section-title {
  color: #2c3e50;
  border-left: 3px solid #3498db;
  padding-left: 10px;
  margin-bottom: 12px;
}
.legend-item {
  display: flex;
  align-items: center;
  margin-right: 12px;
  margin-bottom: 6px;
  font-size: 12px;
}
.legend-color {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  margin-right: 5px;
}
.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;
}
</style>