import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken, removeToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import { getMenu } from "./api/user";
import { addRouter } from "./utils/addRouter";
import user from "./store/modules/user";
NProgress.configure({
  showSpinner: false
}) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  if (getToken()) {
    // 判断cookice是否存在 不存在即为未登录
    if (to.path !== "/login") {
      if (user.state.init) {
        // 获取了动态路由 data一定true,就无需再次请求 直接放行
        next();
      } else {
        // data为false,一定没有获取动态路由,就跳转到获取动态路由的方法
        gotoRouter(to, next);
      }
    } else {
      Message({ message: "您已经登录", type: "info" });
      next("/");
    }
    // }
  } else {
    /* has no token*/

    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      // next(`/login?redirect=${to.path}`)
      next('/login')
      NProgress.done()
    }
  }
})

router.afterEach((to, from) => {
  NProgress.done(); // 结束Progress
});

function gotoRouter(to, next) {
  getMenu() // 获取动态路由的方法
    .then(res => {
      const { menus, allMenus } = res.data
      store.dispatch("user/setAllMenus", allMenus);
      const asyncRouter = addRouter(menus); // 进行递归解析
      return asyncRouter;
    })
    .then(asyncRouter => {
      // 后置添加404页面,防止刷新404
      asyncRouter.push({
        path: "*",
        redirect: "/404",
        hidden: true
      });
      router.addRoutes(asyncRouter); // vue-router提供的addRouter方法进行路由拼接
      store.dispatch("user/setRouterList", asyncRouter); // 存储到vuex
      // store.dispatch("user/GetInfo");
      store.commit("user/set_init", true);
      next({ ...to, replace: true }); // hack方法 确保addRoutes已完成
    })
    .catch(e => {
      console.log(e);
      removeToken();
    });
}
