<template>
  <div>
    <div ref="myChartTitle" style="text-align: center;height: 16px;font-weight: 600;font-size: 14px;line-height:16px">{{config.title}}</div>
    <canvas ref="myChart"></canvas>
  </div>
</template>

<script>
const F2 = require('@antv/f2/lib/index')
const PieLabel = require('@antv/f2/lib/plugin/pie-label')


export default {
  props: {
    data: {
      type: Array,
      default: () => []
    },
    config: {
      type: Object,
      default: () => {}
    },
    width: {
      type: String,
      default: ''
    },
    height: {
      type: String,
      default: ''
    }
  },
  watch: {
    data: {
      handler(newV) {
        this.$nextTick(() => {
          if(newV.length > 0) {
            this.draw()
          }
        })
      },
      immediate: true,
      deep: true
    }
  },
  data() {
    return {
      $__el: null,
      $__myChartTitle: null
    }
  },
  mounted() {
    this.$__el = this.$refs.myChart
    this.$__myChartTitle = this.$refs.myChartTitle
    const myChart = this.$__el
    const mychartTitle = this.$__myChartTitle
    myChart.style.width = this.width ? this.width + 'px' : '100%'
    myChart.style.height = this.height + 'px'
    mychartTitle.style.width = this.width ? this.width + 'px' : '100%'
  },
  methods: {
    draw() {
      const id = Object.keys(this.data[0])[0]
      const type = Object.keys(this.data[0])[1]
      const value = Object.keys(this.data[0])[2]
      const config = this.config
      let color = ''
      if (config && config.color) {
        color = config.color
      }
      const chart = new F2.Chart({
        el: this.$__el,
        plugins: PieLabel
      });
      chart.source(this.data);
      chart.coord('polar', {
        transposed: true,
        radius: 0.9,
        innerRadius: 0.5
      });
      chart.axis(false)
      if(config && config.legend){
        chart.legend({ position: 'bottom'})
      } else {
        chart.legend(false)
      }
      chart.tooltip(config.tooltip)
      chart.interval()
        .position(`${id}*${value}`)
        .adjust('stack')
        .color(type, color)
      chart.pieLabel({
        sidePadding: 30,
        activeShape: true,
        label1: function label1(data) {
          return {
            text: data[value],
            fill: '#333',
            fontWeight: 'bold'
          };
        },
        label2: function label2(data) {
          return {
            text: data[type],
            fill: '#999'
          };
        }
      });
      chart.render();
    }
  }
}
</script>
