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

/**
 * 根据路由名称判断是否有权限
 * @param routes
 * @param pathName
 * @param flag
 * @returns {Promise<*>}
 */
async function filterAsyncRoutes(routes, pathName, flag) {
  for (let i = 0; i < routes.length; i++) {
    const route = routes[i]
    if (flag) {
      return flag
    }
    if (route.name == pathName) {
      flag = true
    }
    if (route.children) {
      flag = await filterAsyncRoutes(route.children, pathName, flag)
    }
  }
  return flag
}
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
  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    } else {
      try {
        // await store.dispatch('user/getAuthAccountQuery')
        // 由于router.addRoutes之后导致刷新页面后 出现路由404的问题放到跳转时候判断路由列表里面是否存在将要跳转的路由地址
        const whiteArr = ['/404', '/dashboard']
        if (whiteArr.indexOf(to.path) !== -1) {
          next()
          return
        }
        const haveAuth = await filterAsyncRoutes(store.getters.routes, to.name, false)
        if (haveAuth) {
          next()
        } else {
          next('/404')
        }
      } catch (error) {
        // remove token and go to login page to re-login
        await store.dispatch('user/resetToken')
        Message.error(error || 'Has Error')
        // ?redirect=${to.path}
        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.  ?redirect=${to.path}
      next(`/login`)
      NProgress.done()
    }
  }
})

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