const BASE_URL = 'http://localhost:4000/api/v1'

class HttpRequest {
  private token: string = ''

  setToken(token: string) {
    this.token = token
  }

  getToken() {
    return this.token
  }

  async request<T>(method: string, url: string, data?: any): Promise<T> {
    return new Promise((resolve, reject) => {
      const header: Record<string, string> = {
        'Content-Type': 'application/json',
      }
      if (this.token) {
        header['Authorization'] = `Bearer ${this.token}`
      }

      uni.request({
        url: `${BASE_URL}${url}`,
        method: method as any,
        data,
        header,
        success: (res) => {
          const result = res.data as any
          if (result.code === 0 || result.code === undefined) {
            resolve(result.data ?? result)
          } else if (res.statusCode === 401) {
            uni.removeStorageSync('token')
            uni.redirectTo({ url: '/pages/login/index' })
            reject(new Error(result.message || '未登录'))
          } else {
            reject(new Error(result.message || '请求失败'))
          }
        },
        fail: (err) => {
          reject(new Error(err.errMsg || '网络错误'))
        },
      })
    })
  }

  get<T>(url: string, params?: any) {
    return this.request<T>('GET', url, params)
  }

  post<T>(url: string, data?: any) {
    return this.request<T>('POST', url, data)
  }

  put<T>(url: string, data?: any) {
    return this.request<T>('PUT', url, data)
  }

  delete<T>(url: string, data?: any) {
    return this.request<T>('DELETE', url, data)
  }
}

export const http = new HttpRequest()
