import router from './router';
import store from './store';
import { Message } from 'element-ui';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { getToken } from '@/utils/token';
// import getPageTitle from '@/utils/get-page-title'
NProgress.configure({ showSpinner: false });
const whiteList = ['/login'];
//路由钩子
router.beforeEach(async (to, from, next) => {
  NProgress.start();
  // document.title = getPageTitle(to.meta.title)
  const hasToken = getToken();
  //是否存在token
  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/' });
      NProgress.done();
    } else {
      const hasGetUserInfo = store.getters.roles;
      if (hasGetUserInfo) {
        next();
      } else {
        try {
          // 获取个人信息
          await store.dispatch('user/getInfo');
          // 获取菜单
          const rolers = 'admin';
          //这里是可以从上面用户信息里获取
          const accessRoutes = await store.dispatch(
            'permission/generateRoutes',
            rolers
          );
          router.addRoutes(accessRoutes);
          console.log(store);
          next({ ...to, replace: true });
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken');
          Message.error(error || 'Has Error');
          next(`/login?redirect=${to.path}`);
          NProgress.done();
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      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(() => {
  // finish progress bar
  NProgress.done();
});
