import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { CreateQuestionClassifyDto } from 'src/assessment-evaluation/dto/dtos-question-manager/question-classify/create-question-classify.dto';
import { UpdateQuestionClassifyDto } from 'src/assessment-evaluation/dto/dtos-question-manager/question-classify/update-question-classify.dto';
import { QuestionClassify } from 'src/assessment-evaluation/entities/entities-question-manager/question-classify.entity';

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