import axios from 'axios';

// 请求缓存
const requestCache = new Map<string, { data: any; timestamp: number }>();
const CACHE_DURATION = 5 * 60 * 1000; // 5分钟缓存

// 创建axios实例
const api = axios.create({
  baseURL: 'http://localhost:3000/api', // 后端API基础URL
  timeout: 10000, // 请求超时时间
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    // 可以在这里添加token等认证信息
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    // 缓存GET请求的响应
    if (response.config.method === 'get') {
      const cacheKey = `${response.config.url}${JSON.stringify(response.config.params)}`;
      requestCache.set(cacheKey, {
        data: response.data,
        timestamp: Date.now()
      });
    }
    return response.data;
  },
  (error) => {
    // 统一错误处理
    console.error('API Error:', error);
    return Promise.reject(error);
  }
);

// 带缓存的GET请求
const cachedGet = async (url: string, params?: any) => {
  const cacheKey = `${url}${JSON.stringify(params)}`;
  const cachedItem = requestCache.get(cacheKey);
  
  if (cachedItem && (Date.now() - cachedItem.timestamp) < CACHE_DURATION) {
    return cachedItem.data;
  }
  
  const response = await api.get(url, { params });
  return response;
};

// 批量请求处理
const batchRequest = async (requests: Array<{ url: string; method: string; data?: any; params?: any }>) => {
  try {
    const responses = await Promise.all(
      requests.map(request => {
        if (request.method === 'get') {
          return cachedGet(request.url, request.params);
        } else {
          return api[request.method as keyof typeof api](request.url, request.data, { params: request.params });
        }
      })
    );
    return responses;
  } catch (error) {
    console.error('Batch request failed:', error);
    throw error;
  }
};

// 商品相关API
export const productApi = {
  // 获取商品列表
  getProducts: (params?: any) => cachedGet('/products', params),
  
  // 获取商品详情
  getProduct: (id: string) => cachedGet(`/products/${id}`),
  
  // 创建商品
  createProduct: (data: any) => api.post('/products', data),
  
  // 更新商品
  updateProduct: (id: string, data: any) => api.put(`/products/${id}`, data),
  
  // 修改商品价格
  updatePrice: (id: string, price: number) => api.patch(`/products/${id}/price`, { price }),
  
  // AI定价
  getAiPricing: (id: string) => cachedGet(`/products/${id}/ai-pricing`),
  
  // 上下架商品
  toggleStatus: (id: string) => api.patch(`/products/${id}/status`),
  
  // 批量操作
  batchUpdate: (ids: string[], data: any) => api.post('/products/batch', { ids, data }),
  
  // 批量获取商品详情
  batchGetProducts: (ids: string[]) => batchRequest(
    ids.map(id => ({ url: `/products/${id}`, method: 'get' }))
  ),
};

// 订单相关API
export const orderApi = {
  // 获取订单列表
  getOrders: (params?: any) => cachedGet('/orders', params),
  
  // 获取订单详情
  getOrder: (id: string) => cachedGet(`/orders/${id}`),
  
  // 更新订单状态
  updateStatus: (id: string, status: string) => api.patch(`/orders/${id}/status`, { status }),
  
  // 处理订单
  processOrder: (id: string, data: any) => api.post(`/orders/${id}/process`, data),
  
  // 批量获取订单详情
  batchGetOrders: (ids: string[]) => batchRequest(
    ids.map(id => ({ url: `/orders/${id}`, method: 'get' }))
  ),
};

// Dashboard相关API
export const dashboardApi = {
  // 获取Dashboard数据
  getDashboardData: (params?: any) => cachedGet('/dashboard', params),
};

// 导出批量请求函数
export const apiUtils = {
  batchRequest,
  cachedGet,
  clearCache: () => requestCache.clear(),
};

export default api;