import axios from 'axios'
import qs from 'qs'
import { ElMessage } from 'element-plus'
import router from '@/router'

const httpRequest = axios.create({
  timeout: 60000,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
})
// 请求拦截
httpRequest.interceptors.request.use(
  function (config) {
    if (config.headers?.['Content-Type'] === 'application/x-www-form-urlencoded') {
      config.data = qs.stringify(config.data, { skipNulls: true })
    }
    if (config.headers?.['Content-Type'] === 'multipart/form-data') {
      const formData = new window.FormData()
      for (const key in config.data) {
        formData.append(key, config.data[key])
      }
      config.data = formData
    }
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)

// 响应拦截
httpRequest.interceptors.response.use(
  function (response) {
    const { data } = response
    // 未登录
    if (data.code === 4001) {
      location.href = `${import.meta.env.VITE_LOGIN_URL}?rd=${encodeURIComponent(location.href)}`
      return Promise.reject(data)
    }
    if (data.code === 1) {
      ElMessage.error(data.message || data.msg)
      return Promise.reject(data)
    }
    if (import.meta.env.VITE_STATIC_URL) {
      try {
        const regex = /(http|https):\/\/(.*?)saas-lab-api/gi
        return JSON.parse(JSON.stringify(data).replaceAll(regex, import.meta.env.VITE_STATIC_URL))
      } catch (error) {
        console.log(error)
      }
    }
    return data
  },
  function (error) {
    if (error.response) {
      const { status, message } = error.response.data
      // 未登录
      if (status === 403) {
        location.href = `${import.meta.env.VITE_LOGIN_URL}?rd=${encodeURIComponent(location.href)}`
      } else if (status === 402) {
        // 未授权
        router.push('/401')
      } else {
        ElMessage.error(message)
        console.error(`${status}: ${message}`)
      }
    } else {
      console.log(error)
    }
    return Promise.reject(error.response || error)
  }
)

export default httpRequest
