import router from './router'
import store from './store'
import NProgress from 'nprogress' // Progress 进度条
import 'nprogress/nprogress.css'// Progress 进度条样式
import { Message } from 'element-ui'
import Cookies from 'js-cookie'
//  import queryInfo from '@/utils/queryInfo'

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

const whiteList = ['/login', '/findPwd'] // 不重定向白名单

router.beforeEach((to, from, next) => {
  NProgress.start()
  if (Cookies.get('userid')) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      if (!store.getters.account) { // 判断当前用户是否已拉取完user_info信息
        store.dispatch('GetUserInfo').then(res => { // 拉取user_info
          if (res.success && res.data) {
            store.dispatch('GenerateRoutes', res.data.rightCode).then(() => { // 根据roles权限生成可访问的路由表
              router.addRoutes(store.getters.addRouters) // 动态添加可访问路由表
              next({ ...to, replace: true })
            })
          }
        }).catch((err) => {
          store.dispatch('LogOut').then(() => {
            Message.error(err || '登录状态失效，请重新登录')
            next({ path: '/' })
          })
        })
      } else {
        next()
      }
      //  queryInfo.queryAllInfo()
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done() // 结束Progress
})
