/**
 * [MOCK-B2B-001] B2B Trade数据源抽象层
 * AI注意: 这是数据源抽象层，业务组件通过此层获取数据
 * 仅在REACT_APP_USE_MOCK=true时启用Mock
 * 
 * @module services/b2bTradeDataSource
 * @created 2026-03-19
 */

import { IDataSource, IMockDataSource } from '@/types/datasource';

// ============================================
// 类型定义
// ============================================

export interface BatchOrderItem {
  key: string;
  lineNumber: number;
  productId: string;
  sku: string;
  productName: string;
  quantity: number;
  unitPrice: number;
  totalPrice: number;
  customerId: string;
  customerName: string;
  status: 'VALID' | 'INVALID' | 'PENDING';
  error?: string;
}

export interface BatchOrder {
  id: string;
  batchId: string;
  customerId: string;
  customerName: string;
  totalItems: number;
  totalAmount: number;
  currency: string;
  status: 'DRAFT' | 'PENDING_REVIEW' | 'CONFIRMED' | 'PROCESSING' | 'COMPLETED' | 'CANCELLED';
  createdAt: string;
  validItems: number;
  invalidItems: number;
}

export interface Customer {
  id: string;
  name: string;
  company: string;
  tier: 'BASIC' | 'PRO' | 'ENTERPRISE';
}

export interface BatchOrderQueryParams {
  customerId?: string;
  status?: string;
  startDate?: string;
  endDate?: string;
}

export interface BatchOrderStats {
  total: number;
  pending: number;
  processing: number;
  completed: number;
  totalAmount: number;
}

// ============================================
// B2B Trade专用接口
// ============================================

export interface IB2BTradeDataSource {
  fetchBatchOrders(params?: BatchOrderQueryParams): Promise<BatchOrder[]>;
  fetchBatchOrderDetail(batchId: string): Promise<BatchOrder | null>;
  fetchCustomers(): Promise<Customer[]>;
  fetchStats(): Promise<BatchOrderStats>;
  createBatchOrder(data: Partial<BatchOrder>): Promise<BatchOrder>;
  approveBatchOrder(batchId: string): Promise<BatchOrder>;
  validateItems(items: BatchOrderItem[]): Promise<BatchOrderItem[]>;
  parseUploadFile(file: File, customerId: string): Promise<BatchOrderItem[]>;
}

// ============================================
// API实现
// ============================================

class ApiB2BTradeDataSource implements IB2BTradeDataSource {
  async fetchBatchOrders(params?: BatchOrderQueryParams): Promise<BatchOrder[]> {
    const query = new URLSearchParams(params as any).toString();
    const response = await fetch(`/api/v1/b2b/batch-orders?${query}`);
    const result = await response.json();
    return result.data;
  }

  async fetchBatchOrderDetail(batchId: string): Promise<BatchOrder | null> {
    const response = await fetch(`/api/v1/b2b/batch-orders/${batchId}`);
    const result = await response.json();
    return result.data;
  }

  async fetchCustomers(): Promise<Customer[]> {
    const response = await fetch('/api/v1/b2b/customers');
    const result = await response.json();
    return result.data;
  }

  async fetchStats(): Promise<BatchOrderStats> {
    const response = await fetch('/api/v1/b2b/batch-orders/stats');
    const result = await response.json();
    return result.data;
  }

  async createBatchOrder(data: Partial<BatchOrder>): Promise<BatchOrder> {
    const response = await fetch('/api/v1/b2b/batch-orders', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data),
    });
    const result = await response.json();
    return result.data;
  }

  async approveBatchOrder(batchId: string): Promise<BatchOrder> {
    const response = await fetch(`/api/v1/b2b/batch-orders/${batchId}/approve`, {
      method: 'POST',
    });
    const result = await response.json();
    return result.data;
  }

  async validateItems(items: BatchOrderItem[]): Promise<BatchOrderItem[]> {
    const response = await fetch('/api/v1/b2b/batch-orders/validate', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ items }),
    });
    const result = await response.json();
    return result.data;
  }

  async parseUploadFile(file: File, customerId: string): Promise<BatchOrderItem[]> {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('customerId', customerId);
    const response = await fetch('/api/v1/b2b/batch-orders/parse', {
      method: 'POST',
      body: formData,
    });
    const result = await response.json();
    return result.data;
  }
}

// ============================================
// Mock实现
// ============================================

/**
 * [MOCK] B2B Trade Mock数据源
 * AI注意: 这是Mock实现，不是真实业务逻辑
 * 仅在REACT_APP_USE_MOCK=true时启用
 */
class MockB2BTradeDataSource implements IB2BTradeDataSource, IMockDataSource {
  readonly __MOCK__ = true as const;
  readonly __MOCK_NAME__ = 'MockB2BTradeDataSource';

  private mockBatchOrders: BatchOrder[] = [
    {
      id: '1',
      batchId: 'BO-2026-001',
      customerId: 'CUST_001',
      customerName: 'ABC Trading Co.',
      totalItems: 50,
      totalAmount: 25000.00,
      currency: 'USD',
      status: 'CONFIRMED',
      createdAt: '2026-03-18 10:00:00',
      validItems: 48,
      invalidItems: 2,
    },
    {
      id: '2',
      batchId: 'BO-2026-002',
      customerId: 'CUST_002',
      customerName: 'XYZ Electronics Ltd.',
      totalItems: 100,
      totalAmount: 45000.00,
      currency: 'USD',
      status: 'PENDING_REVIEW',
      createdAt: '2026-03-17 14:30:00',
      validItems: 95,
      invalidItems: 5,
    },
    {
      id: '3',
      batchId: 'BO-2026-003',
      customerId: 'CUST_003',
      customerName: 'Global Import Inc.',
      totalItems: 200,
      totalAmount: 85000.00,
      currency: 'USD',
      status: 'COMPLETED',
      createdAt: '2026-03-15 09:00:00',
      validItems: 200,
      invalidItems: 0,
    },
  ];

