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 { PaginationDTO } from 'src/assessment-evaluation/dto/pagination.dto';
import { DevicePartOperation } from 'src/train/entities/device/device-part-operation.entity';
import { DevicePartHasOperation } from 'src/train/entities/device/device-part-has-operation.entity';

@Injectable()
export class DevicePartOperationService {
  constructor(
    @InjectRepository(DevicePartOperation)
    private devicePartOperation: Repository<DevicePartOperation>,
    @InjectRepository(DevicePartHasOperation)
    private devicePartHasOperation: Repository<DevicePartHasOperation>,
  ) {}
  /**
   * 创建部件状态
   * @param createClassifyDto
   * @returns
   */
  async create(createClassifyDto: CreateOperationDto) {
    const notExist = await this.checkNotExist(createClassifyDto);
    if (!notExist) throw '名称或键值已存在';
    await this.devicePartOperation.insert(createClassifyDto);
    return true;
  }
  /**
   * 获取所有部件状态
   * @returns
   */
  async findAll() {
    return this.devicePartOperation.find({
      select: ['id', 'name', 'keycode'],
      where: { delFlag: 0 },
    });
  }
  /**
   * 分页获取部件状态
   * @returns
   */
  async paging(paging: PaginationDTO) {
    const res: any = await this.devicePartOperation
      .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: UpdateOperationDto) {
    const notExist = await this.checkNotExist(updateClassifyDto);
    if (!notExist) throw '名称或键值已存在';
    return this.devicePartOperation.update(id, updateClassifyDto);
  }
  async checkNotExist(dto: UpdateOperationDto | CreateOperationDto) {
    return (
      !(await this.devicePartOperation.findOneBy({
        name: dto.name,
        delFlag: 0,
      })) &&
      !(await this.devicePartOperation.findOneBy({
        keycode: dto.keycode,
        delFlag: 0,
      }))
    );
  }
  /**
   *  删除部件状态
   * @param id
   * @returns
   */
  async remove(ids: number[]) {
    await this.devicePartOperation.update(ids, { delFlag: 1 });
    // 删除部件状态时同时删除部件和状态的关联信息
    ids.forEach(async (item) => {
      await this.devicePartHasOperation.delete({ operation: item });
    });
    return true;
  }
}

export class CreateOperationDto extends CreateDto {
  @ApiProperty({ description: '部件状态' })
  @IsNotEmpty({ message: '部件状态不能为空' })
  @MaxLength(20, { message: '部件状态不能超过20个字符' })
  name: string;

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

export class UpdateOperationDto extends CreateDto {
  @ApiProperty({ description: '部件状态' })
  name: string;

  @ApiProperty({ description: '状态键值' })
  keycode: string;
}
