/**
 * [BE-O001] 订单管理数据源抽象层
 * 符合逻辑集中化原则 - 所有订单管理业务逻辑集中在此层
 * AI注意: 这是真实业务逻辑抽象层，不是Mock实现
 */

import { Order, OrderStatus, OrderItem, ShippingAddress } from '../types/order';

// 扩展订单接口，支持多平台多店铺
interface ExtendedOrder extends Order {
  orderId: string;
  platform: string;
  shopId: string;
  shopName: string;
  trackingNumber?: string;
  carrier?: string;
  estimatedDelivery?: string;
  actualDelivery?: string;
  exceptionReason?: string;
  paymentStatus: 'PENDING' | 'PAID' | 'REFUNDED';
  itemCount: number;
}

// 筛选参数接口
interface OrderFilterParams {
  keyword?: string;
  status?: string[];
  platform?: string[];
  shop?: string[];
  paymentStatus?: string[];
  dateRange?: [string, string];
  page?: number;
  pageSize?: number;
}

// 排序参数接口
interface OrderSortParams {
  field: string;
  order: 'ascend' | 'descend' | null;
}

// 订单统计接口
interface OrderStatistics {
  totalOrders: number;
  pending: number;
  processing: number;
  completed: number;
  exception: number;
  totalAmount: number;
}

// 订单管理数据源接口
interface OrderManagementDataSource {
  // 查询订单列表
  listOrders(params: OrderFilterParams & OrderSortParams): Promise<{
    data: ExtendedOrder[];
    total: number;
    statistics: OrderStatistics;
  }>;
  
  // 获取订单详情
  getOrder(id: string): Promise<ExtendedOrder | null>;
  
  // 更新订单状态
  updateOrderStatus(id: string, status: OrderStatus): Promise<ExtendedOrder | null>;
  
  // 批量操作
  batchConfirmOrders(orderIds: string[]): Promise<number>;
  batchShipOrders(orderIds: string[], trackingInfo: { trackingNumber: string; carrier: string }): Promise<number>;
  batchCancelOrders(orderIds: string[], reason: string): Promise<number>;
  
  // 获取统计信息
  getOrderStatistics(params?: { startDate?: string; endDate?: string }): Promise<OrderStatistics>;
  
  // 获取店铺列表
  getShops(): Promise<Array<{
    id: string;
    name: string;
    platform: string;
    status: 'ACTIVE' | 'INACTIVE' | 'SUSPENDED';
    region: string;
    currency: string;
  }>>;
}

// Mock实现 - 开发环境使用
export class OrderManagementMockDataSource implements OrderManagementDataSource {
  private mockOrders: ExtendedOrder[] = [
    {
      id: '1',
      orderId: 'ORD-2026-001',
      platform: 'AMAZON',
      customerId: 'cust_1',
      customerName: '张三',
      shopId: 'shop-amazon-1',
      shopName: 'Amazon美国店A',
      totalAmount: 159.99,
      status: 'shipped',
      paymentStatus: 'PAID',
      itemCount: 3,
      trackingNumber: '1Z999AA10123456784',
      carrier: 'UPS',
      estimatedDelivery: '2026-03-22',
      items: [
        { productId: 'i1', productName: '工业温度传感器', quantity: 2, unitPrice: 89.99, totalPrice: 179.98 },
        { productId: 'i2', productName: '连接线 1m', quantity: 1, unitPrice: 19.99, totalPrice: 19.99 }
      ],
      shippingAddress: {
        name: '张三',
        address: '北京市朝阳区xxx街道xxx号',
        city: '北京',
        country: '中国',
        zip: '100000'
      },
      paymentMethod: 'credit_card',
      createdAt: new Date('2026-03-18'),
      updatedAt: new Date('2026-03-18')
    },
    // 更多模拟订单数据...
  ];

