import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ApiProperty } from '@nestjs/swagger';
import { IsNotEmpty } from 'class-validator';
import { CreateDto } from 'src/common/dto/create.dto';
import { DeviceClassify } from 'src/train/entities/device/device-classify.entity';

@Injectable()
export class DeviceClassifyService {
  constructor(
    @InjectRepository(DeviceClassify)
    private classifyRepository: Repository<DeviceClassify>,
  ) {}
  /**
   * 创建分类
   * @param createClassifyDto
   * @returns
   */
  async create(createClassifyDto: CreateClassifyDto) {
    await this.classifyRepository.insert(createClassifyDto);
    return true;
  }
  /**
   * 获取所有分类
   * @returns
   */
  async findAll() {
    return this.classifyRepository.find({
      select: ['id', 'name', 'pid', 'level'],
      where: { delFlag: 0 },
    });
  }
  /**
   * 更新分类
   * @param id
   * @param updateClassifyDto
   * @returns
   */
  async update(id: number, updateClassifyDto: UpdateClassifyDto) {
    return this.classifyRepository.update(id, updateClassifyDto);
  }
  /**
   *  删除父类型同时删除子类型
   * @param id
   * @returns
   */
  async remove(id: number) {
    if (isNaN(+id) || !id) throw '缺少id';
    await this.classifyRepository.update(id, { delFlag: 1 });
    const children = await this.classifyRepository.find({
      where: { pid: id },
    });
    for (let index = 0; index < children.length; index++) {
      const element = children[index];
      await this.remove(element.id);
    }
    // await this.classifyRepository.update(item.id, { delFlag: 1 });
    return true;
  }
}

export class CreateClassifyDto extends CreateDto {
  @ApiProperty({ description: '设备分类名' })
  @IsNotEmpty({ message: '设备分类名不能为空' })
  name: string;

  @ApiProperty({ description: '上级设备分类', default: 0 })
  @IsNotEmpty({ message: '上级设备分类不能为空' })
  pid: number;

  @ApiProperty({ description: '设备分类层级', default: 1 })
  @IsNotEmpty({ message: '层级不能为空' })
  level: number;
}

export class UpdateClassifyDto extends CreateDto {
  @ApiProperty({ description: '设备分类名' })
  name: string;

  @ApiProperty({ description: '上级设备分类', default: 0 })
  pid: number;

  @ApiProperty({ description: '设备分类层级', default: 1 })
  level: number;
}
