import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { ExamQuestionsResult } from 'src/assessment-evaluation/entities/entities-exam-manager/exam-questions-result.entity';
import { TokenDataEntity } from 'src/common/entities/token-data.entity';
import { Repository } from 'typeorm';

@Injectable()
export class ExamQuestionsResultService {
  constructor(
    @InjectRepository(ExamQuestionsResult)
    private ExamQuestionsResultRepository: Repository<ExamQuestionsResult>,
  ) {}

  /* 
    创建试题答卷答案
  */
  async create(CreateExamQuestionsResultDto: any) {
    await this.ExamQuestionsResultRepository.insert(
      CreateExamQuestionsResultDto,
    );
    return true;
  }
  /* 
    获取所有试题答案
  */
  async findAll() {
    return this.ExamQuestionsResultRepository.find({
      where: { delFlag: 0 },
    });
  }
  /* 
    更新试题答案
  */
  async update(id: number, UpdateExamQuestionsResultDto: any) {
    return this.ExamQuestionsResultRepository.update(
      id,
      UpdateExamQuestionsResultDto,
    );
  }
  /* 
    删除父类型同时删除子类型
  */
  async removeAllByHistoryId(id: number) {
    const rows = await this.ExamQuestionsResultRepository.query(
      `delete from exam_questions_result where del_flag=0 and history_id=${+id}`,
    );
    return rows;
  }
  /* 
    根据ID删除试题答案
  */
  async remove(id: number) {
    await this.ExamQuestionsResultRepository.update(id, { delFlag: 1 });
    return true;
  }
  /* 
    根据试题分类ID获取所有错题
  */
  async getAllMistakeQuestionsByClassifyId(
    classifyId: number,
    token: TokenDataEntity,
    showUserAnswer: number,
  ) {
    const { userId } = token;
    // eqr.user_answer as userAnswer,
    let sql = `
    select 
eqr.creator c,
eqr.question_id as id,
eqr.id as resultId,
q.type as typeId,
q.classify_id as classifyId,
qt.name as type,
qt.element as element,
q.title as title,
q.options as options,
q.answer as answer,
q.analysis  as analysis,
eqr.comment as teacherComment,`;
    if (showUserAnswer == 1) {
      sql += 'eqr.user_answer as userAnswer,';
    }
    sql += `
eqr.question_score as score,
eqr.score  as userScore,
q.knowledge_id as knowledgeId,
q.difficulty_level as difficultyLevelId
from exam_questions_result eqr 
-- 按试题去重
inner join (
	select max(eqr.id) as rid from exam_questions_result eqr 
	group by eqr.question_id,eqr.creator 
) hidt on eqr.id = hidt.rid
left join question q on q.id= eqr.question_id
left join question_type qt on q.type=qt.id
left join online_exam_history oeh on oeh.id=eqr.history_id
left join exam e on oeh.exam_id  = e.id
-- 检测所有试题对应的考试考了多少次了
left join (
	select eqr.question_id qid,group_concat(oeh.id) oehids ,count(oeh.id) count,soe.user_id uid
	from exam_questions_result eqr 
	left join online_exam_history oeh on oeh.id = eqr.history_id 
	left join student_online_exam soe on soe.id = oeh.online_exam_id  
	group by eqr.question_id,oeh.online_exam_id 
) countTable on countTable.qid = q.id and countTable.uid = eqr.creator
where 
eqr.del_flag <=0
and q.del_flag <= 0
and eqr.mistake_score <eqr.question_score 
and eqr.score < eqr.question_score 
-- 考试结束判断，考试时间过了或考试次数用尽   考试次数小于允许考试的次数则显示
and (e.exam_end_time <now() or e.exam_times<= countTable.count)
and eqr.creator = ?
and q.classify_id = ?
order by q.type,eqr.question_id,eqr.id `;
    return await this.ExamQuestionsResultRepository.query(sql, [
      userId,
      classifyId,
    ]);
  }
  async updateMiskateScore(id: number) {
    this.ExamQuestionsResultRepository.query(
      `update exam_questions_result eqr set eqr.mistake_score = eqr.question_score where eqr.id =?`,
      [+id],
    );
  }
  async getLastOnlineExamHistoryInfoByQuestionClassifyId(token, classify) {
    let sql = `select oeh.id,oeh.online_exam_id,oeh.exam_id ,oeh.exam_paper_id  from online_exam_history oeh
    inner join (
      select qfp.id,qfp.exam_paper_id from questions_for_paper qfp inner join (
        select eqr.question_id as qid,
        q.classify_id as classifyId,
        qc.name as classifyName
        from (
          select eqr.question_id  from exam_questions_result eqr 
          where eqr.score<eqr.question_score 
          and eqr.mistake_score <eqr.question_score  
          and eqr.creator='${token.userId}'
          group by eqr.question_id 
          order by eqr.create_time desc
        ) eqr 
        left join question q on q.id = eqr.question_id
        left join question_classify qc on qc.id = q.classify_id
        where q.classify_id  = ${classify} 
        group by q.classify_id 
      
      ) hq on hq.qid=qfp.question_id
    ) qfphistory on qfphistory.exam_paper_id=oeh.exam_paper_id
     where oeh.creator = '${token.userId}' order by oeh.id desc limit 1`;
    sql += '';
    return this.ExamQuestionsResultRepository.query(sql);
  }
}
