<template>
  <div class="chart-container">
    <div ref="chart" style="width: 520px; height: 300px;"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { currentGET } from "api/modules";
export default {
  name: 'BarChart',
  // 修改数据结构和series配置
  data() {
    return {
      currentTab: 'month',
      currentYear: new Date().getFullYear(),
      chartData: {
        month: {
          xData: [],  // 改为空数组，将从接口获取数据
          seriesData: new Array(12).fill(0)
        }
      }
    };
  },
  mounted() {
    this.getData();
  },
  methods: {
    getData() {
        currentGET("big2").then((res) => {
          console.log('big2',res);
          if (res.code === 0) {
            // 重置数组
            this.chartData.month.seriesData = new Array(12).fill(0);
            this.chartData.month.xData = []; // 重置x轴数据
            //生成本年所有月份,填充数据的时候对已存在的月份再进行删除操作
            this.generateMonths();

            console.log('aa月度用氢量数据：', this.chartData.month.seriesData);
            // 按月份排序数据
            const sortedData = res.data.sort((a, b) => {
              const monthA = parseInt(a.months.substring(5, 7));
              const monthB = parseInt(b.months.substring(5, 7));
              return monthA - monthB;
            });
            console.log('sortedData: '+ sortedData);
            // 填充数据
            sortedData.forEach((item) => {
              let monthStr = item.months;  // 获取完整的月份字符串
              console.log('月份：'+monthStr)
              this.chartData.month.xData.pop(monthStr)
              this.chartData.month.xData.push(monthStr);  // 直接使用接口返回的月份字符串
              let month = parseInt(monthStr.substring(5, 7));
              if (month > 0 && month <= 12) {
                this.chartData.month.seriesData[month-1] = item.monthHydrogen || 0;
              }
            });

            console.log('月度用氢量数据：', this.chartData.month.seriesData);
            console.log('月份数据：', this.chartData.month.xData);
            
            this.$nextTick(() => {
              this.initChart();
            });
          }
        });
    },
    generateMonths() {
      this.chartData.month.xData = Array.from({ length: 12 }, (_, i) => {
        return `${this.currentYear}-${(i + 1).toString().padStart(2, '0')}`
      })
    },
    
    switchTab(tab) {
      this.currentTab = tab;
      this.$nextTick(() => {
        this.initChart();
      });
    },
    initChart() {
      if (this.chart) {
        this.chart.dispose();
      }
      this.chart = echarts.init(this.$refs.chart);
      const { xData, seriesData } = this.chartData[this.currentTab];
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: (params) => {
              console.log(params)
            return `用氢量：${params[0].value}kg`;
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          top: '5%',
          bottom: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: xData,
          axisLabel: { 
            color: '#000000',
            interval: 0,
            rotate: 45,  // 保持倾斜以防文字重叠
            fontSize: 12,
          },
          axisLine: {
            lineStyle: {
              color: '#000000'
            }
          }
        },
        yAxis: {
          type: 'value',
          name: '用氢量',
          axisLabel: {
            color: '#000000',
            formatter: '{value}kg'
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(0, 0, 0, 0.1)'
            } 
          },
          axisLine: {
            lineStyle: {
              color: '#000000'
            }
          }
        },
        series: [{
          name: '月度用氢量',
          data: seriesData,
          type: 'bar',
          barWidth: 16,
          barCategoryGap: '30%',
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
              offset: 0,
              color: '#40a9ff'
            }, {
              offset: 1,
              color: '#1890ff'
            }])
          },
          label: {
            show: true,
            position: 'top',
            color: '#000000',
            formatter: (params) => {
              return params.value === 0 ? '' : params.value+'kg';
            }
          }
        }]
      };
      this.chart.setOption(option);
    }
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose();
      this.chart = null;
    }
  }
};
</script>

<style scoped>
.chart-container {
  position: relative;
}

.tabs {
  position: absolute;
  top: -10px;
  left: 10px;
  z-index: 10;
}

button {
  background: #f0f0f0;
  border: 1px solid #d9d9d9;
  color: #000000;
  padding: 5px 15px;
  margin-right: 10px;
  cursor: pointer;
  border-radius: 3px;
}

button.active {
  background: #1890ff;
  border-color: #1890ff;
  color: #000000;
}
</style>