<template>
  <div class="chart" data-title="课程学习状态占比统计"></div>
</template>

<script>
import { Chart } from '@antv/g2'

import { findStatisticDataApi } from '@/api/statistic'

export default {
  methods: {
    async findData () {
      const data = await findStatisticDataApi('learning-state')
      this.chart.data(data)
      let allCount = 0
      data.forEach((count) => {
        allCount += parseInt(+count.count || 0)
      })
      this.chart.data(data)
      this.chart.annotation().html({
        position: ['50%', '50%'],
        html: `<div style="color:#8c8c8c;font-size: 14px;text-align: center;width: 10em;">所有课程<br><span style="color:#8c8c8c;font-size:20px">${allCount}</span>门</div>`,
        alignX: 'middle',
        alignY: 'middle'
      })
      this.chart.render()
    }
  },

  mounted () {
    this.findData()
    this.chart = new Chart({
      padding: [30, 0],
      container: this.$el,
      autoFit: true,
      height: 300
    })
    this.chart.scale('percent', {
      formatter: (val) => {
        val = val * (100).toFixed(2)
        return val + '%'
      }
    })
    this.chart.coordinate('theta', {
      radius: 0.75,
      innerRadius: 0.6
    })
    this.chart.tooltip({
      showTitle: false,
      showMarkers: false,
      itemTpl:
        '<li class="g2-tooltip-list-item"><span style="background-color:{color};" class="g2-tooltip-marker"></span>{name}: {value}</li>'
    })

    this.chart
      .interval()
      .adjust('stack')
      .position('percent')
      .color('item')
      .label('percent', (percent) => {
        return {
          content: (data) => {
            // ${data.item}:
            return `${(percent * 100).toFixed(2)}%`
          }
        }
      })
      .tooltip('item*percent*count', (item, percent, count) => {
        percent = count
        return {
          name: item,
          value: percent + '次'
        }
      })

    this.chart.interaction('element-active')
  }
}
</script>
