import router from "@/router";
import { useUserStoreHook } from "@/store/modules/user";
import { usePermissionStoreHook } from "@/store/modules/permission";

import NProgress from "nprogress";
import "nprogress/nprogress.css";
NProgress.configure({ showSpinner: false }); // 进度条

const permissionStore = usePermissionStoreHook();

// 白名单路由
const whiteList = ["/login"];

router.beforeEach(async (to, from, next) => {
  NProgress.start();
  const hasToken = localStorage.getItem("accessToken");
  // 已登录
  if (hasToken) {
    // 已登录访问/login，跳转首页
    if (to.path === "/login") {
      next({ path: "/" });
      NProgress.done();
    } else {
      const userStore = useUserStoreHook();
      // 未加载过动态路由
      if (!userStore.routeStatus) {
        try {
          const role = await userStore.getInfo();
          const accessRoutes = await permissionStore.generateRoutes(role);
          accessRoutes.forEach((route) => {
            router.addRoute(route);
          });
          // 设置路由加载标志
          userStore.setRouteStatus(true);
          next({ ...to, replace: true });
        } catch (error) {
          // 移除 token 并跳转登录页
          await userStore.resetToken();
          next(`/login?redirect=${to.path}`);
          NProgress.done();
        }
      } else {
        next();
      }
    }
  }
  // 未登录
  else {
    // 未登录可以访问白名单页面
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      next(`/login?redirect=${to.path}`);
      NProgress.done();
    }
  }
});

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