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(async (to, from, next) => {
    if (!getToken()) {
        // 白名单放行
        if (whiteList.indexOf(to.path) !== -1) next();
        else next(`/login?redirect=${to.fullPath}`); // 否则全部重定向到登录页
        return false;
    }

    if (to.path === "/login") {
        next(to.query.redirect || "/");
        return false;
    }

    to.meta.title && useSettingStore().setTitle(to.meta.title);
    if (!usePermissionStore().routes.length) {
        await useUserStore().RefreshInfo();
        const accessRoutes = await usePermissionStore().generateRoutes();
        accessRoutes.forEach(item => router.addRoute(item));
        router.addRoute({
            path: "/:pathMatch(.*)*",
            name: "notFound",
            redirect: "/notfound"
        });

        next(to);
        return false;
    }

    next();
})

router.afterEach(() => { });

router.onError((error) => {
    ElNotification.error({
        title: "路由错误",
        message: error.message
    });
});