/**
 * HTTP请求封装
 */

import { getToken } from './auth';
import { API_BASE_URL, USE_MOCK } from './config';

interface RequestOptions {
  url: string;
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
  data?: any;
  header?: Record<string, string>;
  showLoading?: boolean;
  showError?: boolean;
}

interface Response<T = any> {
  code: number;
  message: string;
  data: T;
}

/**
 * 发起HTTP请求
 */
export function request<T = any>(options: RequestOptions): Promise<T> {
  const { url, method = 'GET', data, header = {}, showLoading = true, showError = true } = options;

  // 如果使用Mock数据，返回Mock数据
  if (USE_MOCK) {
    return handleMockRequest<T>(url, method, data);
  }

  if (showLoading) {
    uni.showLoading({ title: '加载中...', mask: true });
  }

  const token = getToken();
  if (token) {
    header['Authorization'] = `Bearer ${token}`;
  }
  header['Content-Type'] = 'application/json';

  return new Promise((resolve, reject) => {
    uni.request({
      url: `${API_BASE_URL}${url}`,
      method,
      data,
      header,
      success: (res: any) => {
        if (showLoading) {
          uni.hideLoading();
        }
        
        const response = res.data as Response<T>;
        
        if (response.code === 200) {
          resolve(response.data);
        } else if (response.code === 401) {
          // Token过期，跳转登录
          uni.removeStorageSync('admin_token');
          uni.reLaunch({ url: '/pages/login/login' });
          reject(new Error('登录已过期'));
        } else {
          if (showError) {
            uni.showToast({
              title: response.message || '请求失败',
              icon: 'none'
            });
          }
          reject(new Error(response.message));
        }
      },
      fail: (err) => {
        if (showLoading) {
          uni.hideLoading();
        }
        if (showError) {
          uni.showToast({
            title: '网络请求失败',
            icon: 'none'
          });
        }
        reject(err);
      }
    });
  });
}

/**
 * 处理Mock请求 - 简单实现，实际Mock数据在mock.ts中
 */
function handleMockRequest<T>(url: string, method: string, data: any): Promise<T> {
  return new Promise((resolve) => {
    setTimeout(() => {
      // 这里返回空数据，实际由各个API模块处理
      resolve({} as T);
    }, 300);
  });
}

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

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

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

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