<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",
          top: "5%",
          data: ["已启动", "未启动"],
        },

        series: [
          {
            name: "监控摄像头",
            type: "pie",
            radius: ["45%", "75%"],
            center: ["50%", "55%"],
            color: ["#F56C6C", "#67C23A"], // 新增颜色数组配置
            data: this.pieData,
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: "#fff",
              borderWidth: 2,
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 40,
                fontWeight: "bold",
              },
            },
            label: {
              position: "center",
            },
          },
        ],
      });
    },
  },
};
</script>
