/**
 * HTTP请求封装
 */

import { getToken, clearAuth } from './auth';
import { API_BASE_URL } 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;

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

  const token = getToken();
  if (token) {
    header['adminAccessToken'] = 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过期，清除登录状态并跳转登录
          clearAuth();
          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);
      }
    });
  });
}

/**
 * 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 });
}
