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

@Injectable()
export class ExamPaperClassifyService {
  constructor(
    @InjectRepository(ExamPaperClassify)
    private ExamPaperClassifyRepository: Repository<ExamPaperClassify>,
  ) {}
  /* 
  创建试卷分类
  */
  async create(createExamPaperClassifyDto: CreateExamPaperClassifyDto) {
    await this.ExamPaperClassifyRepository.insert(createExamPaperClassifyDto);
    return true;
  }
  /* 
    获取所有试卷分类
  */
  async findAll() {
    return this.ExamPaperClassifyRepository.find({
      select: ['id', 'name', 'pid', 'level'],
      where: { delFlag: 0 },
    });
  }

  /* 
    更新试卷分类
  */
  async update(
    id: number,
    updateExamPaperClassifyDto: UpdateExamPaperClassifyDto,
  ) {
    return this.ExamPaperClassifyRepository.update(
      id,
      updateExamPaperClassifyDto,
    );
  }
  /* 
  删除父类型同时删除子类型
  */
  async remove(id: number) {
    if (isNaN(+id) || !id) throw '缺少id';
    await this.ExamPaperClassifyRepository.update(id, { delFlag: 1 });
    const children = await this.ExamPaperClassifyRepository.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;
  }
}
