import router from "./router"
import { getToken } from "@/utils/auth"
import { useUserStore } from "@/store/user.js"
import { useSettingStore } from "@/store/settings.js"
import { usePermissionStore } from "@/store/permission.js"
import { dynamicRoutes } from "@/router/dynamicRoutes"

const whiteList = ["/login", "/yh", "/ssoyh"]
router.beforeEach((to, from, next) => {
    if (getToken()) {
        to.meta.title && useSettingStore().setTitle(to.meta.title)
        if (useUserStore().roles.length === 0) {
            useUserStore().RefreshInfo().then(res => {
                usePermissionStore().generateRoutes().then(accessRoutes => {
                    accessRoutes.forEach(item => router.addRoute(item))
                    router.addRoute({
                        path: "/:pathMatch(.*)*",
                        name: "notFound",
                        redirect: "/notfound"
                    })
                    next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
                })
            })
        } else {
            next()
        }
    } else { // 登录
        // 白名单放行
        if (whiteList.indexOf(to.path) !== -1) {
            next()
        } else {
            next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
        }
    }
})

router.afterEach(() => {

})

router.onError((error) => {
    console.warn("路由错误", error.message)
})