<template>
  <router-view v-slot="{ Component }">
    <!-- <keep-alive>
      <component v-if="route.meta.keepAlive" :is="Component" />
    </keep-alive> -->
    <component :is="Component" />
    <fee-popup/>
    <vip-popup/>
  </router-view>
</template>
<script lang="ts">
import { close } from '/src/helpers/loading'
import qs from 'query-string'
import request from '/src/helpers/request'
import { getRequestHostname, setVoiceInit } from '/src/helpers/utils'
import FeePopup from '/src/components/fee'
import VipPopup from '/src/components/vip'
import appstate, { IAuth, IAuthKey } from '/src/state'
import './vue-tsx-shim.d'
import './app.d'

const getHasAuth = (list: any[]) => {
  let auths: IAuth = {}
  for (const item of list) {
    const code: IAuthKey = item.code
    auths[code] = item
    if (item.memberPrivilegesItems?.length) {
      auths = {
        ...auths,
        ...getHasAuth(item.memberPrivilegesItems)
      }
    }
  }
  return auths
}

close()
export default {
  name: 'App',
  components: {
    'fee-popup': FeePopup,
    'vip-popup': VipPopup,
  },
  created() {
    setVoiceInit()
  },
  methods: {
    async FeychUser() {
      let saveSibiectId: number = parseFloat(sessionStorage.getItem('subjectId') || '0')
      let subjectId = 0
      appstate.subjectLoading = true
      try {
        if (getRequestHostname() === '/api-teacher') {
          const res = await request.get(`/teacher/queryUserInfo`)
          appstate.user = res.data
          appstate.tenantId = res.data.tenantId
          appstate.organId = res.data.teacherOrganId
          subjectId = Math.floor(saveSibiectId || res.data.subjectId.split(',')[0])
        } else if (getRequestHostname() === '/api-web') {
          const res = await request.get(`/employee/queryUserInfo`)
          appstate.user = res.data
          appstate.tenantId = res.data.tenantId
          appstate.organId = res.data.organIdList
          if (saveSibiectId) {
            subjectId = saveSibiectId
          }
        } else {
          const res = await request.get(`/student/queryUserInfo`)
          console.log(subjectId, 11111111111)
          appstate.user = res.data
          const student = res.data?.student
          appstate.tenantId = student.tenantId
          appstate.organId = student.organId
          subjectId = Math.floor(saveSibiectId || student.subjectIdList.split(',')[0])
          this.subjectFormat(subjectId, student.subjectNames, student.extSjectNamesMap)
        }

        // 学生端萨克斯转中音萨克斯
        if(getRequestHostname() == '/api-student') {
          subjectId = subjectId == 5 ? subjectId = 6 : subjectId
        }
        appstate.subjectId = subjectId
        appstate.origanSubjectId = subjectId
      } catch (error) {
        console.log(error)
      }
      appstate.subjectLoading = false
    },
    // 合并声部数据
    subjectFormat(subjectId: number, subjectName: string, extSubjectIds: any) {
      let inExt = false // 主声部是否在扩展中

      let tempExtSubject = []
      if(extSubjectIds) {
        for(let i in extSubjectIds) {
          if(subjectId === Number(i)) {
            inExt = true
          }
          tempExtSubject.push({
            id: Number(i),
            name: extSubjectIds[i]
          })
        }
      }
      // 是否需要添加主声部
      if(inExt) {
        appstate.extSubjectIds = tempExtSubject
      } else {
        appstate.extSubjectIds = [{id: subjectId, name: subjectName}, ...tempExtSubject]
      }
    },
  },
  async mounted() {
    const parseSearch: any = qs.parse(location.search)
    const hashSearch = qs.parse(location.hash.split('?')[1])
    const Authorization: string = parseSearch.Authorization || hashSearch.Authorization || ''
    const subjectId: string = parseSearch.subjectId || hashSearch.subjectId || ''
    sessionStorage.setItem('Authorization', Authorization)
    sessionStorage.setItem('subjectId', subjectId)
    try {
      await this.FeychUser()
    } catch (error) {}
    const allAutth = appstate.user?.userPrivileges ? getHasAuth(appstate.user.userPrivileges) : []
    const authKeys = Object.keys(allAutth)
    for (const key in appstate.modular) {
      if (Object.prototype.hasOwnProperty.call(appstate.modular, key)) {
        if (getRequestHostname() === '/api-student') {
          (appstate as any).modular[key] = authKeys.includes(key)
        } else {
          (appstate as any).modular[key] = true
        }
      }
    }
  },
}
</script>
