<template>
  <div class="dashboard">
    <div class="chart-container">

      <div class="chart-header">
        <div class="title-group">
             <div class="chart-title">大气污染企业各地区颗粒物排放量统计</div>
             <p class="sample-subtitle">样本来源：{{ totalPoints }}个数据</p>
        </div>
       
        <div class="method-selector">
          <button 
            class="method-btn" 
            :class="{active: currentMethod === 'max'}"
            @click="currentMethod = 'max'"
          >
            最大值
          </button>
          <button 
            class="method-btn" 
            :class="{active: currentMethod === 'avg'}"
            @click="currentMethod = 'avg'"
          >
            平均值
          </button>
        </div>
      </div>

      <div class="chart-wrapper">
        <div v-if="loading" class="loading">
          <div class="spinner"></div>
          <div class="loading-text">数据加载中...</div>
        </div>
        <div v-else-if="error" class="error">
          {{ error }}
        </div>
        <div v-else-if="!processedData.length" class="no-data">
          无有效数据可展示
        </div>
        <div v-else ref="mainChart" style="height:100%;width:100%"></div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { api8000 } from '@/utils/request'

export default {
  data() {
    return {
      loading: true,
      error: null,
      processedData: [],
      currentMethod: 'max',
      apiEndpoint: '/api/vector/export/all?table_name=atmo_company',
      totalPoints: 0,
      originalFeatures: [] // 添加原始数据备份用于调试
    };
  },
  mounted() {
    this.fetchData();
  },
  watch: {
    currentMethod() {
      if (this.processedData.length) {
        this.renderChart();
      }
    }
  },
  methods: {
    async fetchData() {
      try {
        this.loading = true;
        this.error = null;
        
        const response = await api8000.get(this.apiEndpoint);
        
        // 处理NaN问题
        let data = response.data;
        
        // 如果返回的是字符串，尝试解析为JSON
        if (typeof data === 'string') {
          try {
            // 替换NaN为null
            const cleanedData = data.replace(/\bNaN\b/g, 'null');
            data = JSON.parse(cleanedData);
          } catch (parseError) {
            this.loading = false;
            this.error = `数据解析失败: ${parseError.message}`;
            console.error("JSON解析错误:", parseError);
            return;
          }
        }
        
        // 检查处理后的数据结构
        console.log('处理后的API数据:', data);
        
        // 情况1：返回的是FeatureCollection对象
        if (data && data.type === "FeatureCollection" && Array.isArray(data.features)) {
          this.originalFeatures = data.features;
          this.processData(data.features);
        }
        // 情况2：返回的是features数组
        else if (Array.isArray(data)) {
          this.originalFeatures = data;
          this.processData(data);
        }
        // 其他情况
        else {
          this.loading = false;
          this.error = "接口返回数据格式不正确";
          console.error("无效的数据结构:", data);
        }
        
      } catch (err) {
        this.loading = false;
        this.error = `数据加载失败: ${err.message}`;
        console.error("API请求错误:", err);
      }
    },
    
    processData(features) {
      try {
        const countyMap = new Map();
        
        features.forEach(feature => {
          const props = feature.properties || {};
          let county = props.county || '';
          
          // 标准化地区名称 - 增强处理
          county = this.standardizeCountyName(county);
          
          if (county) {
            // 提取并校验排放数据
            const rawEmission = props.particulate_emission;
            let emissionValue = parseFloat(rawEmission);
            
            // 处理可能的字符串值（如"15.836"）
            if (isNaN(emissionValue) && typeof rawEmission === 'string') {
              emissionValue = parseFloat(rawEmission.replace(/[^0-9.]/g, ''));
            }
            
            // 过滤无效值
            if (isNaN(emissionValue) || emissionValue === null) {
              console.warn('无效的排放量值:', rawEmission, '县区:', county);
              return;
            }
            
            // 统计有效数据
            if (!countyMap.has(county)) {
              countyMap.set(county, {
                county,
                values: [emissionValue],
                maxEmission: emissionValue,
                sumEmission: emissionValue,
                pointCount: 1
              });
            } else {
              const countyData = countyMap.get(county);
              countyData.values.push(emissionValue);
              countyData.pointCount++;
              countyData.sumEmission += emissionValue;
              
              if (emissionValue > countyData.maxEmission) {
                countyData.maxEmission = emissionValue;
              }
            }
          } else {
            console.warn('缺少县区名称:', props);
          }
        });
        
        // 计算平均值
        countyMap.forEach(data => {
          data.avgEmission = data.sumEmission / data.values.length;
        });
        
        // 转换为数组并排序
        this.processedData = Array.from(countyMap.values())
          .sort((a, b) => b.maxEmission - a.maxEmission);
        
        // 计算有效样本总数
        this.totalPoints = this.processedData.reduce(
          (sum, item) => sum + item.pointCount, 0
        );

        console.log('处理后数据:', this.processedData);
        
        this.loading = false;
        
        if (this.processedData.length === 0) {
          this.error = "无有效数据可展示";
          console.warn('无有效数据原因:', {
            originalCount: features.length,
            filteredCount: this.processedData.length,
            sampleData: features.slice(0, 3)
          });
        } else {
          this.$nextTick(this.renderChart);
        }
        
      } catch (err) {
        this.loading = false;
        this.error = `数据处理错误: ${err.message}`;
        console.error("数据处理异常:", err);
      }
    },
    
    // 标准化地区名称
    standardizeCountyName(county) {
      if (!county) return '';
      
      // 特殊处理曲江地区
      if (county === '曲江' || county === '曲江新' || county === '曲江开发区') {
        return '曲江区';
      }
      
      return county;
    },
    
    renderChart() {
      const chart = echarts.init(this.$refs.mainChart);
      
      // 根据选择的方法确定数据
      const method = this.currentMethod;
      const valueField = method === 'max' ? 'maxEmission' : 'avgEmission';
      const methodLabel = method === 'max' ? '最高值' : '平均值';
      
      const data = this.processedData.map(item => ({
        name: item.county,
        value: item[valueField],
        pointCount: item.pointCount,
        maxEmission: item.maxEmission,
        avgEmission: item.avgEmission
      }));
      
      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: params => {
            const d = params[0].data;
            return `
              <div style="margin-bottom:5px;font-weight:bold">${d.name}</div>
              <div>最高排放量: ${d.maxEmission} t/a</div>
              <div>平均排放量: ${d.avgEmission} t/a</div>
              <div style="margin-top:5px">监测点数量: ${d.pointCount}个</div>
            `;
          }
        },
        grid: {
          left: 0,
          right: "15%",
          top: 20,
          bottom: "3%",
          containLabel: true
        },
        xAxis: {
          type: 'value',
          name: `颗粒物排放量`,
          nameLocation: 'end',
          nameTextStyle:{
            padding:-30,
            fontSize:12
          },
          axisLabel: {
            formatter: value => value + ' t/a',
            fontSize:11,//字体大小
            rotate: 30
          },
          splitLine: {
            lineStyle: {
              type: 'dashed'
            }
          }
        },
        yAxis: {
          type: 'category',
          data: data.map(d => d.name),
          axisLabel: {
            formatter: value => value,
            fontSize:11,//字体大小
          }
        },
        series: [{
          name: '颗粒物排放量',
          type: 'bar',
          data: data,
          label: {
            show: true,
            position: 'right',
            formatter: params => params.value + ' t/a',
            fontSize:10,//字体大小
            rotate: 15
          },
          barWidth: '60%',
          itemStyle: {
            color: '#3498db'
          }
        }]
      };
      
      chart.setOption(option);
      
      // 响应窗口大小变化
      window.addEventListener('resize', chart.resize);
    }
  }
}
</script>

