import router from "./router";
import store from "./store";
import { Message } from "element-ui";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import Cookies from "js-cookie";

NProgress.configure({ showSpinner: false });

router.beforeEach((to, from, next) => {
  NProgress.start();
  to.meta.title && store.dispatch("settings/setTitle", to.meta.title);
  const cookieToken = Cookies.get('JSESSIONID')
  console.log('cookieToken=', cookieToken)
  if (cookieToken) {
    if (store.getters.permissions.length === 0) {
      store
      .dispatch("GetPermissions")
      .then((res) => {
        store.dispatch("GenerateRoutes", res).then(() => {
          next({ ...to, replace: true });
        });
      })
      .catch((err) => {
        console.error(err);
        store.dispatch("LogOut").then(() => {
          Message.error(err);
          next({ path: "/" });
        });
      });
      return
    }
  } else {
    location.href = process.env.VUE_APP_ADMIN_LOGIN_URL
  }
  next();
});

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