<script>
/**
 * 系统使用时段统计
 */

import { Chart } from '@antv/g2'

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

export default {
  watch: {
    '$parent.active_student': {
      immediate: true,
      handler: 'fetch'
    }
  },

  methods: {
    async fetch (student) {
      const list = await findStatisticDataApi('basic-system-service-period', {
        studentId: student?.id
      })
      const data = [
        { name: '0-4点', value: 0 },
        { name: '4-8点', value: 0 },
        { name: '8-12点', value: 0 },
        { name: '12-16点', value: 0 },
        { name: '16-20点', value: 0 },
        { name: '20-24点', value: 0 }
      ]
      const total = list.reduce((n, c) => {
        data[c.period].value = (c.value *= 1)
        return n + c.value * 1
      }, 0)
      this.draw({ data: total === 0 ? [] : data, total })
    },

    draw ({ data, total }) {
      this.chart?.destroy?.()
      this.chart = new Chart({ padding: [30, 0], container: this.$el, autoFit: true, height: 300 })
      this.chart.scale('value', { formatter: (v) => v * 100 + '%' })
      this.chart.coordinate('theta', { radius: 0.75, innerRadius: 0.6 })
      this.chart.tooltip({
        showTitle: false,
        showMarkers: false,

        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}%</li>
        </ul>`
      })

      this.chart
        .interval()
        .adjust('stack')
        .position('value')
        .color('name')
        .label('value', (v) => ({ content: () => `${(v / total * 100).toFixed(2)}%` }))
        .tooltip('name*value', (name, value) => ({ name, value, percent: (value / total * 100).toFixed(2) }))

      this.chart.interaction('element-active')
      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">${total}</span>次</div>`,
        alignX: 'middle',
        alignY: 'middle'
      })
      this.chart.render()
    }
  },

  render (h) {
    return h('div', { class: 'chart', attrs: { 'data-title': '系统使用时段统计' } })
  }
}
</script>
