import { useUserStore } from '@/store/modules/user.js'
import { usePermissionStore } from '@/store/modules/permission.js'
import { NOT_FOUND_ROUTE, REDIRECT_ROUTE } from '@/router/routes'
import { getQuestion } from '@/utils/question.js'
import { getQuestionList } from '@/utils/dictionary.js'
import { getToken } from '@/utils/token'

const WHITE_LIST = ['/login', '/redirect']
export function createPermissionGuard(router) {
  const userStore = useUserStore()
  const permissionStore = usePermissionStore()
  router.beforeEach(async(to, from, next) => {
    const token = getToken()
    if (token) {
      if (to.path === '/login') {
        next({ path: '/' })
      } else {
        const hasUsers = !!Object.keys(userStore.userInfoMsg).length
        const hasRoutes = !!permissionStore.permissionRoutes.length
        const hasQuestions = getQuestion()
        if (!hasUsers) { await userStore.getUserInfo() }
        if (!hasQuestions) { await getQuestionList() }
        if (hasRoutes) {
          next()
        } else {
          try {
            const routes = await permissionStore.generateRoutes()
            routes.forEach((item) => {
              router.addRoute(item)
            })
            router.addRoute(NOT_FOUND_ROUTE)
            router.addRoute(REDIRECT_ROUTE)
            next({ ...to, replace: true })
          } catch (error) {
            // removeToken()
            // $message.error(error)
            next({ path: '/login', query: { ...to.query, redirect: to.path }})
          }
        }
      }
    } else {
      if (WHITE_LIST.includes(to.path)) {
        next()
      } else {
        next({ path: '/login', query: { ...to.query, redirect: to.path }})
      }
    }
  })
}
