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 { getSsoToken, getToken, setSsoToken, setToken, validateSSOToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import { casLogin } from '@/api/user'
import { isMenHu } from '@/utils/utils'

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

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

  // set page title
  document.title = getPageTitle(to.meta.title)
  // 信创门户的cas单点认证
  if (isMenHu()) {
    // 判断是否携带ticket，存在则进行登陆
    if (to.query.ticket && !getSsoToken()) {
      const service = document.location.origin
      const res = await casLogin({ ticket: to.query.ticket, service })
      setToken(res.data.token)
      setSsoToken(res.data.ssoToken)
      console.log('我登录成功了')
    } else if (!getSsoToken()) {
      // 不携带，则跳转cas登陆
      const service = encodeURIComponent(document.location.href)
      window.location.href = process.env.VUE_APP_CAS_SERVER + '/login?service=' + service
      console.log('已跳转' + service)
      return
    } else {
      console.log(getSsoToken())
    }
  }
  // determine whether the user has logged in
  // const hasToken = getToken()
  const ssoLogin = await validateSSOToken()

  if (ssoLogin) {
    if (to.path === '/login') {
      // 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 hasRoles = store.getters.roles && store.getters.roles.length > 0
      if (hasRoles) {
        next()
      } else {
        try {
          // 获取用户信息与角色权限
          // note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
          const { roles } = await store.dispatch('user/getInfo')

          // 基于角色生成可访问路由图
          const accessRoutes = await store.dispatch('permission/generateRoutes', roles)

          // 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 })
        } catch (error) {
          console.error(error)
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/
    if (to.meta && to.meta.roles && to.meta.roles.indexOf('guest') !== -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({
        path: `/login`,
        query: {
          ...to.query,
          redirect: to.path
        }
      })
      NProgress.done()
    }
  }
})

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