import { Controller, Get, Body, Param, Patch, Query } from '@nestjs/common';
import { ApiTags, ApiBearerAuth, ApiOperation } from '@nestjs/swagger';
import { TokenData } from 'src/common/decorator/token-data.decorator';
import { PagingExamPaperDto } from 'src/assessment-evaluation/dto/dtos-exam-paper-manager/exam-paper/paging-exam-paper.dto';
import { QuestionsForPaperService } from 'src/assessment-evaluation/service/service-exam-paper-manager/questions-for-paper';
import { TokenDataEntity } from 'src/common/entities/token-data.entity';
import { ExamQuestionsResultService } from 'src/assessment-evaluation/service/service-exam-manager/exam-questions-result.service';

@ApiTags('考核测评 - 错题巩固')
@ApiBearerAuth()
// @NoAuthToken()
@Controller('assessmentEvaluation/mistake')
export class MistakeAgainController {
  constructor(
    private readonly QuestionsForPaperService: QuestionsForPaperService,
    private readonly ExamQuestionsResultService: ExamQuestionsResultService,
  ) {}

  /* 
    根据分类查询所有试题
  */
  @Get('questions/:classifyId')
  // @NoAuthToken()
  @ApiOperation({ summary: '根据分类查询所有试题' })
  async getQuestionAndExamInfoByClassifyId(
    @Param('classifyId') classifyId: number,
    @Query() querys: { showUserAnswer: number },
    @TokenData() token: TokenDataEntity,
  ) {
    if (!querys.showUserAnswer) querys.showUserAnswer = 1;
    return this.ExamQuestionsResultService.getAllMistakeQuestionsByClassifyId(
      +classifyId,
      token,
      +querys.showUserAnswer,
    );
  }
  /* 
  分页获取类型错题巩固列表
  */
  @Get('paging')
  // @NoAuthToken()
  @ApiOperation({ summary: '分页获取类型错题巩固列表' })
  async pagingMistakeList(
    @Query() PagingExamPaperDto: PagingExamPaperDto,
    @TokenData() token: TokenDataEntity,
  ) {
    return this.QuestionsForPaperService.pagingMistakeQuestion(
      PagingExamPaperDto,
      token,
    );
  }

  /* 
  根据分类查最后一次考试ID
  */
  @Get('lastExamHistory/:classifyId')
  // @NoAuthToken()
  @ApiOperation({ summary: '根据分类查最后一次考试ID' })
  async getLastOnlineExamHistoryInfoByQuestionClassifyId(
    @Param('classifyId') classifyId: number,
    @TokenData() token: TokenDataEntity,
  ) {
    return this.ExamQuestionsResultService.getLastOnlineExamHistoryInfoByQuestionClassifyId(
      token,
      +classifyId,
    );
  }

  /* 
  将错题得分改为试题分数
  */
  @Patch('submitMistakes/:classifyId')
  // @NoAuthToken()
  @ApiOperation({ summary: '将错题得分改为试题分数' })
  async submitMistakes(
    @Param('classifyId') classifyId: number,
    @Body() answers: Array<any>,
    @TokenData() token: TokenDataEntity,
  ) {
    console.log(answers, token);
    const questions =
      await this.ExamQuestionsResultService.getAllMistakeQuestionsByClassifyId(
        +classifyId,
        token,
        1,
      );
    const res = {
      pass: 0,
      faild: 0,
    };
    questions.forEach((quesItem) => {
      const ansItem = answers.find((ans) => ans.questionId === quesItem.id);
      if (ansItem) {
        const isPass = checkAnswer(quesItem, ansItem.answer);
        console.log(isPass);
        if (isPass.pass) {
          res.pass++;
          this.ExamQuestionsResultService.updateMiskateScore(ansItem.resultId);
        } else {
          res.faild++;
        }
      } else {
        res.faild++;
      }
    });

    // this.OnlineExamHistoryController.checkAnswer()
    // this.ExamQuestionsResultService.updateMiskateScore()
    return res;
    // return true;
  }
}
// 包含率算法
export function jaccard(ans, uans) {
  const ansSet = new Set(ans.split(''));
  const uAnsSet = new Set(uans.split(''));
  const uAnsHasAns = new Set([...ansSet].filter((x) => uAnsSet.has(x)));
  return uAnsHasAns.size / ansSet.size;
}
/* 
判断是否答对
*/
export function checkAnswer(question, userAnswer) {
  // 用户答案
  let answer = userAnswer;
  if (!answer) {
    return { pass: false, score: 0 };
  }
  let oneOptionScore;
  let checkdOptions = null;
  // 正确答案
  try {
    checkdOptions = JSON.parse(question.answer);
  } catch (error) {
    checkdOptions = null;
  }

  if (question.element === 'textarea') {
    answer = userAnswer[0];
    // checkdOptions = JSON.parse(question.options);
    // oneOptionScore = Math.ceil(question.score / checkdOptions.length);
  }
  if (question.element === 'input') {
    checkdOptions = JSON.parse(question.options);
  }
  let isTrue;
  if (question.element === 'textarea') {
    isTrue = { pass: false, score: 0 };
    // for (let ind = 0; ind < checkdOptions.length; ind++) {
    //   const element = checkdOptions[ind];
    //   if (answer.indexOf(element) !== -1) {
    //     isTrue.score += oneOptionScore;
    //     if (isTrue.score >= question.score) {
    //       isTrue.score = question.score;
    //       isTrue.pass = true;
    //     }
    //   }
    // }
    const questionScore = question.score;
    let questionAnswer = '';
    try {
      questionAnswer = JSON.parse(question.answer);
      if (questionAnswer.length > 0) {
        const percent = jaccard(questionAnswer[0], answer);
        isTrue.score = Math.floor(questionScore * percent);
        if (percent === 1) {
          isTrue.pass = true;
        }
      }
    } catch (error) {
      console.log('-?>>>>>>>>>>>>>>>>>>>>>>', error);
    }
  } else {
    isTrue = { pass: true, score: question.score };
    for (let ind = 0; ind < checkdOptions.length; ind++) {
      const element = checkdOptions[ind];
      if (answer.indexOf(element) == -1) {
        isTrue = { pass: false, score: 0 };
      }

      // 填空题必须按顺序
      if (question.element === 'input') {
        if (element !== answer[ind]) {
          isTrue = { pass: false, score: 0 };
        }
      }
    }
  }

  console.log(answer, checkdOptions);
  return isTrue;
}
