import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Exam } from 'src/assessment-evaluation/entities/entities-exam-manager/exam.entity';
import { OnlineExamHistory } from 'src/assessment-evaluation/entities/entities-exam-manager/online-exam-history.entity';
import { ExamPaper } from 'src/assessment-evaluation/entities/entities-exam-paper-manager/exam-paper.entity';
import { Repository } from 'typeorm';

@Injectable()
export class OnlineExamHistoryService {
  constructor(
    @InjectRepository(OnlineExamHistory)
    private OnlineExamHistory: Repository<OnlineExamHistory>,
    @InjectRepository(Exam)
    private ExamRep: Repository<Exam>,
    @InjectRepository(ExamPaper)
    private ExamPaper: Repository<ExamPaper>,
  ) {}

  /* 
    使用考试历史ID查找所有考试结果
  */
  async findAllQuestionResultByHistoryId(id) {
    const onlineExamInfo = await this.OnlineExamHistory.findOneBy({ id });
    if (!onlineExamInfo) {
      throw '学员考试不存在';
    }
    const exam = await this.ExamRep.findOneBy({ id: onlineExamInfo.examId });
    if (!exam) {
      throw '考试不存在';
    }
    const { examPaperId, examId, onlineExamId } = onlineExamInfo;
    let sql = `select
    q.id as id,
    q.type as typeId,
    q.difficulty_level as  difficultyLevelId,
    qdl.name as difficultyLevel,
    q.classify_id as  classifyId,
    qc.name as classify,
    qt.name as type,
    qt.element  as element,
    q.knowledge_id as knowledgeId,
    q.title  as title,
    q.options  as options,
    q.answer as answer ,
    q.analysis as analysis ,
    eqr.question_score as score,
    eqr.score as userScore,
    eqr.user_answer as userAnswer,
    eqr.comment as teacherComment,
    eqr.id as resultId
    from question q
    left join question_type qt on
    qt.id = q.type
    left join question_classify qc on
    qc.id = q.classify_id
    left join question_difficulty_level qdl on
    q.difficulty_level = qdl.id
    inner join questions_for_paper qfp on qfp.del_flag = 0 and  qfp.exam_paper_id = ${examPaperId} and q.id = qfp.question_id
    inner join exam_questions_result eqr on eqr.question_id = q.id and eqr.history_id = ${id}
    order by q.type asc `;

    sql += ``;
    const questions = await this.OnlineExamHistory.query(sql);
    return { onlineExamInfo, exam, questions };
  }
  async create(CreateOnlineExamHistoryDto: any) {
    return await this.OnlineExamHistory.save(CreateOnlineExamHistoryDto);
  }
  /**
   * 根据考试记录返回考试信息和试题
   * @param id 考试记录ID
   * @param isPracticeExam 是否为模拟考试，0否1是，模拟考试将会返回答案和解析
   */
  async findAllQuestionsAndExamInfo(id: number, isPracticeExam = 0) {
    const onlineExamInfo = await this.OnlineExamHistory.findOneBy({ id });
    if (!onlineExamInfo) {
      throw '学员考试不存在';
    }
    const exam = await this.ExamRep.findOneBy({ id: onlineExamInfo.examId });
    if (!exam) {
      throw '考试不存在';
    }
    if (new Date().getTime() >= onlineExamInfo.endTimestamp) {
      throw '已超过规定答题时间';
    }

    const { examPaperId, examId, onlineExamId } = onlineExamInfo;
    const paper = await this.ExamPaper.findOneBy({ id: examPaperId });
    let sql = `select
    q.id as id,
    q.type as typeId,
    q.difficulty_level as  difficultyLevelId,
    qdl.name as difficultyLevel,
    q.classify_id as  classifyId,
    qc.name as classify,
    qt.name as type,
    qt.element  as element,
    q.knowledge_id as knowledgeId,
    q.title  as title,
    `;
    if (isPracticeExam) {
      sql += `
      q.answer as answer ,
      q.analysis as analysis ,
      `;
    }
    sql += ` 
    q.options  as options,
    qfp.score as score
    from question q
    left join question_type qt on
    qt.id = q.type
    left join question_classify qc on
    qc.id = q.classify_id
    left join question_difficulty_level qdl on
    q.difficulty_level = qdl.id
    inner join questions_for_paper qfp on qfp.exam_paper_id = ${examPaperId} and qfp.del_flag = 0 and q.id = qfp.question_id order by q.type asc  `;
    const questions = await this.OnlineExamHistory.query(sql);
    return {
      onlineExamInfo,
      exam,
      questions,
      paper,
      now: new Date().getTime(),
    };
  }

  /* 
    查找所有考试历史记录
  */
  async findAll() {
    return this.OnlineExamHistory.find({
      where: { delFlag: 0 },
    });
  }

  /* 
    根据考试历史ID获取详情
  */
  async findOneById(historyId) {
    return this.OnlineExamHistory.findOneBy({
      id: historyId,
    });
  }
  async update(id: number, UpdateOnlineExamHistoryDto: any) {
    return this.OnlineExamHistory.update(id, UpdateOnlineExamHistoryDto);
  }
  // 删除父类型同时删除子类型
  async remove(id: number) {
    if (isNaN(+id) || !id) throw '缺少id';
    await this.OnlineExamHistory.update(id, { delFlag: 1 });
  }
}
