<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'
const animationDuration = 3000
export default {
  mixins: [resize],
  props: {
    orderData: {
      type: Array,
      default: function() {
        return []
      }
    },
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '80%'
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    orderData: {
      handler: function(el) { // 监听对象的变换使用 function，箭头函数容易出现this指向不正确
        this.initChart(el)
      },
      deep: true
    }
  },
  created() {
    this.$nextTick(() => {
      this.initChart(this.orderData)
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart(data) {
      this.chart = echarts.init(this.$el, 'macarons')
      this.chart.setOption({
        tooltip: {
          trigger: 'hideTip',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        color: ['#417DE6', '#E6A441', '#E67441'],
        legend: {
          // orient: 'vertical',
          // top: 'middle',
          bottom: 0,
          right: 0,
          data: ['已收款订单', '未收款订单', '部分收款订单']
        },
        series: [{
          name: '订单数量',
          type: 'pie',
          radius: ['50%', '70%'],
          avoidLabelOverlap: false,
          center: ['50%', '50%'],
          selectedMode: 'single',
          roseType: false,
          data: data,
          label: {
            fontSize: 14,
            color: '#7C8894',
            lineHeight: 22,
            formatter: function(param) {
              return param.name + '(' + Math.round(param.percent) + '%' + ')' + '\n' + param.value + '个'
            }
          },
          labelLine: {
            smooth: false,
            lineStyle: {
              width: 2
            }
          },
          itemStyle: {
            color: function(params) {
              switch (params.name) {
                case '已收款订单':
                  return '#417DE6'
                case '未收款订单':
                  return '#E6A441'
                case '部分收款订单':
                  return '#E67441'
                default:
                  break
              }
            }
          },
          animationDuration: animationDuration
        }]
      })
    }
  }
}
</script>
