/**
 * 订单管理相关API
 */

import { USE_MOCK } from '@/utils/config';
import { mockOrderList, mockOrderDetail } from '@/mock';

export interface OrderQueryParams {
  page?: number;
  pageSize?: number;
  orderNo?: string;
  status?: number;
  shopId?: number;
  startTime?: string;
  endTime?: string;
}

export interface OrderListResponse {
  list: any[];
  total: number;
  page: number;
  pageSize: number;
}

/**
 * 获取订单列表
 */
export async function getOrderList(params: OrderQueryParams = {}): Promise<OrderListResponse> {
  if (USE_MOCK) {
    const { page = 1, pageSize = 10, status, orderNo } = params;
    let list = [...mockOrderList];
    
    // 状态筛选
    if (status !== undefined && status !== -1) {
      list = list.filter(item => item.status === status);
    }
    
    // 订单号搜索
    if (orderNo) {
      list = list.filter(item => item.orderNo.includes(orderNo));
    }
    
    const total = list.length;
    const startIndex = (page - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    
    return Promise.resolve({
      list: list.slice(startIndex, endIndex),
      total,
      page,
      pageSize
    });
  }
  
  const { get } = await import('@/utils/request');
  return get('/orders', params);
}

/**
 * 获取订单详情
 */
export async function getOrderDetail(orderId: number): Promise<any> {
  if (USE_MOCK) {
    return Promise.resolve(mockOrderDetail);
  }
  
  const { get } = await import('@/utils/request');
  return get(`/orders/${orderId}`);
}

/**
 * 获取订单统计
 */
export async function getOrderStats(): Promise<any> {
  if (USE_MOCK) {
    return Promise.resolve({
      totalCount: 156,
      completedCount: 120,
      pendingCount: 15,
      refundingCount: 8,
      cancelledCount: 13,
      totalAmount: 25680
    });
  }
  
  const { get } = await import('@/utils/request');
  return get('/orders/stats');
}

/**
 * 处理退款
 */
export async function handleRefund(orderId: number, agree: boolean, reason?: string): Promise<void> {
  if (USE_MOCK) {
    return Promise.resolve();
  }
  
  const { post } = await import('@/utils/request');
  await post(`/orders/${orderId}/refund`, { agree, reason });
}
