import router from './router'
import { getToken } from './utils/auth'
import { getLoginInfo, loginOut } from './api/login/login'
import { ftruncate } from 'fs'

const whiteList = ['/login']

router.beforeEach(async (to, _, next) => {
  // 用户刷新页面，localStorage还在，但vuex.store里的东西会reset
  const hasToken = getToken()
  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/' })
    } 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}`)
    }
  }
})


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'
  })
}
