package cn.com.qmth.examcloud.core.questions.api;

import cn.com.qmth.examcloud.api.commons.security.bean.User;
import cn.com.qmth.examcloud.commons.exception.StatusException;
import cn.com.qmth.examcloud.core.questions.base.BeanCopierUtil;
import cn.com.qmth.examcloud.core.questions.base.SpringContextUtils;
import cn.com.qmth.examcloud.core.questions.base.StringSimilarityUtils;
import cn.com.qmth.examcloud.core.questions.base.enums.PaperType;
import cn.com.qmth.examcloud.core.questions.base.question.enums.QuesStructType;
import cn.com.qmth.examcloud.core.questions.dao.ExportServiceManageRepo;
import cn.com.qmth.examcloud.core.questions.dao.PaperRepo;
import cn.com.qmth.examcloud.core.questions.dao.entity.ExportServiceManage;
import cn.com.qmth.examcloud.core.questions.dao.entity.Paper;
import cn.com.qmth.examcloud.core.questions.dao.entity.PaperSearchInfo;
import cn.com.qmth.examcloud.core.questions.dao.entity.Question;
import cn.com.qmth.examcloud.core.questions.service.PaperService;
import cn.com.qmth.examcloud.core.questions.service.QuesService;
import cn.com.qmth.examcloud.core.questions.service.bean.dto.PaperDetailExp;
import cn.com.qmth.examcloud.core.questions.service.bean.dto.PaperDetailUnitExp;
import cn.com.qmth.examcloud.core.questions.service.bean.dto.PaperExp;
import cn.com.qmth.examcloud.core.questions.service.bean.paper.PreviewPaperHandler;
import cn.com.qmth.examcloud.core.questions.service.export.ExportPaperAbstractService;
import cn.com.qmth.examcloud.web.support.ControllerSupport;
import cn.com.qmth.examcloud.web.support.Naked;
import com.google.gson.Gson;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Created by songyue on 16/12/28.
 * updated by weiwenhai on 2018.9.28
 *
 * @code 160
 */
@Controller
@RequestMapping("${api_cqb}/")
public class PaperController extends ControllerSupport {

    @Autowired
    PaperService paperService;

    @Autowired
    PaperRepo paperRepo;

    @Autowired
    Gson gson;

    @Value("${question.reduplicate.similarity}")
    private double reduplicateSimilarity;

    @Autowired
    QuesService quesService;

    @Autowired
    ExportServiceManageRepo exportServiceManageRepo;

    /**
     * 根据Id获取试卷
     *
     * @param paperId
     * @return
     */
    @Naked
    @ResponseBody
    @ApiOperation(value = "根据Id获取试卷", notes = "根据Id获取试卷")
    @GetMapping(value = "/paper/{paperId}")
    public ResponseEntity<Object> getPaperById(@PathVariable String paperId) {
        return new ResponseEntity<Object>(paperService.getPaperDto(paperId), HttpStatus.OK);
    }

