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

  if (store.state.app.isMaintain) {
    if (process.env.VUE_APP_ENV === 'dev') {
      Message.warning({
        message: '当前系统为维护状态，但处于开发环境不进入维护页面',
        duration: 5000
      })
      store.commit('app/IS_MAINTAIN', false)
    } else {
      next(to.path === '/maintain' ? undefined : '/maintain')
      return
    }
  }

  // 信创门户的cas单点认证
  if (isMenHu()) {
    console.log('信创门户----In')
    // 判断是否携带ticket，存在则进行登陆
    if (to.query.ticket && !getSsoToken()) {
      const service = document.location.origin
      const res = await casLogin({ ticket: to.query.ticket, service })
      if (res.code === 3002) {
        Message.error(res.data.message)
      }
      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
    }
  }

  const ssoLogin = await validateSSOToken()

  // 统一门户
  if (isMenHu_Unite()) {
    if (to.path === '/toDoList' && ssoLogin) {
      // 门户待办跳转
    } else {
      // cas单点登录
      const service = document.location.origin + document.location.pathname + '?unite=1'
      if (document.location.search.indexOf('ticket') !== -1 && !ssoLogin) {
        const res = await casLogin_Unite({ ticket: document.location.search.replace(new RegExp(/\?unite=1&ticket=/g, 'g'), ''), service })
        if (res.code === 0) {
          setToken(res.data.token)
          setSsoToken(res.data.ssoToken)
          console.log('统一门户登录成功!')
        } else if (res.data.message.indexOf('INVALID_TICKET') !== -1) { // ticket失效, 新通过CAS获取
          window.location.href = process.env.VUE_APP_CAS_SERVER_UNITE + '/login?service=' + encodeURIComponent(service)
        }
      } else if (!ssoLogin) {
        // 不携带，则跳转cas登陆
        window.location.href = process.env.VUE_APP_CAS_SERVER_UNITE + '/login?service=' + encodeURIComponent(service)
        console.log('已跳转' + service)
        return
      }
    }
  }

  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)
          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) {
          // remove token and go to login page to re-login
          await store.dispatch('user/logout')
          Message.error(error || 'Has Error')
          next(`/login`)
          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(`/login`)
      NProgress.done()
    }
  }
})

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