import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { CreateExamClassifyDto } from 'src/assessment-evaluation/dto/dtos-exam-manager/exam-classify/create-exam-classify.dto';
import { UpdateExamClassifyDto } from 'src/assessment-evaluation/dto/dtos-exam-manager/exam-classify/update-exam-classify.dto';
import { ExamClassify } from 'src/assessment-evaluation/entities/entities-exam-manager/exam-classify.entity';
import { Repository } from 'typeorm';

@Injectable()
export class ExamClassifyService {
  constructor(
    @InjectRepository(ExamClassify)
    private ExamClassifyRepository: Repository<ExamClassify>,
  ) {}
  /* 
    创建考试分类
  */
  async create(CreateExamClassifyDto: CreateExamClassifyDto) {
    await this.ExamClassifyRepository.insert(CreateExamClassifyDto);
    return true;
  }
  /* 
    查找所有分类
  */
  async findAll() {
    return this.ExamClassifyRepository.find({
      select: ['id', 'name', 'pid', 'level'],
      where: { delFlag: 0 },
    });
  }
  /* 
    更新分类
  */
  async update(id: number, UpdateExamClassifyDto: UpdateExamClassifyDto) {
    return this.ExamClassifyRepository.update(id, UpdateExamClassifyDto);
  }
  /* 
    删除父类型同时删除子类型
  */
  async remove(id: number) {
    if (isNaN(+id) || !id) throw '缺少id';
    await this.ExamClassifyRepository.update(id, { delFlag: 1 });
    const children = await this.ExamClassifyRepository.find({
      where: { pid: id },
    });
    for (let index = 0; index < children.length; index++) {
      const element = children[index];
      await this.remove(element.id);
    }
    // await this.ExamPaperClassifyRepository.update(item.id, { delFlag: 1 });
    return true;
  }
}
