package com.ynfy.buss.exam.exam.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.vo.UserExamScoreVO;
import com.ynfy.buss.exam.userexamresult.service.IUserExamResultService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
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.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @Description: exam
 * @Author: jeecg-boot
 * @Date: 2023-02-23
 * @Version: V1.0
 */
@Api(tags = "exam")
@RestController
@RequestMapping("/exam")
@Slf4j
public class ExamController extends JeecgController<Exam, IExamService> {
    @Autowired
    private IExamService examService;

    @Autowired
    private IUserExamService userExamService;

    @Autowired
    private IPaperRuleGroupService paperRuleGroupService;

    @Autowired
    private IUserExamResultService userExamResultService;

    /**
     * 分页列表查询
     *
     * @param exam
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value = "考试-分页列表查询", notes = "考试-分页列表查询")
    @RequiresPermissions("exam:list")
    @GetMapping(value = "/list")
    public Result<IPage<Exam>> queryPageList(Exam exam,
                                             @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                             @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                             HttpServletRequest req) {
        QueryWrapper<Exam> queryWrapper = QueryGenerator.initQueryWrapper(exam, req.getParameterMap());
        Page<Exam> page = new Page<Exam>(pageNo, pageSize);
        IPage<Exam> pageList = examService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param exam
     * @return
     */
    @AutoLog(value = "考试-添加")
    @ApiOperation(value = "考试-添加", notes = "考试-添加")
    @RequiresPermissions("exam:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody Exam exam) {
        examService.save(exam);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param exam
     * @return
     */
    @AutoLog(value = "考试-编辑")
    @ApiOperation(value = "考试-编辑", notes = "考试-编辑")
    @RequiresPermissions("exam:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody Exam exam) {
        //如果考试的试卷没有主观题，清空阅卷相关信息
        if (!Objects.isNull(exam.getPaper()) && !Objects.isNull(exam.getPaper().getHasSubjective()) && !exam.getPaper().getHasSubjective()) {
            exam.setReviewer(null);
            exam.setReviewerType(null);
        }
        examService.updateById(exam);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "考试-通过id删除")
    @ApiOperation(value = "考试-通过id删除", notes = "考试-通过id删除")
    @RequiresPermissions("exam:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        examService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "考试-批量删除")
    @ApiOperation(value = "考试-批量删除", notes = "考试-批量删除")
    @RequiresPermissions("exam:delete")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.examService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "考试-通过id查询", notes = "考试-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<Exam> queryById(@RequestParam 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);
        }

        //获取考试次数
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        UserExamScoreVO userExamScoreVO = userExamResultService.examScore(user.getId(), id);
        if (!Objects.isNull(userExamScoreVO)) {
            exam.setTryCount(userExamScoreVO.getTryCount());
        }
        return Result.OK(exam);
    }

    /**
     * 在线考试
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @AutoLog(value = "考试-在线考试")
    @ApiOperation(value = "考试-在线考试", notes = "考试-在线考试")
    @RequiresPermissions("exam:onlineExam")
    @RequestMapping(value = "/onlineExam", method = RequestMethod.GET)
    public Result<IPage<Exam>> onlineExam(Exam exam, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Result<IPage<Exam>> result = new Result<>();
        Page<Exam> page = new Page<>(pageNo, pageSize);
        IPage<Exam> pageList = examService.selectExamList(page, exam);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    @ApiOperation(value = "考试-获取正在进行的考试")
    @GetMapping(value = "/listExamIn")
    public Result<?> listExamIn() {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 校验是否有正在考试的试卷
        UserExam userExam = userExamService.listExamIn(user.getId());
        if (!Objects.isNull(userExam)) {
            return Result.ok(userExam);
        }
        return Result.OK();
    }

    /**
     * 创建考试
     *
     * @return
     */
    @ApiOperation(value = "考试-创建考试")
    @RequiresPermissions("exam:createExam")
    @GetMapping(value = "/createExam")
    public Result<?> createExam(@RequestParam(name = "examId") String examId) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        return Result.ok(examService.createExam(user.getId(), examId));
    }

    /**
     * 考试详情，包括答题卡，试题（不包含正确答案）
     *
     * @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("提交试卷成功！");
    }

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

    /**
     * 缓存考试答案，用于定时任务强制交卷
     *
     * @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 examId
     * @return
     */
    @GetMapping(value = "/checkToLimit")
    public Result<?> checkToLimit(@RequestParam(name = "examId") String examId) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        return Result.ok(examService.checkToLimit(user.getId(), examId));
    }

    /**
     * 检查是否有考试记录
     *
     * @param examId
     * @return
     */
    @GetMapping(value = "/examRecordExist")
    public Result<?> examRecordExist(@RequestParam(name = "examId") String examId) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        return Result.ok(examService.examRecordExist(user.getId(), examId));
    }
}
