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

@Injectable()
export class SubjectClassifyService {
  constructor(
    @InjectRepository(SubjectClassify)
    private subjectClassifyRepository: Repository<SubjectClassify>,
  ) {}
  /**
   * 创建科目分类
   * @param createClassifyDto
   * @returns
   */
  async create(createClassifyDto: CreateSubjectClassifyDto) {
    await this.subjectClassifyRepository.insert(createClassifyDto);
    return true;
  }
  /**
   * 根据训练类型获取所有科目分类
   * @returns
   */
  async findAll(trainId?: number) {
    return this.subjectClassifyRepository.find({
      where: { delFlag: 0, train: trainId },
    });
  }
  /**
   * 更新科目分类
   * @param id
   * @param updateClassifyDto
   * @returns
   */
  async update(id: number, updateClassifyDto: UpdateSubjectClassifyDto) {
    return this.subjectClassifyRepository.update(id, updateClassifyDto);
  }
  /**
   *  删除父类型同时删除子类型
   * @param id
   * @returns
   */
  async remove(id: number) {
    if (isNaN(+id) || !id) throw '缺少id';
    await this.subjectClassifyRepository.update(id, { delFlag: 1 });
    const children = await this.subjectClassifyRepository.find({
      where: { pid: id },
    });
    for (let index = 0; index < children.length; index++) {
      const element = children[index];
      await this.remove(element.id);
    }
    // await this.subjectClassifyRepository.update(item.id, { delFlag: 1 });
    return true;
  }
}

export class CreateSubjectClassifyDto extends CreateDto {
  @ApiProperty({ description: '科目分类' })
  @IsNotEmpty({ message: '科目分类不能为空' })
  train: number;
  @ApiProperty({ description: '科目分类名' })
  @IsNotEmpty({ message: '科目分类名不能为空' })
  name: string;

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

export class UpdateSubjectClassifyDto extends CreateDto {
  @ApiProperty({ description: '科目分类' })
  train: number;

  @ApiProperty({ description: '科目分类名' })
  name: string;

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

  @ApiProperty({ description: '层级' })
  level: number;
}
export class FindClassifyByTypeDto {
  @ApiProperty({ description: '训练类型,不传就是查询所有', required: false })
  id: number;
}