  private mockShops: Array<{
    id: string;
    name: string;
    platform: string;
    status: 'ACTIVE' | 'INACTIVE' | 'SUSPENDED';
    region: string;
    currency: string;
  }> = [
    { 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' },
  ];

  async listOrders(params: OrderFilterParams & OrderSortParams): Promise<{
    data: ExtendedOrder[];
    total: number;
    statistics: OrderStatistics;
  }> {
    // 筛选逻辑集中在此处
    let filteredOrders = this.mockOrders;
    
    // 关键词筛选
    if (params.keyword) {
      filteredOrders = filteredOrders.filter(order =>
        order.orderId.toLowerCase().includes(params.keyword!.toLowerCase()) ||
        (order.customerName && order.customerName.toLowerCase().includes(params.keyword!.toLowerCase()))
      );
    }
    
    // 状态筛选
    if (params.status && params.status.length > 0) {
      filteredOrders = filteredOrders.filter(order => params.status!.includes(order.status));
    }
    
    // 平台筛选
    if (params.platform && params.platform.length > 0) {
      filteredOrders = filteredOrders.filter(order => params.platform!.includes(order.platform));
    }
    
    // 店铺筛选
    if (params.shop && params.shop.length > 0) {
      filteredOrders = filteredOrders.filter(order => params.shop!.includes(order.shopId));
    }
    
    // 支付状态筛选
    if (params.paymentStatus && params.paymentStatus.length > 0) {
      filteredOrders = filteredOrders.filter(order => params.paymentStatus!.includes(order.paymentStatus));
    }
    
    // 日期范围筛选
    if (params.dateRange) {
      const [startDate, endDate] = params.dateRange;
      filteredOrders = filteredOrders.filter(order => {
        const orderDate = new Date(order.createdAt).getTime();
        return orderDate >= new Date(startDate).getTime() && orderDate <= new Date(endDate).getTime();
      });
    }
    
    // 排序逻辑集中在此处
    if (params.field && params.order) {
      filteredOrders.sort((a, b) => {
        const aValue = a[params.field as keyof ExtendedOrder];
        const bValue = b[params.field as keyof ExtendedOrder];
        
        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 paginatedOrders = filteredOrders.slice(start, end);
    
    // 统计信息计算集中在此处
    const statistics = this.calculateStatistics(filteredOrders);
    
    return {
      data: paginatedOrders,
      total: filteredOrders.length,
      statistics
    };
  }

  async getOrder(id: string): Promise<ExtendedOrder | null> {
    return this.mockOrders.find(order => order.id === id) || null;
  }

  async updateOrderStatus(id: string, status: OrderStatus): Promise<ExtendedOrder | null> {
    const order = await this.getOrder(id);
    if (!order) return null;
    
    order.status = status;
    order.updatedAt = new Date();
    return order;
  }

  async batchConfirmOrders(orderIds: string[]): Promise<number> {
    let count = 0;
    for (const orderId of orderIds) {
      const order = await this.getOrder(orderId);
      if (order && order.status === 'pending') {
        order.status = 'confirmed';
        order.updatedAt = new Date();
        count++;
      }
    }
    return count;
  }

  async batchShipOrders(orderIds: string[], trackingInfo: { trackingNumber: string; carrier: string }): Promise<number> {
    let count = 0;
    for (const orderId of orderIds) {
      const order = await this.getOrder(orderId);
      if (order && order.status === 'confirmed') {
        order.status = 'shipped';
        order.trackingNumber = trackingInfo.trackingNumber;
        order.carrier = trackingInfo.carrier;
        order.updatedAt = new Date();
        count++;
      }
    }
    return count;
  }

  async batchCancelOrders(orderIds: string[], reason: string): Promise<number> {
    let count = 0;
    for (const orderId of orderIds) {
      const order = await this.getOrder(orderId);
      if (order && ['pending', 'confirmed'].includes(order.status)) {
        order.status = 'cancelled';
        order.exceptionReason = reason;
        order.updatedAt = new Date();
        count++;
      }
    }
    return count;
  }

  async getOrderStatistics(params?: { startDate?: string; endDate?: string }): Promise<OrderStatistics> {
    let orders = this.mockOrders;
    
    if (params?.startDate && params?.endDate) {
      orders = orders.filter(order => {
        const orderDate = new Date(order.createdAt).getTime();
        return orderDate >= new Date(params.startDate!).getTime() && 
               orderDate <= new Date(params.endDate!).getTime();
      });
    }
    
    return this.calculateStatistics(orders);
  }

  async getShops(): Promise<Array<{
    id: string;
    name: string;
    platform: string;
    status: 'ACTIVE' | 'INACTIVE' | 'SUSPENDED';
    region: string;
    currency: string;
  }>> {
    return this.mockShops;
  }

  private calculateStatistics(orders: ExtendedOrder[]): OrderStatistics {
    return {
      totalOrders: orders.length,
      pending: orders.filter(o => o.status === 'pending').length,
      processing: orders.filter(o => ['confirmed', 'shipped'].includes(o.status)).length,
      completed: orders.filter(o => o.status === 'delivered').length,
      exception: orders.filter(o => ['cancelled', 'refunded'].includes(o.status)).length,
      totalAmount: orders.reduce((sum, order) => sum + order.totalAmount, 0)
    };
  }
}

// 真实实现 - 生产环境使用
export class OrderManagementDataSourceImpl implements OrderManagementDataSource {
  // 真实API调用实现
  async listOrders(params: OrderFilterParams & OrderSortParams): Promise<{
    data: ExtendedOrder[];
    total: number;
    statistics: OrderStatistics;
  }> {
    // 调用真实API
    throw new Error('真实API实现待开发');
  }

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

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

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

  async batchShipOrders(orderIds: string[], trackingInfo: { trackingNumber: string; carrier: string }): Promise<number> {
    throw new Error('真实API实现待开发');
  }

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

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

  async getShops(): Promise<Array<{
    id: string;
    name: string;
    platform: string;
    status: 'ACTIVE' | 'INACTIVE' | 'SUSPENDED';
    region: string;
    currency: string;
  }>> {
    throw new Error('真实API实现待开发');
  }
}

// 数据源工厂函数
export const createOrderManagementDataSource = (): OrderManagementDataSource => {
  const useMock = process.env.NODE_ENV === 'development' || process.env.REACT_APP_USE_MOCK === 'true';
  return useMock ? new OrderManagementMockDataSource() : new OrderManagementDataSourceImpl();
};

export type { ExtendedOrder, OrderFilterParams, OrderSortParams, OrderStatistics };