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

import { Order } from '../types/order';
import { BaseDataSource, DataSourceFactory } from './baseDataSource';

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>;
  }>;
  
  getOrderTrend(days: number): Promise<{
    date: string;
    orders: number;
    amount: number;
  }[]>;
  
  getPlatformDistribution(): Promise<{
    name: string;
    value: number;
  }[]>;
  
  getStatusDistribution(): Promise<{
    name: string;
    value: number;
    color: string;
  }[]>;
  
  getKeyMetrics(): Promise<{
    totalOrders: number;
    totalAmount: number;
    pendingOrders: number;
    todayOrders: number;
    todayAmount: number;
    avgOrderValue: number;
  }>;
  
  getRecentOrders(limit: number): Promise<{
    id: string;
    customer: string;
    amount: number;
    status: string;
    platform: string;
  }[]>;
}

export class OrderDataSourceImpl extends BaseDataSource implements OrderDataSource {
  async list(params?: {
    page?: number;
    pageSize?: number;
    status?: string;
    customerId?: string;
    startDate?: string;
    endDate?: string;
  }): Promise<{ data: Order[]; total: number }> {
    try {
      await this.delay(300);
      const mockOrders: Order[] = [
        {
          id: '1',
          customerId: 'cust_1',
          customerName: '张三',
          items: [
            {
              productId: '1',
              productName: '智能手表',
              quantity: 1,
              unitPrice: 199.99,
              totalPrice: 199.99
            }
          ],
          totalAmount: 199.99,
          status: 'delivered',
          paymentMethod: 'credit_card',
          shippingAddress: {
            name: '张三',
            address: '北京市朝阳区',
            city: '北京',
            country: '中国',
            zip: '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,
              unitPrice: 129.99,
              totalPrice: 259.98
            }
          ],
          totalAmount: 259.98,
          status: 'processing',
          paymentMethod: 'paypal',
          shippingAddress: {
            name: '李四',
            address: '上海市浦东新区',
            city: '上海',
            country: '中国',
            zip: '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,
              unitPrice: 89.99,
              totalPrice: 89.99
            }
          ],
          totalAmount: 89.99,
          status: 'pending',
          paymentMethod: 'credit_card',
          shippingAddress: {
            name: '张三',
            address: '北京市朝阳区',
            city: '北京',
            country: '中国',
            zip: '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,
      };
    } catch (error) {
      return this.handleError(error, { data: [], total: 0 });
    }
  }

