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 } from '@/utils/auth' // getToken from localstorage

NProgress.configure({ showSpinner: false })// NProgress Configuration

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

router.beforeEach((to, from, next) => {
  NProgress.start()
  /* 路由发生变化修改页面title */
  //   if (to.meta.title) {
  //     document.title = to.meta.title;
  //   }
  if (getToken()) { // 判断是否有 token
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done() // if current page is dashboard will not trigger	afterEach hook, so manually handle it
    } else {
      if (store.getters.menus.length === 0) { // 判断当前用户是否已拉取菜单信息
        store.dispatch('GetInfo').then(res => { // 拉取用户信息
          store.dispatch('GetMenus').then(res => { // 拉取菜单 按钮
            const menuDatas = res.authorizeMenu// 菜单数据
            const buttonDatas = res.authorizeButton// 按钮数据
            store.dispatch('GenerateRoutes', { menuDatas, buttonDatas }).then(() => { // 根据menuDatas buttonDatas生成可访问的路由表
              router.addRoutes(store.getters.addRouters) // 动态添加可访问路由表
              next({ ...to, replace: true }) // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
            })
          })
        }).catch((err) => {
          store.dispatch('FedLogOut').then(() => {
            Message.error(err || '获取菜单权限失败，请重新登录！')
            next({ path: '/' })
          })
        })
      } else {
        next() // 当有用户权限的时候，说明所有可访问路由已生成 如访问没权限的页面会自动进入404页面
      }
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单，直接进入
      next()
    } else {
      next('/login') // 否则全部重定向到登录页
      NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
    }
  }
})

router.afterEach(() => {
  NProgress.done() // finish progress bar
})
