<template>
  <div class="region-average-chart">
    <!-- 重金属选择器 -->
    <div class="metal-selector" v-if="!loading && !error && metals.length > 0">
      <label for="metal-select">选择重金属：</label>
      <select id="metal-select" v-model="selectedMetal">
        <option v-for="metal in metals" :key="metal" :value="metal">{{ metal }}</option>
      </select>
    </div>
    
    <!-- 图表容器 -->
    <div ref="chartRef" class="chart-box"></div>
    
    <!-- 状态信息 -->
    <div v-if="loading" class="status">数据加载中...</div>
    <div v-else-if="error" class="status error">{{ error }}</div>
    <div v-else-if="metals.length === 0" class="status">没有有效的重金属数据</div>
  </div>
</template>

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

// ========== 接口配置 ==========
const SAMPLING_API = 'https://www.soilgd.com:3000/table/Water_sampling_data';
const ASSAY_API = 'https://www.soilgd.com:3000/table/Water_assay_data';

// ========== 配置项 ==========
const EXCLUDE_FIELDS = [
  'water_assay_ID', 'sample_code', 'assayer_ID', 'assay_time', 
  'assay_instrument_model', 'water_sample_ID', 'pH'
];
const COLORS = [
  '#FF6B6B', '#4ECDC4', '#FFD166', '#6A4C93', '#1982C4',
  '#FF9F1C', '#2EC4B6', '#E71D36', '#3A86FF', '#FF006E'
];

// 韶关市下属行政区划
const SG_REGIONS = [
  '浈江区', '武江区', '曲江区', '乐昌市', 
  '南雄市', '始兴县', '仁化县', '翁源县', 
  '新丰县', '乳源瑶族自治县'
];

// ========== 响应式数据 ==========
const chartRef = ref(null);
const loading = ref(true);
const error = ref('');
// 修复 selectedMetal 未定义问题：提前声明变量
const selectedMetal = ref(''); 
const metals = ref([]);
const chartData = ref(null);
let myChart = null;

// ========== 地区提取函数 ==========
const extractRegion = (location) => {
  if (!location || typeof location !== 'string') return null;

  // 1. 精确匹配官方区县名称
  const officialMatch = SG_REGIONS.find(region => 
    location.includes(region)
  );
  if (officialMatch) return officialMatch;

  // 2. 处理嵌套格式（如"韶关市-浈江区"）
  const nestedMatch = location.match(/(韶关市)([^市]+?[区市县])/);
  if (nestedMatch && nestedMatch[2]) {
    const region = nestedMatch[2].replace("韶关市", "").trim();
    // 验证是否为合法区县
    const validRegion = SG_REGIONS.find(r => r.includes(region));
    if (validRegion) return validRegion;
  }

  // 3. 特殊格式处理（如"韶关市浈江区"）
  const shortMatch = location.match(/韶关市([区市县][^市]{2,5})/);
  if (shortMatch && shortMatch[1]) return shortMatch[1];

  // 4. 修正常见拼写错误
  if (location.includes('乐昌')) return '乐昌市';
  if (location.includes('乳源')) return '乳源瑶族自治县';

  console.warn(`⚠️ 未识别地区: ${location}`);
  return '未知区县';
};

// ========== 数据处理流程 ==========
const processMergedData = (samplingData, assayData) => {
  // 1. 构建采样点ID到区县的映射
  const regionMap = new Map();
  const uniqueSampleIds = new Set();
  
  samplingData.forEach(item => {
    const region = extractRegion(item.sampling_location || '');
    if (region && region !== '未知区县') {
      regionMap.set(item.water_sample_ID, region);
    }
  });

  // 2. 关联重金属数据与区县
  const mergedData = assayData.map(item => ({
    ...item,
    region: regionMap.get(item.water_sample_ID) || '未知区县'
  }));

  // 3. 识别重金属字段
  const detectedMetals = Object.keys(mergedData[0] || {})
    .filter(key => !EXCLUDE_FIELDS.includes(key) && !isNaN(parseFloat(mergedData[0][key])));
  
  metals.value = detectedMetals;
  if (detectedMetals.length > 0 && !selectedMetal.value) {
    selectedMetal.value = detectedMetals[0];
  }

  // 4. 按区县分组统计
  const regionGroups = {};
  
  mergedData.forEach(item => {
    const region = item.region;
    const sampleId = item.water_sample_ID;
    
    if (sampleId) uniqueSampleIds.add(sampleId);
    
    // 初始化区县数据
    if (!regionGroups[region]) {
      regionGroups[region] = {};
      detectedMetals.forEach(metal => {
        regionGroups[region][metal] = { sum: 0, count: 0 };
      });
    }

    // 统计重金属数据
    detectedMetals.forEach(metal => {
      const val = parseFloat(item[metal]);
      if (!isNaN(val)) {
        regionGroups[region][metal].sum += val;
        regionGroups[region][metal].count++;
      }
    });
  });

  // 5. 构建扇形图数据
  const pieSeriesData = detectedMetals.map(metal => {
    // 该重金属在各区县的平均浓度总和
    let totalAverage = 0;
    
    // 收集各区县该重金属的平均值
    const regionAverages = SG_REGIONS.map(region => {
      if (!regionGroups[region]) return null;
      
      const group = regionGroups[region][metal];
      const avg = group.count ? group.sum / group.count : 0;
      totalAverage += avg;
      
      return { 
        name: region,
        value: avg
      };
    }).filter(Boolean);

    // 计算占比
    const seriesData = regionAverages.map(item => ({
      name: item.name,
      value: totalAverage > 0 ? (item.value / totalAverage) * 100 : 0,
      rawValue: item.value // 保留原始浓度值用于显示
    }));

    return {
      metal,
      seriesData
    };
  });

  return {
    regions: SG_REGIONS,
    pieSeriesData,
    totalSamples: uniqueSampleIds.size
  };
};

