<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: {
    receivab: {
      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: {
    receivab: {
      handler: function(el) { // 监听对象的变换使用 function，箭头函数容易出现this指向不正确
        this.initChart(el)
      },
      deep: true
    }
  },
  created() {
    this.$nextTick(() => {
      this.initChart(this.receivab)
    })
  },
  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'],
        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: '#545454',
            lineHeight: 22,
            formatter: function(param) {
              let result = (+param.value || 0).toString().replace(/^-?\d+/g, m => m.replace(/(?=(?!\b)(\d{3})+$)/g, ','))
              const temp = result.split('.')
              if (temp.length === 1) {
                result += '.00'
              } else if (temp.length > 1) {
                if (temp[1].length < 2) {
                  result += '0'
                }
              }
              return param.name + '(' + Math.round(param.percent) + '%' + ')' + '\n¥' + result
            }
          },
          labelLine: {
            smooth: false,
            lineStyle: {
              width: 2
            }
          },
          itemStyle: {
            color: function(params) {
              switch (params.name) {
                case '已收金额':
                  return '#417DE6'
                case '未收金额':
                  return '#E6A441'
              }
            }
          },
          animationDuration: animationDuration
        }]
      })
    }
  }
}
</script>
