import NProgress from "nprogress";
import router from "./index";
import store from "../store";

//  获取角色信息，根据用户权限动态加载路由
router.beforeEach((to, from, next) => {
  NProgress.start();
  if (to.path === "/login") {
    next();
  } else {
    if (store.getters.token) {
      if ((to.path == '/device' && from.path == '/deviceLog') || (to.path == '/device' && from.path == '/deviceError')) {
        to.query.back = true
      }
      next();
    } else {
      if (store.getters.info && store.getters.addRouters) {
        store.commit("setToken", "isLogin");
        let userInfo = store.getters.info;
        let authorityRouterObj = userInfo.permissions.filter((item) => {
          return item.roleName == userInfo.showRoleName;
        });
        store.commit("setRouters", [...authorityRouterObj[0]?.authorityRouter]);
        store.commit("setInfo", { ...userInfo });
        store.getters.addRouters.forEach((res) => {
          router.addRoute(res);
        });
        router.addRoute({
          path: "*",
          redirect: "/404",
          hidden: true,
          children: [],
        });
        next({ path: to.fullPath });
      } else {
        if (store.getters.code) {
          next();
        } else {
          if (to.path === "/login") {
            next();
          } else {
            next({ path: "/login" });
          }
        }
      }
    }
  }
});

router.afterEach(() => {
  NProgress.done();
});
router.onError((error) => {
  const pattern = /Loading chunk (\d)+ failed/g;
  const isChunkLoadFailed = error.message.match(pattern);
  const targetPath = router.history.pending.fullPath;
  if (isChunkLoadFailed) {
    router.replace(targetPath);
  }
});
