<template>
  <div :class="className" :style="{height:height,width:width}"></div>
</template>

<script>
import echarts from 'echarts'
require('echarts/theme/macarons')
import { debounce } from './chart'

export default {
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '350px'
    },
    chartData: {
      type: Object
    }
  },
  data() {
    return {
      chart: null
    }
  },
  mounted() {
    this.initChart()
    this.__resizeHanlder = debounce(() => {
      if (this.chart) {
        this.chart.resize()
      }
    }, 100)
    window.addEventListener('resize', this.__resizeHanlder)
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    window.removeEventListener('resize', this.__resizeHanlder)
    this.chart.dispose()
    this.chart = null
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.setOptions(val)
      }
    }
  },
  methods: {
    setOptions(datastr) {
      this.chart.setOption({
        title: {
          text: '合计：' + datastr.all,
          textStyle: {
            color: '#333',
            fontSize: 14
          },
          left: 'center',
          top: '8%'
        },
        toolbox: {
          show: true,
          feature: {
            dataView: { readOnly: false },
            restore: {},
            saveAsImage: {}
          }
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          data: ['未激活企业', '激活企业', '合计']
        },
        series: [
          {
            name: '企业状态',
            type: 'pie',
            radius: '65%',
            center: ['50%', '56%'],
            data: [
              {
                name: '未激活企业',
                value: datastr.unactived
              },
              {
                name: '激活企业',
                value: datastr.actived
              }
            ],
            itemStyle: {
              emphasis: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              },
              normal: {
                label: {
                  show: true,
                  formatter: '{b} : {c} ({d}%)'
                },
                labelLine: { show: true }
              }
            }
          }
        ]
      })
    },
    initChart() {
      this.chart = echarts.init(this.$el) // , 'macarons'
      var that = this
      setTimeout(function() {
        that.setOptions(that.chartData)
      }, 1)
    }
  }
}
</script>
