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

const instance = axiosFactory()

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

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

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

addResErrorHandler((response, data) => {
  if (response && response.status && response.status !== 200) {
    message.error(ui18n.t('sys.ERROR'))
  } else if (data) {
    const msg =
      data.code && ResCodeDesc[data.code]
        ? ResCodeDesc[data.code]
        : data?.message || data?.msg

    console.log(ResCodeDesc, data.code)
    if (data.code === ResCode.TOKEN_INVALID) {
      gotoLogin()
    } else if (data.code === ResCode.NO_ACCESS) {
      router.replace({ name: RoutesName.projects })
    } else {
      message.error(msg)
    }
  }
})

addHook({
  before: config => {
    if (![GET_TAGGING_TOTAL, GET_PROJECT].includes(config?.url as any)) {
      showLoading()
    }
  },
  after: config => {
    if (![GET_TAGGING_TOTAL, GET_PROJECT].includes(config?.url as any)) {
      hideLoading()
    }
  }
})

setDefaultURI(baseURL)
addUnsetTokenURLS(POST_LOGIN)

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

export default axios
