import { AppDataSource } from '../../data-source';
import { Order } from './order.entity';
import { OrderStatus, PaymentStatus } from '../../share/order.types';
import { OrderStats, OrderCreateInput } from './order.schema';

export class OrderService {
  private orderRepository = AppDataSource.getRepository(Order);

  /**
   * 创建订单
   */
  async createOrder(userId: number, orderData: OrderCreateInput) {
    const order = this.orderRepository.create({
      userId,
      routeId: orderData.routeId,
      passengerCount: orderData.passengerCount,
      totalAmount: orderData.totalAmount,
      status: OrderStatus.PENDING_PAYMENT,
      paymentStatus: PaymentStatus.PENDING,
      passengerSnapshots: orderData.passengerSnapshots,
      routeSnapshot: orderData.routeSnapshot,
      createdBy: orderData.createdBy || userId
    });

    const savedOrder = await this.orderRepository.save(order);

    // 返回包含关联数据的订单
    const orderWithRelations = await this.orderRepository.findOne({
      where: { id: savedOrder.id },
      relations: ['user', 'route']
    });

    if (!orderWithRelations) {
      throw new Error('订单创建后查询失败');
    }

    // 返回与OrderResponseSchema匹配的数据结构
    return {
      id: orderWithRelations.id,
      userId: orderWithRelations.userId,
      routeId: orderWithRelations.routeId,
      passengerCount: orderWithRelations.passengerCount,
      totalAmount: orderWithRelations.totalAmount,
      status: orderWithRelations.status,
      paymentStatus: orderWithRelations.paymentStatus,
      passengerSnapshots: orderWithRelations.passengerSnapshots,
      routeSnapshot: orderWithRelations.routeSnapshot,
      createdBy: orderWithRelations.createdBy,
      updatedBy: orderWithRelations.updatedBy,
      createdAt: orderWithRelations.createdAt,
      updatedAt: orderWithRelations.updatedAt,
      user: {
        id: orderWithRelations.user.id,
        username: orderWithRelations.user.username,
        phone: orderWithRelations.user.phone
      },
      route: {
        id: orderWithRelations.route.id,
        name: orderWithRelations.route.name,
        description: orderWithRelations.route.description
      }
    };
  }

  /**
   * 获取订单统计信息
   */
  async getOrderStats(): Promise<OrderStats> {
    const total = await this.orderRepository.count();
    const pendingPayment = await this.orderRepository.count({
      where: { status: OrderStatus.PENDING_PAYMENT }
    });
    const waitingDeparture = await this.orderRepository.count({
      where: { status: OrderStatus.WAITING_DEPARTURE }
    });
    const inProgress = await this.orderRepository.count({
      where: { status: OrderStatus.IN_PROGRESS }
    });
    const completed = await this.orderRepository.count({
      where: { status: OrderStatus.COMPLETED }
    });
    const cancelled = await this.orderRepository.count({
      where: { status: OrderStatus.CANCELLED }
    });

    return {
      total,
      pendingPayment,
      waitingDeparture,
      inProgress,
      completed,
      cancelled
    };
  }

  /**
   * 根据状态筛选订单
   */
  async getOrdersByStatus(status: OrderStatus, page: number = 1, pageSize: number = 20) {
    const skip = (page - 1) * pageSize;

    const [orders, total] = await this.orderRepository.findAndCount({
      where: { status },
      relations: ['user', 'route'],
      order: { id: 'DESC' },
      skip,
      take: pageSize
    });

    return {
      data: orders,
      total,
      page,
      pageSize
    };
  }
}