/**
 * HTTP请求工具类
 * 封装uni.request，统一处理请求和响应
 */

import { API_CONFIG } from './config';
import { getToken, removeToken } from './auth';

/**
 * 请求配置接口
 */
interface RequestConfig {
  url: string;
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
  data?: any;
  header?: any;
  timeout?: number;
}

/**
 * 响应数据接口
 */
interface ResponseData<T = any> {
  code: number;
  message: string;
  data?: T;
}

/**
 * 发起HTTP请求
 * @param config 请求配置
 * @returns Promise<响应数据>
 */
export const request = <T = any>(config: RequestConfig): Promise<T> => {
  return new Promise((resolve, reject) => {
    const { url, method = 'GET', data, header = {}, timeout = API_CONFIG.timeout } = config;
    
    // 构建完整URL
    const fullUrl = url.startsWith('http') ? url : `${API_CONFIG.baseUrl}${url}`;
    
    // 添加token到请求头
    const token = getToken();
    if (token) {
      header['access_token'] = token;
    }
    
    // 添加Content-Type
    if (!header['Content-Type']) {
      header['Content-Type'] = 'application/json';
    }
    
    // 打印请求日志
    if (API_CONFIG.enableLog) {
      console.log(`[请求] ${method} ${fullUrl}`, data);
    }
    
    // 发起请求
    uni.request({
      url: fullUrl,
      method,
      data,
      header,
      timeout,
      success: (res: any) => {
        // 打印响应日志
        if (API_CONFIG.enableLog) {
          console.log(`[响应] ${method} ${fullUrl}`, res.data);
        }
        
        const responseData = res.data as ResponseData<T>;
        
        // 处理HTTP状态码
        if (res.statusCode !== 200) {
          const errorMsg = `请求失败: HTTP ${res.statusCode}`;
          uni.showToast({
            title: errorMsg,
            icon: 'none'
          });
          reject(new Error(errorMsg));
          return;
        }
        
        // 处理业务状态码
        if (responseData.code === 200 || responseData.code === 0) {
          // 成功
          resolve(responseData.data as T);
        } else if (responseData.code === 401) {
          // 未登录或token过期
          uni.showToast({
            title: '请先登录',
            icon: 'none'
          });
          // 清除token
          removeToken();
          // 跳转到登录页
          setTimeout(() => {
            uni.reLaunch({ url: '/pages/login/login' });
          }, 1500);
          reject(new Error(responseData.message || '未登录'));
        } else {
          // 业务错误
          const errorMsg = responseData.message || '操作失败';
          uni.showToast({
            title: errorMsg,
            icon: 'none'
          });
          reject(new Error(errorMsg));
        }
      },
      fail: (err: any) => {
        // 网络错误
        console.error(`[请求失败] ${method} ${fullUrl}`, err);
        
        let errorMsg = '网络请求失败';
        if (err.errMsg) {
          if (err.errMsg.includes('timeout')) {
            errorMsg = '请求超时，请检查网络';
          } else if (err.errMsg.includes('fail')) {
            errorMsg = '网络连接失败，请检查网络';
          }
        }
        
        uni.showToast({
          title: errorMsg,
          icon: 'none'
        });
        
        reject(new Error(errorMsg));
      }
    });
  });
};

/**
 * GET请求
 */
export const get = <T = any>(url: string, data?: any): Promise<T> => {
  return request<T>({ url, method: 'GET', data });
};

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

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

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