import axios from 'axios'
import queryString from 'query-string'
import { Message } from 'element-ui'

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 = queryString.stringify(config.data)
    }
    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) {
      return Promise.reject(data)
    }
    return data
  },
  function (error) {
    if (error.response) {
      const { status, message } = error.response.data
      // 未登录
      if (status === 403) {
        window.location.href = `${import.meta.env.VITE_LOGIN_URL}?rd=${encodeURIComponent(window.location.href)}`
      } else {
        Message.error(message || error.response.data)
      }
      return Promise.reject(error.response)
    } else {
      console.log(error)
    }
    return Promise.reject(error)
  }
)

export default httpRequest
