import { useUserStore } from '@/store/modules/user'
import { usePermissionStore } from '@/store/modules/permission'
import { NOT_FOUND_ROUTE, REDIRECT_ROUTE } from '@/router/routes'
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()
    const token = true
    if (token) {
      if (to.path === '/login') {
        next({ path: '/' })
      } else {
        // const hasRoutes = !!permissionStore.permissionRoutes.length
        /* 暂无权限和菜单 */
        const hasRoutes = true
        if (hasRoutes) {
          next()
        } else {
          try {
            // await userStore.getUserInfo()
            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 }})
      }
    }
  })
}