<style>
.dashboard {
  height: 100%;
  width: 100%;
  max-width: 1000px;
  margin: 0 auto;
}

h1 {
  font-size: 24px;
  color: #2980b9;
  margin-bottom: 8px;
}

.subtitle {
  color: #7f8c8d;
  font-size: 14px;
}

.chart-container {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
  padding: 15px;
  height: 100%;
  display: flex;
  flex-direction:column;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 10px;
}

.chart-title {
  font-size: 16px;
  color: #2980b9;
  font-weight: 600;
}

.title-group {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
}

.method-selector {
  background: #f1f8ff;
  border-radius: 8px;
  padding: 4px 8px;
  display: flex;
  gap: 6px;
}

.method-btn {
  padding: 3px 8px;
  border-radius: 6px;
  background: transparent;
  border: none;
  cursor: pointer;
  font-size: 12px;
  transition: all 0.3s;
}

.method-btn.active {
  background: #3498db;
  color: white;
}

.chart-wrapper {
  flex: 1;
  min-height: 0;
  height: 400px;
}

.loading, .no-data {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  width: 100%;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(52, 152, 219, 0.2);
  border-radius: 50%;
  border-top-color: #3498db;
  animation: spin 1s linear infinite;
  margin-bottom: 10px;
}

.loading-text {
  font-size: 14px;
  color: #3498db;
}

.no-data {
  height: 300px;
  font-size: 18px;
  font-weight: bold;
  color: #dc3232;
  background-color: #fce4e4;
  border-radius: 8px;
  text-align: center;
  padding: 10px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.sample-subtitle {
    color: #7f8c8d;
    font-size: 12px;
    margin-top: 2px;
}
</style>
