import router from "./router";
import store from "./store";
import { Message } from "element-ui";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { getToken } from "@/utils/auth";
import { isRelogin } from "@/utils/request";
import { getUseInfo } from "@/api/login.js";

NProgress.configure({ showSpinner: false });

const whiteList = ["/login"];

router.beforeEach((to, from, next) => {
  NProgress.start();
  if (getToken()) {
    to.meta.title && store.dispatch("settings/setTitle", to.meta.title);
    /* has token*/
    if (to.path === "/login") {
      next({ path: "/" });
      NProgress.done();
    } else {
      if (store.getters.roles.length === 0) {
        isRelogin.show = true;
        // 判断当前用户是否已拉取完user_info信息
        store.dispatch("GetInfo").then((res) => {
          isRelogin.show = false;
          store.dispatch("GenerateRoutes").then((accessRoutes) => {
            // 根据roles权限生成可访问的路由表
            // console.log(res);
            router.addRoutes(accessRoutes); // 动态添加可访问路由表
            //刷新之后,要去的路由肯定是自己已经保存过的新路由
            let refresh = "";
            if (store.state.user.new1.indexOf(to.path) != -1) {
              refresh = to.path;
            }
            // console.log(to.path);
            //进入添加的第一个路由
            next({ path: refresh || res[0].path });
          });
        });
        // .catch((err) => {
        //   store.dispatch("LogOut").then(() => {
        //     Message.error(err);
        //     next({ path: "/" });
        //   });
        // });
      } else {
        if (
          store.state.user.old1.indexOf(to.path) != -1 &&
          store.state.user.new1.indexOf(to.path) == -1
        ) {
          next({ path: "/404" });
        } else {
          next();
        }
      }
    }
  } else {
    // 没有token
    if (window.location.href.includes("?code")) {
      // console.log(window.location.href)
      var reg = new RegExp(/[?&]code=([^&#]+)/);
      var r = window.location.href.match(reg);
      // console.log('有code')
      // const code = window.location.href.split("?")[1].split('=')[1];
      const code = r && r[1];
      // console.log(code)
      getUseInfo({ code: code })
        .then((user) => {
          // console.log(user, "用户信息");
          localStorage.setItem("isGovernmentAffairsNetwork", "1");
          localStorage.setItem("G_USER_INFO", JSON.stringify(user));
          store
            .dispatch("LoginNoCaptcha", {
              username: "admin",
              password: "admin@123Jichuang",
            })
            .then((res) => {
              next("/home");
            });
        })
        .catch((err) => {
          location.href = process.env.VUE_APP_SSO_LOGIN_N;
        });
    } else {
      // console.log('没code')
      if (whiteList.indexOf(to.path) !== -1) {
        // 在免登录白名单，直接进入
        next();
        NProgress.done();
      } else {
        location.href = process.env.VUE_APP_SSO_LOGIN_N;
        NProgress.done();
      }
    }
  }
});

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