import config from "@/config";

export default function request ( { 
  url = '', 
  method = 'GET', 
  data = {}, 
  showLoading = false, 
  header = {} ,
  needToken = false, // 需要token
  showToast = true // 默认显示失败的提示

} ) {
  if (showLoading) uni.showLoading({title: '加载中'})
  if(needToken) {
    const token = uni.getStorageSync('token')
    if (token) {
      header['X-Access-Token'] = token
    }else {
      if (showLoading) {
        uni.hideLoading()
      }
      uni.showToast({
        title: '请先登录',
        icon: 'none'
      })
      uni.reLaunch({ url: '/subPages/login/login' })
      return
    }
  }
  return new Promise((resolve, reject) => {
    uni.request({
      url: config.baseURL + url,
      method,
      data,
      header: {
        'Content-Type': 'application/x-www-form-urlencoded',
        ...header
      },
      success: (res) => {
        console.log(`Success ${method} ${url}`, res);

        // 优先处理业务逻辑响应
        if (res.statusCode === 200 && res.data) {
          // 业务成功
          if (res.data.code === 200 ) {
            if (showLoading) {
              uni.hideLoading()
            }
            resolve(res.data)
            return
          }
          
          // 业务失败但有具体错误信息
          const errorMsg = res.data.message || '请求失败'
          
          if (showToast) {
            if (showLoading) {
              uni.hideLoading()
            }
            uni.showToast({
              title: errorMsg,
              icon: 'none',
              duration: 3000
            })
          }
          reject({
            code: res.data.code,
            message: errorMsg,
            data: res.data
          })
          return
        }

        // 处理HTTP状态码错误（无有效响应体的情况）
        const error = {
          code: res.statusCode,
          message: '网络请求错误'
        }

        switch (res.statusCode) {
          case 401:
          case 403:
            uni.removeStorageSync('token')
            uni.reLaunch({ url: '/subPages/login/login' })
            error.message = '登录已过期，请重新登录'
            break;
          case 404:
            error.message = '资源不存在'
            break;
          case 500: 
            error.message = '服务器错误'
            break;
        }
        if (showToast) {
          if (showLoading) {
            uni.hideLoading()
          }
          uni.showToast({
            title: error.message,
            icon: 'none'
          })
        }
        reject(error)
      },
      fail: (err) => {
        console.log(`Fail ${method} ${url}`, err);
        const errorMsg = err.errMsg || '请求失败'
        if (showToast) {
          if (showLoading) {
            uni.hideLoading()
          }
          uni.showToast({
            title: errorMsg,
            icon: 'none'
          })
        }

        reject({
          code: -1,
          message: errorMsg,
          data: err
        })
      },

    })
  })
}