<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: '350px'
    },
    autoResize: {
      type: Boolean,
      default: true
    },
    pieTypeData: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    pieTypeData: {
      deep: true,
      handler(val) {
        this.setOptions(val)
        console.log('watch拿到的val', val)
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
      this.setOptions(this.pieTypeData)
      // console.log('methods拿到的pieTypeData', this.pieTypeData)
    },
    setOptions({ TypeData, text } = {}) {
      // console.log('setOptions拿到的TypeData', TypeData)
      this.chart.setOption({
        title: {
          text: text + '月类型统计',
          subtext: '',
          x: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: ['', '', '', '', '']
        },
        series: [
          {
            name: text + '月',
            type: 'pie',
            radius: '55%',
            center: ['50%', '60%'],
            data: TypeData,
            // data: [
            //   { value: 335, name: '直接访问' },
            //   { value: 310, name: '邮件营销' },
            //   { value: 234, name: '联盟广告' },
            //   { value: 135, name: '视频广告' },
            //   { value: 1548, name: '搜索引擎' }
            // ],
            itemStyle: {
              emphasis: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      })
      const that = this
      // 点击饼图拿到对应内容
      this.chart.on('click', function(params) {
        console.log(params)
        that.$emit('chartClickType', params.name)
      })
    }
  }
}
</script>
