import {
  Controller,
  Get,
  Post,
  Body,
  Param,
  Delete,
  Query,
} from '@nestjs/common';
import { ApiTags, ApiBearerAuth } from '@nestjs/swagger';
import { TokenData } from 'src/common/decorator/token-data.decorator';
import { ExamPaperService } from 'src/assessment-evaluation/service/service-exam-paper-manager/exam-paper.service';
import { PagingExamPaperDto } from 'src/assessment-evaluation/dto/dtos-exam-paper-manager/exam-paper/paging-exam-paper.dto';
import { CreateExamPaperDto } from 'src/assessment-evaluation/dto/dtos-exam-paper-manager/exam-paper/create-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 { ExamService } from 'src/assessment-evaluation/service/service-exam-manager/exam.service';
import { StudentOnlineExamService } from 'src/assessment-evaluation/service/service-exam-manager/student-online-exam.service';

@ApiTags('模拟考试')
@ApiBearerAuth()
// @NoAuthToken()
@Controller('assessmentEvaluation/simtest')
export class SimTestController {
  constructor(
    private readonly ExamPaperService: ExamPaperService,
    private readonly QuestionsForPaperService: QuestionsForPaperService,
    private readonly ExamService: ExamService,
    private readonly StudentOnlineExam: StudentOnlineExamService,
  ) {}

  /* 
    分页获取模拟考试
  */
  @Get('paging')
  // @NoAuthToken()
  async paging(
    @Query() PagingExamPaperDto: PagingExamPaperDto,
    @TokenData() token: TokenDataEntity,
  ) {
    return this.ExamPaperService.pagingSim(PagingExamPaperDto, token, -1);
  }

  /* 
    创建模拟考试
  */
  @Post()
  // @NoAuthToken()
  async create(
    @Body() CreateExamPaperDto: CreateExamPaperDto,
    @TokenData() token: any,
  ) {
    CreateExamPaperDto.creator = CreateExamPaperDto.updater = token.userId;
    CreateExamPaperDto['delFlag'] = -1;
    const newPaper = await this.ExamPaperService.create(CreateExamPaperDto);
    await this.saveQuestionInfo(
      newPaper.id,
      token,
      CreateExamPaperDto.questionInfo,
    );
    // 创建完成试卷创建考试
    const now = new Date();
    const exam = await this.ExamService.create({
      title: CreateExamPaperDto.title,
      classifyId: -1,
      examDesc: '',
      examStartTime: now,
      examEndTime: now,
      examDuration: CreateExamPaperDto.paperDuration,
      examTimes: -1,
      passPercent: CreateExamPaperDto.passPercent,
      questionsIsRandomSort: 0,
      optionsIsRandomSort: 0,
      successTips: '恭喜您，考试通过',
      failedTips: '您本次考试未通过',
      waitingTips: '请等待人工评分',
      examPaperId: newPaper.id,
      examMode: 0,
      totalScore: CreateExamPaperDto.totalScore,
      gradePaperMode: 0,
      examinerId: token.userId,
      joinMode: 0,
      delFlag: -1,
      joinPassword: '',
      creator: token.userId,
      updater: token.userId,
    });
    console.log(exam);
    const studentOnlineExam = await this.StudentOnlineExam.createOne({
      userId: token.userId,
      examId: exam.id,
      mistakes: 0,
      examTimes: 0,
      delFlag: -1,
      creator: token.userId,
      updater: token.userId,
    });
    return { newPaper, exam, studentOnlineExam };
  }
  /* 
    保存试题信息
  */
  async saveQuestionInfo(paperId: any, token: any, questionInfo: any) {
    const { fixdQuestions, randQuestions } = questionInfo;
    const fixdNew = fixdQuestions.map((fixItem) => {
      return {
        examPaperId: paperId,
        questionId: fixItem.id,
        score: fixItem['itemScore'],
        isFixed: 1,
        type: fixItem['typeId'],
        updater: token.userId,
        creator: token.userId,
      };
    });
    const randNew = randQuestions.map((fixItem) => {
      return {
        examPaperId: paperId,
        questionId: fixItem.id,
        score: fixItem['itemScore'],
        isFixed: 0,
        type: fixItem['typeId'],
        updater: token.userId,
        creator: token.userId,
      };
    });
    const FixRes = await this.QuestionsForPaperService.create(fixdNew);
    const RandRes = await this.QuestionsForPaperService.create(randNew);
    return { FixRes, RandRes };
  }

  /* 
    删除模拟考试
  */
  @Delete('item/:id')
  async remove(@Param('id') id: string) {
    await this.ExamPaperService.remove(+id);
    return;
  }
}
