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' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

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

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

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

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

  // determine whether the user has logged in
  const hasToken = getToken()
  if (hasToken) {
    if (to.path === '/login') {
      // 如果有tonken直接跳转到首页
      next({ path: '/' })
      NProgress.done()
    } else {
      const hasGetUserInfo = store.getters.name
      // 有名字 说明有用户信息 跳走
      if (hasGetUserInfo) {
        // const accessRoutes = await store.dispatch('permission/generateRoutes')

        // 动态添加可访问的路由
        // router.addRoutes(accessRoutes)
        next()
      } else {
        try {
          // 异步获取用户信息
          await store.dispatch('user/getInfo')
          // 请求接口 生成可访问路由
          const accessRoutes = await store.dispatch('permission/generateRoutes')
          // 动态添加可访问的路由
          router.addRoutes(accessRoutes)
          // 确保addroutes完整的hack方法
          // 设置replace:true，这样导航就不会留下历史记录。
          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`)
          NProgress.done()
        }
      }
    }
  } 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`)
      NProgress.done()
    }
  }
})

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