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 { TrainType } from 'src/train/entities/subject/train-type.entity';
import { SubjectClassify } from 'src/train/entities/subject/subject-classify.entity';

@Injectable()
export class TrainTypeService {
  constructor(
    @InjectRepository(TrainType)
    private trainTypeRepository: Repository<TrainType>,
    @InjectRepository(SubjectClassify)
    private subjectClassifyRepository: Repository<SubjectClassify>,
  ) {
    // 如果没有默认训练类型，则增加默认数据
    this.findAll().then((res) => {
      if (!res || res.length == 0) {
        const datas = [
          { id: 1, name: '虚拟训练', pid: 0 },
          { id: 2, name: '操作训练', pid: 1 },
          { id: 3, name: '认知训练', pid: 1 },
          { id: 4, name: '拆装训练', pid: 1 },
        ];
        this.trainTypeRepository.save(datas);
      }
    });
  }
  /**
   * 创建训练类型
   * @param createClassifyDto
   * @returns
   */
  async create(createClassifyDto: CreateTrainTypeDto) {
    await this.trainTypeRepository.insert(createClassifyDto);
    return true;
  }
  /**
   * 获取所有训练类型
   * @returns
   */
  async findAll() {
    return this.trainTypeRepository.find({
      select: ['id', 'name', 'pid'],
      where: { delFlag: 0 },
    });
  }
  /**
   * 更新训练类型
   * @param id
   * @param updateClassifyDto
   * @returns
   */
  async update(id: number, updateClassifyDto: UpdateTrainTypeDto) {
    return this.trainTypeRepository.update(id, updateClassifyDto);
  }
  /**
   *  删除父类型同时删除子类型
   * @param id
   * @returns
   */
  async remove(id: number) {
    if (isNaN(+id) || !id) throw '缺少id';
    await this.trainTypeRepository.update(id, { delFlag: 1 });
    const children = await this.trainTypeRepository.find({
      where: { pid: id },
    });
    for (let index = 0; index < children.length; index++) {
      const element = children[index];
      await this.remove(element.id);
    }
    // await this.trainTypeRepository.update(item.id, { delFlag: 1 });
    return true;
  }
}

export class CreateTrainTypeDto extends CreateDto {
  @ApiProperty({ description: '训练类型名' })
  @IsNotEmpty({ message: '训练类型名不能为空' })
  name: string;

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

export class UpdateTrainTypeDto extends CreateDto {
  @ApiProperty({ description: '训练类型名' })
  name: string;

  @ApiProperty({ description: '上级训练类型啊', default: 0 })
  pid: number;
}
