import axios from 'axios'
import message from '@/utils/message'
import qs from 'qs'

const instance = axios.create({ timeout: 1000 * 300 })
axios.defaults.withCredentials = true
// POST传参序列化(添加请求拦截器)

instance.interceptors.request.use(
  (config) => {
    // 修复 config.url 可能为 undefined 的问题
    const url = config.url ?? ''
    // 修复 config.data 可能为 undefined 的问题
    const data = config.data ?? {}

    // 确保每个请求都带上cookie
    config.withCredentials = true

    if (url.includes('https://gpt4.cocorobo.cn') || url.includes('https://appapi.cocorobo.cn') || url.includes('https://ccrb.s3.cn-northwest-1.amazonaws.com.cn')) {
      config.withCredentials = false 
    }

    // 需要 form-urlencoded 且 data 为数组的情况
    if (
      config.method === 'post' &&
      (
        url.includes('http://localhost:7003/api/pbl/') ||
        url.includes('https://pbl.cocorobo.cn/api/mongo/') ||
        url.includes('https://pbl.cocorobo.cn/api/pbl/') ||
        url.includes('https://r2rapi.cocorobo.cn/') ||
        url.includes('http://10.1.82.64:7004/file/')
      )
    ) {
      // 修复 headers 类型问题
      if (config.headers) {
        config.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
      }
      else {
        // @ts-ignore
        config.headers = { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' }
      }
      // 处理 data[0] 为对象的情况
      const encoded: Record<string, any> = {}
      if (Array.isArray(data) && data.length > 0 && typeof data[0] === 'object') {
        for (const key in data[0]) {
          if (Object.prototype.hasOwnProperty.call(data[0], key)) {
            encoded[key] = encodeURIComponent(data[0][key])
          }
        }
        config.data = qs.stringify([encoded]) // 序列化post参数
      }
    }
    // 需要对 data 进行 encode 的情况
    else if (
      url.includes('http://localhost:7003/api/pbl/') ||
      url.includes('https://pbl.cocorobo.cn/api/mongo/') ||
      url.includes('https://pbl.cocorobo.cn/api/pbl/') ||
      url.includes('https://r2rapi.cocorobo.cn/')
    ) {
      const encoded: Record<string, any> = {}
      for (const key in data) {
        if (Object.prototype.hasOwnProperty.call(data, key)) {
          encoded[key] = encodeURIComponent(data[key])
        }
      }
      config.data = encoded
    }

    return config
  },
  (error) => {
    console.log('错误的传参')
    return Promise.reject(error)
  }
)

instance.interceptors.response.use(
  (response) => {
    if (response.status >= 200 && response.status < 400) {
      return Promise.resolve(response.data)
    }
    message.error(response.config.url || '')
    message.error('未知的请求错误！')
    return Promise.reject(response)
  },
  (error) => {
    const config = error.config
    let fullUrl = '未知请求'
  
    if (config) {
      // 拼接 baseURL 和 url
      const baseURL = config.baseURL || ''
      const url = config.url || ''
      fullUrl = baseURL + url
  
      // 如果有查询参数，添加到 URL 中
      if (config.params) {
        const params = new URLSearchParams(config.params).toString()
        if (params) {
          fullUrl += '?' + params
        }
      }

      // 检查是否需要显示错误信息
      const showError = config.showError !== false
      if (!showError) {
        return Promise.reject(error)
      }
    }

    if (error && error.response) {
      if (error.response.status >= 400 && error.response.status < 500) {
        return Promise.reject(error.message)
      }
      else if (error.response.status >= 500) {
        return Promise.reject(error.message)
      }
      
      message.error('服务器遇到未知错误！')
      return Promise.reject(error.message)
    }
    message.error(fullUrl)
    message.error(error)
    return Promise.reject(error)
  }
)

export default instance
