/**
 * [BE-P001] 商品管理数据源抽象层
 * 符合逻辑集中化原则 - 所有商品管理业务逻辑集中在此层
 * AI注意: 这是真实业务逻辑抽象层，不是Mock实现
 * 类型定义: Schema驱动，从productManagement.schema.ts推导
 */

import { 
  ExtendedProduct, 
  ProductFilterParams, 
  ProductSortParams, 
  ProductStatistics, 
  Shop,
  ProductManagementStatus 
} from '../types/productManagement';

// 商品管理数据源接口
interface ProductManagementDataSource {
  // 查询商品列表
  listProducts(params: ProductFilterParams & ProductSortParams): Promise<{
    data: ExtendedProduct[];
    total: number;
    statistics: ProductStatistics;
  }>;
  
  // 获取商品详情
  getProduct(id: string): Promise<ExtendedProduct | null>;
  
  // 更新商品状态
  updateProductStatus(id: string, status: ProductManagementStatus): Promise<ExtendedProduct | null>;
  
  // 批量操作
  batchUpdateProducts(productIds: string[], updates: Partial<ExtendedProduct>): Promise<number>;
  batchDeleteProducts(productIds: string[]): Promise<number>;
  
  // 获取统计信息
  getProductStatistics(params?: { startDate?: string; endDate?: string }): Promise<ProductStatistics>;
  
  // 获取店铺列表
  getShops(): Promise<Shop[]>;
  
  // 获取分类列表
  getCategories(): Promise<string[]>;
}

// Mock实现 - 开发环境使用
export class ProductManagementMockDataSource implements ProductManagementDataSource {
  private mockProducts: ExtendedProduct[] = [
    {
      id: '1',
      sku: 'TP-TEMP-001',
      name: '工业温度传感器',
      images: ['https://via.placeholder.com/60x60'],
      categories: ['传感器'],
      price: 89.99,
      costPrice: 45.50,
      profit: 44.49,
      roi: 97.8,
      stock: 150,
      status: 'active',
      platformStatus: { 'AMAZON': 'Active', 'EBAY': 'Active' },
      shopId: 'shop-amazon-1',
      shopName: 'Amazon美国店A',
      platform: 'Amazon',
      managementStatus: 'LIVE',
      createdAt: '2026-03-18T10:30:00Z',
      updatedAt: '2026-03-18T10:30:00Z'
    },
    // 更多模拟商品数据...
  ];

  private mockShops: Shop[] = [
    // TikTok平台 - 多个店铺
    { id: 'shop-tiktok-1', name: 'TikTok旗舰店A', platform: 'TikTok', status: 'ACTIVE', region: '中国', currency: 'CNY' },
    { id: 'shop-tiktok-2', name: 'TikTok旗舰店B', platform: 'TikTok', status: 'ACTIVE', region: '美国', currency: 'USD' },
    { id: 'shop-tiktok-3', name: 'TikTok精品店C', platform: 'TikTok', status: 'ACTIVE', region: '欧洲', currency: 'EUR' },
    
    // Shopee平台 - 多个店铺
    { id: 'shop-shopee-1', name: 'Shopee官方店A', platform: 'Shopee', status: 'ACTIVE', region: '东南亚', currency: 'SGD' },
    { id: 'shop-shopee-2', name: 'Shopee官方店B', platform: 'Shopee', status: 'ACTIVE', region: '台湾', currency: 'TWD' },
    
    // Amazon平台 - 多个店铺
    { id: 'shop-amazon-1', name: 'Amazon美国店A', platform: 'Amazon', status: 'ACTIVE', region: '美国', currency: 'USD' },
    { id: 'shop-amazon-2', name: 'Amazon美国店B', platform: 'Amazon', status: 'ACTIVE', region: '美国', currency: 'USD' },
    { id: 'shop-amazon-3', name: 'Amazon欧洲店C', platform: 'Amazon', status: 'ACTIVE', region: '欧洲', currency: 'EUR' },
  ];

  private mockCategories = ['传感器', '控制器', '执行器', '连接器', '显示器', '电源', '通信模块'];

