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 storage
import getPageTitle from '@/utils/get-page-title'
import { getMenu } from '@/api/user'
import { queryURLparamsByReg } from '@/utils'

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

const whiteList = ['/login'] // no redirect whitelist

let iframeLoginFail = false //如果iframe传token方式登录失败后，不再自动将token写入本地内存
router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start()
  if (!iframeLoginFail) {
    // 如果url包含token自动登录
    const url = decodeURI(window.location.href)
    const params = queryURLparamsByReg(url)
    // console.log(params)

    // nolayout=1 时不显示头部和侧边栏
    if (params.hasOwnProperty('nolayout')) {
      const state = params['nolayout'] != '1'
      const settings = {
        needHeader: state,
        needSidebar: state,
        needBreadcrumb: state,
        tagsView: state,
      }
      for (const key in settings) {
        await store.dispatch('settings/changeSetting', { key, value: settings[key] })
      }
    }
    // token存在时自动登录
    if (params.hasOwnProperty('token') && !!params['token']) {
      await store.dispatch('user/loginByUrl', params['token'])
    }
  }

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

  // 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 {
      // 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 {
          // get user info
          // note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
          const { roles } = await store.dispatch('user/getInfo')
          // generate accessible routes map based on roles
          // console.log(roles)
          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 })
          if (iframeLoginFail) iframeLoginFail = false
        } catch (error) {
          // 暂时解决iframe跳转登录问题
          // 如果传入的token无效，获取用户信息失败，不再将传过来的token写入内存
          if (error.toString().includes('获取用户信息失败')) {
            iframeLoginFail = true
          }
          // 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 (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.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})
router.onError((error) => {
  const isNotFindFailed = error.message.includes('Cannot find module')
  if (isNotFindFailed) {
    router.replace('/404')
    NProgress.done()
  }
})
router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
