import { AppDataSource } from '../../data-source';
import { Passenger } from './passenger.entity';
import { PassengerListParams, PassengerCreateInput, PassengerUpdateInput } from './passenger.schema';

export class PassengerService {
  private passengerRepository = AppDataSource.getRepository(Passenger);

  /**
   * 获取乘客列表
   */
  async getPassengers(params: PassengerListParams) {
    const { page = 1, pageSize = 20, keyword, userId } = params;
    const skip = (page - 1) * pageSize;

    const queryBuilder = this.passengerRepository
      .createQueryBuilder('passenger')
      .leftJoinAndSelect('passenger.user', 'user')
      .skip(skip)
      .take(pageSize);

    // 按用户筛选
    if (userId) {
      queryBuilder.andWhere('passenger.userId = :userId', { userId });
    }

    // 关键词搜索
    if (keyword) {
      queryBuilder.andWhere(
        '(passenger.name LIKE :keyword OR passenger.phone LIKE :keyword OR passenger.idNumber LIKE :keyword)',
        { keyword: `%${keyword}%` }
      );
    }

    // 按创建时间倒序排列
    queryBuilder.orderBy('passenger.createdAt', 'DESC');

    const [data, total] = await queryBuilder.getManyAndCount();

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

  /**
   * 获取乘客详情
   */
  async getPassengerById(id: number) {
    return await this.passengerRepository.findOne({
      where: { id },
      relations: ['user']
    });
  }

  /**
   * 创建乘客
   */
  async createPassenger(input: PassengerCreateInput) {
    const passenger = this.passengerRepository.create(input);
    return await this.passengerRepository.save(passenger);
  }

  /**
   * 更新乘客
   */
  async updatePassenger(id: number, input: PassengerUpdateInput) {
    const result = await this.passengerRepository.update(id, input);
    if (result.affected === 0) {
      throw new Error('乘客不存在');
    }
    return await this.getPassengerById(id);
  }

  /**
   * 删除乘客
   */
  async deletePassenger(id: number) {
    const result = await this.passengerRepository.delete(id);
    if (result.affected === 0) {
      throw new Error('乘客不存在');
    }
    return { success: true };
  }

  /**
   * 获取用户的乘客列表
   */
  async getPassengersByUserId(userId: number) {
    return await this.passengerRepository.find({
      where: { userId },
      order: { isDefault: 'DESC', createdAt: 'DESC' }
    });
  }

  /**
   * 设置默认乘客
   */
  async setDefaultPassenger(userId: number, passengerId: number) {
    // 先取消所有乘客的默认状态
    await this.passengerRepository.update(
      { userId },
      { isDefault: false }
    );

    // 设置指定乘客为默认
    await this.passengerRepository.update(
      { id: passengerId, userId },
      { isDefault: true }
    );

    return await this.getPassengerById(passengerId);
  }
}