/**version-1.0*/
import router from "@base/router";
import store from "./store";
import {
  Message
} from "element-ui";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style
import {
  getToken
} from "./utils/auth"; // get token from cookie
import settingConfig from "@/settings";

import {
  saveAccessMenuLog
} from "./api/user";
import indexUtil from "./utils/index.js"

NProgress.configure({
  showSpinner: false,
}); // NProgress Configuration

const whiteList = [
  "/login",
  "/auth-redirect",
  "/report/vform/out_render",
  "/report/xform/out_render",
]; // no redirect whitelist

router.beforeEach((to, from, next) => {
  // start progress bar
  NProgress.start();

  store.dispatch("user/initLoginConfig").then(() => {
    const hasToken = getToken();

    if (hasToken) {
      if (to.path === "/login") {
        // if is logged in, redirect to the home page
        next({
          path: "/",
        });
        NProgress.done(); // hack: https://github.com/PanJiaChen/vue-element-admin/pull/2939
      } else {
        // determine whether the user has obtained his permission roles through getInfo
        const hasRoles =
          store.getters.roles &&
          store.getters.roles.length > 0;
        if (to.meta.checkToken === false || hasRoles) {
          next();
        } else {
          try {
            store
              .dispatch("user/getInfo2")
              .then((res) => {
                if (res && res.type == "success") {
                  store
                    .dispatch("permission/generateRoutes2", res.objx)
                    .then((accessRoutes) => {
                      // 根据roles权限生成可访问的路由表
                      // router.addRoutes(accessRoutes); // 动态添加可访问路由表
                      next({
                        ...to,
                        replace: true,
                      }); // hack方法 确保addRoutes已完成
                    });
                } else {
                  store.dispatch("user/resetToken").then(() => {
                    next("/login");
                    NProgress.done();
                  });
                }
              })
              .catch((error) => {
                store.dispatch("user/resetToken").then(() => {
                  next("/login");
                  NProgress.done();
                });
              });
          } catch (error) {
            // remove token and go to login page to re-login
            //await store.dispatch('user/resetToken')
            Message.error(error || "Has Error");
            next("/login");
            NProgress.done();
          }
        }
      }
    } else {
      /* has no token*/
      if (to.meta.checkToken === false) {
        next();
      } else if (whiteList.indexOf(to.path) !== -1) {
        // in the free login whitelist, go directly
        next();
      } else {
        // other pages that do not have permission to access are redirected to the login page.
        next("/login");
        NProgress.done();
      }
    }
  })


});

router.onError((error) => {
  // finish progress bar
  console.error(error);
  NProgress.done();
});

router.afterEach((to, from, next) => {
  if (settingConfig.i18nEnabled === true && to.path !== "/login" && to.meta.checkToken !== false) {
    indexUtil.initI18nMessage("business");
  }
  if (settingConfig.accessLogEnabled === true && to.meta.title && to.name !== 'home') {
    let visitedViews = store.getters.visitedViews;
    let item = visitedViews.find(visitedView => visitedView.fullPath == to.fullPath)
    if (!item) {
      let treePathName = to.meta.treePathName || "";
      let content = treePathName ?
        treePathName + to.meta.title + "," :
        to.meta.title;
      saveAccessMenuLog({
        data: {
          businessCode: content,
          content: content,
          path: to.path
        },
      });
    }
  }
  NProgress.done();
});
