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

import Home from "./views/Home.vue";
import HomePage from "./views/HomePage.vue";
import NotFound from "./views/404.vue";

import login from "./modules/login/router";
// module-example
import base from "./modules/base/router";
import exam from "./modules/exam/router";
import print from "./modules/print/router";
import customer from "./modules/customer/router";
import stmms from "./modules/stmms/router";
import analysis from "./modules/analysis/router";
// admin
import admin from "./modules/admin/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);

let router = new Router({
  routes: [
    {
      path: "/",
      name: "Index",
      redirect: { name: "Login" }
    },
    {
      path: "/home/:nextRouter?",
      name: "Home",
      component: Home,
      children: [
        {
          path: "/home-page",
          name: "HomePage",
          component: HomePage
        },
        ...base,
        ...exam,
        ...print,
        ...customer,
        ...stmms,
        ...analysis
      ]
    },
    { ...login },
    { ...admin },
    {
      path: "*",
      name: "404",
      component: NotFound
    }
    // [lazy-loaded] route level code-splitting
    // {
    //   path: "/about",
    //   name: "about",
    //   // this generates a separate chunk (about.[hash].js) for this route
    //   // which is lazy-loaded when the route is visited.
    //   component: () =>
    //     import(/* webpackChunkName: "about" */ "./views/About.vue")
    // }
  ]
});

// route interceptor
router.beforeEach((to, from, next) => {
  const token = Vue.ls.get("token");
  if (to.meta.noRequire) {
    next();
    return;
  }

  if (!token) {
    // 登录失效的处理
    Vue.ls.clear();
    next({ name: "Login" });
    return;
  }

  next();
});

export default router;
