/**
 * [MOCK-008] 订单模块DataSource
 * AI注意: 这是Mock实现，不是真实业务逻辑
 * 仅在USE_MOCK=true时启用
 */

import { Order } from '../types/order';

// 订单数据接口
export interface OrderDataSource {
  list(params?: {
    page?: number;
    pageSize?: number;
    status?: string;
    customerId?: string;
    startDate?: string;
    endDate?: string;
  }): Promise<{ data: Order[]; total: number }>;
  
  get(id: string): Promise<Order | null>;
  
  create(order: Omit<Order, 'id' | 'createdAt' | 'updatedAt'>): Promise<Order>;
  
  update(id: string, order: Partial<Order>): Promise<Order | null>;
  
  updateStatus(id: string, status: string): Promise<Order | null>;
  
  cancel(id: string): Promise<Order | null>;
  
  getByCustomerId(customerId: string): Promise<Order[]>;
  
  getStatistics(params?: {
    startDate?: string;
    endDate?: string;
  }): Promise<{
    totalOrders: number;
    totalAmount: number;
    averageOrderValue: number;
    statusDistribution: Record<string, number>;
  }>;
}

// 订单DataSource实现
export class OrderDataSourceImpl implements OrderDataSource {
  async list(params?: {
    page?: number;
    pageSize?: number;
    status?: string;
    customerId?: string;
    startDate?: string;
    endDate?: string;
  }): Promise<{ data: Order[]; total: number }> {
    // 这里应该调用实际的API
    // 暂时返回Mock数据
    const mockOrders: Order[] = [
      {
        id: '1',
        customerId: 'cust_1',
        customerName: '张三',
        items: [
          {
            productId: '1',
            productName: '智能手表',
            quantity: 1,
            price: 199.99
          }
        ],
        totalAmount: 199.99,
        status: 'completed',
        paymentMethod: 'credit_card',
        shippingAddress: {
          street: '北京市朝阳区',
          city: '北京',
          country: '中国',
          zipCode: '100000'
        },
        createdAt: new Date('2026-03-10'),
        updatedAt: new Date('2026-03-10'),
      },
      {
        id: '2',
        customerId: 'cust_2',
        customerName: '李四',
        items: [
          {
            productId: '2',
            productName: '无线耳机',
            quantity: 2,
            price: 129.99
          }
        ],
        totalAmount: 259.98,
        status: 'processing',
        paymentMethod: 'paypal',
        shippingAddress: {
          street: '上海市浦东新区',
          city: '上海',
          country: '中国',
          zipCode: '200000'
        },
        createdAt: new Date('2026-03-11'),
        updatedAt: new Date('2026-03-11'),
      },
      {
        id: '3',
        customerId: 'cust_1',
        customerName: '张三',
        items: [
          {
            productId: '3',
            productName: '运动鞋',
            quantity: 1,
            price: 89.99
          }
        ],
        totalAmount: 89.99,
        status: 'pending',
        paymentMethod: 'credit_card',
        shippingAddress: {
          street: '北京市朝阳区',
          city: '北京',
          country: '中国',
          zipCode: '100000'
        },
        createdAt: new Date('2026-03-12'),
        updatedAt: new Date('2026-03-12'),
      },
    ];

    let filteredOrders = mockOrders;
    
    if (params?.status) {
      filteredOrders = filteredOrders.filter(o => o.status === params.status);
    }
    
    if (params?.customerId) {
      filteredOrders = filteredOrders.filter(o => o.customerId === params.customerId);
    }

    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);

