<template>
  <div class="chart" data-title="练习习题占类型统计">
  </div>
</template>

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

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

export default {
  props: {
    user: {}
  },
  watch: {
    user: {
      deep: true,
      immediate: true,
      handler (nv) {
        nv && this.$nextTick(() => { this.findData(nv.id) })
      }
    }
  },
  methods: {
    // 挂载组件时调用的方法。
    async  findData (userId) {
      if (this.chart) {
        this.chart.destroy()
      }
      this.chart = new Chart({
        padding: [30],
        container: this.$el,
        autoFit: true,
        height: 500
      })
      this.chart.scale('percent', {
        formatter: (val) => {
          val = val * 100 + '%'
          return val
        }
      })
      this.chart.coordinate('theta', {
        radius: 0.75,
        innerRadius: 0.6
      })
      this.chart.tooltip({
        showTitle: false,
        showMarkers: false,
        /**
         * <ul class="g2-tooltip-list">
    <li class="g2-tooltip-list-item">
      <span style="background-color:{color};" class="g2-tooltip-marker"></span>
      <span class="g2-tooltip-name">分数：</span><span class="g2-tooltip-value">{score}分</span>
    </li>
  </ul>
         */
        itemTpl: '<ul class="g2-tooltip-list"><li class="g2-tooltip-list-item">{name}: {value}</li><li class="g2-tooltip-list-item"><span style="background-color:{color};" class="g2-tooltip-marker"></span>题型占比: {percent}</ul>'
      })

      this.chart
        .interval()
        .adjust('stack')
        .position('times')
        .color('item')
        .label('percent', (percent) => {
          return {
            content: (data) => {
            // ${data.item}:
              return `${percent.toFixed(2)}%`
            }
          }
        })
        .tooltip('item*percent*count', (item, percent, count) => {
          return {
            name: item,
            value: count,
            percent: `${percent.toFixed(2)}%`
          }
        })
      this.chart.interaction('element-active')
      const data = await findStatisticDataApi('exercise-qus-type-percent', { noCatch: true, userId })
      this.chart.data(data)
      const mistakesPercent = Math.round(data?.[0]?.total)
      this.chart.annotation().html({
        position: ['50%', '50%'],
        html: `<div style="color:#8c8c8c;font-size: 12px;text-align: center;width: 10em;">练习习题数<br><span style="color:#8c8c8c;font-size:20px">${isNaN(mistakesPercent) ? '--' : mistakesPercent}道</span></div>`,
        alignX: 'middle',
        alignY: 'middle'
      })
      this.chart.render()
    }
  }

}
</script>
