import {
  Controller,
  Get,
  Post,
  Body,
  Param,
  Delete,
  Patch,
} from '@nestjs/common';
import {
  ApiTags,
  ApiBearerAuth,
  ApiProperty,
  ApiOperation,
} from '@nestjs/swagger';
import { ExamQuestionsResultService } from 'src/assessment-evaluation/service/service-exam-manager/exam-questions-result.service';
import { ExamService } from 'src/assessment-evaluation/service/service-exam-manager/exam.service';
import { OnlineExamHistoryService } from 'src/assessment-evaluation/service/service-exam-manager/online-exam-history.service';
import { StudentOnlineExamService } from 'src/assessment-evaluation/service/service-exam-manager/student-online-exam.service';
import { NoAuthToken } from 'src/common/decorator/no-token.decorator';
import { TokenData } from 'src/common/decorator/token-data.decorator';
import { CreateDto } from 'src/common/dto/create.dto';
import { TokenDataEntity } from 'src/common/entities/token-data.entity';
import { checkAnswer } from 'src/assessment-evaluation/controller/sim-test/mistake-again.controller';
export class CreateOnlineExamHistoryDto extends CreateDto {
  @ApiProperty({ description: '试题名模糊查询', required: true })
  onlineExamId: number;

  @ApiProperty({ description: '试题名模糊查询', required: false, default: 0 })
  isPracticeExam: number;
}
@ApiTags('考试管理 - 考试历史')
@ApiBearerAuth()
// @NoAuthToken()
@Controller('assessmentEvaluation/OnlineExamHistory')
export class OnlineExamHistoryController {
  constructor(
    private readonly OnlineExamHistoryService: OnlineExamHistoryService,
    private readonly StudentOnlineExamService: StudentOnlineExamService,
    private readonly ExamService: ExamService,
    private readonly ExamQuestionResultService: ExamQuestionsResultService,
  ) {}
  @Patch('result/:historyId')
  @ApiOperation({ summary: '传入修改数组，修改题目result相关字段' })
  // 修改results字段
  async updateResults(
    @Param('historyId') historyId,
    @Body() body: { id: number; score: number; comment: string }[],
  ) {
    console.log(body);
    const promiseList = [];
    body.forEach(async (item) => {
      promiseList.push(
        this.ExamQuestionResultService.update(item.id, {
          score: item.score,
          comment: item.comment,
        }),
      );
    });
    const res = await Promise.all(promiseList);

    return await this.OnlineExamHistoryService.update(historyId, {
      isGradePaper: 1,
    });
  }
  @Post('submitExam/:id')
  // @NoAuthToken()
  // 查一个
  async findOne(
    @Param('id') historyId: string,
    @Body() answers: Array<any>,
    @TokenData() token: TokenDataEntity,
  ) {
    console.log(historyId, answers, token);
    const historyItem = await this.OnlineExamHistoryService.findOneById(
      historyId,
    );
    if (
      historyItem != null &&
      historyItem.reportTime - new Date(historyItem.createTime).getTime() > 500
    ) {
      console.log(
        historyItem.reportTime,
        new Date(historyItem.createTime).getTime(),
      );
      throw '本次考试已交卷过，请重新点击开始考试';
    }
    const { onlineExamInfo, exam, questions } =
      await this.OnlineExamHistoryService.findAllQuestionsAndExamInfo(
        +historyId,
        1,
      );
    // 更新记录中交卷时间
    this.OnlineExamHistoryService.update(+historyId, {
      reportTime: new Date().getTime(),
      isGradePaper: exam.gradePaperMode == 1 ? 0 : 1,
    });
    // 将答题记录保存至试题结果表中
    const questionsResult = questions.map((ques) => {
      let ans = answers.find((ans) => ans.questionId === ques.id);
      let userScore = 0;
      if (ans == null) {
        ans = [];
      } else {
        ans = ans.answer;
        const result = checkAnswer(ques, ans);
        console.log(result);
        // if (result.pass === true) {
        //   userScore = ques.score;
        // } else {
        userScore = result.score;
        // }
      }
      return {
        historyId: +historyId,
        questionId: +ques.id,
        questionScore: ques.score,
        score: userScore,
        userAnswer: JSON.stringify(ans),
        creator: token.userId,
        updater: token.userId,
      };
    });
    await this.ExamQuestionResultService.removeAllByHistoryId(+historyId);
    const createRes = await this.ExamQuestionResultService.create(
      questionsResult,
    );
    const usertotalScore = questionsResult.reduce((prev, item) => {
      return prev + item.score;
    }, 0);

    return {
      score: usertotalScore,
      paperScore: exam.totalScore,
      passPercent: exam.passPercent,
      gradePaperMode: exam.gradePaperMode,
      isPass:
        Math.round((exam.totalScore * exam.passPercent) / 100) <=
        usertotalScore,
    };
  }
  @Post('simtest')
  // 创建模拟考试
  async createSim(
    @Body() CreateOnlineExamHistoryDto: CreateOnlineExamHistoryDto,
    @TokenData() token: any,
  ) {
    // 查询学员考试
    const onlineExamItem = await this.StudentOnlineExamService.findOneById(
      +CreateOnlineExamHistoryDto.onlineExamId,
      false,
    );
    if (!onlineExamItem) {
      throw '数据错误，没找到模拟考试';
    }
    const formDto = {
      onlineExamId: CreateOnlineExamHistoryDto.onlineExamId,
      examId: null,
      examPaperId: null,
      examDuration: 0,
      reportTime: 0,
      endTimestamp: 0,
      isAnonymous: 0,
      isGradePaper: 0,
      createTime: new Date(),
      creator: token.userId,
      updater: token.userId,
      isPracticeExam: CreateOnlineExamHistoryDto.isPracticeExam ?? 0,
    };
    formDto.examId = onlineExamItem.examId;

    // console.log(studentExamTimes);
    // 查询考试
    const examItem = await this.ExamService.findOne(onlineExamItem.examId);
    formDto.examDuration = examItem.examInfo.examDuration;
    formDto.examPaperId = examItem.examInfo.examPaperId;
    const endTime = new Date().getTime() + formDto.examDuration * 60 * 1000;
    formDto.reportTime = formDto.createTime.getTime();
    formDto.endTimestamp = endTime;
    // 存入考试记录
    return await this.OnlineExamHistoryService.create(formDto);
    // console.log(onlineExamItem, examItem);
    // return false;
  }

