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

  /**
   * 获取用户订单列表
   */
  async getUserOrders(userId: number, filters: {
    status?: OrderStatus;
    paymentStatus?: PaymentStatus;
    page?: number;
    pageSize?: number;
  } = {}) {
    const {
      status,
      paymentStatus,
      page = 1,
      pageSize = 20
    } = filters;

    const skip = (page - 1) * pageSize;

    // 构建查询条件
    const where: any = { userId };

    if (status) {
      where.status = status;
    }

    if (paymentStatus) {
      where.paymentStatus = paymentStatus;
    }

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

    // 转换响应格式
    const data = orders.map(order => ({
      id: order.id,
      userId: order.userId,
      routeId: order.routeId,
      passengerCount: order.passengerCount,
      totalAmount: order.totalAmount,
      status: order.status,
      paymentStatus: order.paymentStatus,
      passengerSnapshots: order.passengerSnapshots,
      routeSnapshot: order.routeSnapshot,
      createdBy: order.createdBy,
      updatedBy: order.updatedBy,
      createdAt: order.createdAt,
      updatedAt: order.updatedAt,
      user: {
        id: order.user.id,
        username: order.user.username,
        phone: order.user.phone
      },
      route: {
        id: order.route.id,
        name: order.route.name,
        description: order.route.description
      }
    }));

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

  /**
   * 获取订单详情
   */
  async getOrderDetail(userId: number, orderId: number) {
    // 查询订单
    const order = await this.orderRepository.findOne({
      where: { id: orderId },
      relations: ['user', 'route']
    });

    if (!order) {
      throw new Error('订单不存在');
    }

    // 权限验证：只能查看自己的订单
    if (order.userId !== userId) {
      throw new Error('权限不足，只能查看自己的订单');
    }

    // 转换响应格式
    return {
      id: order.id,
      userId: order.userId,
      routeId: order.routeId,
      passengerCount: order.passengerCount,
      totalAmount: order.totalAmount,
      status: order.status,
      paymentStatus: order.paymentStatus,
      passengerSnapshots: order.passengerSnapshots,
      routeSnapshot: order.routeSnapshot,
      createdBy: order.createdBy,
      updatedBy: order.updatedBy,
      createdAt: order.createdAt,
      updatedAt: order.updatedAt,
      user: {
        id: order.user.id,
        username: order.user.username,
        phone: order.user.phone
      },
      route: {
        id: order.route.id,
        name: order.route.name,
        description: order.route.description
      }
    };
  }

  /**
   * 取消订单
   */
  async cancelOrder(userId: number, orderId: number) {
    // 查询订单
    const order = await this.orderRepository.findOne({
      where: { id: orderId },
      relations: ['user', 'route']
    });

    if (!order) {
      throw new Error('订单不存在');
    }

    // 权限验证：只能取消自己的订单
    if (order.userId !== userId) {
      throw new Error('权限不足，只能取消自己的订单');
    }

    // 状态验证：只能取消待出发状态的订单
    if (order.status !== OrderStatus.WAITING_DEPARTURE) {
      throw new Error('只能取消待出发状态的订单');
    }

    // 时间验证：取消时间必须在出发时间前1小时以上
    const routeSnapshot = order.routeSnapshot;
    if (routeSnapshot && routeSnapshot.departureTime) {
      const departureTime = new Date(routeSnapshot.departureTime);
      const now = new Date();
      const timeDiff = departureTime.getTime() - now.getTime();
      const oneHour = 60 * 60 * 1000; // 1小时毫秒数

      if (timeDiff < oneHour) {
        throw new Error('距离出发时间不足1小时，无法取消订单');
      }
    }

    // 更新订单状态
    order.status = OrderStatus.CANCELLED;
    order.updatedBy = userId;
    order.updatedAt = new Date();

    // 如果已支付，更新支付状态为已退款
    if (order.paymentStatus === PaymentStatus.PAID) {
      order.paymentStatus = PaymentStatus.REFUNDED;
    }

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

    // 转换响应格式
    return {
      id: updatedOrder.id,
      userId: updatedOrder.userId,
      routeId: updatedOrder.routeId,
      passengerCount: updatedOrder.passengerCount,
      totalAmount: updatedOrder.totalAmount,
      status: updatedOrder.status,
      paymentStatus: updatedOrder.paymentStatus,
      passengerSnapshots: updatedOrder.passengerSnapshots,
      routeSnapshot: updatedOrder.routeSnapshot,
      createdBy: updatedOrder.createdBy,
      updatedBy: updatedOrder.updatedBy,
      createdAt: updatedOrder.createdAt,
      updatedAt: updatedOrder.updatedAt,
      user: {
        id: updatedOrder.user.id,
        username: updatedOrder.user.username,
        phone: updatedOrder.user.phone
      },
      route: {
        id: updatedOrder.route.id,
        name: updatedOrder.route.name,
        description: updatedOrder.route.description
      }
    };
  }
}