<template>
  <div class="chart" ref="chart"></div>
</template>

<script>
import * as echarts from 'echarts'
export default {
  name: 'ComProgressPieChart', //进度饼图
  props: {
    chartData: {}
  },
  data() {
    return { myChart: null }
  },
  watch: {
    chartData(val) {
      this.$nextTick(() => {
        this.initialChart()
      })
    }
  },
  mounted() {
    //图表大小自适应
    window.addEventListener('resize', this.onResize)
  },
  methods: {
    destroyChart() {
      if (this.myChart != null) {
        this.myChart.dispose()
        this.myChart = null
      }
    },
    onResize() {
      if (this.myChart) {
        // this.myChart.resize()
        this.initialChart()
      }
    },
    initialChart() {
      this.destroyChart()
      let data = this.chartData
      let pieData = []
      data.forEach((item) => {
        pieData.push({
          ...item,
          labelLine: {
            show: true,
            length: 30,
            length2: 70
          }
        })
      })
      let option = {
        series: [
          {
            type: 'pie',
            radius: ['28%', '40%'],
            center: ['50%', '50%'],
            avoidLabelOverlap: true,
            label: {
              show: true,
              formatter: '{a|{b}}\n{num|{c}万元}',
              color: '#fff',
              lineHeight: 20,
              overflow: 'none',
              padding: [0, -40],
              rich: {
                a: { color: '#99D0FE', align: 'left', fontSize: 14, fontFamily: 'Source Han Sans CN', fontWeight: 500 },
                num: {
                  color: ' #FEFFFF',
                  align: 'left',
                  fontSize: 14,
                  fontWeight: 500,
                  fontFamily: 'Source Han Sans CN'
                }
              }
            },
            data: pieData
          }
          //   {
          //     type: 'pie',
          //     radius: ['36%', '43%'],
          //     center: ['50%', '50%'],
          //     silent: true,
          //     data: [
          //       {
          //         name: '',
          //         value: 1
          //       }
          //     ]
          //   }
        ]
      }
      this.creatChart(option, this.$refs.chart)
    },
    creatChart(option, ref) {
      this.myChart = echarts.init(ref) //this.$refs.chart
      this.myChart.resize()
      this.myChart.setOption(option, {
        notMerge: true
      })
    }
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.onResize)
    this.destroyChart()
  }
}
</script>

<style lang='scss' scoped>
.chart {
  height: 100%;
  width: 100%;
}
</style>