<template>
  <TrainChunkBox style="150px" title="训练用时统计">
    <div class="user-position" ref="userPosition"></div>
  </TrainChunkBox>
</template>

<script>
import TrainChunkBox from '@/views/training/training/components/train-chunk-box.vue'
import { getUserTrainDurationApi } from '@/api/training/train-evealuation'
import { Chart } from '@antv/g2'
export default {
  components: { TrainChunkBox },
  props: {
    userId: {
      type: Number,
      default: null
    }
  },
  data () {
    return {
      baseData: null
    }
  },
  created () {},
  methods: {
    async getBaseData () {
      if (!this.userId) return
      const { data } = await getUserTrainDurationApi(this.userId)
      data.forEach(element => {
        element.percent = Math.round(element.percent)
      })
      // data.reverse()
      this.baseData = data
      this.init()
    },
    init () {
      this.chart?.destroy()
      const chart = new Chart({
        container: this.$refs.userPosition,
        autoFit: true,
        height: 500
      })
      chart.data(this.baseData)
      chart.coordinate('theta', {
        radius: 0.75
      })
      chart.legend({ position: 'right' })
      chart.tooltip('name*value', (name, value) => {
        return {
          name,
          value: Math.round(value)
        }
      })
      chart.tooltip({
        showTitle: false,
        showMarkers: false,
        itemTpl: `<ul class="g2-tooltip-list">
          <li class="g2-tooltip-list-item">{name}</li>
          <li class="g2-tooltip-list-item"><span style="background-color:{color};" class="g2-tooltip-marker"></span>总数占比: {value}%</li>
        </ul>`
      })
      chart
        .interval()
        .adjust('stack')
        .position('percent')
        .color('title')
        .style({ opacity: 0.4 })
        .state({
          active: {
            style: (element) => {
              const shape = element.shape
              return {
                matrix: Util.zoom(shape, 1.1)
              }
            }
          }
        })
        .label('type', (val) => {
          return {
            offset: -20,
            content: (obj) => {
              return Math.round(obj.percent) + '%'
            },
            autoRotate: false
          }
        })
      chart.interaction('element-single-selected')

      chart.render()
      this.chart = chart
    }
  },
  watch: {
    userId () {
      this.getBaseData()
    }
  }
}
</script>

<style lang="scss" scoped>
.user-position {
  height: 100%;
  width: 100%;
  padding: 10px;
}
</style>
