<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();
    });
    window.addEventListener('resize', () => {
      this.chart.resize();
    });
  },
  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) {
      let data = chartData;
      this.chart.setOption({
        tooltip: {
          trigger: 'item',
          formatter: '{b} : {d}%'
        },
        color: ['#fddb78', '#2561ef', '#3ed59f', '#fa746b', '#666ee8'],
        legend: {
          orient: 'vertical',
          top: '18%',
          x: 'left',
          itemWidth: 12,
          itemGap: 16,
          icon: 'circle',
          textStyle: {
            color: '#545555',
            fontSize: 12
          },
          formatter: function (name) {
            let total = 0;
            for (let i = 0; i < data.length; i++) {
              total += data[i].value;
            }
            for (let i = 0; i < data.length; i++) {
              if (data[i].name === name) {
                let percent = ((data[i].value / total) * 100).toFixed(2); // 计算百分比并保留两位小数
                return name + ' (' + data[i].value + '亿，' + percent + '%)';
              }
            }
          }
        },
        series: [
          {
            type: 'pie',
            radius: ['20%', '40%'],
            center: ['70%', '45%'],
            data: data,
            show: true,
            label: {
              normal: {
                show: false
              }
            }
          }
        ]
      });
    }
  }
};
</script>
