<template>
  <div :class="className" :style="{ height: height, width: width }" />
</template>

<script>
import * as echarts from "echarts";
require("echarts/theme/macarons"); // echarts theme
import resize from "./mixins/resize";

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: "chart",
    },
    width: {
      type: String,
      default: "100%",
    },
    height: {
      type: String,
      default: "300px",
    },
    pieData: {
      type: Array,
      default: function () {
        return [
          { value: 0, name: "已启动" },
          { value: 0, name: "未启动" },
        ];
      },
    },
  },
  watch: {
    pieData: {
      handler(newVal, oldVal) {
        if (this.chart) {
          this.chart.setOption({
            series: [
              {
                data: newVal,
              },
            ],
          });
        }
      },
      deep: true,
    },
  },
  data() {
    return {
      chart: null,
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart();
    });
  },
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    this.chart.dispose();
    this.chart = null;
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, "macarons");

      this.chart.setOption({
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b} : {c} ({d}%)",
        },
        legend: {
          left: "center",
          bottom: "1%",
          data: ["已启动", "未启动"],
          textStyle: {
            color: "#fff", // 设置图例文字颜色为白色
          },
        },
        series: [
          {
            name: "监控摄像头",
            type: "pie",
            color: ["#c9cee2", "#184ff0"], // 新增颜色数组配置
            data: this.pieData,
            avoidLabelOverlap: false,
            emphasis: {
              label: {
                show: true,
                fontSize: 40,
                fontWeight: "bold",
              },
            },
            label: {
              position: "center",
            },
          },
        ],
      });
    },
  },
};
</script>
