import router from './router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from './utils/auth'
import { getLoginInfo, loginOut } from './api/login/login'

NProgress.configure({ showSpinner: false })

const whiteList = ['/login', '/auth-redirect']

router.beforeEach(async (to, _, next) => {
  NProgress.start()

  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      if (to.path != '/login') {
        checkLoginUser()
      }
      next()
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      if (to.path != '/login') {
        checkLoginUser()
      }
      next()
    } else {
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

function checkLoginUser () {
  if (location.port) {
    return;
  }
  // let urlType = location.hostname.substring(0, location.hostname.indexOf('.'))
  let urlType = location.pathname.replace(/\//g, '');
  getLoginInfo().then((res) => {
    let account = res.userInfo;
    switch (account.accountType) {
      case "MANAGER":
        if (urlType != 'mgr') {
          loginUserOut();
        }
        break;
      case "OPERATOR":
        if (urlType != 'opr') {
          loginUserOut();
        }
        break;
      case "STAFF":
        if (urlType == 'mgr' || urlType == 'opr') {
          loginUserOut();
        }
        break;
    }
  })
}

function loginUserOut () {
  loginOut();
  this.$router.push({
    name: 'login'
  })
}


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