// ========== 初始化/更新图表 ==========
const initChart = () => {
  if (!chartRef.value || !selectedMetal.value || !chartData.value) return;
  
  if (myChart) myChart.dispose();
  myChart = echarts.init(chartRef.value);

  // 获取当前重金属的数据
  const currentMetalData = chartData.value.pieSeriesData.find(
    item => item.metal === selectedMetal.value
  );

  if (!currentMetalData) return;

  const option = {
    title: { 
      text: `韶关市${selectedMetal.value}平均浓度区域占比`, 
      left: 'center',
      subtext: `数据来源: ${chartData.value.totalSamples}个有效检测样本`
    },
    tooltip: {
      trigger: 'item',
      formatter: function(params) {
        return `${params.name}<br/>
                ${selectedMetal.value}: ${params.data.rawValue.toFixed(4)} mg/L<br/>
                占比: ${params.percent}%`;
      }
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      data: currentMetalData.seriesData.map(item => item.name)
    },
    series: [
      {
        name: selectedMetal.value,
        type: 'pie',
        radius: ['35%', '65%'],
        center: ['45%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '16',
            fontWeight: 'bold',
            formatter: '{b}\n{c}%'
          }
        },
        labelLine: {
          show: false
        },
        data: currentMetalData.seriesData
      }
    ],
    color: COLORS
  };

  myChart.setOption(option);
};

// ========== 生命周期钩子 ==========
onMounted(async () => {
  try {
    // 修复请求超时问题：将超时时间延长至10秒
    const [samplingRes, assayRes] = await Promise.all([
      axios.get(SAMPLING_API, { timeout: 10000 }), // 10秒超时
      axios.get(ASSAY_API, { timeout: 10000 })
    ]);
    
    chartData.value = processMergedData(samplingRes.data, assayRes.data);
    initChart();
  } catch (err) {
    // 处理超时错误
    if (err.code === 'ECONNABORTED') {
      error.value = '请求超时：服务器响应时间超过10秒';
    } else {
      error.value = '数据加载失败: ' + (err.message || '未知错误');
    }
    console.error('接口错误:', err);
  } finally {
    loading.value = false;
  }
});

// 监听重金属选择变化
watch(selectedMetal, (newVal) => {
  if (newVal && myChart && chartData.value) {
    initChart();
  }
});

// 响应式布局
const resizeHandler = () => myChart && myChart.resize();
onMounted(() => window.addEventListener('resize', resizeHandler));
onUnmounted(() => window.removeEventListener('resize', resizeHandler));
</script>

<style scoped>
.region-average-chart {
  width: 100%;
  max-width: 1200px;
  margin: 20px auto;
  position: relative;
}
.chart-box {
  width: 100%;
  height: 600px;
  min-height: 400px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.1);
}
.status {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  padding: 15px;
  background: rgba(255,255,255,0.8);
  border-radius: 4px;
  text-align: center;
}
.error { 
  color: #ff4d4f;
  font-weight: bold;
}
.metal-selector {
  margin-bottom: 15px;
  text-align: center;
  padding: 10px;
}
.metal-selector label {
  margin-right: 10px;
  font-weight: bold;
}
.metal-selector select {
  padding: 8px 15px;
  border-radius: 4px;
  border: 1px solid #ddd;
  background-color: #f8f8f8;
  font-size: 14px;
  min-width: 150px;
  cursor: pointer;
  transition: border 0.3s;
}
.metal-selector select:hover {
  border-color: #1890ff;
}
</style>