<template>
  <div class="chart-container">
    <div ref="chart" style="width: 520px; height: 280px;margin-top: 0%;"></div>
  </div>
</template>
 
<script>
import * as echarts from 'echarts';
import { currentGET } from "api/modules";
export default {
  name: 'DoubleAxisChart',
  mounted() {
    this.getData();
    // 初始化时设置标题
    this.$emit('update-title', '月度用氢量'); 
  }, 
  beforeDestroy() {
    if (this.intervalId) {
      clearInterval(this.intervalId);
    }
    // Cleanup chart instance
    if (this.chart) {
      this.chart.dispose();
      this.chart = null;
    }
  },
  data() {
    return {
      dailyHydrogen: [],
      dailyCarbon: [],
      dailyMileage: [],
      XAxisData: [],
      seriesData: [],
      currentChartIndex: 0,
      intervalId: null,
      currentMonth: new Date().getMonth() + 1,
      currentYear: new Date().getFullYear(),
      chart: null
    };
  },
  methods: {
    updateParentTitle(title) {
      this.$emit('update-title', title)
    },
    getDaysInMonth(year, month) {
      return new Date(year, month, 0).getDate();
    },
    generateDaysArray() {
      const daysInMonth = this.getDaysInMonth(this.currentYear, this.currentMonth);
      return Array.from({length: daysInMonth}, (_, i) => `${this.currentMonth}月${i+1}日`);
    },
    getData() {
      this.XAxisData = this.generateDaysArray();
      
      const daysInMonth = this.getDaysInMonth(this.currentYear, this.currentMonth);
      this.dailyHydrogen = new Array(daysInMonth).fill(0);
      this.dailyCarbon = new Array(daysInMonth).fill(0);
      this.dailyMileage = new Array(daysInMonth).fill(0);

      const formattedMonth = `${this.currentYear}-${String(this.currentMonth).padStart(2, '0')}`;
      
      currentGET("big12").then((res) => {
        console.log('每日数据');          
        this.monthItems = res.data;
        console.log(this.monthItems);
        
        this.monthItems.forEach((item) => {
          const day = parseInt(item.dates.substring(8, 10));
          if (day > 0 && day <= daysInMonth) {
            this.dailyHydrogen[day - 1] = item.dayHydrogen;
            this.dailyCarbon[day - 1] = item.dayCarbon;
            this.dailyMileage[day - 1] = item.dayMileage || 0;
          }
        });
        
        console.log('用氢量：', this.dailyHydrogen);
        console.log('碳排放：', this.dailyCarbon);
        console.log('行驶里程：', this.dailyMileage);
        this.initChart();
        this.intervalId = setInterval(this.switchChart, 5000);
      });
    },
    switchChart() {
      this.currentChartIndex = (this.currentChartIndex + 1) % 3;
      const titles = ['日用氢量', '日碳排放量', '日行驶里程'];
      this.$emit('update-title', titles[this.currentChartIndex]);
      console.log('切换图表', titles[this.currentChartIndex]);
      this.initChart();
    },
    initChart() {
      const chartDom = this.$refs.chart;
      if (this.chart) {
        this.chart.dispose();
      }
      this.chart = echarts.init(chartDom);
      let legendData = [];
      let seriesName = '';
      let seriesColor = '';
      let areaColor = '';

      if (this.currentChartIndex === 0) {
        legendData = ['用氢量'];
        this.seriesData = this.dailyHydrogen;
        seriesName = '用氢量';
        seriesColor = 'orange';
        areaColor = 'orange';
      } else if (this.currentChartIndex === 1) {
        legendData = ['碳排放'];
        this.seriesData = this.dailyCarbon;
        seriesName = '碳排放';
        seriesColor = 'green';
        areaColor = 'green';
      } else {
        legendData = ['行驶里程'];
        this.seriesData = this.dailyMileage;
        seriesName = '行驶里程';
        seriesColor = '#1890ff';
        areaColor = '#1890ff';
      }

      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        legend: {
          data: legendData,
          left: 'right',
          icon: 'line',
          itemWidth: 30,
          itemHeight: .0,
          itemGap: 10,
          textStyle: {
            color: '#000000',
            fontSize: 16,
            fontWeight: 'normal',
            fontFamily: 'Arial, sans-serif'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          top: '10%',
          bottom: '10%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            boundaryGap: false,
            data: this.XAxisData,
            axisLine: {
              lineStyle: {
                color: '#000000',
                width: 1
              }
            },
            axisTick: {
              show: true,
              alignWithLabel: true,
              lineStyle: {
                color: 'white'
              }
            },
            axisLabel: {
              color: '#000000',
              fontSize: 12,
              interval: 1,
              rotate: 45
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '',
            offset: 10,
            axisLine: {
              lineStyle: {
                color: 'white'
              }
            },
            splitLine: { lineStyle: { color: '#081b42' } },
            axisLabel: {
              formatter: '{value}',
              align: 'right',
              padding: [0, 5, 0, 0]
            }
          },
          {
            type: 'value',
            name: '',
            axisLine: {
              lineStyle: {
                color: 'white'
              }
            },
            splitLine: { lineStyle: { color: '#081b42' } },
            axisLabel: {
              formatter: '{value}'
            }
          }
        ],
        series: [
          {
            name: seriesName,
            type: 'line',
            stack: '总量',
            areaStyle: {color: areaColor},
            emphasis: {
              focus: 'series'
            },
            data: this.seriesData,
            lineStyle: {
              color: seriesColor,
              width: 2,
            },
            label: {
              show: true,
              position: 'top',
              color: '#000000',
              fontSize: 12,
              formatter: (params) => {
                return params.value === 0 ? '' : params.value;
              },
              textShadowBlur: 10,
              textShadowColor: 'rgba(0,0,0,0.5)'
            }
          }
        ]
      };
      this.chart.setOption(option);
    }
  }
};
</script>

<style scoped>
.chart-container {
  position: relative;
  border: 1px solid red; /* 添加边框用于调试 */
}
</style>