import Vue from "vue";
import Router from "vue-router";
import loginRouter from "./login";
import homeRouter from "./home";
import portalRouter from "./portal";
import centerRouter from "./center";
import loanRouter from "./loan";
import queryRouter from "./query";
import settingRouter from "./setting";
import agreementRouter from "./agreement";
import utils from 'utils/utils.js'

Vue.use(Router);

const router = new Router({
  mode: "history",
  routes: [
    ...loginRouter,
    ...homeRouter,
    ...portalRouter,
    ...centerRouter,
    ...loanRouter,
    ...queryRouter,
    ...settingRouter,
    ...agreementRouter,
    {
      path: "/404",
      name: "404",
      component: () => import("components/404.vue")
    },
    {
      path: "*",
      redirect: "/404"
    }
  ],
  scrollBehavior(to, from, savedPosition) {
    return {
      x: 0,
      y: 0
    }
  }
});

router.beforeEach((to, from, next) => {
  if (to.meta.title) {
    document.title = to.meta.title;
  }
  if (to.matched.some(res => res.meta.requireAuth)) {
    // 判断是否需要登录权限
    if (utils.getCookie("token")) {
      // 判断是否登录
      let emailActiveFlag = JSON.parse(localStorage.getItem("initVuex")).userInfo.loginInfo.emailActiveFlag;

      if (!emailActiveFlag && emailActiveFlag != undefined && emailActiveFlag != null) {
        next("/emailActivation");
      } else {
        next();
      }

    } else {
      // 没登录则跳转到登录界面
      next("/login");
    }
  } else {
    next();
  }
});

export default router;
