import Vue from 'vue'
import Router from "vue-router";
import routes from "../config/routes";
import AuthDao from "@/dao/auth";
import store from '../store'

// 注册路由
Vue.use(Router);

// 解决路由未跳转就点击其他路由报错
const originalPush = Router.prototype.push;
const originalReplace = Router.prototype.replace;
Router.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject)
    return originalPush.call(this, location, onResolve, onReject);
  return originalPush.call(this, location).catch((err) => err);
};
Router.prototype.replace = function push(location, onResolve, onReject) {
  if (onResolve || onReject)
    return originalReplace.call(this, location, onResolve, onReject);
  return originalReplace.call(this, location).catch((err) => err);
};


// 配置路由
const router = new Router({
  routes: [
    {
      path: "*",
      name: "404",
      component: (resolve) => require(["@/views/404/index"], resolve),
    },
    ...routes,
  ],
});

// 路由白名单
const whiteList = [];

// 全局路由守卫
router.beforeEach((to, from, next) => {
  if (whiteList.includes(to.path)) {
    next();
    return;
  }
  const parentId = map_config.SYS_ID;
  AuthDao.queryMenu({
    params: {
      parentId,
      isRecursion: true,
    },
  }).then((res) => {
    let routes = res.data.content;
    for (let route of routes) {
      if (route.url === to.path) {
        next();
      }
    }
  });
});

router.afterEach((to, from) =>{
  store.commit("setPathActive", to.fullPath);
})

export default router;