  async get(id: string): Promise<Order | null> {
    try {
      await this.delay(200);
      const mockOrders: Order[] = [
        {
          id: '1',
          customerId: 'cust_1',
          customerName: '张三',
          items: [
            {
              productId: '1',
              productName: '智能手表',
              quantity: 1,
              unitPrice: 199.99,
              totalPrice: 199.99
            }
          ],
          totalAmount: 199.99,
          status: 'delivered',
          paymentMethod: 'credit_card',
          shippingAddress: {
            name: '张三',
            address: '北京市朝阳区',
            city: '北京',
            country: '中国',
            zip: '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,
              unitPrice: 129.99,
              totalPrice: 259.98
            }
          ],
          totalAmount: 259.98,
          status: 'processing',
          paymentMethod: 'paypal',
          shippingAddress: {
            name: '李四',
            address: '上海市浦东新区',
            city: '上海',
            country: '中国',
            zip: '200000'
          },
          createdAt: new Date('2026-03-11'),
          updatedAt: new Date('2026-03-11'),
        },
      ];

      const order = mockOrders.find(o => o.id === id);
      return order || null;
    } catch (error) {
      return this.handleError(error, null);
    }
  }

  async create(order: Omit<Order, 'id' | 'createdAt' | 'updatedAt'>): Promise<Order> {
    try {
      await this.delay(200);
      const newOrder: Order = {
        ...order,
        id: `order_${Date.now()}`,
        createdAt: new Date(),
        updatedAt: new Date(),
      };

      return newOrder;
    } catch (error) {
      throw error;
    }
  }

  async update(id: string, order: Partial<Order>): Promise<Order | null> {
    try {
      await this.delay(200);
      const existingOrder = await this.get(id);
      if (!existingOrder) {
        return null;
      }

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

      return updatedOrder;
    } catch (error) {
      return this.handleError(error, null);
    }
  }

  async updateStatus(id: string, status: string): Promise<Order | null> {
    try {
      await this.delay(200);
      const existingOrder = await this.get(id);
      if (!existingOrder) {
        return null;
      }

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

      return updatedOrder;
    } catch (error) {
      return this.handleError(error, null);
    }
  }

  async cancel(id: string): Promise<Order | null> {
    try {
      await this.delay(200);
      const existingOrder = await this.get(id);
      if (!existingOrder) {
        return null;
      }

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

      return updatedOrder;
    } catch (error) {
      return this.handleError(error, null);
    }
  }

  async getByCustomerId(customerId: string): Promise<Order[]> {
    try {
      await this.delay(300);
      const mockOrders: Order[] = [
        {
          id: '1',
          customerId: 'cust_1',
          customerName: '张三',
          items: [
            {
              productId: '1',
              productName: '智能手表',
              quantity: 1,
              unitPrice: 199.99,
              totalPrice: 199.99
            }
          ],
          totalAmount: 199.99,
          status: 'delivered',
          paymentMethod: 'credit_card',
          shippingAddress: {
            name: '张三',
            address: '北京市朝阳区',
            city: '北京',
            country: '中国',
            zip: '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,
              unitPrice: 89.99,
              totalPrice: 89.99
            }
          ],
          totalAmount: 89.99,
          status: 'pending',
          paymentMethod: 'credit_card',
          shippingAddress: {
            name: '张三',
            address: '北京市朝阳区',
            city: '北京',
            country: '中国',
            zip: '100000'
          },
          createdAt: new Date('2026-03-12'),
          updatedAt: new Date('2026-03-12'),
        },
      ];

      return mockOrders.filter(o => o.customerId === customerId);
    } catch (error) {
      return this.handleError(error, []);
    }
  }

  async getStatistics(params?: {
    startDate?: string;
    endDate?: string;
  }): Promise<{
    totalOrders: number;
    totalAmount: number;
    averageOrderValue: number;
    statusDistribution: Record<string, number>;
  }> {
    try {
      await this.delay(300);
      const mockOrders: Order[] = [
        {
          id: '1',
          customerId: 'cust_1',
          customerName: '张三',
          items: [
            {
              productId: '1',
              productName: '智能手表',
              quantity: 1,
              unitPrice: 199.99,
              totalPrice: 199.99
            }
          ],
          totalAmount: 199.99,
          status: 'delivered',
          paymentMethod: 'credit_card',
          shippingAddress: {
            name: '张三',
            address: '北京市朝阳区',
            city: '北京',
            country: '中国',
            zip: '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,
              unitPrice: 129.99,
              totalPrice: 259.98
            }
          ],
          totalAmount: 259.98,
          status: 'processing',
          paymentMethod: 'paypal',
          shippingAddress: {
            name: '李四',
            address: '上海市浦东新区',
            city: '上海',
            country: '中国',
            zip: '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,
              unitPrice: 89.99,
              totalPrice: 89.99
            }
          ],
          totalAmount: 89.99,
          status: 'pending',
          paymentMethod: 'credit_card',
          shippingAddress: {
            name: '张三',
            address: '北京市朝阳区',
            city: '北京',
            country: '中国',
            zip: '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,
      };
    } catch (error) {
      return this.handleError(error, {
        totalOrders: 0,
        totalAmount: 0,
        averageOrderValue: 0,
        statusDistribution: {}
      });
    }
  }

  async getOrderTrend(days: number): Promise<{
    date: string;
    orders: number;
    amount: number;
  }[]> {
    try {
      await this.delay(300);
      const mockTrend = [
        { date: '3月12日', orders: 12, amount: 2500 },
        { date: '3月13日', orders: 18, amount: 3200 },
        { date: '3月14日', orders: 15, amount: 2800 },
        { date: '3月15日', orders: 22, amount: 4100 },
        { date: '3月16日', orders: 19, amount: 3500 },
        { date: '3月17日', orders: 25, amount: 4800 },
        { date: '3月18日', orders: 30, amount: 5200 },
      ];
      return mockTrend;
    } catch (error) {
      return this.handleError(error, []);
    }
  }

  async getPlatformDistribution(): Promise<{
    name: string;
    value: number;
  }[]> {
    try {
      await this.delay(200);
      const mockPlatform = [
        { name: 'Amazon', value: 45 },
        { name: 'eBay', value: 25 },
        { name: 'Shopify', value: 15 },
        { name: 'Shopee', value: 10 },
        { name: 'Lazada', value: 5 },
      ];
      return mockPlatform;
    } catch (error) {
      return this.handleError(error, []);
    }
  }

  async getStatusDistribution(): Promise<{
    name: string;
    value: number;
    color: string;
  }[]> {
    try {
      await this.delay(200);
      const mockStatus = [
        { name: '待处理', value: 12, color: '#faad14' },
        { name: '已确认', value: 18, color: '#1890ff' },
        { name: '已发货', value: 25, color: '#13c2c2' },
        { name: '已完成', value: 45, color: '#52c41a' },
        { name: '已取消', value: 5, color: '#ff4d4f' },
        { name: '退款中', value: 3, color: '#722ed1' },
      ];
      return mockStatus;
    } catch (error) {
      return this.handleError(error, []);
    }
  }

  async getKeyMetrics(): Promise<{
    totalOrders: number;
    totalAmount: number;
    pendingOrders: number;
    todayOrders: number;
    todayAmount: number;
    avgOrderValue: number;
  }> {
    try {
      await this.delay(200);
      const mockMetrics = {
        totalOrders: 108,
        totalAmount: 21500,
        pendingOrders: 12,
        todayOrders: 30,
        todayAmount: 5200,
        avgOrderValue: 199.07,
      };
      return mockMetrics;
    } catch (error) {
      return this.handleError(error, {
        totalOrders: 0,
        totalAmount: 0,
        pendingOrders: 0,
        todayOrders: 0,
        todayAmount: 0,
        avgOrderValue: 0
      });
    }
  }

  async getRecentOrders(limit: number): Promise<{
    id: string;
    customer: string;
    amount: number;
    status: string;
    platform: string;
  }[]> {
    try {
      await this.delay(200);
      const mockRecentOrders = [
        { id: 'ORD-2026-001', customer: '张三', amount: 159.99, status: '已发货', platform: 'Amazon' },
        { id: 'ORD-2026-002', customer: '李四', amount: 299.99, status: '待处理', platform: 'eBay' },
        { id: 'ORD-2026-003', customer: '王五', amount: 459.98, status: '已确认', platform: 'Shopify' },
        { id: 'ORD-2026-004', customer: '赵六', amount: 89.99, status: '已完成', platform: 'Shopee' },
      ];
      return mockRecentOrders.slice(0, limit);
    } catch (error) {
      return this.handleError(error, []);
    }
  }
}

// 创建数据源实例
const orderDataSourceInstance = new OrderDataSourceImpl();

// 注册到数据源工厂
DataSourceFactory.register('order', orderDataSourceInstance);

export const orderDataSource = orderDataSourceInstance;
