<template>
  <div class="full-size">
    <div
      ref="myEchart"
      class="full-size"
    ></div>
  </div>
</template>

<script>
import echarts from 'echarts'
export default {
  props: {
    chartData: {
      type: Object,
      default: () => {}
    }
  },
  data () {
    return {

    }
  },
  watch: {
    chartData: {
      deep: true,
      handler (newVal) {
        this.chartData = newVal
        this.draw()
      }
    }
  },
  mounted () {
    this.draw()
  },
  methods: {
    draw () {
      const myEchart = echarts.init(this.$refs.myEchart, 'light')
      const o = this.chartData
      const data = o.series.data
      let sum = 0
      const obj = {}
      data.forEach(item => {
        obj[item.name] = item.value
        sum += item.value
      })
      const option = {
        color: ['#3AA0FF', '#35CACA', '#4FCB74', '#FAD337', '#F1627B', '#965DE4'],
        legend: {
          orient: 'vertical',
          y: 'center',
          left: '52%',
          formatter(name) {
            const text = Number(obj[name]) === 0 ? '0' : `${(parseFloat(obj[name] / sum) * 100).toFixed(2)}%`
            return '{b|' + name + '}  ' + '{a|' + text + '}' + `¥${obj[name]}`
          },
          itemGap: 25,
          textStyle: {
            rich: {
              b: {
                align: 'left',
                fontSize: 16,
                width: 120

              },
              a: {
                align: 'left',
                fontSize: 16,
                width: 100
              }
            },
            fontSize: 16,
            color: '#666666',
            textAlign: 'right'
          }
        },
        series: [
          Object.assign({}, {
            type: 'pie',
            radius: ['45%', '60%'],
            center: ['26%', '55%'],
            label: {
              normal: {
                show: false,
                formatter: function (p) {
                  const t = o.lineBreak ? '\n' : ' '
                  return `{a|${p.name + t}}{b|${p.value + o.unit} ${p.percent}%}`
                },
                rich: {
                  a: {
                    color: '#fff',
                    fontSize: 16
                  },
                  b: {
                    color: '#A4B5DA',
                    fontSize: 16
                  }
                }
              }
            }

          }, o.series),
          o.firstSeries || ''
        ]
      }
      myEchart.setOption(option)
    }
  }
}
</script>
