import router from "./router";
import store from "./store";
import { Message } from "element-ui";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { isRelogin } from "@/utils/request";

NProgress.configure({ showSpinner: false });

router.beforeEach((to, from, next) => {
  NProgress.start();
  to.meta.title && store.dispatch("settings/setTitle", to.meta.title);
  if (store.getters.permissions.length === 0) {
    isRelogin.show = true;
    // 判断当前用户是否已拉取完user_info信息
    store
      .dispatch("GetPermissions")
      .then((res) => {
        isRelogin.show = false;
        store.dispatch("GenerateRoutes", res).then(() => {
          next({ ...to, replace: true });
        });
      })
      .catch((err) => {
        console.error(err);
        store.dispatch("LogOut").then(() => {
          Message.error(err);
          next({ path: "/" });
        });
      });
    return;
  }

  next();
});

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