import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Order } from '@/entities/order.entity';
import { QueryOrderDto } from './dto/order.dto';

@Injectable()
export class AdminOrderService {
  constructor(
    @InjectRepository(Order)
    private orderRepo: Repository<Order>,
  ) {}

  async findAll(query: QueryOrderDto) {
    const { page = 1, pageSize = 10, status, keyword } = query;
    const qb = this.orderRepo.createQueryBuilder('order')
      .leftJoinAndSelect('order.user', 'user')
      .leftJoinAndSelect('order.room', 'room')
      .leftJoinAndSelect('order.merchant', 'merchant');

    if (status) {
      qb.andWhere('order.status = :status', { status });
    }

    if (keyword) {
      qb.andWhere('order.orderNo LIKE :keyword', { keyword: `%${keyword}%` });
    }

    qb.orderBy('order.createdAt', 'DESC')
      .skip((page - 1) * pageSize)
      .take(pageSize);

    const [list, total] = await qb.getManyAndCount();

    return {
      list,
      total,
      page,
      pageSize,
      totalPages: Math.ceil(total / pageSize),
    };
  }

  async findById(id: number) {
    const order = await this.orderRepo.findOne({
      where: { id },
      relations: ['user', 'room', 'merchant'],
    });
    if (!order) throw new NotFoundException('订单不存在');
    return order;
  }

  async getServiceFees(query: QueryOrderDto) {
    const { page = 1, pageSize = 10 } = query;
    const qb = this.orderRepo.createQueryBuilder('order')
      .leftJoinAndSelect('order.merchant', 'merchant')
      .where('order.status IN (:...statuses)', { statuses: ['completed', 'finished'] })
      .andWhere('order.serviceFee > 0');

    qb.orderBy('order.createdAt', 'DESC')
      .skip((page - 1) * pageSize)
      .take(pageSize);

    const [list, total] = await qb.getManyAndCount();

    return {
      list,
      total,
      page,
      pageSize,
      totalPages: Math.ceil(total / pageSize),
    };
  }
}
