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 { CreateQuestionDto } from 'src/assessment-evaluation/dto/dtos-question-manager/question/create-question.dto';
import { PagingQuestionDto } from 'src/assessment-evaluation/dto/dtos-question-manager/question/paging-question.dto';
import { UpdateQuestionDto } from 'src/assessment-evaluation/dto/dtos-question-manager/question/update-question.dto';
import { QuestionDifficultyLevelService } from 'src/assessment-evaluation/service/service-question-manager/question-difficulty-level.service';
import { QuestionTypeService } from 'src/assessment-evaluation/service/service-question-manager/question-type.service';
import { QuestionService } from 'src/assessment-evaluation/service/service-question-manager/question.service';
import { GetQuestionCountDto } from 'src/assessment-evaluation/dto/dtos-question-manager/question/get-question-count.dto';
import { KnowledgePointService } from 'src/assessment-evaluation/service/service-question-manager/knowledge-point.service';

@ApiTags('试题管理 - 试题')
@ApiBearerAuth()
// @NoAuthToken()
@Controller('assessmentEvaluation/questions')
export class QuestionController {
  constructor(
    private readonly QuestionService: QuestionService,
    private readonly QuestionDifficultyLevelService: QuestionDifficultyLevelService,
    private readonly QuestionTypeService: QuestionTypeService,
    private readonly KnowledgePointService: KnowledgePointService,
  ) {}

  @Post()
  // @NoAuthToken()
  /*
   创建试题
   */
  async create(
    @Body() createQuestionDto: CreateQuestionDto,
    @TokenData() token: any,
  ) {
    createQuestionDto.creator = createQuestionDto.updater = token.userId;
    return this.QuestionService.create(createQuestionDto);
  }

  /* 
    导入试题到某个分类下
  */
  @Post('import/:classifyId')
  // @NoAuthToken()
  async importQuestions(
    @Param('classifyId') classifyId: number,
    @Body() questions: any[],
    @TokenData() token: any,
  ) {
    const difficultys = await this.QuestionDifficultyLevelService.findAll();
    const types = await this.QuestionTypeService.findAll();
    // return this.QuestionService.create(createQuestionDto);
    const formatedQuestion: CreateQuestionDto[] = [];
    for (let ind = 0; ind < questions.length; ind++) {
      const item = questions[ind];
      const type = types.find((t) => t.name === item.type);
      const difficulty = difficultys.find((d) => d.name === item.difficulty);
      let knowledge = null;
      if (item.knowledge && item.knowledge.trim() !== '') {
        knowledge = await this.KnowledgePointService.create({
          name: item.knowledge,
          creator: token.userId,
          updater: token.userId,
        });
      }
      const queTemp: CreateQuestionDto = {
        type: type.id,
        difficultyLevel: difficulty.id,
        classifyId,
        title: item.title,
        options: item.options,
        answer: item.answer,
        knowledgeId: knowledge ? knowledge.id : null,
        analysis: item.analysis,
        creator: token.userId,
        updater: token.userId,
        student: 0,
      };
      formatedQuestion.push(queTemp);
    }

    return await this.QuestionService.importQuestions(formatedQuestion);
  }
  /* 
    随机选题
  */
  @Get('random')
  @NoAuthToken()
  @ApiOperation({ summary: '传入选题个数，随机从数据库中抽取对应题数' })
  async random(
    @Query()
    getQuestionCountDto: GetQuestionCountDto,
  ) {
    console.log('===================>', getQuestionCountDto);
    return this.QuestionService.random(getQuestionCountDto);
  }

  /* 
    导出某个分类下的试题,没有传入分类ID则导出所有试题
  */
  @Get('export/:classifyId?')
  @NoAuthToken()
  async exportQuestion(
    @Param('classifyId')
    classifyId: number,
  ) {
    return this.QuestionService.exportAllQuestion(+classifyId);
  }
  /* 
    获取所有试题
  */
  @Get()
  async findAll() {
    return this.QuestionService.findAll();
  }

  /* 
    获取单个试题
  */
  @Get('item/:id')
  // @NoAuthToken()
  async findOne(@Param('id') id: string) {
    return this.QuestionService.findOne(+id);
  }

  /* 
    获取试题数量,可以排除某些试题ID
  */
  @Get('count')
  @NoAuthToken()
  async getCount(@Query() getQuestionCountDto: GetQuestionCountDto) {
    return this.QuestionService.getCount(getQuestionCountDto);
  }

  /* 
    批量查询试题信息
  */
  @Post('items')
  @NoAuthToken()
  @ApiOperation({ summary: '传入[试题ID,试题ID...]批量查询试题信息' })
  async getQuestions(@Body() ids: number[]) {
    return this.QuestionService.getQuestions(ids);
  }

  /* 
  分页获取试题
  */
  @Get('paging')
  @NoAuthToken()
  async paging(@Query() pagingInfo: PagingQuestionDto) {
    console.log(pagingInfo);
    return this.QuestionService.paging(pagingInfo);
  }

  /* 
    获取试题难度和试题类型
  */
  @Get('queryParams')
  async getQueryParams() {
    const difficultyLevel = await this.QuestionDifficultyLevelService.findAll();
    const questionType = await this.QuestionTypeService.findAll();
    return { difficultyLevel, questionType };
  }

  /* 
    更新试题数据
  */
  @Patch('item/studentCanUse/:id')
  async studentCanUse(
    @Param('id') id: string,
    @Body() body: { student: number },
  ) {
    return this.QuestionService.updateStudentCanUse(+id, body);
  }
  /* 
    更新试题数据
  */
  @Patch('item/:id')
  async update(
    @Param('id') id: string,
    @Body() updateQuestionDto: UpdateQuestionDto,
  ) {
    return this.QuestionService.update(+id, updateQuestionDto);
  }
  /* 
    根据ID删除试题
  */
  @Delete('item/:id')
  async remove(@Param('id') id: string) {
    return this.QuestionService.remove(+id);
  }
  /* 批量删除试题 */
  @Delete()
  async removeAll(@Body() ids: number[]) {
    try {
      for (const item of ids) {
        await this.QuestionService.remove(+item);
      }
    } catch (error) {
      return false;
    }
    return true;
  }
}