    /**
     * 保存试卷
     *
     * @param paper
     * @return
     */
    @ResponseBody
    @ApiOperation(value = "保存试卷", notes = "保存试卷")
    @PutMapping(value = "/paper")
    public ResponseEntity<Object> savePaperById(@RequestBody PaperExp paper) {
        User user = getAccessUser();
        Map<String, Object> msgMap = paperService.savePaper(paper, user);
        if ("success".equals(msgMap.get("msg"))) {
            return new ResponseEntity<Object>(msgMap, HttpStatus.OK);
        } else {
            return new ResponseEntity<Object>(msgMap, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 查询所有导入试卷
     *
     * @param paperSearchInfo
     * @param curPage
     * @param pageSize
     * @return
     */
    @ResponseBody
    @ApiOperation(value = "查询所有导入试卷", notes = "查询所有导入试卷")
    @GetMapping(value = "/importPaper/{curPage}/{pageSize}")
    public ResponseEntity<Object> getImportPapers(@ModelAttribute PaperSearchInfo paperSearchInfo,
                                                  @PathVariable int curPage,
                                                  @PathVariable int pageSize) {
        User user = getAccessUser();
        paperSearchInfo.setOrgId(user.getRootOrgId().toString());
        return new ResponseEntity<Object>(paperService.getImportPapers(paperSearchInfo, curPage, pageSize), HttpStatus.OK);
    }

    @ResponseBody
    @ApiOperation(value = "查询所有待审核和审核不通过的导入试卷", notes = "查询所有待审核和审核不通过的导入试卷")
    @GetMapping(value = "/importPaperNotSuccess/{curPage}/{pageSize}")
    public ResponseEntity<Object> getImportPapersNotSuccess(@ModelAttribute PaperSearchInfo paperSearchInfo, @PathVariable int curPage, @PathVariable int pageSize) {
        User user = getAccessUser();
        paperSearchInfo.setOrgId(user.getRootOrgId().toString());
        return new ResponseEntity<Object>(paperService.getImportPapersNotSuccess(paperSearchInfo, curPage, pageSize),
                HttpStatus.OK);
    }

    @ResponseBody
    @ApiOperation(value = "根据条件查询导入试卷", notes = "根据条件查询导入试卷")
    @GetMapping(value = "/getImportPaper")
    public ResponseEntity<List<Paper>> getImportPapersBySearch(@ModelAttribute PaperSearchInfo paperSearchInfo) {
        User user = getAccessUser();
        paperSearchInfo.setOrgId(user.getRootOrgId().toString());
        return new ResponseEntity<List<Paper>>(paperService.getImportPapersBySearch(paperSearchInfo), HttpStatus.OK);
    }

    @ResponseBody
    @ApiOperation(value = "根据条件查询已组试卷", notes = "根据条件查询已组试卷")
    @GetMapping(value = "/getGenPaper")
    public ResponseEntity<List<Paper>> getGenPapersBySearch(@ModelAttribute PaperSearchInfo paperSearchInfo) {
        User user = getAccessUser();
        paperSearchInfo.setOrgId(user.getRootOrgId().toString());
        return new ResponseEntity<List<Paper>>(paperService.getGenPapersBySearch(paperSearchInfo), HttpStatus.OK);
    }

    /**
     * 查询所有已组试卷
     *
     * @param paperSearchInfo
     * @param curPage
     * @param pageSize
     * @return
     */
    @ResponseBody
    @ApiOperation(value = "查询所有已组试卷", notes = "查询所有已组试卷")
    @GetMapping(value = "/genPaper/{curPage}/{pageSize}")
    public ResponseEntity<Object> getGenPapers(@ModelAttribute PaperSearchInfo paperSearchInfo,
                                               @PathVariable int curPage, @PathVariable int pageSize) {
        User user = getAccessUser();
        paperSearchInfo.setOrgId(user.getRootOrgId().toString());
        return new ResponseEntity<Object>(paperService.getGenPapers(paperSearchInfo, curPage, pageSize), HttpStatus.OK);
    }

    /**
     * @param paperSearchInfo
     * @param ids
     * @param curPage
     * @param pageSize
     * @return
     */
    @ResponseBody
    @ApiOperation(value = "查询所有导入试卷(not in paperIds)", notes = "查询所有导入试卷(not in paperIds)")
    @GetMapping(value = "/genPaper/{ids}/{curPage}/{pageSize}")
    public ResponseEntity<Object> getGenPapersNotInIds(@ModelAttribute PaperSearchInfo paperSearchInfo,
                                                       @PathVariable String[] ids, @PathVariable int curPage, @PathVariable int pageSize) {
        User user = getAccessUser();
        paperSearchInfo.setOrgId(user.getRootOrgId().toString());
        if (ids != null && ids.length > 0) {
            return new ResponseEntity<Object>(paperService.getPapersNotInIds(paperSearchInfo, ids, curPage, pageSize, PaperType.GENERATE),
                    HttpStatus.OK);
        } else {
            return new ResponseEntity<Object>(paperService.getGenPapers(paperSearchInfo, curPage, pageSize), HttpStatus.OK);
        }
    }

    /**
     * 删除试卷
     *
     * @param paperIds
     * @return
     */
    @ResponseBody
    @ApiOperation(value = "删除试卷", notes = "删除试卷")
    @DeleteMapping(value = "/paper/{paperIds}")
    public ResponseEntity<Object> delPaper(@PathVariable String paperIds) {
        List<String> paperList = Stream.of(paperIds.split(",")).collect(Collectors.toList());
        Map<String, Object> msgMap = paperService.deletePapers(paperList);
        if (msgMap.get("msg").equals("success")) {
            return new ResponseEntity<Object>(msgMap, HttpStatus.OK);
        } else {
            return new ResponseEntity<Object>(msgMap, HttpStatus.INTERNAL_SERVER_ERROR);
        }

    }

    /**
     * 批量通过试卷
     *
     * @param paperSearchInfo
     * @return
     */
    @ResponseBody
    @ApiOperation(value = "批量通过试卷", notes = "批量通过试卷")
    @PutMapping(value = "/paper/pass")
    public ResponseEntity<Object> passPapers(@RequestBody PaperSearchInfo paperSearchInfo) {
        paperService.passPapers(Arrays.asList(paperSearchInfo.getPaperIds()));
        return new ResponseEntity<Object>(HttpStatus.OK);
    }

    /**
     * 批量不通过试卷
     *
     * @param paperSearchInfo
     * @return
     */
    @ResponseBody
    @ApiOperation(value = "批量不通过试卷", notes = "批量不通过试卷")
    @PutMapping(value = "/paper/noPass")
    public ResponseEntity<Object> noPassPapers(@RequestBody PaperSearchInfo paperSearchInfo) {
        paperService.noPassPapers(Arrays.asList(paperSearchInfo.getPaperIds()));
        return new ResponseEntity<Object>(HttpStatus.OK);
    }

    /**
     * 批量待审核试卷
     *
     * @param paperSearchInfo
     * @return
     */
    @ResponseBody
    @ApiOperation(value = "批量待审核试卷", notes = "批量待审核试卷")
    @PutMapping(value = "/paper/draft")
    public ResponseEntity<Object> initPapers(@RequestBody PaperSearchInfo paperSearchInfo) {
        paperService.backPapers(Arrays.asList(paperSearchInfo.getPaperIds()));
        return new ResponseEntity<Object>(HttpStatus.OK);
    }

    /**
     * 获取卷库考试试卷
     *
     * @param examId
     * @param courseCode
     * @param groupCode
     * @return
     */
    @ResponseBody
    @ApiOperation(value = "获取卷库考试试卷", notes = "获取卷库考试试卷")
    @GetMapping(value = "/paper/list/{examId}/{courseCode}/{groupCode}")
    public List<Paper> listPaperById(@PathVariable String examId, @PathVariable String courseCode,
                                     @PathVariable String groupCode) {
        return paperService.listExamPapers(Long.parseLong(examId), courseCode, groupCode);
    }

    /**
     * 新增考试试卷
     *
     * @param examId
     * @param courseCode
     * @param groupCode
     * @param paperId
     * @return
     */
    @ResponseBody
    @ApiOperation(value = "新增考试试卷", notes = "新增考试试卷")
    @PostMapping(value = "/paper/join/{examId}/{courseCode}/{groupCode}/{paperId}")
    public ResponseEntity<Object> joinExamPaper(@PathVariable String examId, @PathVariable String courseCode,
                                                @PathVariable String groupCode, @PathVariable String paperId) {
        paperService.joinToExamPaper(Long.parseLong(examId), courseCode, groupCode, paperId);
        return new ResponseEntity<Object>(HttpStatus.OK);
    }

    /**
     * 删除考试试卷
     *
     * @param examId
     * @param courseCode
     * @param groupCode
     * @param paperId
     * @return
     */
    @ResponseBody
    @ApiOperation(value = "删除考试试卷", notes = "删除考试试卷")
    @DeleteMapping(value = "/paper/release/{examId}/{courseCode}/{groupCode}/{paperId}")
    public ResponseEntity<Object> releaseExamPaper(@PathVariable String examId, @PathVariable String courseCode,
                                                   @PathVariable String groupCode, @PathVariable String paperId) {

        paperService.releaseExamPaper(Long.parseLong(examId), courseCode, groupCode, paperId);
        return new ResponseEntity<Object>(HttpStatus.OK);
    }

    /**
     * 获取卷库考试试卷类型集合
     *
     * @param examId
     * @param courseCode
     * @return
     */
    @ResponseBody
    @ApiOperation(value = "获取考试试卷类型集合", notes = "获取考试试卷类型集合")
    @GetMapping(value = "/paper/groupCode/{examId}/{courseCode}")
    public Set<String> listGroup(@PathVariable String examId, @PathVariable String courseCode) {
        return paperService.listGroupCodes(Long.parseLong(examId), courseCode);
    }

    /**
     * 删除考试试卷类型
     *
     * @param examId
     * @param courseCode
     * @param groupCode
     * @return
     */
    @ResponseBody
    @ApiOperation(value = "删除考试试卷类型", notes = "删除考试试卷类型")
    @DeleteMapping(value = "/paper/groupCode/{examId}/{courseCode}/{groupCode}")
    public ResponseEntity<Object> deleteGroup(@PathVariable String examId, @PathVariable String courseCode,
                                              @PathVariable String groupCode) {
        paperService.deletGroupCode(Long.parseLong(examId), courseCode, groupCode);
        return new ResponseEntity<Object>(HttpStatus.OK);
    }

    /**
     * 删除导入试卷中的试题
     *
     * @param questionId
     * @return
     */
    @ResponseBody
    @ApiOperation(value = "删除导入试卷中的试题", notes = "删除导入试卷中的试题")
    @DeleteMapping(value = "/paper/deleteQuestion/{questionId}")
    public ResponseEntity<Object> deleteImportPaperQuestion(@PathVariable String questionId) {
        User user = getAccessUser();
        List<String> paperNames = paperService.deleteImportQuestionById(questionId, user);
        return new ResponseEntity<Object>(paperNames, HttpStatus.OK);
    }

    /**
     * 向导入试卷中的新增试题
     *
     * @param paperId
     * @param paperDetailId
     * @param question
     * @return
     */
    @ResponseBody
    @ApiOperation(value = "向导入试卷中的新增试题", notes = "向导入试卷中的新增试题")
    @PostMapping(value = "/paper/addQuestion/{paperId}/{paperDetailId}")
    public ResponseEntity<Object> insertQuestionToPaper(@PathVariable String paperId,
                                                        @PathVariable String paperDetailId, @RequestBody Question question) {
        User user = getAccessUser();
        return new ResponseEntity<Object>(paperService.insertQuestionToPaper(paperId, paperDetailId, question, user),
                HttpStatus.OK);

    }

    @ResponseBody
    @ApiOperation(value = "获取试卷的重复试题", notes = "获取试卷的重复试题")
    @GetMapping(value = "/paper/{paperId}/reduplicate-questions")
    public ResponseEntity<Object> reduplicateQuestions(@PathVariable String paperId) {
        List<PaperDetailUnitExp> allPaperDetailUnitList = new ArrayList<>();
        List<Set<String>> reduplicateId = new ArrayList<>();
        PaperExp paperExp = paperService.getPaperDto(paperId);
        List<PaperDetailExp> paperDetailExpList = paperExp.getPaperDetails();
        if (paperDetailExpList != null && paperDetailExpList.size() > 0) {
            for (PaperDetailExp paperDetailExp : paperDetailExpList) {
                if (paperDetailExp.getPaperDetailUnits() != null) {
                    allPaperDetailUnitList.addAll(paperDetailExp.getPaperDetailUnits());
                }
            }
        }
        int length = allPaperDetailUnitList.size();
        for (int i = 0; i < length - 1; i++) {
            PaperDetailUnitExp paperDetailUnitExp1 = allPaperDetailUnitList.get(i);
            String quesText1 = quesService.getExtractText(paperDetailUnitExp1.getQuestion());
            if (StringUtils.isEmpty(quesText1)) {
                continue;
            }
            for (int j = i + 1; j < length; j++) {
                PaperDetailUnitExp paperDetailUnitExp2 = allPaperDetailUnitList.get(j);
                String quesText2 = quesService.getExtractText(paperDetailUnitExp2.getQuestion());
                if (StringUtils.isEmpty(quesText2)) {
                    continue;
                }
                double similarity = StringSimilarityUtils.getSimilarityWithCosinesBySeg(quesText1, quesText2);
                if (similarity > reduplicateSimilarity) {
                    boolean found = false;
                    for (int k = 0; k < reduplicateId.size(); k++) {
                        if (reduplicateId.get(k).contains(paperDetailUnitExp1.getId())
                                && !reduplicateId.get(k).contains(paperDetailUnitExp2.getId())) {
                            found = true;
                            reduplicateId.get(k).add(paperDetailUnitExp2.getId());
                            break;
                        } else if (!reduplicateId.get(k).contains(paperDetailUnitExp1.getId())
                                && reduplicateId.get(k).contains(paperDetailUnitExp2.getId())) {
                            found = true;
                            reduplicateId.get(k).add(paperDetailUnitExp1.getId());
                            break;
                        } else if (reduplicateId.get(k).contains(paperDetailUnitExp1.getId())
                                && reduplicateId.get(k).contains(paperDetailUnitExp2.getId())) {
                            found = true;
                            // 两个题都在分组里，就不加了
                            break;
                        }
                    }
                    if (!found) {
                        Set<String> redupSet = new HashSet<>();

                        redupSet.add(paperDetailUnitExp1.getId());
                        redupSet.add(paperDetailUnitExp2.getId());
                        reduplicateId.add(redupSet);
                    }
                    // reduplicateId.add(paperDetailUnitExp1.getId());
                    // reduplicateId.add(paperDetailUnitExp2.getId());
                }
            }
        }
        return new ResponseEntity<Object>(reduplicateId, HttpStatus.OK);
    }

    /**
     * 根据试题获取试卷名称
     *
     * @param
     * @return
     */
    @ResponseBody
    @ApiOperation(value = "获取试题所在的试卷名称", notes = "获取试题所在的试卷名称")
    @GetMapping(value = "/paper/listNames/{questionId}")
    public ResponseEntity<Object> getPaperNamesByQuesId(@PathVariable String questionId) {
        return new ResponseEntity<Object>(paperService.getPaperNamesByQuestionId(questionId), HttpStatus.OK);
    }

    /**
     * 根据试题获取试卷名称
     *
     * @param
     * @return
     */
    @ResponseBody
    @ApiOperation(value = "查询用于选题的试题列表", notes = "查询用于选题的试题列表")
    @GetMapping(value = "/paper/listQuestion/{paperId}/{curPage}/{pageSize}")
    public ResponseEntity<Object> listQuestionforSelect(@PathVariable String paperId,
                                                        @PathVariable int curPage,
                                                        @PathVariable int pageSize,
                                                        @RequestParam(name = "quesType") String quesType,
                                                        @RequestParam(name = "quesBody") String quesBody) {
        User user = getAccessUser();
        if (user == null) {
            return new ResponseEntity<Object>(new PageImpl<Question>(new ArrayList<Question>()), HttpStatus.OK);
        }
        QuesStructType quesStructType = null;
        if (StringUtils.isNotEmpty(quesType)) {
            quesStructType = QuesStructType.valueOf(quesType);
        }
        Page<Question> questionPageList = paperService.listQuestionforSelect(paperId, curPage, pageSize, quesStructType, user, quesBody);
        return new ResponseEntity<Object>(questionPageList, HttpStatus.OK);
    }

    /**
     * 向试卷中某道大题插入多道试题（已存在的试题）
     *
     * @param paperId
     * @param paperDetailId
     * @param questions
     * @return
     */
    @ResponseBody
    @ApiOperation(value = "向导入试卷中的新增试题", notes = "向导入试卷中的新增试题")
    @PostMapping(value = "/paper/selectQuestions/{paperId}/{paperDetailId}")
    public ResponseEntity<Object> selectQuestionsToPaper(@PathVariable String paperId,
                                                         @PathVariable String paperDetailId, @RequestBody List<Question> questions) {
        User user = getAccessUser();
        return new ResponseEntity<Object>(paperService.selectQuestionsToPaper(paperId, paperDetailId, questions, user),
                HttpStatus.OK);

    }

    /**
     * @param paperSearchInfo
     * @param ids
     * @param curPage
     * @param pageSize
     * @return
     */
    @ResponseBody
    @ApiOperation(value = "查询所有导入试卷(not in paperIds)", notes = "查询所有导入试卷(not in paperIds)")
    @GetMapping(value = "/importPaper/{ids}/{curPage}/{pageSize}")
    public ResponseEntity<Object> getImportPapersNotInIds(@ModelAttribute PaperSearchInfo paperSearchInfo, @PathVariable String[] ids, @PathVariable int curPage,
                                                          @PathVariable int pageSize) {
        User user = getAccessUser();
        paperSearchInfo.setOrgId(user.getRootOrgId().toString());
        if (ids != null && ids.length > 0) {
            return new ResponseEntity<Object>(paperService.getPapersNotInIds(paperSearchInfo, ids, curPage, pageSize, PaperType.IMPORT),
                    HttpStatus.OK);
        } else {
            return new ResponseEntity<Object>(paperService.getImportPapers(paperSearchInfo, curPage, pageSize), HttpStatus.OK);
        }
    }

    /**
     * @param paperSearchInfo
     * @return
     */
    @ResponseBody
    @ApiOperation(value = "查询该课程的所有导入试卷", notes = "查询该课程的所有导入试卷")
    @GetMapping(value = "/importPaper/course")
    public ResponseEntity<Object> getImportPapersByCourseNo(@ModelAttribute PaperSearchInfo paperSearchInfo) {
        User user = getAccessUser();
        paperSearchInfo.setOrgId(user.getRootOrgId().toString());
        paperService.formatPaperSearchInfo(paperSearchInfo);
        Paper importPaper = BeanCopierUtil.copyProperties(paperSearchInfo, Paper.class);
        importPaper.setPaperType(PaperType.IMPORT);
        return new ResponseEntity<Object>(paperRepo.findAll(Example.of(importPaper)), HttpStatus.OK);

    }

    /**
     * 使用原卷
     *
     * @param paperIds
     * @return
     */
    @ResponseBody
    @ApiOperation(value = "复制导入试卷为组卷", notes = "复制导入试卷为组卷")
    @PutMapping(value = "/useBasePaper/{paperIds}")
    public ResponseEntity<Object> useBasePaper(@PathVariable String paperIds) {
        User user = getAccessUser();
        try {
            String[] paperIdArray = paperIds.split(",");
            for (int i = 0; i < paperIdArray.length; i++) {
                Paper oldpaper = cn.com.qmth.examcloud.core.questions.base.Model.of(paperRepo.findById(paperIdArray[i]));
                boolean result = paperService.checkPaperName(oldpaper.getName(), PaperType.GENERATE, user.getRootOrgId() + "");
                if (!result) {
                    throw new StatusException("Q-160565", "考试试卷:" + oldpaper.getName() + "已经存在");
                }
            }
            paperService.useBasePaper(paperIds, user.getDisplayName());
            return new ResponseEntity<Object>(HttpStatus.OK);
        } catch (Exception e) {
            throw new StatusException("Q-160537", e.getMessage());
        }
    }

    /**
     * 上传音频文件检查
     *
     * @param paperId
     * @param filesName
     * @return
     */
    @ResponseBody
    @ApiOperation(value = "上传音频文件检查", notes = "上传音频文件检查")
    @PostMapping(value = "/checkRadioFile/{paperId}")
    public ResponseEntity<Object> checkRadioFile(@PathVariable String paperId, @RequestBody List<String> filesName) {
        Map<String, String> errorMessage = paperService.checkRadioFile(paperId, filesName);
        return new ResponseEntity<Object>(errorMessage, HttpStatus.OK);
    }

    @ResponseBody
    @ApiOperation(value = "上传音频文件", notes = "上传音频文件")
    @PostMapping(value = "/uploadRadio/{paperId}")
    public ResponseEntity<Object> uploadRadio(List<MultipartFile> files, @PathVariable String paperId) {
        User user = getAccessUser();
        try {
            paperService.uploadRadio(files, paperId, user);
            return new ResponseEntity<Object>(HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<Object>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @Naked
    @ApiOperation(value = "预览试卷页面")
    @GetMapping(value = "/paper/pdf/{paperId}")
    public String viewPaper(Model model, @PathVariable String paperId, @RequestParam(required = false) String examName) {
        Paper paper = cn.com.qmth.examcloud.core.questions.base.Model.of(paperRepo.findById(paperId));
        if (paper == null) {
            throw new StatusException("500", "试卷信息不存在！");
        }

        ExportServiceManage manager = exportServiceManageRepo.findByOrgId(paper.getOrgId());
        if (manager == null) {
            throw new StatusException("500", "当前学校尚未配置试卷模板！");
        }

        ExportPaperAbstractService exportPaperService = SpringContextUtils.getBean(ExportPaperAbstractService.class, manager.getExportServiceName());
        PaperExp previewPaper = exportPaperService.previewPaperForPDF(paper);

        model.addAttribute("htmlList", PreviewPaperHandler.convertPaperHtml(previewPaper));
        model.addAttribute("orgName", manager.getOrgName());
        model.addAttribute("examName", examName);
        model.addAttribute("courseNo", previewPaper.getCourseNo());
        model.addAttribute("courseName", previewPaper.getCourseName());
        model.addAttribute("courseLevel", previewPaper.getCourseLevel());

        //目前只“山东大学”和“陕师大”配了试卷模板
        if ("sddxExportPaperService".equals(manager.getExportServiceName())
                || "sxsfExportPaperService".equals(manager.getExportServiceName())) {
            return String.format("%s_paper", manager.getExportServiceName());
        } else {
            return "default_paper";
        }
    }

    @Naked
    @ApiOperation(value = "预览试卷答案页面")
    @GetMapping(value = "/paper/answer/pdf/{paperId}")
    public String viewPaperAnswer(Model model, @PathVariable String paperId, @RequestParam(required = false) String examName) {
        Paper paper = cn.com.qmth.examcloud.core.questions.base.Model.of(paperRepo.findById(paperId));
        if (paper == null) {
            throw new StatusException("500", "试卷答案信息不存在！");
        }

        ExportServiceManage manager = exportServiceManageRepo.findByOrgId(paper.getOrgId());
        if (manager == null) {
            throw new StatusException("500", "当前学校尚未配置试卷模板！");
        }

        ExportPaperAbstractService exportPaperService = SpringContextUtils.getBean(ExportPaperAbstractService.class, manager.getExportServiceName());
        PaperExp previewPaper = exportPaperService.previewPaperForPDF(paper);

        model.addAttribute("htmlList", PreviewPaperHandler.convertPaperAnswerHtml(previewPaper));
        model.addAttribute("orgName", manager.getOrgName());
        model.addAttribute("examName", examName);
        model.addAttribute("courseNo", previewPaper.getCourseNo());
        model.addAttribute("courseName", previewPaper.getCourseName());
        model.addAttribute("courseLevel", previewPaper.getCourseLevel());

        //目前只“山东大学”和“陕师大”配了试卷模板
        if ("sddxExportPaperService".equals(manager.getExportServiceName())
                || "sxsfExportPaperService".equals(manager.getExportServiceName())) {
            return String.format("%s_answer", manager.getExportServiceName());
        } else {
            return "default_answer";
        }
    }

    @ApiOperation(value = "传送到印刷平台", notes = "传送到印刷平台")
    @GetMapping(value = "/sendPrint/{paperId}/{examId}/{orgId}")
    public ResponseEntity<Object> sendPrint(@PathVariable String paperId,
                                            @PathVariable String orgId,
                                            @PathVariable String examId) {
        paperService.sendPrint(paperId, orgId, examId);
        return new ResponseEntity<Object>(HttpStatus.OK);
    }

    @ResponseBody
    @ApiOperation(value = "根绝试卷id查询不同类型，题的数量")
    @GetMapping(value = "/paper/questionNumbers/{paperId}/{publicityType}/{difficultyType}")
    public ResponseEntity<Object> questionNumbers(@PathVariable String paperId,
                                                  @PathVariable Integer publicityType,
                                                  @PathVariable Integer difficultyType) {
        int total = paperService.getQuestionTypeNumbers(paperId, publicityType, difficultyType);
        return new ResponseEntity<Object>(total, HttpStatus.OK);
    }

    @ResponseBody
    @ApiOperation(value = "根绝试卷id查询不同类型，题的数量")
    @GetMapping(value = "/paper/questionScores/{paperId}/{publicityType}/{difficultyType}")
    public ResponseEntity<Object> questionScores(@PathVariable String paperId,
                                                 @PathVariable Integer publicityType,
                                                 @PathVariable Integer difficultyType) {
        double total = paperService.getQuestionTypeScore(paperId, publicityType, difficultyType);
        return new ResponseEntity<Object>(total, HttpStatus.OK);
    }
}
