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.entity.ExamPapers;
import com.ynfy.buss.exam.exam.service.IExamPapersService;
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 = "考试")
@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;

    @Autowired
    private IExamPapersService iExamPapersService;

    /**
     * 分页列表查询
     *
     * @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);
        if (!CollectionUtils.isEmpty(pageList.getRecords())) {
            pageList.getRecords().forEach(item -> item.setState(examService.getExamState(item)));
            pageList.getRecords().forEach(item -> item.setExamPapers(iExamPapersService.ExamIdExamPapers(item.getId())));
        }
        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:addExamPapers")
    @PostMapping(value = "/addExamPapers")
    public Result<String> addExamPapers(@RequestBody Exam exam) {
        examService.save(exam);
        List<ExamPapers> examPapers=exam.getExamPapers();
        for (ExamPapers examPaper : examPapers) {
            //添加试卷时为试卷赋值考试id
            examPaper.setExamId(exam.getId());
            //添加
            iExamPapersService.save(examPaper);
        }
        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);
        //先删除
        List<ExamPapers> examPapersList=iExamPapersService.ExamIdAllExamPapers(exam.getId());
        for (ExamPapers examPaper:examPapersList) {
            iExamPapersService.removeById(examPaper);
        }
        //添加考试绑定的试卷信息
        List<ExamPapers> examPapers=exam.getExamPapers();
        for (ExamPapers examPaper : examPapers) {
            examPaper.setExamId(exam.getId());
            //添加
            iExamPapersService.save(examPaper);
        }
        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);
        //删除考试绑定的试卷信息
        List<ExamPapers> examPapers=iExamPapersService.ExamIdAllExamPapers(id);
        for (ExamPapers examPaper : examPapers) {
            //删除
            iExamPapersService.removeById(examPaper);
        }
        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(",")));
        List<String> examIds=Arrays.asList(ids.split(","));
        //循环删除考试绑定的试卷信息
        for (String examId : examIds) {
            List<ExamPapers> examPapers=iExamPapersService.ExamIdAllExamPapers(examId);
            for (ExamPapers examPaper : examPapers) {
                //删除
                iExamPapersService.removeById(examPaper);
            }
        }
        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());
        }
        //获取考试绑定的试卷信息
        List<ExamPapers> examPapers=iExamPapersService.ExamIdExamPapers(id);
        for (ExamPapers papers: examPapers) {
            papers.setJoinType_dictText(JoinType.getByCode(papers.getJoinType()).getValue());
        }
        exam.setExamPapers(examPapers);
        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);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        IPage<Exam> pageList = examService.selectExamList(page, exam, user);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }
    /**
     * 在线考试列表全
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @AutoLog(value = "考试-在线考试列表根据考试获取考试和试卷信息")
    @ApiOperation(value = "考试-在线考试列表根据考试获取考试和试卷信息", notes = "考试-在线考试列表根据考试获取考试和试卷信息")
    @RequiresPermissions("exam:onlineExamPapers")
    @RequestMapping(value = "/onlineExamPapers", method = RequestMethod.GET)
    public Result<IPage<Exam>> onlineExamPapers(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);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        IPage<Exam> pageList = examService.selectExamList(page, exam, user);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }
//    yyz
    @ApiOperation(value = "考试-获取正在进行中的考试及试卷")
    @GetMapping(value = "/listExamPapers")
    public Result<?> listExamPapers() {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 校验是否有正在考试的试卷
        UserExam userExam = userExamService.listExamPapers(user.getId());
        if (!Objects.isNull(userExam)) {
            return Result.OK("您有正在进行中的考试",userExam);
        }
        return Result.OK();
    }
    @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();
    }
    /**
     * yyz创建考试并添加试卷
     *
     * @return
     */
    @ApiOperation(value = "考试-创建考试并添加试卷")
    @RequiresPermissions("exam:createExamPapers")
    @GetMapping(value = "/createExamPapers")
    public Result<?> createExamPapers(@RequestParam(name = "examId") String examId) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        return Result.ok(examService.createExamPapers(user.getId(), examId));
    }
    /**
     * 创建考试
     *
     * @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 = "考试-考试及试卷详情")
    @GetMapping(value = "/examPaperDetail")
    public Result<?> examPaperDetail(@RequestParam(name = "userExamId") String userExamId) {
        return Result.ok(examService.examDetail(userExamId));
    }
    /**
     * 考试提交单个试卷
     *
     * @return
     */
    @ApiOperation(value = "考试-单个试卷交卷")
    @PostMapping(value = "/submitExamPaper")
    public Result<?> submitExamPaper(@RequestBody ExamSubmitDTO dto) {
        String biaozhi=examService.submitExamPaper(dto);
        if (biaozhi.equals("0")) {
            return Result.ok();
        }else if(biaozhi.equals("1")){
            //开启下一套试卷
            LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            UserExam userExam= examService.createExamPapers(user.getId(), userExamService.getById(dto.getUserExamId()).getExamId());
        return Result.ok(examService.examDetail(userExam.getId()));
        }else {
            return Result.ok(examService.examDetail(dto.getUserExamId()));
        }
    }
    /**
     * 交卷
     *
     * @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,@RequestParam(name = "paperId") String paperId) {
        return Result.ok(examService.userExamResultDetail(userExamId,paperId));
    }
    /**
     * 用户考试成绩详情，下一张试卷阅卷
     *
     * @param paperId
     * @return
     */
    @ApiOperation(value = "考试-用户考试成绩详情-阅卷切换下一套")
    @GetMapping(value = "/userExamResultDetails")
    public Result<?> userExamResultDetails(@RequestParam(name = "paperId") String paperId) {
        return Result.ok(examService.userExamResultDetails(paperId));
    }
    /**
     * 缓存考试试卷答案，用于定时任务强制交卷
     *
     * @return
     */
    @ApiOperation(value = "缓存考试试卷答案")
    @PostMapping(value = "/cacheExamPaperAnswer")
    public Result<?> cacheExamPaperAnswer(@RequestBody ExamSubmitDTO dto) {
        examService.cacheExamPaperAnswer(dto);
        return Result.ok();
    }
    /**
     * 缓存考试答案，用于定时任务强制交卷
     *
     * @return
     */
    @ApiOperation(value = "缓存考试答案")
    @PostMapping(value = "/cacheExamAnswer")
    public Result<?> cacheExamAnswer(@RequestBody ExamSubmitDTO dto) {
        examService.cacheExamAnswer(dto);
        return Result.ok();
    }

    /**
     * 获取缓存的考试试卷答案
     *
     * @return
     */
    @ApiOperation(value = "获取缓存的考试试卷答案")
    @GetMapping(value = "/getCacheExamPaperAnswer")
    public Result<?> getCacheExamPaperAnswer(@RequestParam(name = "userExamId") String userExamId) {
    return Result.ok(examService.getCacheExamPaperAnswer(userExamId));
    }
    /**
     * 获取缓存的考试答案
     *
     * @return
     */
    @ApiOperation(value = "获取缓存的考试答案")
    @GetMapping(value = "/getCacheAnswer")
    public Result<?> getCacheAnswer(@RequestParam(name = "userExamId") String userExamId) {
        return Result.ok(examService.getCacheAnswer(userExamId));
    }
    /**
     * 检查是否达到考试限制次数
     *
     * @param examId
     * @return
     */
    @ApiOperation(value = "检查是否达到考试限制次数")
    @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
     */
    @ApiOperation(value = "检查是否有考试记录")
    @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));
    }
}
