<script>
import VTitle from './components/VTitle.vue'
import VCard from './components/VCard.vue'
import VChartTab from './components/VChartTab.vue'

import Admin from './charts/admin'
import Teacher from './charts/teacher'
import Student from './charts/student'
import { findStatisticDataApi } from '@/api/statistic'

const charts = {}
const options = { Admin, Teacher, Student }

for (const name in options) {
  for (const v of options[name]) {
    if (v.chart) {
      v.key ??= v.chart.replace('-', '_')
      v.componentName = `${name}-${v.chart}`.replace(/-(.)/g, (m, r) => r.toUpperCase())
      charts[v.componentName] = () => import(`./charts/${name.toLowerCase()}/${v.chart}/index.vue`)
    }

    if (v.key) v.data = null
  }
}

export default {
  name: 'Statistic',

  components: { VTitle, VCard, ...charts },

  data: () => ({ modelList: [], actived: null }),

  provide: {
    watchComponentVisible (el, fn = () => {}) {
      this.intersectionObserver ??= new IntersectionObserver(([{ target, isIntersecting }], obs) => {
        if (isIntersecting) {
          obs.unobserve(target)
          el.visibled()
          delete el.visibled
        }
      })

      el.visibled = fn

      this.intersectionObserver.observe(el)
    }
  },

  created () {
    this.modelList = options[Object.keys(options)[this.$store.user.baseRole - 1]]
    this.findData()
  },

  methods: {
    async findData () {
      window.__CHART_MODULE__ = 'index'
      const data = await findStatisticDataApi('index')
      this.modelList.forEach((v) => {
        if (v.key) v.data = data[v.key]
      })
    }
  },

  render (h) {
    const childs = []
    for (let i = 0, v; (v = this.modelList[i]); i++) {
      childs.push(
        h(v.model, { attrs: { 'data-index': i }, props: { options: v } })
      )
    }

    if (this.actived) {
      if (!this.actived.hideTab) childs.push(h(VChartTab))

      childs.push(h(this.actived.componentName, { class: 'chart_layout' }))
    }
    return h('div', { class: 'statistic' }, childs)
  }
}
</script>

<style lang="scss">
.statistic {
  display: flex;
  flex-wrap: wrap;

  .block {
    flex-basis: 100%;
  }

  h2 {
    font-size: 15px;
    color: #3d3d3d;
    font-weight: bold;
  }

  .chart_layout {
    display: flex;
    flex-wrap: wrap;
    flex-basis: 100%;

    .chart {
      margin-right: 20px;
      margin-bottom: 20px;
      width: 23%;
      min-width: 180px;
      height: 300px;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      overflow: hidden;
      position: relative;

      &::before {
        content: attr(data-title);
        position: absolute;
        left: 12px;
        top: 12px;
        font-size: 15px;
        color: #3d3d3d;
        font-weight: bold;
      }
    }
  }

  .box1 {
    margin: 6px;
    width: 200px;
    height: 100px;
    background-color: #000;
  }

  .g2-html-annotation {
    pointer-events: none !important;
  }

}
</style>
