<template>
  <div class="chart" :id="id"></div>
</template>

<script>
export default {
  name: "pieChart",
  props: {
    id: String,
    params: Array,
  },
  watch: {
    params: {
      handler: function (val) {
        if (val.length) {
          this.initData();
        }
      },
      deep: true,
    },
  },
  data() {
    return {
      chart: null,
    };
  },
  created() {},
  mounted() {
    this.initData();
  },
  methods: {
    setOption() {
      const that = this;
      const options = {
        color: this.colors || ["#ff80db", "#c8cc00", "#67c6b5"],
        backgroundColor: "#f8f8f8",
        tooltip: {
          trigger: "item",
          confine: true,
          formatter(v) {
            return `${v.marker} ${v.name}：${v.value}`
          },
        },
        legend: {
          show: false,
          bottom: 40,
          left: 60,
          tight: 60,
          selectedMode: false,
          formatter: function (name) {},
          textStyle: {
            rich: {
              b: {
                color: "#999",
              },
            },
          },
        },
        series: {
          type: "pie",
          center: ["50%", "50%"], // 位置
          radius: [0, "80%"],
          data: that.params,
          label: {
            normal: {
              formatter(v) {
                let rate = v.data.rate*100
                return v.name + rate.toFixed(2) + "%";
              },
            },
          },
          selectedMode: true,
          hoverAnimation: true,
          avoidLabelOverlap: true,
          animationType: "scale",
          animationEasing: "elasticOut",
          animationDelay() {
            return Math.random() * 100;
          },
        },
      };
      return options;
    },
    initData() {
      if (!this.chart) {
        const div = document.getElementById(this.id);
        this.chart = this.$echarts.init(div);
      }
      const options = this.setOption();
      this.chart?.clear();
      this.chart.setOption(options, true);
      this.chart.off("click");
      this.chart.on("click", "series", (params) => {
        this.$emit("clickPieChart", params);
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.chart {
  height: 100%;
}
</style>
