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

<script>
import echarts from "echarts";
import { currentGET } from "api/modules";
import { color } from "echarts/lib/export";
export default {
  data() {
    return {
      showPercentage: true, // 默认显示数量
      chartData: [
        [
          { modelName: "冷藏", total: 190 },
          { modelName: "普货", total: 40 },
          // { name: '海格：20%', value: 160 },
          // { name: '宇通：20%', value: 260 },
          // { name: '其它：10%', value: 260 }
        ],
      ],
      colors: [
        "#46AEF4",
        "#10B981",
        "#04724F",
        "#C2F1E1",
        "#EAFAF5",
        "#F6F8FA",
      ],
      //colors: ["#00E5FF", "#FF5733",  "#FFBF00", "#5CDB95"]
    };
  },
  mounted() {
    this.getData();
    window.addEventListener("resize", this.handleResize);

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

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

    if (this.chart) {
      this.chart.dispose();
    }
  },
  methods: {
    getData() {
      currentGET("big5").then((res) => {
        if (res.code == 0) {
          // 确保接口返回的code正确
          // 转换数据结构为饼图需要的格式
          this.chartData = [
            res.data.map((item) => ({
              name: item.modelName,
              value: item.total,
            })),
          ];
          console.log("车型分布");
          console.log(this.chartData);
          //未显示成功，没有用到，后台增加模拟数据
          //增加模拟数据
          // this.chartData.push([{name: '氢能集卡', value: 20}]);
          // this.chartData.push({name: '氢能叉车', value: 8});
          // this.chartData.push({name: '无人机', value: 5});
          // this.chartData.push({name: '装载机', value: 10});
          this.initChart();
        }
      });
    },

    handleResize() {
      if (this.chart) {
        this.chart.resize();
      }
    },
    initChart() {
      this.$nextTick(() => {
        if (!this.$refs.chart) return;

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

        // 计算总数和每项的百分比
        const chartData = this.chartData[0];
        console.log("图表数据:", chartData);

        if (!chartData || chartData.length === 0) {
          console.warn("图表数据为空");
          return;
        }

        const total = chartData.reduce(
          (sum, item) => sum + Number(item.value),
          0
        );
        console.log("总数:", total);

        // 创建name到数据的映射
        const dataMap = {};
        chartData.forEach((item) => {
          const numValue = Number(item.value);
          const percent =
            total > 0 ? ((numValue / total) * 100).toFixed(1) : "0.0";
          dataMap[item.name] = {
            value: numValue,
            percent: percent,
          };
          console.log(`${item.name}: ${numValue}辆, ${percent}%`);
        });

        let option = {
          title: {
            text: `总计`,
            subtext: `${total}`,
            left: "24%",
            top: "39%",
            textAlign: "center",
            textStyle: {
              fontSize: 13,
              color: "#64748B",
            },
            subtextStyle: {
              fontSize: 20,
              fontWeight: "bold",
              color: "#1E293B",
            },
          },
          tooltip: {
            trigger: "item",
            formatter: "{b}: {c}辆 ",
          },
          legend: {
            orient: "vertical",
            right: "5%",
            top: "middle",
            formatter: (name) => {
              const data = dataMap[name];
              if (data) {
                return `${name}  ${data.percent}%`;
              }
              return name;
            },
            textStyle: {
              color: "#333333",
              fontSize: 13,
            },
            itemGap: 15,
            itemWidth: 14,
            itemHeight: 14,
          },
          series: [
            {
              name: "车型分布",
              type: "pie",
              radius: ["45%", "65%"],
              center: ["25%", "50%"],
              avoidLabelOverlap: false,
              itemStyle: {
                borderRadius: 4,
                borderColor: "#fff",
                borderWidth: 2,
              },
              label: {
                show: false,
                position: "center",
              },
              emphasis: {
                label: {
                  show: true,
                  color: "#1E293B",
                  fontSize: 14,
                  fontWeight: "bold",
                  formatter: "{b}\n{c}辆",
                },
              },
              labelLine: {
                show: false,
              },
              data: chartData.map((item, index) => ({
                name: item.name,
                value: Number(item.value),
                itemStyle: {
                  color: this.colors[index % this.colors.length],
                },
              })),
            },
          ],
        };

        option && myChart.setOption(option);
        this.chart = myChart;
        this.chart.resize();

        let isHoveringChart = false;

        // 鼠标悬停在扇区时
        myChart.on("mouseover", "series", () => {
          isHoveringChart = true;
          myChart.setOption({
            title: {
              show: false,
            },
          });
        });

        // 鼠标离开扇区时
        myChart.on("mouseout", "series", () => {
          isHoveringChart = false;
          myChart.setOption({
            title: {
              show: true,
            },
          });
        });

        // 监听高亮事件（包括legend悬停触发的）
        myChart.on("highlight", () => {
          // 如果不是在扇区上悬停，说明是legend触发的
          if (!isHoveringChart) {
            myChart.setOption({
              title: {
                show: false,
              },
            });
          }
        });

        // 监听取消高亮事件
        myChart.on("downplay", () => {
          if (!isHoveringChart) {
            myChart.setOption({
              title: {
                show: true,
              },
            });
          }
        });
      });
    },
    toggleMode() {
      this.showPercentage = !this.showPercentage;
      this.initChart(); // 重新渲染图表
    },
  },
};
</script>

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