// utils/request.js

const BASE_URL = process.env.VUE_APP_API_BASE_URL
const TOKEN_KEY = 'auth_token'

/**
 * 基础请求方法
 */
export function request(options) {
  // 默认配置
  const defaultOptions = {
    url: '',
    method: 'GET',
    data: {},
    header: {
      'Content-Type': 'application/json'
    },
    timeout: 10000,
    showLoading: false,
    loadingText: '加载中...',
    checkAuth: true
  }

  // 合并配置
  options = { ...defaultOptions, ...options }

  // 请求拦截 - 处理URL
  if (!options.url.startsWith('http')) {
    options.url = BASE_URL + options.url
  }

  // 请求拦截 - 添加token
  if (options.checkAuth) {
    const token = uni.getStorageSync(TOKEN_KEY)
    if (token) {
      options.header.Authorization = `Bearer ${token}`
    }
  }

  // 显示加载提示
  if (options.showLoading) {
    uni.showLoading({
      title: options.loadingText,
      mask: true
    })
  }

  return new Promise((resolve, reject) => {
    uni.request({
      ...options,
      success: (res) => {
        handleResponse(res, resolve, reject)
      },
      fail: (err) => {
        handleError(err, reject)
      },
      complete: () => {
        if (options.showLoading) {
          uni.hideLoading()
        }
      }
    })
  })
}

// 响应处理函数
function handleResponse(res, resolve, reject) {
  if (res.statusCode === 200) {
    resolve(res.data)
  } else if (res.statusCode === 401) {
    handleUnauthorized()
    reject(new Error('未授权'))
  } else {
    handleHttpError(res.statusCode)
    reject(new Error(`HTTP错误: ${res.statusCode}`))
  }
}

// 错误处理函数
function handleError(err, reject) {
  uni.showToast({
    title: '网络连接错误',
    icon: 'none',
    duration: 2000
  })
  reject(err)
}

// HTTP错误处理
function handleHttpError(statusCode) {
  const errorMap = {
    400: '请求参数错误',
    403: '拒绝访问',
    404: '资源不存在',
    500: '服务器错误'
  }
  uni.showToast({
    title: errorMap[statusCode] || `请求错误: ${statusCode}`,
    icon: 'none',
    duration: 2000
  })
}

// 未授权处理
function handleUnauthorized() {
  uni.removeStorageSync(TOKEN_KEY)
  uni.showToast({
    title: '登录已过期',
    icon: 'none',
    duration: 1500
  })
  setTimeout(() => {
    uni.navigateTo({
      url: '/pages/login/login'
    })
  }, 1500)
}

/**
 * 快捷方法
 */
export const http = {
  get: (url, params, options) => 
    request({ url, params, method: 'GET', ...options }),
  
  post: (url, data, options) => 
    request({ url, data, method: 'POST', ...options }),
  
  put: (url, data, options) => 
    request({ url, data, method: 'PUT', ...options }),
  
  delete: (url, data, options) => 
    request({ url, data, method: 'DELETE', ...options })
}
