<template>
  <div ref="chart" class="chart-container"></div>
</template>

<script>
import echarts from "echarts";
import { currentGET } from "api/modules";

export default {
  name: "LeftBottomChart",
  data() {
    return {
      monthItems: [],
      monthHydrogen: [],
      monthMileage: [],
      monthCarbon: [],
      seriesData: [
        "1月",
        "2月",
        "3月",
        "4月",
        "5月",
        "6月",
        "7月",
        "8月",
        "9月",
        "10月",
        "11月",
        "12月",
      ],
    };
  },
  mounted() {
    this.getMonthData();
    window.addEventListener("resize", this.handleResize);

    // 监听事件总线的刷新事件
    this.$eventBus.$on('refresh-all-data', this.getMonthData);
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.handleResize);

    // 移除事件总线的刷新事件监听
    this.$eventBus.$off('refresh-all-data', this.getMonthData);

    if (this.chart) {
      this.chart.dispose();
    }
  },
  methods: {
    handleResize() {
      if (this.chart) {
        this.chart.resize();
      }
    },
    getMonthData() {
      currentGET("big2").then((res) => {
        console.log("月度行驶里程&用氢量");
        this.monthItems = res.data;
        console.log(this.monthItems);

        // 初始化12个月的数据为0
        this.monthHydrogen = new Array(12).fill(0);
        this.monthMileage = new Array(12).fill(0);
        this.monthCarbon = new Array(12).fill(0);

        this.monthItems.forEach((item) => {
          let month = parseInt(item.months.substring(5, 7));
          this.monthMileage[month - 1] = item.monthMileage || 0;
          this.monthCarbon[month - 1] = item.monthCarbon || 0;
          this.monthHydrogen[month - 1] = item.monthHydrogen || 0;
        });

        console.log('用氢量：', this.monthHydrogen);
        console.log('里程数：', this.monthMileage);
        this.initChart();
      });
    },
    initChart() {
      this.$nextTick(() => {
        if (!this.$refs.chart) return;

        const chart = echarts.init(this.$refs.chart);

        // 初始化12个月的数据
        const hydrogenData = new Array(12).fill(0);
        const mileageData = new Array(12).fill(0);

        // 填充数据并转换单位
        this.monthHydrogen.forEach((value, index) => {
          hydrogenData[index] = value ? Number((value / 1000).toFixed(2)) : 0; // kg转吨
        });

        this.monthMileage.forEach((value, index) => {
          mileageData[index] = value ? Number((value / 10000).toFixed(2)) : 0; // km转万km
        });

        // 计算数据范围
        const hydrogenMax = Math.max(...hydrogenData);
        const mileageMax = Math.max(...mileageData);

        console.log('===== 月度行驶里程&用氢量 数据分析 =====');
        console.log('用氢量数据(吨):', hydrogenData);
        console.log('里程数据(万km):', mileageData);
        console.log('用氢量最大值(吨):', hydrogenMax);
        console.log('里程最大值(万km):', mileageMax);
        console.log('用氢量原始数据(kg):', this.monthHydrogen);
        console.log('里程原始数据(km):', this.monthMileage);

        let option = {
          grid: {
            left: "12%",
            right: "12%",
            top: "15%",
            bottom: "12%",
            containLabel: true
          },
          tooltip: {
            trigger: "axis",
            backgroundColor: "rgba(255, 255, 255, 0.9)",
            borderColor: "#059669",
            borderWidth: 1,
            textStyle: { color: "#333333" },
            formatter: (params) => {
              const month = params[0].name;
              const hydrogen = params[0].value;
              const mileage = params[1].value;
              return `${month}<br/>用氢量：${hydrogen}吨<br/>行驶里程：${mileage}万公里`;
            },
          },
          legend: {
            show: true,
            data: ["用氢量(吨)", "行驶里程(万公里)"],
            textStyle: {
              color: "#64748b",
              fontSize: 12
            },
            top: 0,
            itemWidth: 20,
            itemHeight: 10
          },
          xAxis: {
            type: "category",
            boundaryGap: false,
            data: [
              "1月",
              "2月",
              "3月",
              "4月",
              "5月",
              "6月",
              "7月",
              "8月",
              "9月",
              "10月",
              "11月",
              "12月",
            ],
            axisLine: {
              lineStyle: { color: "#d1d5db" }
            },
            axisLabel: {
              color: "#64748b",
              fontSize: 11,
              interval: 0, // 显示所有月份
              rotate: 0
            },
            axisTick: {
              show: false
            }
          },
          yAxis: [
            {
              type: "value",
              name: "吨",
              nameTextStyle: {
                color: "#059669",
                fontSize: 12,
                padding: [0, 0, 0, 0]
              },
              min: 0,
              max: hydrogenMax > 0 ? Math.ceil(hydrogenMax * 1.5) : 10, // 用氢量Y轴设置为最大值的1.5倍
              axisLine: {
                show: false
              },
              axisLabel: {
                color: "#64748b",
                fontSize: 11,
                formatter: "{value}"
              },
              splitLine: {
                lineStyle: {
                  color: "#f1f5f9",
                  type: 'dashed'
                }
              }
            },
            {
              type: "value",
              name: "万公里",
              nameTextStyle: {
                color: "#85E0E5",
                fontSize: 12,
                padding: [0, 0, 0, 0]
              },
              min: 0,
              max: mileageMax > 0 ? Math.ceil(mileageMax * 1.1) : 10, // 里程Y轴设置为最大值的1.1倍
              axisLine: {
                show: false
              },
              axisLabel: {
                color: "#64748b",
                fontSize: 11,
                formatter: "{value}"
              },
              splitLine: {
                show: false
              }
            }
          ],
          series: [
            {
              name: "用氢量(吨)",
              type: "line",
              yAxisIndex: 0,
              data: hydrogenData,
              itemStyle: { color: "#059669" },
              lineStyle: {
                width: 2,
                color: "#059669"
              },
              smooth: true,
              symbol: "circle",
              symbolSize: 6,
              showSymbol: false,
              emphasis: {
                showSymbol: true
              }
            },
            {
              name: "行驶里程(万公里)",
              type: "line",
              yAxisIndex: 1,
              data: mileageData,
              itemStyle: { color: "#85E0E5" },
              lineStyle: {
                width: 2,
                color: "#85E0E5"
              },
              smooth: true,
              symbol: "circle",
              symbolSize: 6,
              showSymbol: false,
              emphasis: {
                showSymbol: true
              }
            },
          ],
        };
        chart.setOption(option);
        this.chart = chart;
        this.chart.resize();
      });
    },
  },
};
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 100%;
  min-height: 200px;
}
</style>
