<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";

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: "chart"
    },
    width: {
      type: String,
      default: "100%"
    },
    height: {
      type: String,
      default: "270px"
    },
    chartData: {
      type: Array,
      required: true
    },
    title: {
      type: String,
      default: "饼图"
    },
    tag: {
      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() {
      this.chart = echarts.init(this.$el, "macarons");
      this.setOptions(this.chartData);
    },
    setOptions(chartData) {
      let data = chartData;
      this.chart.setOption({
        tooltip: {
          trigger: "item",
          formatter: "{b} : {d}%"
        },
        legend: {
          left: 'center',
          bottom: '15%',
          textStyle: {
            fontSize: "14"
          }
        },
        series: [
          {
            type: "pie",
            radius: ["30%", "50%"],
            center: ["45%", "30%"],
            data: data,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)"
              }
            },
            label: {
              normal: {
                show: true,
                formatter: "{d}%",
                fontSize: "13"
              }
            }
          }
        ]
      });
    }
  }
};
</script>