  async listProducts(params: ProductFilterParams & ProductSortParams): Promise<{
    data: ExtendedProduct[];
    total: number;
    statistics: ProductStatistics;
  }> {
    // 筛选逻辑集中在此处
    let filteredProducts = this.mockProducts;
    
    // 关键词筛选
    if (params.keyword) {
      filteredProducts = filteredProducts.filter(product => 
        product.sku.toLowerCase().includes(params.keyword!.toLowerCase()) ||
        product.name.toLowerCase().includes(params.keyword!.toLowerCase())
      );
    }
    
    // 分类筛选
    if (params.category && params.category.length > 0) {
      filteredProducts = filteredProducts.filter(product =>
        product.categories && params.category!.some(cat => product.categories!.includes(cat))
      );
    }
    
    // 平台筛选
    if (params.platform && params.platform.length > 0) {
      filteredProducts = filteredProducts.filter(product => params.platform!.includes(product.platform));
    }
    
    // 店铺筛选
    if (params.shop && params.shop.length > 0) {
      filteredProducts = filteredProducts.filter(product => params.shop!.includes(product.shopId));
    }
    
    // 状态筛选
    if (params.status && params.status.length > 0) {
      filteredProducts = filteredProducts.filter(product => params.status!.includes(product.managementStatus));
    }
    
    // 价格范围筛选
    if (params.priceRange) {
      const [min, max] = params.priceRange;
      filteredProducts = filteredProducts.filter(product => product.price >= min && product.price <= max);
    }
    
    // 日期范围筛选
    if (params.dateRange) {
      const [startDate, endDate] = params.dateRange;
      filteredProducts = filteredProducts.filter(product => {
        const productDate = new Date(product.createdAt).getTime();
        return productDate >= new Date(startDate).getTime() && productDate <= new Date(endDate).getTime();
      });
    }
    
    // 排序逻辑集中在此处
    if (params.field && params.order) {
      filteredProducts.sort((a, b) => {
        const aValue = a[params.field as keyof ExtendedProduct];
        const bValue = b[params.field as keyof ExtendedProduct];
        
        if (typeof aValue === 'number' && typeof bValue === 'number') {
          return params.order === 'ascend' ? aValue - bValue : bValue - aValue;
        }
        
        if (typeof aValue === 'string' && typeof bValue === 'string') {
          return params.order === 'ascend' ? aValue.localeCompare(bValue) : bValue.localeCompare(aValue);
        }
        
        return 0;
      });
    }
    
    // 分页逻辑集中在此处
    const page = params.page || 1;
    const pageSize = params.pageSize || 10;
    const start = (page - 1) * pageSize;
    const end = start + pageSize;
    const paginatedProducts = filteredProducts.slice(start, end);
    
    // 统计信息计算集中在此处
    const statistics = this.calculateStatistics(filteredProducts);
    
    return {
      data: paginatedProducts,
      total: filteredProducts.length,
      statistics
    };
  }

  async getProduct(id: string): Promise<ExtendedProduct | null> {
    return this.mockProducts.find(product => product.id === id) || null;
  }

  async updateProductStatus(id: string, status: ProductManagementStatus): Promise<ExtendedProduct | null> {
    const product = await this.getProduct(id);
    if (!product) return null;

    product.managementStatus = status;
    product.updatedAt = new Date().toISOString();
    return product;
  }

  async batchUpdateProducts(productIds: string[], updates: Partial<ExtendedProduct>): Promise<number> {
    let count = 0;
    for (const productId of productIds) {
      const product = await this.getProduct(productId);
      if (product) {
        Object.assign(product, updates);
        product.updatedAt = new Date().toISOString();
        count++;
      }
    }
    return count;
  }

  async batchDeleteProducts(productIds: string[]): Promise<number> {
    let count = 0;
    for (const productId of productIds) {
      const index = this.mockProducts.findIndex(p => p.id === productId);
      if (index !== -1) {
        this.mockProducts.splice(index, 1);
        count++;
      }
    }
    return count;
  }

  async getProductStatistics(params?: { startDate?: string; endDate?: string }): Promise<ProductStatistics> {
    let products = this.mockProducts;
    
    if (params?.startDate && params?.endDate) {
      products = products.filter(product => {
        const productDate = new Date(product.createdAt).getTime();
        return productDate >= new Date(params.startDate!).getTime() && 
               productDate <= new Date(params.endDate!).getTime();
      });
    }
    
    return this.calculateStatistics(products);
  }

  async getShops() {
    return this.mockShops;
  }

  async getCategories() {
    return this.mockCategories;
  }

  private calculateStatistics(products: ExtendedProduct[]): ProductStatistics {
    return {
      totalProducts: products.length,
      draft: products.filter(p => p.managementStatus === 'DRAFT').length,
      priced: products.filter(p => p.managementStatus === 'PRICED').length,
      listed: products.filter(p => p.managementStatus === 'LISTED').length,
      live: products.filter(p => p.managementStatus === 'LIVE').length,
      offline: products.filter(p => p.managementStatus === 'OFFLINE').length,
      totalValue: products.reduce((sum, product) => sum + product.price * product.stock, 0),
      totalProfit: products.reduce((sum, product) => sum + (product.profit || 0), 0)
    };
  }
}

// 真实实现 - 生产环境使用
export class ProductManagementDataSourceImpl implements ProductManagementDataSource {
  // 真实API调用实现
  async listProducts(params: ProductFilterParams & ProductSortParams): Promise<{
    data: ExtendedProduct[];
    total: number;
    statistics: ProductStatistics;
  }> {
    // 调用真实API
    throw new Error('真实API实现待开发');
  }

  async getProduct(id: string): Promise<ExtendedProduct | null> {
    throw new Error('真实API实现待开发');
  }

  async updateProductStatus(id: string, status: ProductManagementStatus): Promise<ExtendedProduct | null> {
    throw new Error('真实API实现待开发');
  }

  async batchUpdateProducts(productIds: string[], updates: Partial<ExtendedProduct>): Promise<number> {
    throw new Error('真实API实现待开发');
  }

  async batchDeleteProducts(productIds: string[]): Promise<number> {
    throw new Error('真实API实现待开发');
  }

  async getProductStatistics(params?: { startDate?: string; endDate?: string }): Promise<ProductStatistics> {
    throw new Error('真实API实现待开发');
  }

  async getShops(): Promise<Shop[]> {
    throw new Error('真实API实现待开发');
  }

  async getCategories(): Promise<string[]> {
    throw new Error('真实API实现待开发');
  }
}

// 数据源工厂函数
export const createProductManagementDataSource = (): ProductManagementDataSource => {
  const useMock = process.env.NODE_ENV === 'development' || process.env.REACT_APP_USE_MOCK === 'true';
  return useMock ? new ProductManagementMockDataSource() : new ProductManagementDataSourceImpl();
};

export type { ExtendedProduct, ProductFilterParams, ProductSortParams, ProductStatistics, Shop };