import { createRouter, createWebHashHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import { asyncRoutes, constantRoutes } from './routes'
import { getUserRole, user } from '~/store/index'
const adminRoleId = '69'
// const isAdmin = user.value.user_role_id == '69' ? true : false;

console.log('constantRoutes :>> ', constantRoutes)
console.log('asyncRoutes :>> ', asyncRoutes)

const router = createRouter({
  history: createWebHashHistory(),
  routes: constantRoutes,
  // routes: [...constantRoutes, ...asyncRoutes],
})

export default router

export const FilteredRoutesMap = ref(JSON.parse(localStorage.getItem('filteredRoutesMap') ?? '{}'))
export const asyncFilteredRoutes = ref<RouteRecordRaw[]>(JSON.parse(localStorage.getItem('asyncFilteredRoutes') ?? '[]'))

watch(
  () => FilteredRoutesMap.value,
  (val) => {
    const isAdmin = user.value.user_role_id == adminRoleId

    if (val === null) { localStorage.removeItem('filteredRoutesMap') }
    else {
      localStorage.setItem('filteredRoutesMap', JSON.stringify(val))
      function handleFilterRoutes(routes: RouteRecordRaw[]): RouteRecordRaw[] {
        // console.log(routes, 888)
        const res: RouteRecordRaw[] = []
        routes.forEach((route) => {
          const tmp = { ...route }

          if (val[tmp.name!] || (isAdmin && tmp.name !== 'PTSZ_XXSZ_XD')) {
            // if (!isAdmin) {
            //   tmp.meta.checkList = requestRoutes[tmp.name]?.split(',')
            // }
            // RoutesCheck[tmp.name] = tmp.meta.checkList
            if (tmp.children)
              tmp.children = handleFilterRoutes(tmp.children)

            res.push(tmp)
          }
          // else if(!tmp?.meta?.checkList){
          //   if (tmp.children) {
          //     tmp.children = handleFilterRoutes(tmp.children)
          //   }
          //   res.push(tmp)
          // }
        })
        return res
      }
      // user.value.user_role_id === '69' ? asyncRoutes :
      asyncFilteredRoutes.value = (handleFilterRoutes(asyncRoutes)).sort((a, b) => (a?.meta?.sort as number) - (b?.meta?.sort as number))
      asyncFilteredRoutes.value.forEach((route: RouteRecordRaw) => {
        router.addRoute(route)
      })
    }
  },
  {
    immediate: true,
  },
)

router.beforeEach((to, from) => {
  console.groupCollapsed(`%c${from.name?.toString()} => ${to.name?.toString()}`, 'color:#0ff')
  console.log(`%c${from.meta.title} => ${to.meta.title}`, 'color:#0cc')
  console.groupEnd()
  console.log('user.value :>> ', user.value)
  if (to.name == 'login' && from.name) {
    window.location.reload()
    window.localStorage.clear()
  }
  if (user.value?.token) {
    if (to.name === 'init') {
      const UserRole = getUserRole()
      console.log('UserRole :>> ', UserRole)
      const redirectName = UserRole === 'qxgly' ? 'HOME' : UserRole === 'xgly' ? 'PTSZ_XXSZ' : UserRole === 'teacher' ? 'yhzx_grzx' : 'login'

      const isAdmin = user.value.user_role_id == adminRoleId

      if (router.hasRoute(redirectName) || isAdmin) {
        return {
          name: redirectName,
        }
      }
      else {
        return {
          name: 'noSet',
        }
      }
    }
    else {
      if (to.meta.externalLink) {
        const toLink = to.meta.externalLink.endsWith('&') ? `${to.meta.externalLink}token=${user.value.token}` : to.meta.externalLink
        window.open(toLink, '_blank')
      }
      else {
        return true
      }
    }
  }

  if (!user.value?.token && to.name !== 'login')
    return { name: 'login' }
})
