import Vue from "vue";
import VueRouter from "vue-router";
import store from "../store";

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    redirect: "inspectorList"
  },
  {
    path: "/home",
    name: "home",
    component: () => import("../views/Home.vue")
  },
  {
    path: "/login",
    name: "login",
    component: () => import("../views/login.vue")
  },
  {
    path: "/inspectorList",
    name: "inspectorList",
    component: () => import("../views/inspector/inspectorList.vue"),
    meta: {
      checkLogin: true
    }
  },
  {
    path: "/inspectorRecord",
    name: "inspectorRecord",
    component: () => import("../views/inspector/inspectorRecord.vue"),
    meta: {
      checkLogin: true
    }
  },
  {
    path: "/addRecord",
    name: "addRecord",
    component: () => import("../views/inspector/addRecord.vue"),
    meta: {
      checkLogin: true
    }
  },
  {
    path: "/expertList",
    name: "expertList",
    component: () => import("../views/expert/expertList.vue"),
    meta: {
      checkLogin: true
    }
  },
  {
    path: "/expertDetail",
    name: "expertDetail",
    component: () => import("../views/expert/expertDetail.vue"),
    meta: {
      checkLogin: true
    }
  },
  {
    path: "/expertAdd",
    name: "expertAdd",
    component: () => import("../views/expert/expertAdd.vue"),
    meta: {
      checkLogin: true
    }
  }
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
  scrollBehavior(to, from, savedPosition) {
    console.log(savedPosition);
    if (savedPosition) {
      return new Promise(resolve => {
        setTimeout(() => {
          resolve(savedPosition);
        }, 200);
      });
    } else if (to.hash) {
      return {
        selector: to.hash
      };
    } else {
      return { x: 0, y: 0 };
    }
  }
});

router.beforeEach((to, from, next) => {
  let exports = ["ROLE_EXPERT", "ROLE_DISTRICT_STAFF"];
  let exportsInfo = store.state.roles.find(item => {
    return exports.includes(item);
  });
  let inspectors = ["ROLE_SUPERVISOR"];
  let inspectorsInfo = store.state.roles.find(item => {
    return inspectors.includes(item);
  });
  if (!store.state.userInfo && to.path !== "/login" && to.meta.checkLogin) {
    store
      .dispatch("getUserInfo")
      .then(() => {
        if (to.name === "inspectorList") {
          if (exportsInfo) {
            next("/expertList");
          } else {
            next();
          }
        } else {
          next();
        }
        return;
      })
      .catch(() => {
        next("/login");
      });
  } else if (store.state.userInfo && to.name === "inspectorList") {
    if (inspectorsInfo) {
      next();
    } else if (exportsInfo) {
      next("/expertList");
    }
  } else if (!to.matched.length) {
    next("/404");
  } else {
    next();
  }
});

export default router;
