/**
 * HTTP请求工具类
 * 封装uni.request，提供统一的请求接口
 */

class HttpService {
  constructor() {
    this.baseURL = 'http://110.40.171.179:7999'
    this.timeout = 10000
    this.defaultHeaders = {
      'Content-Type': 'application/json'
    }
  }

  // 设置基础URL
  setBaseURL(url) {
    this.baseURL = url
  }

  // 设置超时时间
  setTimeout(timeout) {
    this.timeout = timeout
  }

  // 设置默认请求头
  setDefaultHeaders(headers) {
    this.defaultHeaders = { ...this.defaultHeaders, ...headers }
  }

  // 通用请求方法
  request(options) {
    return new Promise((resolve, reject) => {
      const {
        url,
        method = 'GET',
        data = {},
        headers = {},
        timeout = this.timeout
      } = options

      // 构建完整URL
      const fullUrl = url.startsWith('http') ? url : `${this.baseURL}${url}`
      // 合并请求头
      const requestHeaders = { ...this.defaultHeaders, ...headers }
      uni.request({
        url: fullUrl,
        method,
        data,
        header: requestHeaders,
        timeout,
        success: (response) => {
          // 检查HTTP状态码
          if (response.statusCode >= 200 && response.statusCode < 300) {
            resolve(response.data)
          } else {
            reject(new Error(`HTTP ${response.statusCode}: ${response.data?.message || '请求失败'}`))
          }
        },
        fail: (error) => {
          console.error('❌ HTTP请求失败:', error)
          reject(new Error(error.errMsg || '网络请求失败'))
        }
      })
    })
  }

  // GET请求
  get(url, params = {}, options = {}) {
    return this.request({
      url,
      method: 'GET',
      data: params,
      ...options
    })
  }

  // POST请求
  post(url, data = {}, options = {}) {
    return this.request({
      url,
      method: 'POST',
      data,
      ...options
    })
  }

  // PUT请求
  put(url, data = {}, options = {}) {
    return this.request({
      url,
      method: 'PUT',
      data,
      ...options
    })
  }

  // DELETE请求
  delete(url, params = {}, options = {}) {
    return this.request({
      url,
      method: 'DELETE',
      data: params,
      ...options
    })
  }

  // 上传文件
  upload(url, filePath, formData = {}, options = {}) {
    return new Promise((resolve, reject) => {
      const fullUrl = url.startsWith('http') ? url : `${this.baseURL}${url}`
      uni.uploadFile({
        url: fullUrl,
        filePath,
        name: 'file',
        formData,
        header: { ...this.defaultHeaders, ...options.headers },
        success: (response) => {
          try {
            const data = JSON.parse(response.data)
            resolve(data)
          } catch (error) {
            resolve(response.data)
          }
        },
        fail: (error) => {
          console.error('❌ 文件上传失败:', error)
          reject(new Error(error.errMsg || '文件上传失败'))
        }
      })
    })
  }

  // 下载文件
  download(url, options = {}) {
    return new Promise((resolve, reject) => {
      const fullUrl = url.startsWith('http') ? url : `${this.baseURL}${url}`
      uni.downloadFile({
        url: fullUrl,
        header: { ...this.defaultHeaders, ...options.headers },
        success: (response) => {
          resolve(response)
        },
        fail: (error) => {
          console.error('❌ 文件下载失败:', error)
          reject(new Error(error.errMsg || '文件下载失败'))
        }
      })
    })
  }
}

// 创建单例实例
const httpService = new HttpService()

export default httpService