import router from './router'
import store from './store'
// import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import { OSSclient } from './utils/oss'
// import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false })

const whiteList = ['/ReviewersResearch', '/login', '/error', '/resetpassword', '/recompose', '/email-recompose', '/trialStats', '/showdicom', '/imagesShare', '/audit', '/preview', '/researchLogin', '/blindResumeInfo', '/trialsResume', '/joinVerify', '/showNoneDicoms', '/noneDicomReading', '/clinicalData', '/readingDicoms', '/readingPage', '/visitDicomReview', '/visitNondicomReview', '/globalReview', '/adReview', '/oncologyReview', '/nonedicoms']

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  // 设置页面标题
  // document.title = getPageTitle(to.meta.title)

  // 确定用户是否已登录
  await OSSclient()
  next()
  const hasToken = getToken()
  if (hasToken) {
    if (to.path === '/login' || to.path === '/recompose' || to.path === '/email-recompose' || to.path === '/error' || to.path === '/ReviewersResearchForm' || to.path === '/ReviewersResearch') {

      next()
      NProgress.done()
    } else {
      const hasGetUserInfo = store.getters.name
      if (hasGetUserInfo) {
        next()
      } else {
        try {
          // 获取用户信息
          await store.dispatch('user/getInfo')
          // const accessRoutes = await store.dispatch('permission/generateRoutes')
          // router.addRoutes(accessRoutes)
          next({ ...to, replace: true })
        } catch (error) {
          // 删除token并进入登录页面以重新登录
          await store.dispatch('user/resetToken')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录whiteList中，直接进入
      next()
    } else {
      if (to.path === '/researchForm') {
        next(`/researchLogin?`)
        NProgress.done()
      } else if (to.path === '/ReviewersResearchForm') {
        next(`/ReviewersResearch?`)
        NProgress.done()
      } else {
        // 其他无权访问的页面将重定向到登录页面。
        next(`/login?`)
        NProgress.done()
      }
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
