import router from '@/router'

import { Notice } from 'iview'
import { clearAdminInfo as clearInfo } from '@/libs/util'

const SUCCESS_CODE = '00000'
const TOKEN_NULL_CODE = 'A0101'
const TOKEN_ERR_CODE = 'A0102'
const NO_AUTH_CODE = 'A0401'
const TOKEN_INVALID_CODE = 'A0302'

function apiVerify ({ res, success, error, alertServerErrMsg, clearAdminInfo, url }) {
  if (!alertServerErrMsg) {
    alertServerErrMsg = msg => {
      Notice.error({
        title: msg || '服务端请求异常'
      })
    }
  }
  if (!clearAdminInfo) {
    clearAdminInfo = clearInfo
  }

  let data = res.data || {}
  if (res.data.code === SUCCESS_CODE) {
    success && success(data)
  } else if (data.code == TOKEN_NULL_CODE || data.code == TOKEN_ERR_CODE) {
    clearAdminInfo && clearAdminInfo()
    error && error(data.msg)
    if (router.currentRoute.name != 'login') {
      router.push({ name: 'login' }).catch(err => {})
      alertServerErrMsg('密码格式错误，请重新登录')
    }
  } else if (data.code == NO_AUTH_CODE) {
    router.push({ name: 'error_401' }).catch(err => {})
  } else if (data.code == TOKEN_INVALID_CODE) {
    clearAdminInfo && clearAdminInfo()
    error && error(data.msg)
    if (router.currentRoute.name != 'login') {
      router.push({ name: 'login' }).catch(err => {})
      alertServerErrMsg('登录已失效，请重新登录')
    }
  } else {
    if (error) {
      error(data)
    } else {
      alertServerErrMsg(data.msg)
    }
  }
  return null
}

export {
  SUCCESS_CODE,
  TOKEN_NULL_CODE,
  TOKEN_ERR_CODE,
  apiVerify
}
