import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { PagingStudentOnlineExamDto } from 'src/assessment-evaluation/dto/dtos-exam-manager/student-online-exam/paging-student-online-exam.dto';
import { QuestionsForPaper } from 'src/assessment-evaluation/entities/entities-exam-paper-manager/questions-for-paper.entity';
import { TokenDataEntity } from 'src/common/entities/token-data.entity';
import { Repository } from 'typeorm';
import { QuestionTypeService } from '../service-question-manager/question-type.service';

@Injectable()
export class QuestionsForPaperService {
  constructor(
    @InjectRepository(QuestionsForPaper)
    private QuestionsForPaperRepository: Repository<QuestionsForPaper>,
    private readonly QuestionTypeService: QuestionTypeService,
  ) {}

  async create(createQuestionsForPaperDto: any) {
    await this.QuestionsForPaperRepository.insert(createQuestionsForPaperDto);
    return true;
  }

  async findAll() {
    return this.QuestionsForPaperRepository.find({
      where: { delFlag: 0 },
    });
  }
  async pagingMistakeQuestion(
    pagingInfo: PagingStudentOnlineExamDto,
    token: TokenDataEntity,
  ) {
    const { currentPage, pageSize, title } = pagingInfo;
    const { userId } = token;
    let countSql = `
    select
	q.classify_id  as classifyId,
	qc.name as classify
from
	exam_questions_result eqr
left join question q on
	q.id = eqr.question_id 
	left join question_classify qc on q.classify_id = qc.id
where
	eqr.del_flag <=0 and q.del_flag <= 0
	and eqr.score < eqr.question_score and eqr.mistake_score < eqr.question_score 
    `;
    let sql = `
    select qcc.classify,qcc.classifyId,group_concat(qcc.typeId,':',qcc.count) as times  from
(

	select 	ifnull(count(1),0) as count,
	axx.classify,axx.type,axx.classifyId,axx.typeId
	from (
	
		select
			qc.name as classify,
			qt.name as type,
			q.classify_id as classifyId,
			q.type as typeId
		from
			exam_questions_result eqr
		left join question q on
			q.id = eqr.question_id 
		right join question_type qt on qt.id = q.type
		left join question_classify qc on qc.id = q.classify_id
-- 		使用试题ID查询resultID,去重
		inner join (
			select max(eqr.id) as rid from exam_questions_result eqr 
			left join online_exam_history oeh on oeh.id=eqr.history_id  
			where oeh.is_grade_paper =1
			group by eqr.question_id,eqr.creator
		) hidt on eqr.id = hidt.rid
		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 (e.exam_end_time <now() or e.exam_times<= countTable.count)
			and eqr.score < eqr.question_score and eqr.mistake_score < eqr.question_score 
    `;
    if (userId) {
      sql += `
      and eqr.creator ='${userId}' `;
      countSql += `	and eqr.creator ='${userId}' 
      `;
    }
    sql += `
    group by eqr.question_id) axx group by
	 axx.classifyId ,axx.typeId order by  axx.classifyId ,axx.typeId 
) qcc `;
    if (title) {
      sql += `
  where qcc.classify like '%${title}%' `;
      countSql += `and qc.name like '%${title}%' `;
    }
    sql += `
group by qcc.classifyId order by qcc.classifyId desc limit ?,?
    `;
    countSql += `group by q.classify_id order by q.classify_id limit ?,?`;
    const list = await this.QuestionsForPaperRepository.query(sql, [
      +(currentPage - 1) * pageSize,
      +pageSize,
    ]);
    const count = await this.QuestionsForPaperRepository.query(countSql, [
      +(currentPage - 1) * pageSize,
      +pageSize,
    ]);
    const types = await this.QuestionTypeService.findAll();
    return { total: count.length, currentPage, pageSize, data: list, types };
  }
  /**
   * 根据试卷id获取试卷与试题的关系列表
   */
  async getAllPapersQuestions(id: number) {
    return this.QuestionsForPaperRepository.find({
      where: { delFlag: 0, examPaperId: id },
    });
  }
  /**
   * 根据试卷id复制所有试题关系到新试卷id
   * @param id 试卷id
   * @param nid 复制到的新的试卷id
   * @param uid 用户id
   * @returns 影响行数
   */
  async copyPapersQuestionToPaper(id: number, nid: number, uid: string) {
    const sql = `insert
    into
    questions_for_paper(version,exam_paper_id,creator,updater,question_id,score,type,is_fixed)
  select
    1 as version,
    ${nid} as exam_paper_id,
    ${uid} as creator,
    ${uid} as updater,
    qfp.question_id as question_id,
    qfp.score as score,
    qfp.type as type,
    qfp.is_fixed as is_fixed
  from
    questions_for_paper qfp
  where
    qfp.del_flag = 0
    and qfp.exam_paper_id = ${id}`;

    return await this.QuestionsForPaperRepository.query(sql);
  }
  // 删除父类型同时删除子类型
  async remove(id: number) {
    if (isNaN(+id) || !id) throw '缺少id';
    await this.QuestionsForPaperRepository.update(id, { delFlag: 1 });
    return true;
  }
  async getQuestionsByPaperId(id: number) {
    return await this.QuestionsForPaperRepository.query(
      `
    select
          qq.id as id,
          qq.type as typeId,
          qq.title as title,
          users.name as creator ,
          qq.creator as creatorId,
          qq.classify_id  as classifyId,
          qc.name  as classify,
          qq.options as options,
          date_format(qq.create_time, '%Y-%m-%d') as createTime,
          qq.answer as answer,
          types.name as type,
          types.element as element,
          qq.difficulty_level as difficultyLevelId,
          levels.name as difficultyLevel,
          qq.knowledge_id as knowledgeId,
          knows.name as knowledgePoint,
          qfp.score score
        from
          question qq
          inner join (select qfp.id as id,qfp.question_id as questionId,qfp.score score  from questions_for_paper qfp  
    where qfp.exam_paper_id =? and qfp.del_flag =0) qfp on qfp.questionId = qq.id
        left join question_type types on
          qq.type = types.id
        left join question_difficulty_level levels on
          qq.difficulty_level = levels.id
        left join knowledge_point knows on
          qq.knowledge_id = knows.id
          left join user users on qq.creator = users.id
          left join question_classify qc on qq.classify_id  = qc.id
       
        order by qq.type`,
      [+id],
    );
  }
}
