import { axiosFactory } from './setup'
import { message } from 'ant-design-vue'
import { showLoading, hideLoading } from '@/components/loading'
import { ResCode, ResCodeDesc, POST_LOGIN } from './constant'
import { baseURL } from '@/env'
import { router, RoutesName } from '@/router'

const instance = axiosFactory()

export const {
  axios,
  addUnsetTokenURLS,
  delUnsetTokenURLS,
  addReqErrorHandler,
  addResErrorHandler,
  delReqErrorHandler,
  delResErrorHandler,
  getToken,
  setToken,
  delToken,
  setDefaultURI,
  addHook,
  delHook,
  setHook
} = instance

export const gotoLogin = () => {
  router.push({ name: RoutesName.login })
}

const tokenInvalid = () => {
  message.error(ResCodeDesc[ResCode.TOKEN_INVALID])
  gotoLogin()
}

addReqErrorHandler(err => {
  // showLoading()
  tokenInvalid()
})

addResErrorHandler((response, data) => {
  console.log(response)
  if (!response || !response.data || response.status !== 200) {
    message.error('服务错误，请稍后再试')
  } else if (data) {
    const msg =
      data.code && ResCodeDesc[data.code]
        ? ResCodeDesc[data.code]
        : data?.message || data?.msg
    if (data.code === ResCode.TOKEN_INVALID) {
      tokenInvalid()
    } else {
      message.error(msg)
    }
  }
})

addHook({
  before: () => {
    showLoading()
  },
  after: () => {
    hideLoading()
  }
})

setDefaultURI(baseURL)
addUnsetTokenURLS(POST_LOGIN)

// if (!token) {
//   tokenInvalid()
// } else {
//   setToken(token)
// }

export default axios
