/** 全局API工具 统一管理所有HTTP请求，确保都通过中间件处理 */

import { demoRequest, request } from '@/service/request';
import type { RequestInstanceState } from '@/service/request/type';

// 创建全局API对象，供动态组件使用
export const globalAPI = {
  // 标准请求实例（带完整中间件）
  request,

  // 演示请求实例
  demoRequest,

  // 便捷方法 - 封装常用HTTP方法
  get: <T = any>(url: string, params?: any) => {
    return request<T>({
      method: 'GET',
      url,
      params
    });
  },

  post: <T = any>(url: string, data?: any) => {
    return request<T>({
      method: 'POST',
      url,
      data
    });
  },

  put: <T = any>(url: string, data?: any) => {
    return request<T>({
      method: 'PUT',
      url,
      data
    });
  },

  delete: <T = any>(url: string, params?: any) => {
    return request<T>({
      method: 'DELETE',
      url,
      params
    });
  },

  // 批量请求工具
  batch: {
    parallel: async <T = any>(requests: Array<() => Promise<T>>) => {
      return Promise.all(requests.map(req => req()));
    },

    serial: async <T = any>(requests: Array<() => Promise<T>>) => {
      const results: T[] = [];
      for (const req of requests) {
        const result = await req();
        results.push(result);
      }
      return results;
    }
  },

  // 状态管理
  getState: (): RequestInstanceState => request.state,

  // 请求取消
  cancel: (requestId?: string) => {
    if (requestId) {
      request.cancelRequest(requestId);
    } else {
      request.cancelAllRequest();
    }
  }
};

// 类型定义
export type GlobalAPI = typeof globalAPI;

// 扩展window类型
declare global {
  interface Window {
    $api: GlobalAPI;
  }
}
