// 请求工具类
const auth = require('./auth.js')

const request = (options) => {
  return new Promise((resolve, reject) => {
    // 添加认证头
    const token = auth.getToken()
    if (token) {
      options.header = {
        ...options.header,
        'Authorization': `Bearer ${token}`
      }
    }

    // 添加基础URL
    const app = getApp()
    if (!options.url.startsWith('http')) {
      options.url = app.globalData.baseUrl + options.url
    }

    // 添加默认配置
    const config = {
      timeout: 10000,
      dataType: 'json',
      responseType: 'text',
      ...options
    }

    console.log('发起请求:', config)

    wx.request({
      ...config,
      success: (res) => {
        console.log('请求成功:', res)
        
        // 检查响应状态
        if (res.statusCode === 200) {
          const { code, message, data } = res.data
          
          if (code === 200) {
            resolve(data)
          } else if (code === 401) {
            // token过期，清除本地存储并跳转登录
            auth.clearToken()
            wx.reLaunch({
              url: '/pages/login/login'
            })
            reject(new Error(message || '认证失败'))
          } else {
            reject(new Error(message || '请求失败'))
          }
        } else {
          reject(new Error(`请求失败: ${res.statusCode}`))
        }
      },
      fail: (err) => {
        console.error('请求失败:', err)
        reject(new Error(err.errMsg || '网络请求失败'))
      }
    })
  })
}

// GET请求
const get = (url, params = {}) => {
  const queryString = Object.keys(params)
    .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
    .join('&')
  
  const fullUrl = queryString ? `${url}?${queryString}` : url
  
  return request({
    url: fullUrl,
    method: 'GET'
  })
}

// POST请求
const post = (url, data = {}) => {
  return request({
    url,
    method: 'POST',
    data,
    header: {
      'Content-Type': 'application/json'
    }
  })
}

// PUT请求
const put = (url, data = {}) => {
  return request({
    url,
    method: 'PUT',
    data,
    header: {
      'Content-Type': 'application/json'
    }
  })
}

// DELETE请求
const del = (url) => {
  return request({
    url,
    method: 'DELETE'
  })
}

module.exports = {
  get,
  post,
  put,
  delete: del
}
