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

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

export default {
  methods: {
    async findData () {
      const data = await findStatisticDataApi('study-course-hour')
      // 添加文本标注
      data.forEach((item) => {
        this.chart
          .annotation()
          .text({
            position: [item.type, item.value],
            content: item.value + '分钟',
            style: {
              textAlign: 'center'
            },
            offsetY: -5
          })
          .text({
            position: [item.type, item.value],
            style: {
              textAlign: 'center'
            },
            offsetY: -12
          })
      })

      this.chart.data(data)

      this.chart.render()
    }
  },

  mounted () {
    this.chart = new Chart({
      container: this.$el,
      autoFit: true,
      height: 500,
      padding: [50, 20, 50, 20]
    })
    // this.chart.scale('value', {
    //   formatter: (val) => {
    //     val = (val * 100).toFixed(2) + '%'
    //     return val
    //   }
    // })
    this.findData()

    this.chart.axis('type', {
      tickLine: {
        alignTick: false
      }
    })
    this.chart.axis('value', false)

    this.chart.tooltip({
      showTitle: false,
      showMarkers: false,
      itemTpl: '<li class="g2-tooltip-list-item">{name}<div><span style="background-color:{color};" class="g2-tooltip-marker"></span>时间: {value}</div></li>'
    })
    this.chart.interval().position('type*value').tooltip('type*value', (type, value) => {
      return {
        name: type,
        value: value + '分钟'
      }
    })
  },

  render (h) {
    return h('div', { class: 'chart', attrs: { 'data-title': '课程学习时长统计' } })
  }
}
</script>
