let BASE_URL = '/api/v1'

// #ifdef APP || MP-WEIXIN
BASE_URL = 'https://6m4685017o.goho.co/api/v1'
// #endif

function request(options) {
  return new Promise((resolve, reject) => {
    // 请求拦截器逻辑
    if (!options.hideLoading) {
      uni.showLoading({ title: '加载中' })
    }

    // 添加公共请求头，例如 token
    const token = uni.getStorageSync('token')
    options.header = {
      ...options.header,
      Authorization: `${token}`,
    }
    // 如果是 GET 请求，并且有参数，将参数拼接到 URL
    let url = BASE_URL + options.url
    if (options.method === 'GET' && options.params) {
      const queryParams = Object.keys(options.params)
        .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(options.params[key])}`)
        .join('&')
      url += `?${queryParams}`
    }
    uni.request({
      url,
      method: options.method || 'GET',
      data: options.method === 'GET' ? {} : options.data,
      header: options.header,
      success: (res) => {
        // 响应拦截器逻辑
        if (res.statusCode === 200) {
          resolve(res.data)
        }
        else if (res.statusCode === 401) {
          uni.removeStorageSync('token')
          uni.redirectTo({
            url: '/pages/login',
          })
        }
        else {
          uni.showToast({ title: res.data.msg || '请求失败', icon: 'none' })
          reject(res.data)
        }
      },
      fail: (err) => {
        uni.showToast({ title: '网络错误', icon: 'none' })
        reject(err)
      },
      complete: () => {
        if (!options.hideLoading) {
          uni.hideLoading()
        }
      },
    })
  })
}

export default request