    return {
      data: paginatedOrders,
      total: filteredOrders.length,
    };
  }

  async get(id: string): Promise<Order | null> {
    // 这里应该调用实际的API
    // 暂时返回Mock数据
    const mockOrders: Order[] = [
      {
        id: '1',
        customerId: 'cust_1',
        customerName: '张三',
        items: [
          {
            productId: '1',
            productName: '智能手表',
            quantity: 1,
            price: 199.99
          }
        ],
        totalAmount: 199.99,
        status: 'completed',
        paymentMethod: 'credit_card',
        shippingAddress: {
          street: '北京市朝阳区',
          city: '北京',
          country: '中国',
          zipCode: '100000'
        },
        createdAt: new Date('2026-03-10'),
        updatedAt: new Date('2026-03-10'),
      },
      {
        id: '2',
        customerId: 'cust_2',
        customerName: '李四',
        items: [
          {
            productId: '2',
            productName: '无线耳机',
            quantity: 2,
            price: 129.99
          }
        ],
        totalAmount: 259.98,
        status: 'processing',
        paymentMethod: 'paypal',
        shippingAddress: {
          street: '上海市浦东新区',
          city: '上海',
          country: '中国',
          zipCode: '200000'
        },
        createdAt: new Date('2026-03-11'),
        updatedAt: new Date('2026-03-11'),
      },
    ];

    const order = mockOrders.find(o => o.id === id);
    return order || null;
  }

  async create(order: Omit<Order, 'id' | 'createdAt' | 'updatedAt'>): Promise<Order> {
    // 这里应该调用实际的API
    // 暂时返回Mock数据
    const newOrder: Order = {
      ...order,
      id: `order_${Date.now()}`,
      createdAt: new Date(),
      updatedAt: new Date(),
    };

    return newOrder;
  }

  async update(id: string, order: Partial<Order>): Promise<Order | null> {
    // 这里应该调用实际的API
    // 暂时返回Mock数据
    const existingOrder = await this.get(id);
    if (!existingOrder) {
      return null;
    }

    const updatedOrder: Order = {
      ...existingOrder,
      ...order,
      updatedAt: new Date(),
    };

    return updatedOrder;
  }

  async updateStatus(id: string, status: string): Promise<Order | null> {
    // 这里应该调用实际的API
    // 暂时返回Mock数据
    const existingOrder = await this.get(id);
    if (!existingOrder) {
      return null;
    }

    const updatedOrder: Order = {
      ...existingOrder,
      status: status as any,
      updatedAt: new Date(),
    };

    return updatedOrder;
  }

  async cancel(id: string): Promise<Order | null> {
    // 这里应该调用实际的API
    // 暂时返回Mock数据
    return this.updateStatus(id, 'cancelled');
  }

  async getByCustomerId(customerId: string): Promise<Order[]> {
    // 这里应该调用实际的API
    // 暂时返回Mock数据
    const mockOrders: Order[] = [
      {
        id: '1',
        customerId: 'cust_1',
        customerName: '张三',
        items: [
          {
            productId: '1',
            productName: '智能手表',
            quantity: 1,
            price: 199.99
          }
        ],
        totalAmount: 199.99,
        status: 'completed',
        paymentMethod: 'credit_card',
        shippingAddress: {
          street: '北京市朝阳区',
          city: '北京',
          country: '中国',
          zipCode: '100000'
        },
        createdAt: new Date('2026-03-10'),
        updatedAt: new Date('2026-03-10'),
      },
      {
        id: '3',
        customerId: 'cust_1',
        customerName: '张三',
        items: [
          {
            productId: '3',
            productName: '运动鞋',
            quantity: 1,
            price: 89.99
          }
        ],
        totalAmount: 89.99,
        status: 'pending',
        paymentMethod: 'credit_card',
        shippingAddress: {
          street: '北京市朝阳区',
          city: '北京',
          country: '中国',
          zipCode: '100000'
        },
        createdAt: new Date('2026-03-12'),
        updatedAt: new Date('2026-03-12'),
      },
    ];

    return mockOrders.filter(o => o.customerId === customerId);
  }

  async getStatistics(params?: {
    startDate?: string;
    endDate?: string;
  }): Promise<{
    totalOrders: number;
    totalAmount: number;
    averageOrderValue: number;
    statusDistribution: Record<string, number>;
  }> {
    // 这里应该调用实际的API
    // 暂时返回Mock数据
    const mockOrders: Order[] = [
      {
        id: '1',
        customerId: 'cust_1',
        customerName: '张三',
        items: [
          {
            productId: '1',
            productName: '智能手表',
            quantity: 1,
            price: 199.99
          }
        ],
        totalAmount: 199.99,
        status: 'completed',
        paymentMethod: 'credit_card',
        shippingAddress: {
          street: '北京市朝阳区',
          city: '北京',
          country: '中国',
          zipCode: '100000'
        },
        createdAt: new Date('2026-03-10'),
        updatedAt: new Date('2026-03-10'),
      },
      {
        id: '2',
        customerId: 'cust_2',
        customerName: '李四',
        items: [
          {
            productId: '2',
            productName: '无线耳机',
            quantity: 2,
            price: 129.99
          }
        ],
        totalAmount: 259.98,
        status: 'processing',
        paymentMethod: 'paypal',
        shippingAddress: {
          street: '上海市浦东新区',
          city: '上海',
          country: '中国',
          zipCode: '200000'
        },
        createdAt: new Date('2026-03-11'),
        updatedAt: new Date('2026-03-11'),
      },
      {
        id: '3',
        customerId: 'cust_1',
        customerName: '张三',
        items: [
          {
            productId: '3',
            productName: '运动鞋',
            quantity: 1,
            price: 89.99
          }
        ],
        totalAmount: 89.99,
        status: 'pending',
        paymentMethod: 'credit_card',
        shippingAddress: {
          street: '北京市朝阳区',
          city: '北京',
          country: '中国',
          zipCode: '100000'
        },
        createdAt: new Date('2026-03-12'),
        updatedAt: new Date('2026-03-12'),
      },
    ];

    const totalOrders = mockOrders.length;
    const totalAmount = mockOrders.reduce((sum, order) => sum + order.totalAmount, 0);
    const averageOrderValue = totalOrders > 0 ? totalAmount / totalOrders : 0;

    const statusDistribution: Record<string, number> = {};
    mockOrders.forEach(order => {
      statusDistribution[order.status] = (statusDistribution[order.status] || 0) + 1;
    });

    return {
      totalOrders,
      totalAmount,
      averageOrderValue,
      statusDistribution,
    };
  }
}

// 导出DataSource实例
export const orderDataSource = new OrderDataSourceImpl();
