import { getEnvValue, isDev } from '../config/env.js'

const API_BASE_URL = getEnvValue('API_BASE_URL')

/**
 * 请求拦截处理
 * 自动添加token到请求头
 */
const getHeaders = () => {
  const token = uni.getStorageSync('access_token')
  const headers = {
    'Content-Type': 'application/json'
  }
  if (token) {
    headers.Authorization = `Bearer ${token}`
  }
  return headers
}

/**
 * 统一请求方法
 * @param {Object} options - 请求配置
 * @returns {Promise} 请求Promise
 */
const request = (options) => {
  return new Promise((resolve, reject) => {
    uni.request({
      url: `${API_BASE_URL}${options.url}`,
      method: options.method || 'GET',
      data: options.data,
      header: getHeaders(),
      timeout: 30000,
      success: (res) => {
        const { data, statusCode } = res
        
        // 处理401未授权
        if (statusCode === 401) {
          uni.removeStorageSync('access_token')
          uni.removeStorageSync('refresh_token')
          uni.redirectTo({ url: '/pages/login/index' })
          reject(new Error('登录已过期，请重新登录'))
          return
        }
        
        // 后端返回格式: { code, message, data }
        if (data.code === 200 || data.code === 0) {
          resolve(data)
        } else {
          reject(new Error(data.message || '请求失败'))
        }
      },
      fail: (err) => {
        reject(new Error(err.errMsg || '网络错误'))
      }
    })
  })
}

/**
 * GET请求
 */
export 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请求
 */
export const post = (url, data = {}) => {
  return request({ url, method: 'POST', data })
}

/**
 * PUT请求
 */
export const put = (url, data = {}) => {
  return request({ url, method: 'PUT', data })
}

/**
 * DELETE请求
 */
export const del = (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: 'DELETE' })
}

export default {
  get,
  post,
  put,
  del
}
