import {
  Controller,
  Get,
  Post,
  Body,
  Param,
  Delete,
  Patch,
  Query,
} from '@nestjs/common';
import { ApiTags, ApiBearerAuth, ApiOperation } from '@nestjs/swagger';
import { NoAuthToken } from 'src/common/decorator/no-token.decorator';
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 { UpdateExamPaperDto } from 'src/assessment-evaluation/dto/dtos-exam-paper-manager/exam-paper/update-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';

@ApiTags('试卷管理 - 试卷')
@ApiBearerAuth()
// @NoAuthToken()
@Controller('assessmentEvaluation/exampaper')
export class ExamPaperController {
  constructor(
    private readonly ExamPaperService: ExamPaperService,
    private readonly QuestionsForPaperService: QuestionsForPaperService,
  ) {}
  @Get('questionsByPaper/:id')
  @NoAuthToken()
  /* 
  使用试卷id获取对应试题
  */
  async getQuestionsByPaperId(@Param('id') id: number) {
    return this.QuestionsForPaperService.getQuestionsByPaperId(id);
  }
  @Post('copy/:id')
  /* 
    复制试卷
  */
  async copyNewPaper(
    @Param('id') id: number,
    @Body() data,
    @TokenData() token: any,
  ) {
    const oldPaperItem = await this.ExamPaperService.findOne(id);
    delete oldPaperItem['id'];
    delete oldPaperItem['createTime'];
    delete oldPaperItem['updateTime'];
    oldPaperItem.title = data.title;
    oldPaperItem.status = 0;
    oldPaperItem.creator = oldPaperItem.updater = token.userId;
    const res = await this.create(oldPaperItem, token);
    return res;
  }

  @Post()
  /* 
    创建试卷
  */
  // @NoAuthToken()
  async create(
    @Body() CreateExamPaperDto: CreateExamPaperDto,
    @TokenData() token: any,
  ) {
    CreateExamPaperDto.creator = CreateExamPaperDto.updater = token.userId;
    const newPaper = await this.ExamPaperService.create(CreateExamPaperDto);
    const { FixRes, RandRes } = await this.saveQuestionInfo(
      newPaper.id,
      token,
      CreateExamPaperDto.questionInfo,
    );
    return { newPaper, FixRes, RandRes };
  }
  /* 
    保存试卷中试题的
  */
  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 };
  }
  @Get('item/:id')
  // @NoAuthToken()
  /* 
  获取试卷详情
  */
  async findOne(@Param('id') id: string) {
    return this.ExamPaperService.findOne(+id);
  }
  @Get('checkQuote/:id')
  @NoAuthToken()
  @ApiOperation({ summary: '检查试卷被哪些考试引用' })
  /* 
  检查试卷被哪些考试引用
  */
  async checkQuote(@Param('id') id: string) {
    return this.ExamPaperService.checkPaperHasQuote(+id);
  }

  @Get('paging')
  // @NoAuthToken()
  /* 
    分页查询试卷
  */
  async paging(
    @Query() PagingExamPaperDto: PagingExamPaperDto,
    @TokenData() token: TokenDataEntity,
  ) {
    return this.ExamPaperService.paging(PagingExamPaperDto, token);
  }

  @Patch('item/:id')
  /* 
    更新试卷
  */
  async update(
    @Param('id') id: string,
    @Body() UpdateExamPaperDto: UpdateExamPaperDto,
    @TokenData() token,
  ) {
    console.log(UpdateExamPaperDto);
    if ('questionInfo' in UpdateExamPaperDto) {
      await this.ExamPaperService.removeAllQuestionByPaperId(+id);
      const { FixRes, RandRes } = await this.saveQuestionInfo(
        +id,
        token,
        UpdateExamPaperDto.questionInfo,
      );
      delete UpdateExamPaperDto.questionInfo;
    }
    const newPaper = await this.ExamPaperService.update(
      +id,
      UpdateExamPaperDto,
    );
    return { newPaper };
  }

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

  /* 
    批量删除试卷
  */
  @Delete()
  async removeAll(@Body() ids: number[]) {
    try {
      for (const item of ids) {
        await this.ExamPaperService.remove(+item);
      }
    } catch (error) {
      return false;
    }
    return true;
  }

  /* 
    修改ID
  */
  @Patch('putchAllClassifyId')
  async putchAllClassifyId(
    @Body() body: { ids: number[]; classifyId: number },
  ) {
    console.log('================>', body);
    const { ids, classifyId } = body;
    if (!ids) return '必须传入id';
    if (!classifyId) return '必须传入classifyId';
    try {
      await this.ExamPaperService.batchMovePaperToClassify(ids, classifyId);
    } catch (error) {
      console.log(error);
      return false;
    }
    return true;
  }
}
