/**
 * 商品管理相关API
 */

import { USE_MOCK } from '@/utils/config';
import { mockProductList, mockProductCategories } from '@/mock';

export interface ProductQueryParams {
  page?: number;
  pageSize?: number;
  name?: string;
  category?: string;
  status?: number;
}

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

/**
 * 获取商品列表
 */
export async function getProductList(params: ProductQueryParams = {}): Promise<ProductListResponse> {
  if (USE_MOCK) {
    const { page = 1, pageSize = 10, status, name, category } = params;
    let list = [...mockProductList];
    
    // 状态筛选
    if (status !== undefined && status !== -1) {
      list = list.filter(item => item.status === status);
    }
    
    // 分类筛选
    if (category) {
      list = list.filter(item => item.category === category);
    }
    
    // 名称搜索
    if (name) {
      list = list.filter(item => item.name.includes(name));
    }
    
    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('/products', params);
}

/**
 * 获取商品分类
 */
export async function getProductCategories(): Promise<any[]> {
  if (USE_MOCK) {
    return Promise.resolve(mockProductCategories);
  }
  
  const { get } = await import('@/utils/request');
  return get('/products/categories');
}

/**
 * 获取商品详情
 */
export async function getProductDetail(productId: number): Promise<any> {
  if (USE_MOCK) {
    const product = mockProductList.find(item => item.id === productId);
    return Promise.resolve(product || null);
  }
  
  const { get } = await import('@/utils/request');
  return get(`/products/${productId}`);
}
