import Vue from "vue";
import Router from "vue-router";

import Home from "@/views/Home.vue";
import NotFound from "@/views/404.vue";
import login from "@/modules/login/router";
import admin from "@/modules/admin/router";

import college from "./modules/college/router";
import base from "./modules/base/router";
import student from "./modules/student/router";

// ignore NavigationDuplicated. https://github.com/vuejs/vue-router/issues/2881
const originalPush = Router.prototype.push;
Router.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject)
    return originalPush.call(this, location, onResolve, onReject);
  try {
    return originalPush.call(this, location).catch(err => err);
  } catch (error) {
    console.log(error);
  }
};
// end ignore

Vue.use(Router);

// history:
// location / {
//   try_files $uri $uri/ /index.html;
// }
let router = new Router({
  // mode: "history",
  routes: [
    {
      path: "/",
      name: "Index",
      redirect: { name: "Login" }
    },
    {
      path: "/home",
      name: "Home",
      component: Home,
      children: [...college, ...base]
    },
    { ...login },
    { ...admin },
    ...student,
    {
      path: "*",
      name: "404",
      component: NotFound,
      meta: {
        noRequire: true
      }
    }
  ]
});

// route interceptor
router.beforeEach((to, from, next) => {
  const token = Vue.ls.get("token");
  if (to.meta.noRequire) {
    next();
  } else {
    // 需要登录的路由
    if (token) {
      next();
    } else {
      // 登录失效的处理
      Vue.ls.clear();
      const ipDomainCode = window.sessionStorage.getItem("ipDomainCode");
      if (ipDomainCode) {
        next({ name: "Login", query: { code: ipDomainCode } });
      } else {
        next({ name: "Login" });
      }
    }
  }
});

export default router;
