<template>
    <!--柱状图容器-->
  <div class="chart-page">
    <div ref="chartContainer" class="chart-container"></div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import { wgs84togcj02 } from 'coordtransform';
import * as echarts from 'echarts'

// 状态管理
const error = ref(null)
const chartContainer=ref(null)
let chart = null
const state = reactive({
  excelData: [], // 存储解析后的断面数据
  riverAvgData:[],//存储按河流分组后的平均数据
})

// 初始化断面数据（直接嵌入你的Excel数据）
const initData = () => {
  const rawData = [
    { "断面编号": 0, "所属河流": "浈江", "断面位置": "小古录", "所属区县": "始兴县", "经度": 114.208543, "纬度": 25.059851, "Cd(ug/L)": 0.11 },
    { "断面编号": 1, "所属河流": "浈江", "断面位置": "长坝", "所属区县": "仁化县", "经度": 113.692874, "纬度": 24.874845, "Cd(ug/L)": 1.116 },
    { "断面编号": 2, "所属河流": "浈江", "断面位置": "东河桥", "所属区县": "浈江区", "经度": 113.601631, "纬度": 24.80784, "Cd(ug/L)": 3.46 },
    { "断面编号": 3, "所属河流": "武江", "断面位置": "坪石", "所属区县": "乐昌市", "经度": 113.066281, "纬度": 25.274421, "Cd(ug/L)": 0.98 },
    { "断面编号": 4, "所属河流": "武江", "断面位置": "乐昌", "所属区县": "乐昌市", "经度": 113.338782, "纬度": 25.129212, "Cd(ug/L)": 0.11 },
    { "断面编号": 5, "所属河流": "武江", "断面位置": "武江桥", "所属区县": "乐昌市", "经度": 113.349815, "纬度": 25.120278, "Cd(ug/L)": 0.15 },
    { "断面编号": 6, "所属河流": "北江", "断面位置": "九公里", "所属区县": "浈江区", "经度": 113.580758, "纬度": 24.761299, "Cd(ug/L)": 7.83 },
    { "断面编号": 7, "所属河流": "北江", "断面位置": "白土", "所属区县": "曲江区", "经度": 113.531284, "纬度": 24.679958, "Cd(ug/L)": 5.94 },
    { "断面编号": 8, "所属河流": "浈江", "断面位置": "昆仑水站", "所属区县": "南雄市", "经度": 114.3629285, "纬度": 25.10053746, "Cd(ug/L)": 0.517 },
    { "断面编号": 9, "所属河流": "北江", "断面位置": "白沙", "所属区县": "曲江", "经度": 113.5707136, "纬度": 24.58139261, "Cd(ug/L)": 1.54 },
    { "断面编号": 10, "所属河流": "浈江", "断面位置": "周田水站", "所属区县": "仁化县", "经度": 113.8293461, "纬度": 24.97851516, "Cd(ug/L)": 0.182 },
    { "断面编号": 11, "所属河流": "武江", "断面位置": "坪石水站", "所属区县": "乐昌市", "经度": 113.0467854, "纬度": 25.28883459, "Cd(ug/L)": 1.071 }
  ];

  // 处理坐标（WGS84转GCJ02，腾讯地图用GCJ02）
  state.excelData = rawData.map(item => {
    const lng = Number(item.经度);
    const lat = Number(item.纬度);
    if (isNaN(lat) || isNaN(lng)) {
      console.error('无效经纬度:', item);
      return null;
    }
    const [gcjLng, gcjLat] = wgs84togcj02(lng, lat); // 坐标转换
    return {
      id: item.断面编号,
      river: item.所属河流,
      location: item.断面位置,
      district: item.所属区县,
      cdValue: item["Cd(ug/L)"],
      latitude: gcjLat,
      longitude: gcjLng,
    };
  }).filter(item => item !== null);
  calculateRiverAvg();
}

const calculateRiverAvg = () => {
  // 按河流分组
  const riverGroups = {};
  
  // 分组并累加浓度值
  state.excelData.forEach(item => {
    if (!riverGroups[item.river]) {
      riverGroups[item.river] = {
        total: 0,
        count: 0,
        avg: 0
      };
    }
    riverGroups[item.river].total += item.cdValue;
    riverGroups[item.river].count += 1;
  });
  
  // 计算每组平均值
  const riverAvg = [];
  let totalAll = 0;
  let countAll = 0;
  
  for (const river in riverGroups) {
    const avg = riverGroups[river].total / riverGroups[river].count;
    riverAvg.push({
      river,
      avg: parseFloat(avg.toFixed(3)) // 保留3位小数
    });
    totalAll += riverGroups[river].total;
    countAll += riverGroups[river].count;
  }
  
  // 计算总平均值并添加到数组
  const totalAvg = {
    river: '总河流平均',
    avg: parseFloat((totalAll / countAll).toFixed(3))
  };
  
  riverAvg.push(totalAvg);
  state.riverAvgData = riverAvg;
  
  // 更新图表
  updateChart();
}

// 新增：初始化图表
const initChart = () => {
  if (chartContainer.value) {
    chart = echarts.init(chartContainer.value);
    updateChart();
  }
}

// 新增：更新图表数据
const updateChart = () => {
  if (!chart || state.riverAvgData.length === 0) return;
  
  // 准备图表数据
  const rivers = state.riverAvgData.map(item => item.river);
  const avgs = state.riverAvgData.map(item => item.avg);
  
  // 配置图表选项
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: '{a} <br/>{b}: {c} ug/L'
    },
    grid: {
      //left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: rivers,
      axisLabel: {
        interval: 0,
        fontSize:18
      }
    },
    yAxis: {
      type: 'value',
      name: 'Cd浓度 (ug/L)',
      min: 0,
      nameTextStyle:{
        fontSize:18,
      },
      axisLabel: {
        formatter: '{value}',
        fontSize:18
      }
    },
    series: [
      {
        name: '平均镉浓度',
        type: 'bar',
        data: avgs,
        itemStyle: {
          // 为总平均值设置不同颜色
          color: function(params) {
            return params.dataIndex === rivers.length - 1 ? '#FF4500' : '#1E88E5';
          }
        },
        label: {
          show: true,
          position: 'top',
          formatter: '{c}',
          fontSize:18
        },
        emphasis: {
          focus: 'series'
        }
      }
    ]
  };
  
  // 设置图表选项
  chart.setOption(option);
}

// 生命周期
onMounted(async () => {
  try {
    initData();
    initChart();
    //监听窗口大小变化，调整图表
    window.addEventListener('resize',()=>{
      if(chart){
        chart.resize();
      }
    })
  } catch (err) {
    error.value = err.message;
  }
})

onBeforeUnmount(() => {
  if(chart){
    chart.dispose();
  }
})
</script>

<style>

/* 图表容器样式 */
.chart-container {
  width: 100%; /* 占满图表容器宽度 */
  height: 400px;
  margin: 0 auto;
  border-radius: 12px;
}
</style>