  private mockCustomers: Customer[] = [
    { id: 'CUST_001', name: 'ABC Trading Co.', company: 'ABC Trading', tier: 'ENTERPRISE' },
    { id: 'CUST_002', name: 'XYZ Electronics Ltd.', company: 'XYZ Electronics', tier: 'PRO' },
    { id: 'CUST_003', name: 'Global Import Inc.', company: 'Global Import', tier: 'ENTERPRISE' },
  ];

  async fetchBatchOrders(params?: BatchOrderQueryParams): Promise<BatchOrder[]> {
    await this.simulateDelay(400);
    let result = [...this.mockBatchOrders];
    if (params?.customerId) {
      result = result.filter(o => o.customerId === params.customerId);
    }
    if (params?.status) {
      result = result.filter(o => o.status === params.status);
    }
    return result;
  }

  async fetchBatchOrderDetail(batchId: string): Promise<BatchOrder | null> {
    await this.simulateDelay(300);
    return this.mockBatchOrders.find(o => o.batchId === batchId) || null;
  }

  async fetchCustomers(): Promise<Customer[]> {
    await this.simulateDelay(200);
    return [...this.mockCustomers];
  }

  async fetchStats(): Promise<BatchOrderStats> {
    await this.simulateDelay(150);
    return {
      total: this.mockBatchOrders.length,
      pending: this.mockBatchOrders.filter(o => o.status === 'PENDING_REVIEW').length,
      processing: this.mockBatchOrders.filter(o => o.status === 'PROCESSING').length,
      completed: this.mockBatchOrders.filter(o => o.status === 'COMPLETED').length,
      totalAmount: this.mockBatchOrders.filter(o => o.status === 'COMPLETED').reduce((sum, o) => sum + o.totalAmount, 0),
    };
  }

  async createBatchOrder(data: Partial<BatchOrder>): Promise<BatchOrder> {
    await this.simulateDelay(500);
    const newOrder: BatchOrder = {
      id: `${Date.now()}`,
      batchId: `BO-${Date.now()}`,
      customerId: data.customerId || '',
      customerName: data.customerName || '',
      totalItems: data.totalItems || 0,
      totalAmount: data.totalAmount || 0,
      currency: data.currency || 'USD',
      status: 'DRAFT',
      createdAt: new Date().toISOString(),
      validItems: data.validItems || 0,
      invalidItems: data.invalidItems || 0,
    };
    this.mockBatchOrders.unshift(newOrder);
    return newOrder;
  }

  async approveBatchOrder(batchId: string): Promise<BatchOrder> {
    await this.simulateDelay(300);
    const index = this.mockBatchOrders.findIndex(o => o.batchId === batchId);
    if (index === -1) throw new Error('Batch order not found');
    this.mockBatchOrders[index] = { ...this.mockBatchOrders[index], status: 'CONFIRMED' };
    return this.mockBatchOrders[index];
  }

  async validateItems(items: BatchOrderItem[]): Promise<BatchOrderItem[]> {
    await this.simulateDelay(1000);
    return items.map(item => ({
      ...item,
      status: item.productId ? 'VALID' : 'INVALID',
      error: item.productId ? undefined : 'Product not found',
    }));
  }

  async parseUploadFile(file: File, customerId: string): Promise<BatchOrderItem[]> {
    await this.simulateDelay(800);
    const customer = this.mockCustomers.find(c => c.id === customerId);
    return [
      { key: '1', lineNumber: 1, productId: 'PROD_001', sku: 'SKU-001', productName: 'Wireless Headphones', quantity: 100, unitPrice: 22.00, totalPrice: 2200.00, customerId, customerName: customer?.name || '', status: 'VALID' },
      { key: '2', lineNumber: 2, productId: 'PROD_002', sku: 'SKU-002', productName: 'USB-C Cable', quantity: 500, unitPrice: 4.50, totalPrice: 2250.00, customerId, customerName: customer?.name || '', status: 'VALID' },
      { key: '3', lineNumber: 3, productId: 'PROD_003', sku: 'SKU-003', productName: 'Phone Case', quantity: 200, unitPrice: 7.00, totalPrice: 1400.00, customerId, customerName: customer?.name || '', status: 'VALID' },
      { key: '4', lineNumber: 4, productId: 'PROD_004', sku: 'SKU-004', productName: 'Invalid Product', quantity: 50, unitPrice: 0, totalPrice: 0, customerId, customerName: customer?.name || '', status: 'INVALID', error: 'Product not found' },
    ];
  }

  private simulateDelay(ms: number): Promise<void> {
    return new Promise(resolve => setTimeout(resolve, ms));
  }
}

// ============================================
// 导出数据源实例
// ============================================

const useMock = process.env.REACT_APP_USE_MOCK === 'true';

export const b2bTradeDataSource: IB2BTradeDataSource = useMock
  ? new MockB2BTradeDataSource()
  : new ApiB2BTradeDataSource();

export const __MOCK__ = useMock;
export const __DATA_SOURCE_TYPE__ = useMock ? 'mock' : 'api';
