<template>
  <div :id="id" :class="className" :style="{ height:height,width:width }" />
</template>
<script>
  import echarts from 'echarts'
  import resize from './mixins/resize'

  export default {
    mixins: [resize],
    props: {
      className: {
        type: String,
        default: "chart"
      },
      id: {
        type: String,
        default: "chart"
      },
      width: {
        type: String,
        default: "100%"
      },
      height: {
        type: String,
        default: "400px"
      },
      data: {
        type: Object,
        default: {}
      },
    },
    data() {
      return {
        chart: null
      };
    },
      watch: {
          data: {
              handler(newVal, oldVal) {
                  if (newVal) {
                      this.initChart();
                  }
              },
              deep: true //对象内部属性的监听，关键。
          }
      },
    mounted() {
        this.$nextTick(() => {
            this.initChart();
        })
    },
    beforeDestroy() {
      if (!this.chart) {
        return;
      }
      this.chart.dispose();
      this.chart = null;
    },
    methods: {
      initChart() {
        let that = this;
        this.chart = echarts.init(document.getElementById(this.id));
        let legendData = [];
        that.data.seriesData.forEach(function(item,index){
          if(item.name){
             legendData.push(item.name);
          }
        })
        let option = {
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b} : {c} ({d}%)'
          },
          color:that.data.color,
          legend: {
            left: 'right',
            top: 'middle',
            orient:'vertical',
            data: legendData
          },
          series: [
            {
              name: '拥有保单件数分布',
              type: 'pie',
              // roseType: 'radius',
              radius: ['30%', '75%'],
              center: ['40%', '55%'],
              label: {
                show:false,
                formatter: '{b}：\n{d}%'
              },
              data: this.data.seriesData,
            }
          ]
        };
        this.chart.setOption(option);
      }
    }
  };
</script>