  @Post()
  // 创建考试
  async create(
    @Body() CreateOnlineExamHistoryDto: CreateOnlineExamHistoryDto,
    @TokenData() token: any,
  ) {
    // 查询学员考试
    const onlineExamItem = await this.StudentOnlineExamService.findOneById(
      +CreateOnlineExamHistoryDto.onlineExamId,
    );
    const formDto = {
      onlineExamId: CreateOnlineExamHistoryDto.onlineExamId,
      examId: null,
      examPaperId: null,
      examDuration: 0,
      reportTime: 0,
      endTimestamp: 0,
      isAnonymous: 0,
      isGradePaper: 0,
      createTime: new Date(),
      creator: token.userId,
      updater: token.userId,
      isPracticeExam: CreateOnlineExamHistoryDto.isPracticeExam ?? 0,
    };
    if (!onlineExamItem) throw '该学员考试不存在';
    formDto.examId = onlineExamItem.examId;

    // console.log(studentExamTimes);
    // 查询考试
    const examItem = await this.ExamService.findOne(onlineExamItem.examId);
    if (!examItem.examInfo) throw '该考试不存在';
    if (
      examItem.examInfo.delFlag != -1 &&
      new Date() > new Date(examItem.examInfo.examEndTime)
    ) {
      throw '考试已结束';
    }
    const studentExamTimes = await this.StudentOnlineExamService.checkExamTimes(
      token.userId,
      CreateOnlineExamHistoryDto.onlineExamId,
    );
    if (Array.isArray(studentExamTimes) && studentExamTimes.length > 0) {
      if (studentExamTimes[0].times >= examItem.examInfo.examTimes) {
        throw '您已没有考试机会了';
      }
    }
    formDto.examDuration = examItem.examInfo.examDuration;
    formDto.examPaperId = examItem.examInfo.examPaperId;
    const endTime = new Date().getTime() + formDto.examDuration * 60 * 1000;
    formDto.reportTime = formDto.createTime.getTime();
    formDto.endTimestamp = endTime;
    // 存入考试记录
    return await this.OnlineExamHistoryService.create(formDto);
    // console.log(onlineExamItem, examItem);
    // return false;
  }
  @Get('examQuestionResult/:onlineExamId')
  @NoAuthToken()
  // 获取试题
  async getQuestionResult(@Param('onlineExamId') onlineExamId: number) {
    return this.OnlineExamHistoryService.findAllQuestionResultByHistoryId(
      onlineExamId,
    );
  }
  @Get(`questions/:id`)
  // 使用历史记录ID获取试题
  async findQuestionByHistoryId(@Param('id') id: string) {
    return this.OnlineExamHistoryService.findAllQuestionsAndExamInfo(+id);
  }
  @Get()
  // 获取所有考试
  async findAll() {
    return this.OnlineExamHistoryService.findAll();
  }

  @Patch(':id')
  // 更新
  async update(
    @Param('id') id: string,
    @Body() UpdateOnlineExamHistoryDto: any,
  ) {
    return this.OnlineExamHistoryService.update(
      +id,
      UpdateOnlineExamHistoryDto,
    );
  }

  @Delete(':id')
  // 删除考试
  async remove(@Param('id') id: string) {
    return this.OnlineExamHistoryService.remove(+id);
  }
}
