import Vue from 'vue';
import Router from 'vue-router';
import layout from '@views/index';
import subLayout from '@views/layout/layout';
import store from '../store';
import { getStore } from '@utils/store';
import { isArray } from '@utils/validate';

Vue.use(Router);

const whiteListRouterMap = [
  {
    name: 'login',
    id: 'login',
    path: '/login',
    meta: {
      name: '登陆'
    },
    component: () => import('@views/login/login')
  },
  {
    name: 'update-pwd',
    id: 'update-pwd',
    path: '/update-pwd',
    meta: {
      name: '修改密码'
    },
    component: () => import('@views/login/update-pwd')
  },
  {
    name: '404',
    id: '404',
    path: '/404',
    meta: {
      name: '404错误'
    },
    component: () => import('@views/error-page/404')
  }
];

export const noMenuRouterMap = [
  {
    name: 'Home',
    id: 'Home',
    path: '/home',
    meta: {
      name: '首页',
      icon: 'el-icon-s-home',
      keepAlive: true
    },
    component: (resolve) => require(['@views/home'], resolve)
  }
];

export const constantRouterMap = [
  {
    name: 'Main',
    id: 'Main',
    path: '/',
    meta: {
      name: '应用'
    },
    redirect: '/home',
    component: layout
    // children: noMenuRouterMap
  },
  ...whiteListRouterMap
];

const originalPush = Router.prototype.push;
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err);
};

const createRouter = () => {
  return new Router({
    routes: constantRouterMap
  });
};

export function resetRouter() {
  const newRouter = createRouter();
  router.matcher = newRouter.matcher;
}

const router = createRouter();

const whiteList = () => {
  return whiteListRouterMap.map((menu) => menu.path);
};

router.beforeEach((to, from, next) => {
  // 判断token是否过期,如果过期则跳回登录页
  let token = getStore('accessToken');
  if (token) {
    if (to.path === '/login') {
      next();
    } else {
      if (store.getters.routers.length === 0) {
        store.dispatch('generateRoutes').then((res) => {
          res.forEach((item) => {
            router.addRoute('Main', item);
          });
          next({ ...to, replace: true });
        });
      } else {
        if (to.matched.length === 0) {
          next('/404'); // 判断此跳转路由的来源路由是否存在，存在的情况跳转到来源路由，否则跳转到404页面
        }
        next();
      }
    }
  } else {
    if (whiteList().indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next();
    } else {
      next({ name: 'login' });
    }
  }
});
export default router;

export function filterAsyncRoutes(asyncRouter, parentPath) {
  // 遍历后台传来的路由字符串，转换为组件对象
  let accessedRoutes = [];
  if (asyncRouter != null) {
    asyncRouter.forEach((myRouter) => {
      let path = parentPath + '/' + myRouter.path;
      let treeRouter = {
        name: myRouter.path,
        path: path,
        id: myRouter.id,
        meta: {
          name: myRouter.title,
          icon: myRouter.icon,
          keepAlive: myRouter.keepAlive === '1',
          hidden: myRouter.hidden === '1'
        }
      };
      if (myRouter.component) {
        if (myRouter.component === 'layout') {
          treeRouter.component = layout;
        } else if (myRouter.component === 'subLayout') {
          treeRouter.component = subLayout;
        } else {
          treeRouter.component = (resolve) => require([`@views/${myRouter.component}`], resolve);
        }
      }
      let children = myRouter.children;
      if (children && isArray(children)) {
        children = filterAsyncRoutes(children, path);
      }
      treeRouter.children = children;
      accessedRoutes.push(treeRouter);
    });
  }
  return accessedRoutes;
}
