import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ACCESS_TOKEN, TOKEN_PREFIX } from '@/utils/constants'
import { useUserStore } from '@/stores/user'
import { logout } from '@/utils/micro'

const request = axios.create({
  baseURL: import.meta.env.VITE_BASE_API,
  timeout: 1000
})

// 异常拦截处理器
const errorHandler = (error: any) => {
  const status = error.response?.status
  const data = error.response?.data

  if (status === 400) {
    ElMessage.error(data.msg)
  } else if (status === 401) {
    ElMessageBox.confirm('无权限访问当前资源，请尝试重新登录后再操作。', '无权限访问', {
      type: 'error',
      closeOnClickModal: false,
      center: true,
      confirmButtonText: '重新登录'
    }).then(() => {
      logout()
    })
  } else if (status === 403) {
    ElMessage.error('无权限访问')
  } else if (status === 404) {
    ElMessage.error('接口不存在')
  } else if (status === 500) {
    ElMessage.error('服务器错误')
  }

  return Promise.reject(error.response)
}

request.interceptors.request.use(config => {
  const userStore = useUserStore()
  const token = TOKEN_PREFIX + userStore.token
  config.headers = config.headers || {}

  if (token) {
    config.headers[ACCESS_TOKEN] = token
  }

  return config
})

request.interceptors.response.use(res => {
  const data = res.data
  if (data.success || data.code === 200) {
    return data
  } else {
    if (data.code === 201 && data.msg === '登录超时，请登录') {
      logout()
    } else {
      ElMessage.error(data.msg)
    }
    return Promise.reject(data)
  }
}, errorHandler)

export default request
