import router from '@/router'
import { WHITE_LIST, LOGIN_URL } from '@/constants'
import { useAuthStore, useUserStore } from '@/stores'
import { getToken, removeToken } from '@/utils/token'
import { type RouteRecordRaw } from 'vue-router'
import { useNProgress } from '@/utils/nprogress'
const { start, done } = useNProgress()
export const setupAuthRoutes = () => {
  router.beforeEach(async (to, _from, next) => {
    start()
    if (getToken()) {
      if (to.path.toLocaleLowerCase() === LOGIN_URL) {
        // 如果已登录，跳转到首页
        next({ path: '/' })
        return
      }
      const authStore = useAuthStore()
      const userStore = useUserStore()
      const hasRoles = userStore.roles && userStore.roles.length > 0
      if (hasRoles) return next()
      await userStore.getUserInfo()
      await authStore.setAuthRoutes()
      const authRoutes = authStore.getAuthRoutes
      authRoutes.forEach((route: RouteRecordRaw) => router.addRoute(route))
      return next({ ...to, replace: true })
    } else {
      if (WHITE_LIST.includes(to.path)) return next()
      removeToken()
      // 重定向登录页面
      next(`/login?redirect=${to.path}`)
    }
  })
  router.afterEach(() => {
    done() // 结束Progress
  })
}
