UserPaperController.java 11.1 KB
package com.skua.modules.edu.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.skua.core.api.vo.Result;
import com.skua.core.aspect.annotation.AutoLog;
import com.skua.core.context.BaseContextHandler;
import com.skua.modules.edu.entity.Paper;
import com.skua.modules.edu.entity.Question;
import com.skua.modules.edu.entity.QuestionOption;
import com.skua.modules.edu.entity.UserPaper;
import com.skua.modules.edu.service.IPaperService;
import com.skua.modules.edu.service.IUserPaperService;
import com.skua.modules.edu.vo.PaperVO;
import com.skua.modules.edu.vo.UserPaperVO;
import com.skua.modules.guest.util.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSpacing;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STLineSpacingRule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.util.Date;

@Slf4j
@Api(tags="在线考试-用户考试")
@RestController("userPaperController")
@RequestMapping("/web/edu/exam")
public class UserPaperController {
    @Autowired
    private IPaperService paperService;

    @Autowired
    private IUserPaperService userPaperService;



    // 我的 考试
    @AutoLog(value = "在线考试--试卷列表")
    @ApiOperation(value="在线考试--试卷列表", notes="在线考试--试卷列表")
    @GetMapping(value = "/paperList")
    public Result<IPage<Paper>> queryPageList(@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                              @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                              HttpServletRequest req) {
        Result<IPage<Paper>> result = new Result<IPage<Paper>>();
        QueryWrapper<Paper> queryWrapper = new QueryWrapper<>() ;// QueryGenerator.initQueryWrapper(paperAnswer, req.getParameterMap());
        Page<Paper> page = new Page<Paper>(pageNo, pageSize);
        queryWrapper.like("exam_user_ids", BaseContextHandler.getUserId());
        queryWrapper.eq("send_status","1");//已发布的状态

        String currentDate = DateUtil.formatDate(new Date(),"yyyy-MM-dd HH:mm:ss");
        queryWrapper.le("start_time",currentDate);//  当前时间  > 开始结束时间
        queryWrapper.ge("end_time",currentDate);
        IPage<Paper> pageList = paperService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    // 根据试卷获取试题
    @AutoLog(value = "在线考试--开始考试")
    @ApiOperation(value="在线考试--开始考试", notes="在线考试--开始考试")
    @GetMapping(value = "/startExam")
    public Result<PaperVO> startExam(@RequestParam(name="id",required=true) String id) {
        Result<PaperVO> result = new Result<PaperVO>();
        Boolean  flag = paperService.checkExamCount(id,BaseContextHandler.getUserId());
        if(flag){
            PaperVO paperVO = paperService.queryById(id);
            if(paperVO == null) {
                result.error500("未找到对应实体");
            }else  if( paperVO!= null && !"1".equals(paperVO.getSendStatus() ) ) {
                result.error500("试卷未发布!");
            }else{
                result.setResult(paperVO);
                result.setSuccess(true);
            }
        }else{
            result.error500("考试次数已用完!不能参加考试");
        }
        return result;
    }
    // 在线答题


    // 保存答题卡,并计算成绩
    @AutoLog(value = "在线考试--提交试卷")
    @ApiOperation(value="在线考试--提交试卷", notes="在线考试--提交试卷")
    @PostMapping(value = "/submitPaper")
    public Result<UserPaperVO> submitPaper(@RequestBody UserPaperVO  userPaperVO) {
        Result<UserPaperVO> result = new Result<UserPaperVO>();
        String paperScore = "0";
        try {
            userPaperVO.setEndTime(DateUtil.getCurrentDate());
            userPaperVO.setUserId(BaseContextHandler.getUserId());//考试人编号
            paperScore =  paperService.submitPaper(userPaperVO);
            userPaperVO.setScore( paperScore );
            result.setResult( userPaperVO );
            result.success("交卷成功!");
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            result.error500("操作失败");
        }
        return result;
    }
    //试卷详情

    //开始


    // 提交试卷submitPaper

    //历史试卷   history
    // 我的 考试
    @AutoLog(value = "在线考试--历史试卷列表")
    @ApiOperation(value="在线考试--历史试卷列表", notes="在线考试--历史试卷列表")
    @GetMapping(value = "/historyList")
    public Result<IPage<UserPaper>> historyList(
            @RequestParam(name="paperId",required=true) String paperId,
            @RequestParam(name="userId") String userId,
            @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                              @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                              HttpServletRequest req) {
        Result<IPage<UserPaper>> result = new Result<IPage<UserPaper>>();
        QueryWrapper<UserPaper> queryWrapper = new QueryWrapper<>() ;// QueryGenerator.initQueryWrapper(paperAnswer, req.getParameterMap());
        Page<UserPaper> page = new Page<UserPaper>(pageNo, pageSize);
        queryWrapper.eq("paper_id",paperId);
        if(userId == null ){
            userId = BaseContextHandler.getUserId();
        }
        queryWrapper.eq("user_id",userId);//已发布的状态

        IPage<UserPaper> pageList =  userPaperService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }
    //历史试卷详情 history_detail
    @AutoLog(value = "在线考试--历史试卷详情(复习)")
    @ApiOperation(value="在线考试--历史试卷详情(复习)", notes="在线考试--历史试卷详情(复习)")
    @GetMapping(value = "/historyDetail")
    public Result<PaperVO> historyDetail(@RequestParam(name="userPaperId",required=true) String userPaperId) {
        Result<PaperVO> result = new Result<PaperVO>();
        PaperVO paperVO = paperService.queryPaperByUserPaperId(userPaperId);
        if(paperVO == null) {
            result.error500("未找到对应实体");
        }else  if( paperVO!= null && !"1".equals(paperVO.getSendStatus() ) ) {
            result.error500("试卷未发布!");
        }else{
            result.setResult(paperVO);
            result.setSuccess(true);
        }
        return result;
    }



    @AutoLog(value = "在线考试-下载试卷")
    @ApiOperation(value="在线考试-下载试卷", notes="在线考试-下载试卷")
    @GetMapping(value = "/exportDoc")
    public void exportDoc(@RequestParam(name="id",required=true) String id, HttpServletResponse response) {
        String exportName  =  "试卷名称";
        PaperVO paperVO = paperService.queryById(id);
        // 创建一个新的Word文档
        XWPFDocument document = new XWPFDocument();
        exportName = paperVO.getPaperTitle();

        // 生成标题段落
        XWPFParagraph paragraphTitle = document.createParagraph();
        paragraphTitle.setAlignment(ParagraphAlignment.CENTER);

        XWPFRun titleRun = paragraphTitle.createRun();
        titleRun.setBold(true);
        titleRun.setFontSize(36);
        titleRun.setText(exportName);

        // 空行段落
        XWPFParagraph paragraphBlank = document.createParagraph();
        XWPFRun blankRun = paragraphBlank.createRun();
        blankRun.setText("");

        if( paperVO.getQuestionList() != null && !paperVO.getQuestionList().isEmpty()){
            XWPFParagraph paragraphContent = null;//// 题干段落
            XWPFRun contentRun = null;
            XWPFParagraph paragraphOption = null;//选项段落
            XWPFRun optionRun = null;//
            int index = 1;
            for(Question question  :  paperVO.getQuestionList()){
                paragraphContent = document.createParagraph();
                //设置行高
                setHight( paragraphContent , "500"  );
                contentRun = paragraphContent.createRun();
                // 拼接题干 题目索引.题目类型 题干内容
                contentRun.setFontSize(16);
                //contentRun.setBold(true);
                contentRun.setText(" 第"+index +"题:"+question.getQuestionTitle());

                // 遍历试题选项集合
                if( question.getOptionList() != null ){
                    for(QuestionOption option : question.getOptionList()){
                        // 选项段落
                        paragraphOption = document.createParagraph();
                        setHight( paragraphOption , "500"  );
                        optionRun = paragraphOption.createRun();
                        optionRun.setText(" "+option.getAlias()+"."+ option.getOptionTitle());
                    }
                }
                index++;
            }
        }

        // 将文档写入到磁盘文件
        //FileOutputStream out = new FileOutputStream("D://test//导出试卷.docx");
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/msword");
            // 设置浏览器以下载的方式处理该文件名
            response.setHeader("Content-Disposition", "attachment;filename=".concat(String.valueOf(URLEncoder.encode(exportName + ".doc", "UTF-8"))));

            document.write(response.getOutputStream());
            response.getOutputStream().flush();
            response.getOutputStream().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /***
     * 设置行高
     * @param paragraphContent
     * @param rowHight
     */
    public static  void setHight(XWPFParagraph paragraphContent,String rowHight){
        // 获取段落的CTPPr对象
        CTPPr pPr = paragraphContent.getCTP().getPPr();

        // 如果pPr为null,则新建一个
        if (pPr == null) {
            pPr = paragraphContent.getCTP().addNewPPr();
        }
        // 获取或创建行间距(Spacing)属性
        CTSpacing spacing = pPr.isSetSpacing() ? pPr.getSpacing() : pPr.addNewSpacing();
        // 设置行高的值,这里以200为例(Twips单位,1 Twip = 1/20 点)
        spacing.setLine(new BigInteger(rowHight));
        spacing.setLineRule(STLineSpacingRule.EXACT);
    }

}