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

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

const animationDuration = 6000;

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: "chart",
    },
    width: {
      type: String,
      default: "100%",
    },
    chartData: {
      type: Array,
      required: true,
    },
    height: {
      type: String,
      default: "400px",
    },
    title: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      chart: null,
    };
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.setOptions(val);
      },
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart();
    });
  },
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    this.chart.dispose();
    this.chart = null;
  },
  methods: {
    initChart() {
      setTimeout(() => {
        this.chart = echarts.init(this.$el, "macarons");
        this.setOptions(this.chartData);
      }, 300);
    },
    setOptions(chartData) {
      console.log(chartData);
      let seriesData = [];
      if (chartData) {
        chartData.forEach((item, index) => {
          seriesData.push({
            name: item.normName,
            value: item.cvalue,
          });
        });
      }
      this.chart.setOption({
        title: {
          text: this.title,
          left: "center",
        },
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b} : {c} ({d}%)",
        },
        legend: {
          orient: "vertical",
          left: "left",
        },
        series: [
          {
            label: {
              normal: {
                formatter: "{b}:{c}: ({d}%)",
                textStyle: {
                  fontWeight: "normal",
                  fontSize: 15,
                },
              },
            },
            name: "饼图",
            type: "pie",
            radius: "50%",
            data: seriesData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)",
              },
            },
          },
        ],
      });
    },
  },
};
</script>
