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 getPageTitle from '@/utils/get-page-title'
import { getToken } from '@/utils/auth'

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

const loginPath = '/login'

const whiteList = [
  loginPath,
  '/auth-redirect',
  '/401',
  '/sso',
  '/signin-oidc',
  '/signout-callback-oidc',
  '/gride-work-info',
  '/beam-carrier-work-info'
] // no redirect whitelist

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

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

  if (whiteList.indexOf(to.path) !== -1) {
    // in the free login whitelist, go directly
    next()
    return
  }

  // determine whether the user has logged in
  const hasToken = getToken()

  if (hasToken) {
    if (to.path === loginPath) {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    } else {
      // determine whether the user has obtained his permission roles through getInfo
      const hasPermissions =
        store.getters.permissions && store.getters.permissions.length > 0
      if (hasPermissions) {
        next()
      } else {
        try {
          await signin(to, from, next)
        } catch (error) {
          console.dir(error)
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`${loginPath}?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/
    // other pages that do not have permission to access are redirected to the login page.
    next(`${loginPath}?redirect=${to.path}`)
    NProgress.done()
  }
})

async function signin(to, from, next) {
  // get user info
  // note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
  const { roleNames, permissions } = await store.dispatch('user/getInfo')

  if (!permissions.length) {
    await store.dispatch('user/resetToken')
    Message.error('您没有访问任何功能的权限!')
    next(`${loginPath}?redirect=${to.path}`)
    NProgress.done()
  }

  // generate accessible routes map based on roles
  const accessRoutes = await store.dispatch('permission/generateRoutes', {
    roleNames,
    permissions
  })

  // dynamically add accessible routes
  router.addRoutes(accessRoutes)

  // hack method to ensure that addRoutes is complete
  // set the replace: true, so the navigation will not leave a history record
  next({ ...to, replace: true })
}

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