<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() {
      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: {
          left: 'center',
          bottom: '0%',
           itemGap: 15,
          textStyle: {
            fontSize: '14',
            color: '#545555'
          }
        },
        series: [
          {
            type: 'pie',
            radius: ['40%', '57%'],
            center: ['55%', '35%'],
            data: data,
            show: true,
            label: {
              position: 'center',
              formatter: function (params) {
                return '{a|进出口总值}\n\n' + 1000;
              },
              rich: {
                a: {
                  color: 'gray',
                  fontSize: 14,
                  lineHeight: 20
                },
                b: {
                  color: '#FFA500',
                  fontSize: 20,
                  fontWeight: 'bold',
                  lineHeight: 30
                }
              }
            }
          }
        ]
      });
    }
  }
};
</script>
