import axios from 'axios'
import { message } from 'antd'

const axiosInstance = axios.create({
  // timeout: 60000,
  // withCredentials: true,
  // headers: {
  //   'Content-Type': 'application/x-www-form-urlencoded',
  // },
})

// 请求拦截
axiosInstance.interceptors.request.use(
  function (config) {
    const params = new URLSearchParams(window.location.search)

    if (config.method === 'get')
      config.params = Object.assign({}, config.params, {
        experiment_id: params.get('experiment_id') || '7028276368903241728',
      })

    if (config.method === 'post')
      config.data = Object.assign({}, config.data, {
        experiment_id: params.get('experiment_id') || '7028276368903241728',
      })

    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)

axiosInstance.interceptors.response.use(
  (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 || data.code === -1) {
      message.error(data.message || data.msg)
      return Promise.reject(data)
    }
    return data
  },
  (error) => {
    if (error.response) {
      const { status, message: errorMessage } = error.response.data
      // 未登录
      if (status === 403) {
        location.href = `${import.meta.env.VITE_LOGIN_URL}?rd=${encodeURIComponent(location.href)}`
      } else {
        message.error(errorMessage || error.message)
        console.error(`${status}: ${errorMessage}`)
      }
    } else {
      console.error(error)
    }
    return Promise.reject(error.response || error)
  }
)

export default axiosInstance
