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

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

export default {
  mounted () {
    this.fetch()
  },

  methods: {
    async fetch () {
      const ages = await findStatisticDataApi('basic-trainee-age')

      const data = {
        total: ages.length,
        data: [
          { name: '16至18岁', value: 0, filter: (v) => v > 16 && v <= 18 },
          { name: '18至20岁', value: 0, filter: (v) => v > 18 && v <= 20 }
        ]
      }

      let otherAge = data.total

      for (const { age } of ages) {
        const item = data.data.find((v) => v.filter(age))
        if (item) {
          item.value++
          otherAge--
        }
      }

      data.data.push({ name: '其他年龄', value: otherAge })

      this.draw(data)
    },

    draw ({ total, data }) {
      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 ?? 0)}</span>人</div>`,
        alignX: 'middle',
        alignY: 'middle'
      })
      this.chart.render()
    }
  },

  render (h) {
    return h('div', { class: 'chart', attrs: { 'data-title': '学员年龄统计' } })
  }
}
</script>
