// 全站权限配置
import router from "./router";
import store from "./store";
import { validatenull } from "@/utils/validate";
import { ElMessage } from "element-plus";
import { formatRoutes, setTitle } from "@/router/Routermethods";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style

NProgress.configure({ showSpinner: false });

let flag = true;

router.beforeEach(async (to, from, next) => {
  NProgress.start();
  if (store.getters.access_token) {
    if (flag) {
      flag = false;
      await store.dispatch("GetMenu", { type: true }).then((res) => {
        formatRoutes(res);
        next(to.path);
      });
    } else {
      const meta = to.meta || {};
      if (to.path === "/login" || to.path === "/shuju") {
        next({ path: "/" });
      } else {
        const value = to.query.src || to.fullPath;
        const label = to.query.name || to.name;
        if (meta.isTab !== false && !validatenull(value) && !validatenull(label)) {
          store.commit("ADD_TAG", {
            label: label,
            value: value,
            params: to.params,
            query: to.query
          });
        }
        next();
      }
    }
  } else {
    if (to.path === "/login" || to.path === "/shuju") {
      next();
    } else {
      // if (to.path !== "/") {
      //   ElMessage.warning("请先登录后再访问其他页面!");
      // }
      next(`/login`); // 否则全部重定向到登录页
    }
    NProgress.done();
  }
});

router.afterEach(() => {
  let title = store.getters.tag.label;
  if (!store.getters.access_token) title = undefined;
  setTitle(title);
  NProgress.done();
});
