UserPaperController.java 13.2 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.core.util.DateUtils;
import com.skua.modules.common.service.ICommonSqlService;
import com.skua.modules.edu.entity.*;
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.equipment.pojo.Equipment;
import com.skua.modules.equipment.util.EquipmentUtils;
import com.skua.modules.equipment.vo.EquipmentVO;
import com.skua.modules.guest.util.DateUtil;
import com.skua.tool.util.JoinSqlUtils;
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;
import java.util.List;
import java.util.Map;

@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(Paper paper,
                                              @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                              @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                              HttpServletRequest req) throws Exception{
        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");//已发布的状态
        queryWrapper.le("start_time",currentDate);//  当前时间  > 开始结束时间
        queryWrapper.ge("end_time",currentDate);
        IPage<Paper> pageList = paperService.page(page, queryWrapper);*/
        paper.setUserId(BaseContextHandler.getUserId());
        paper.setStartTime(DateUtils.now());
        paper.setEndTime( DateUtils.now() );
        IPage<Paper> pageList = paperService.queryMyPaperByList(page ,paper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
       /* String currentDate = DateUtil.formatDate(new Date(),"yyyy-MM-dd HH:mm:ss");
        StringBuffer sql = new StringBuffer();
        sql.append("select aaa.* from ( ");
        sql.append("   select ifnull(up.user_id ,0) 'user_id', ifnull(count(up.id) ,0) as user_count, d.depart_name ,   p.*  from edu_paper p ");
        sql.append("   left join edu_user_paper  up on p.id = up.paper_id ");
        sql.append("    left join sys_depart d on p.depart_id  = d.id");
        sql.append("     where  p.send_status =1   and p.exam_user_ids like '%"+BaseContextHandler.getUserId()+"%'");
        if(  paper.getDepartId() != null &&  paper.getDepartId().length() > 0){
            sql.append("         and p.depart_id= '"+paper.getDepartId()+"' ");
        }
        if(  paper.getPaperTitle() != null &&  paper.getPaperTitle().length() > 0){
            sql.append("         and p.paper_title like  '%"+paper.getPaperTitle()+"%' ");
        }
        if(  paper.getDepartId() != null &&  paper.getDepartId().length() > 0){
            sql.append("         and p.depart_id= '"+paper.getDepartId()+"' ");
        }
        sql.append("        and p.send_time >= '"+currentDate+"' and and p.send_time <= '"+currentDate+"'");
        sql.append(" )aaa where aaa.user_id = 0        ");
        // 分页查询
        Page<Map<String, Object>> pageList = iCommonSqlService.queryForPage(page, sql.toString());
        List<Paper> paperList = JoinSqlUtils.multiMaps2Beans(pageList.getRecords(), Paper.class);
        //List<Paper> paperList = EquipmentUtils.equipEntities2VOs(dataList);
      */

    }

    // 根据试卷获取试题
    @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>();
        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);
        }
       /* Boolean  flag = paperService.checkExamCount(id,BaseContextHandler.getUserId());
        if(flag){

        }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(DateUtils.now());
            userPaperVO.setUserId(BaseContextHandler.getUserId());//考试人编号
            paperScore =  paperService.submitPaper(userPaperVO);
            userPaperVO.setScore( paperScore );

            //计算排名
            userPaperService.changeRankByPaperId(userPaperVO.getPaperId() ) ;
            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<Paper>> historyList(
            Paper paper,
            @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
            @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
            HttpServletRequest req) throws Exception {
        Result<IPage<Paper>> result = new Result<IPage<Paper>>();
       /* StringBuffer sql = new StringBuffer();
        sql.append("select  up.score, p.* from edu_user_paper up ");
        sql.append("  left join edu_paper p on   p.id = up.paper_id        ");
        sql.append("   where up.user_id = '"+BaseContextHandler.getUserId()+"'     ");

        // 分页查询
        Page page = new Page(pageNo, pageSize);
        Page<Map<String, Object>> pageList = iCommonSqlService.queryForPage(page, sql.toString());
        List<Paper> paperList = JoinSqlUtils.multiMaps2Beans(pageList.getRecords(), Paper.class);
        */

        Page<Paper> page = new Page<Paper>(pageNo, pageSize);
        paper.setUserId(BaseContextHandler.getUserId());//获取当前用户编号
        IPage<Paper> paperList = paperService.queryMyPaperRecoredByList(page,paper);

        result.setResult(paperList);
        result.setSuccess(true);
        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);
    }

}