<script>
/**
 * 资源数量占比统计
 */

import { Chart } from '@antv/g2'

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

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

  methods: {
    async fetch () {
      const list = await findStatisticDataApi('res-quantity')
      let total = 0
      const data = list.map((v) => {
        total += (v.count *= 1)
        return { name: ACCEPT_MAP[v.type].name, value: v.count }
      })
      this.draw({ total, 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}</span>个</div>`,
        alignX: 'middle',
        alignY: 'middle'
      })
      this.chart.render()
    }
  },

  render (h) {
    return h('div', { class: 'chart', attrs: { 'data-title': '资源数量占比统计' } })
  }
}
</script>
