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("/");
    }
    // if (to.path === '/login') {
    //   // if is logged in, redirect to the home page
    //   next({
    //     path: '/'
    //   })
    //   NProgress.done()
    // } else {
    //   // next()
    //   // NProgress.done()
    //   if (user.state.init) {
    //     // 获取了动态路由 data一定true,就无需再次请求 直接放行
    //     next();
    //   } else {
    //     // data为false,一定没有获取动态路由,就跳转到获取动态路由的方法
    //     gotoRouter(to, 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}`)
      NProgress.done()
    }
  }
})

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

function gotoRouter(to, next) {
  getMenu() // 获取动态路由的方法
    .then(res => {
      console.log("解析后端动态路由", res);
      const asyncRouter = addRouter(res.data.menus); // 进行递归解析
      // store.dispatch("user/setroles", res.data.permit);
      return asyncRouter;
    })
    .then(asyncRouter => {
      // 后置添加404页面,防止刷新404
      asyncRouter.push({
        path: "*",
        redirect: "/404",
        hidden: true
      });
      router.addRoutes(asyncRouter); // vue-router提供的addRouter方法进行路由拼接
      console.log(asyncRouter);
      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();
    });
}
