package com.ynfy.app.api.v1.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ynfy.app.api.v1.entity.dto.ExamDTO;
import com.ynfy.app.api.v1.util.TokenUtil;
import com.ynfy.buss.exam.exam.dto.ExamSubmitDTO;
import com.ynfy.buss.exam.exam.dto.QuestionTypeCountDTO;
import com.ynfy.buss.exam.exam.entity.Exam;
import com.ynfy.buss.exam.exam.service.IExamService;
import com.ynfy.buss.exam.paper.enmus.JoinType;
import com.ynfy.buss.exam.paper.entity.Paper;
import com.ynfy.buss.exam.paperrulegroup.service.IPaperRuleGroupService;
import com.ynfy.buss.exam.question.enums.QuestionType;
import com.ynfy.buss.exam.userexam.entity.UserExam;
import com.ynfy.buss.exam.userexam.service.IUserExamService;
import com.ynfy.buss.exam.userexamresult.entity.UserExamResult;
import com.ynfy.buss.exam.userexamresult.service.IUserExamResultService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;

@Slf4j
@RestController
@RequestMapping("/api/v1/exam")
public class ApiExamController extends ApiBaseController {

    @Autowired
    public IExamService examService;

    @Autowired
    private IUserExamService userExamService;

    @Autowired
    private IPaperRuleGroupService paperRuleGroupService;

    @Autowired
    private IUserExamResultService userExamResultService;

    /**
     * 获取考试列表
     *
     * @return
     */
    @PostMapping("/list")
    public Result<IPage<Exam>> list(@RequestBody ExamDTO dto) {
        Page<Exam> page = new Page<>(dto.getPageNo(), dto.getPageSize());
        Exam exam = new Exam();
        exam.setTitle(dto.getExamTitle());
        IPage<Exam> pageList = examService.selectExamList(page, exam);
        return Result.OK(pageList);
    }

    @GetMapping(value = "/queryById")
    public Result<Exam> queryById(@RequestParam(name = "id", required = true) String id) {
        Exam exam = examService.detail(id);
        if (Objects.isNull(exam)) {
            return Result.error("考试不存在");
        }
        Paper paper = exam.getPaper();
        if (!Objects.isNull(paper)) {
            paper.setJoinType_dictText(JoinType.getByCode(paper.getJoinType()).getValue());
        }
        List<QuestionTypeCountDTO> dtoList = paperRuleGroupService.sumQuestionCount(exam.getPaperId());
        if (!CollectionUtils.isEmpty(dtoList)) {
            dtoList.stream().forEach(dto -> dto.setQuestionTypeName(QuestionType.getByCode(dto.getQuestionType()).getValue()));
            exam.setQuestionTypeCountList(dtoList);
        }
        return Result.OK(exam);
    }


    @GetMapping(value = "/createExam")
    public Result<?> createExam(@RequestParam(name = "examId") String examId) {
        return Result.ok(examService.createExam(TokenUtil.getUserId(TokenUtil.getToken(request)), examId));
    }

    @GetMapping(value = "/listExamIn")
    public Result<?> listExamIn() {
        // 校验是否有正在考试的试卷
        UserExam userExam = userExamService.listExamIn(TokenUtil.getUserId(TokenUtil.getToken(request)));
        if (!Objects.isNull(userExam)) {
            return Result.ok(userExam);
        }
        return Result.OK();
    }

    /**
     * 考试详情，包括答题卡，试题（不包含正确答案）
     *
     * @return
     */
    @ApiOperation(value = "考试-考试详情")
    @GetMapping(value = "/examDetail")
    public Result<?> examDetail(@RequestParam(name = "userExamId") String userExamId) {
        return Result.ok(examService.examDetail(userExamId));
    }

    /**
     * 交卷
     *
     * @return
     */
    @ApiOperation(value = "考试-交卷")
    @PostMapping(value = "/submitExam")
    public Result<?> submitExam(@RequestBody ExamSubmitDTO dto) {
        examService.submitExam(dto);
        return Result.ok("提交试卷成功！");
    }


    /**
     * 缓存考试答案，用于定时任务强制交卷
     *
     * @return
     */
    @PostMapping(value = "/cacheExamAnswer")
    public Result<?> cacheExamAnswer(@RequestBody ExamSubmitDTO dto) {
        examService.cacheExamAnswer(dto);
        return Result.ok();
    }


    /**
     * 获取缓存的考试答案
     *
     * @return
     */
    @GetMapping(value = "/getCacheAnswer")
    public Result<?> getCacheAnswer(@RequestParam(name = "userExamId") String userExamId) {
        return Result.ok(examService.getCacheAnswer(userExamId));
    }

    /**
     * 用户考试成绩详情，包括答题卡，试题（包含正确答案）
     *
     * @param userExamId
     * @return
     */
    @ApiOperation(value = "考试-用户考试成绩详情")
    @GetMapping(value = "/userExamResultDetail")
    public Result<?> userExamResultDetail(@RequestParam(name = "userExamId") String userExamId) {
        return Result.ok(examService.userExamResultDetail(userExamId));
    }

    @GetMapping(value = "/userExamResult/list")
    public Result<IPage<UserExamResult>> queryPageList(UserExamResult userExamResult,
                                                       @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<UserExamResult> page = new Page<UserExamResult>(pageNo, pageSize);
        IPage<UserExamResult> pageList = userExamResultService.selectPageList(page, userExamResult);
        return Result.OK(pageList);
    }

    @GetMapping(value = "/userExamDetail/list")
    public Result<IPage<UserExam>> queryPageList(UserExam userExam,
                                                 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                 HttpServletRequest req) {
        Page<UserExam> page = new Page<UserExam>(pageNo, pageSize);
        IPage<UserExam> pageList = userExamService.selectPageList(page, userExam);
        return Result.OK(pageList);
    }

    /**
     * 检查是否达到考试限制次数
     *
     * @param examId
     * @return
     */
    @GetMapping(value = "/checkToLimit")
    public Result<?> checkToLimit(@RequestParam(name = "examId") String examId) {
        return Result.ok(examService.checkToLimit(TokenUtil.getUserId(TokenUtil.getToken(request)), examId));
    }

    /**
     * 检查是否有考试记录
     *
     * @param examId
     * @return
     */
    @GetMapping(value = "/examRecordExist")
    public Result<?> examRecordExist(@RequestParam(name = "examId") String examId) {
        return Result.ok(examService.examRecordExist(TokenUtil.getUserId(TokenUtil.getToken(request)), examId));
    }

    /**
     * 获取用户考试成绩
     *
     * @param examId
     * @return
     */
    @GetMapping(value = "/examScore")
    public Result<?> examScore(@RequestParam(name = "examId") String examId) {
        return Result.ok(userExamResultService.examScore(TokenUtil.getUserId(TokenUtil.getToken(request)), examId));
    }

}
