import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ApiProperty } from '@nestjs/swagger';
import { IsNotEmpty, MaxLength } from 'class-validator';
import { CreateDto } from 'src/common/dto/create.dto';
import { DeviceNumberPosition } from 'src/train/entities/device/device-number-position.entity';
import { PaginationDTO } from 'src/assessment-evaluation/dto/pagination.dto';

@Injectable()
export class DeviceNumberPositionService {
  constructor(
    @InjectRepository(DeviceNumberPosition)
    private classifyRepository: Repository<DeviceNumberPosition>,
  ) {}
  /**
   * 创建号位
   * @param createClassifyDto
   * @returns
   */
  async create(createClassifyDto: CreatePositionDto) {
    const notExist = await this.checkNotExist(createClassifyDto);
    if (!notExist) throw '名称或键值已存在';
    await this.classifyRepository.insert(createClassifyDto);
    return true;
  }
  /**
   * 获取所有号位
   * @returns
   */
  async findAll() {
    return this.classifyRepository.find({
      select: ['id', 'name', 'keycode'],
      where: { delFlag: 0 },
    });
  }
  /**
   * 分页获取号位
   * @returns
   */
  async paging(paging: PaginationDTO) {
    const res: any = await this.classifyRepository
      .createQueryBuilder('positions')
      .andWhere({
        delFlag: 0,
      })
      .orderBy('positions.id', 'DESC')
      .skip((paging.currentPage - 1) * paging.pageSize)
      .take(paging.pageSize)
      .getManyAndCount();
    return {
      data: res[0],
      total: res[1],
    };
  }
  /**
   * 更新号位
   * @param id
   * @param updateClassifyDto
   * @returns
   */
  async update(id: number, updateClassifyDto: UpdatePositionDto) {
    const notExist = await this.checkNotExist(updateClassifyDto);
    if (!notExist) throw '名称或键值已存在';
    return this.classifyRepository.update(id, updateClassifyDto);
  }
  async checkNotExist(dto: UpdatePositionDto | CreatePositionDto) {
    return (
      !(await this.classifyRepository.findOneBy({
        name: dto.name,
        delFlag: 0,
      })) &&
      !(await this.classifyRepository.findOneBy({
        keycode: dto.keycode,
        delFlag: 0,
      }))
    );
  }
  /**
   *  删除号位
   * @param id
   * @returns
   */
  async remove(ids: number[]) {
    await this.classifyRepository.update(ids, { delFlag: 1 });
    // await this.classifyRepository.update(item.id, { delFlag: 1 });
    return true;
  }
}

export class CreatePositionDto extends CreateDto {
  @ApiProperty({ description: '号位名' })
  @IsNotEmpty({ message: '号位名不能为空' })
  @MaxLength(20, { message: '号位名不能超过20个字符' })
  name: string;

  @ApiProperty({ description: '号位键值' })
  @IsNotEmpty({ message: '号位键值不能为空' })
  @MaxLength(20, { message: '键值不能超过20个字符' })
  keycode: string;
}

export class UpdatePositionDto extends CreateDto {
  @ApiProperty({ description: '号位名' })
  name: string;

  @ApiProperty({ description: '号位键值' })
  keycode: string;
}
