// HTTP请求工具类
import { API, buildURL, getHeaders } from '../config/api';

// 请求响应接口
interface ApiResponse<T = any> {
  code: number;
  message: string;
  data?: T;
}

// 请求配置
interface RequestOptions {
  url: string;
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
  data?: any;
  showLoading?: boolean;
  loadingText?: string;
}

/**
 * 统一请求方法
 */
export function request<T = any>(options: RequestOptions): Promise<ApiResponse<T>> {
  const {
    url,
    method = 'GET',
    data,
    showLoading = true,
    loadingText = '加载中...'
  } = options;

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

  return new Promise((resolve, reject) => {
    wx.request({
      url: buildURL(url),
      method,
      data,
      header: getHeaders(),
      timeout: API.timeout,
      success: (res: any) => {
        if (showLoading) {
          wx.hideLoading();
        }

        const response = res.data as ApiResponse<T>;

        // 处理业务状态码
        if (response.code === 200) {
          resolve(response);
        } else if (response.code === 401) {
          // Token过期或未登录
          wx.showToast({
            title: '请先登录',
            icon: 'none'
          });
          // 清除token并跳转到登录页
          wx.removeStorageSync('token');
          wx.removeStorageSync('userInfo');
          setTimeout(() => {
            wx.redirectTo({
              url: '/pages/login/login'
            });
          }, 1500);
          reject(response);
        } else {
          // 其他错误
          wx.showToast({
            title: response.message || '请求失败',
            icon: 'none'
          });
          reject(response);
        }
      },
      fail: (error) => {
        if (showLoading) {
          wx.hideLoading();
        }
        
        console.error('请求失败:', error);
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
        reject(error);
      }
    });
  });
}

/**
 * GET请求
 */
export function get<T = any>(url: string, data?: any, showLoading = true): Promise<ApiResponse<T>> {
  // 将参数拼接到URL
  if (data) {
    const params = Object.keys(data)
      .map(key => `${key}=${encodeURIComponent(data[key])}`)
      .join('&');
    url = `${url}?${params}`;
  }

  return request<T>({
    url,
    method: 'GET',
    showLoading
  });
}

/**
 * POST请求
 */
export function post<T = any>(url: string, data?: any, showLoading = true): Promise<ApiResponse<T>> {
  return request<T>({
    url,
    method: 'POST',
    data,
    showLoading
  });
}

/**
 * PUT请求
 */
export function put<T = any>(url: string, data?: any, showLoading = true): Promise<ApiResponse<T>> {
  return request<T>({
    url,
    method: 'PUT',
    data,
    showLoading
  });
}

/**
 * DELETE请求
 */
export function del<T = any>(url: string, data?: any, showLoading = true): Promise<ApiResponse<T>> {
  return request<T>({
    url,
    method: 'DELETE',
    data,
    showLoading
  });
}
