import { BASE_URL } from "./config";
// 获取本地Token的同步方法
const getToken = () => {
  try {
    return uni.getStorageSync('token') || null
  } catch (e) {
    console.error('获取本地Token失败:', e)
    return null
  }
}

// 统一请求方法
export const request = (options) => {
  return new Promise((resolve, reject) => {
    // 合并请求头
    const header = {
      'Content-Type': 'application/json',
      ...(options.header || {}), // 允许覆盖默认header
      Authorization: getToken() ? `Bearer ${getToken()}` : undefined
    }

    // 过滤掉undefined的header项
    const filteredHeader = Object.fromEntries(
      Object.entries(header).filter(([_, v]) => v !== undefined)
    )

    uni.request({
      url: `${BASE_URL}${options.url}`,
      method: options.method || 'GET',
      data: options.data || {},
      header: filteredHeader,
      success: (res) => {
        // 处理401未授权
        if (res.statusCode === 401) {
          uni.removeStorageSync('token')
          // uni.showToast({ title: '请前往"个人中心页"登录', icon: 'none' })
          // uni.navigateTo({ url: '/pages/mine/index' })
          return reject(new Error('登录状态已过期'))
        }

        // 处理其他错误状态码
        if (res.statusCode < 200 || res.statusCode >= 300) {
          const errorMsg = res.data?.message || `请求失败 (${res.statusCode})`
          uni.showToast({ title: errorMsg, icon: 'none' })
          return reject(new Error(errorMsg))
        }

        resolve(res.data)
      },
      fail: (err) => {
        const errorMsg = err.errMsg.includes('timeout') 
          ? '网络请求超时' 
          : '网络连接失败'
        uni.showToast({ title: errorMsg, icon: 'none' })
        reject(new Error(errorMsg))
      }
    })
  })
}

// 封装常用方法
export const get = (url, data, header) => request({ url, method: 'GET', data, header })

export const post = (url, data, header) => request({ url, method: 'POST', data, header })

export const put = (url, data, header) => request({ url, method: 'PUT', data, header })

export const del = (url, data, header) => request({ url, method: 'DELETE', data, header })