<template>
  <div style="width:200px;height:200px;">
  </div>
</template>

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

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

export default {
  props: {
    exam: {
      default: null
    }
  },
  watch: {
    exam: {
      handler (nv) {
        this.findData(nv)
      }
    }
  },
  methods: {
    async findData (exam) {
      if (this.chart) {
        this.chart.destroy()
      }
      this.chart = new Chart({
        padding: [30],
        container: this.$el,
        autoFit: true,
        height: 300
      })
      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('scorePercent')
        .color('name')
        .label('scorePercent', (percent) => {
          return {
            content: (data) => {
            // ${data.item}:
              return `${(percent * 100).toFixed(2)}%`
            }
          }
        })
        .tooltip('name*scorePercent*score', (item, percent, count) => {
          return {
            name: item,
            value: count + '分',
            percent: `${(percent * 100).toFixed(2)}%`
          }
        })

      this.chart.interaction('element-active')
      const data = await findStatisticDataApi('exam-details-question-score-count-percent', { exam })
      this.chart.data(data)
      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">${(data?.[0]?.totalScore ?? 0)}</span></div>`,
        alignX: 'middle',
        alignY: 'middle'
      })
      this.chart.render()
    }
  },

  mounted () {
    this.findData()
  }
}
</script>
