package com.qmth.qrzk.web.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.qmth.qrzk.repository.common.base.BaseDao;
import com.qmth.qrzk.repository.exception.BizException;
import com.qmth.qrzk.repository.pager.model.PagerConstruct;
import com.qmth.qrzk.repository.pager.model.PagerConstructDetail;
import com.qmth.qrzk.repository.pager.model.PagerConstructQtype;
import com.qmth.qrzk.repository.pager.model.PaperDifficultyEstimateDetail;
import com.qmth.qrzk.repository.pager.model.PaperSkeleton;
import com.qmth.qrzk.repository.pager.service.PagerConstructService;
import com.qmth.qrzk.repository.pager.service.PaperDifficultyEstimateService;
import com.qmth.qrzk.repository.pager.service.ZujuanService;
import com.qmth.qrzk.repository.service.query.AvailableQuesQueryParams;
import com.qmth.qrzk.repository.service.query.PagerQueryParams;
import com.qmth.qrzk.repository.service.query.PaperSimilarityQueryParams;
import com.qmth.qrzk.repository.task.PaperTask;
import com.qmth.qrzk.repository.user.model.Attachment;
import com.qmth.qrzk.repository.user.model.Code;
import com.qmth.qrzk.repository.user.model.Course;
import com.qmth.qrzk.repository.user.model.Question;
import com.qmth.qrzk.repository.user.model.SimilarPaper;
import com.qmth.qrzk.repository.user.model.SimilarPaperQuestion;
import com.qmth.qrzk.repository.user.model.User;
import com.qmth.qrzk.repository.user.service.ICodeSerivce;
import com.qmth.qrzk.repository.user.service.IQuestionTypeService;
import com.qmth.qrzk.repository.user.service.impl.CourseServiceImpl;
import com.qmth.qrzk.repository.user.service.impl.PaperSkeletonService;
import com.qmth.qrzk.repository.user.service.impl.PaperTaskServiceImpl;
import com.qmth.qrzk.repository.user.service.impl.QuestionServiceImpl;
import com.qmth.qrzk.repository.utils.Consts;

@Controller
@RequestMapping("/zujuan")
public class ZujuanController extends BaseAjaxController {

    private static final String BASE_JSP_PATH = "zujuan/";

    private static final Logger log = Logger.getLogger(ZujuanController.class);
    
	@Autowired private BaseDao dao;
    
    @Autowired
    private PagerConstructService pagerConstructSerivce;

    @Autowired
    private PaperTaskServiceImpl paperTaskService;

    @Autowired
    private ZujuanService zujuanService;

    @Autowired
    private PaperSkeletonService pagerSkeltionSerice;

    @Autowired
    private CourseServiceImpl courseService;

    @Autowired
    @Qualifier("questionTypeServiceImpl")
    private IQuestionTypeService questionTypeService;

    @Autowired
    @Qualifier("codeServiceImpl")
    private ICodeSerivce codeSerivce;

    @Autowired
    private PaperDifficultyEstimateService paperDifficultyEstimateService;

    @Autowired
    private QuestionServiceImpl questionService;

    // 自动组卷入口方法，菜单
    @RequestMapping(value = "/auto")
    public ModelAndView autoGenerate(HttpServletRequest request, HttpSession session) {
        User user = this.getCurUser(session);
        List<Course> courses = courseService.findCoursesByUserId(user.getId());
        return new ModelAndView(BASE_JSP_PATH + "auto", "courses", courses);
    }

    /**
     * 组卷公用方法
     * <p>
     * </p>
     * 
     * @param request
     * @param session
     * @return
     */
    @RequestMapping(value = "/autoGeneratedPapers")
    @ResponseBody
    public Map<String, Object> autoGeneratedPapers(int skeletion, String head, int zjsl, int sameCount, int oldCount,
            HttpSession session) {
        try {
            User user = getCurUser(session);

            List<PagerConstruct> listSJ = pagerConstructSerivce.dealZujuan(skeletion, head, zjsl, user, sameCount,
                    oldCount);
            String pcIdArrStr = "";
            for (int i = 0; i < listSJ.size(); i++) {
                pcIdArrStr = pcIdArrStr + listSJ.get(i).getId();
                if (i < listSJ.size() - 1) {
                    pcIdArrStr = pcIdArrStr + ";";
                }
            }
            Map<String, Object> resultMap = this.successResult("组卷成功");
            resultMap.put("pcIdArrStr", pcIdArrStr);
            return resultMap;
        } catch (BizException e) {
            log.error("根据细目表[id=" + skeletion + "]组卷失败，原因:" + e.getMessage(), e);
            return this.failedResult("组卷失败，原因：" + e.getMessage());
        } catch (Exception e) {
            log.error("根据细目表[id=" + skeletion + "]组卷失败，原因:" + e.getMessage(), e);
            return this.failedResult("组卷失败，请与管理员联系!");
        }
    }

    @RequestMapping(value = "/savePaper")
    @ResponseBody
    public Map<String, Object> savePaper(int pcId, String pcName, String pcHead, String qtArrStr, HttpSession session) {
        try {
            User user = getCurUser(session);
            PagerConstruct pc = new PagerConstruct();
            pc.setId(pcId);
            pc.setName(pcName);
            pc.setHead(pcHead);
            pc.setUpdatedBy(user.getId());
            List<PagerConstructQtype> qtList = new ArrayList<PagerConstructQtype>();
            pc.setQtypeList(qtList);
            int qtOrder = 1;
            for (String qtObjStr : qtArrStr.split(";")) {
                PagerConstructQtype qtype = new PagerConstructQtype();
                qtype.setSortNo(qtOrder++);
                qtype.setUpdatedBy(user.getId());
                qtList.add(qtype);
                String[] arrTmp = qtObjStr.split("@");
                qtype.setId(Integer.parseInt(arrTmp[0]));
                List<PagerConstructDetail> detailList = new ArrayList<PagerConstructDetail>();
                qtype.setConstructDetails(detailList);
                int quesOrder = 1;
                if (arrTmp.length == 2) {
                    for (String detailObjStr : arrTmp[1].split("\\|")) {
                        PagerConstructDetail detail = new PagerConstructDetail();
                        detail.setSortNo(quesOrder++);
                        detail.setUpdatedBy(user.getId());
                        detailList.add(detail);
                        String[] arrTmp2 = detailObjStr.split(":");
                        detail.setId(Integer.parseInt(arrTmp2[0]));
                        detail.setQuestionId(Integer.parseInt(arrTmp2[1]));
                    }
                }
            }
            pagerConstructSerivce.savePaper(pc);
            return this.successResult("保存成功");
        } catch (Exception e) {
            log.error("保存试卷[id=" + pcId + "]失败，原因:" + e.getMessage(), e);
            return this.failedResult("保存失败，请与管理员联系!");
        }
    }
    
//	@RequestMapping(value = "/getQtypeMap")
//	@ResponseBody
//	public List<Map<Integer, String>> getQtypeMap(String paperNo, HttpSession session) throws BizException {
//		List<Map<Integer, String>> result = dao.getList("getQtypeMapByPaperNo", paperNo);
//        return result;
//    }

	@RequestMapping(value = "/manualAdd")
	public ModelAndView manualAdd(Integer taskId, String paperNo, HttpSession session) throws BizException {
        return this.zujuanLogic(taskId, paperNo, session);
    }

	/**
	 * 重新组卷
	 * @param paperId
	 * @param taskId
	 * @param paperNo
	 * @param session
	 * @return
	 * @throws BizException
	 */
	@RequestMapping(value = "/reManualAdd")
	public ModelAndView reManualAdd(Integer paperId, Integer taskId, HttpSession session) throws BizException {
		//删除
        try {
            zujuanService.deletePaper(paperId);
        } catch (Exception e) {
            log.error("删除试卷[id=" + paperId + "]失败，原因：" + e.getMessage(), e);
        }
		return this.zujuanLogic(taskId, null, session);
    }
	
	private ModelAndView zujuanLogic(Integer taskId, String paperNo, HttpSession session) throws BizException {
        User curUser = this.getCurUser(session);
		if (taskId == null) {
			PaperTask task = dao.get("getPaperTaskByPaperNo", paperNo);
			taskId = task.getId();
		}
        ModelAndView result = new ModelAndView(BASE_JSP_PATH + "viewPaperNew");
        PaperTask task = paperTaskService.getPaperTaskById(taskId);
        boolean canPaperEdit = curUser.getId().equals(task.getCurDealer())
                && (task.getStatus().equals(Consts.PaperTaskStatus.GENERATE_PAPER)
                        || task.getStatus().equals(Consts.PaperTaskStatus.TO_AUDIT_PAPER) || task.getStatus().equals(
                        Consts.PaperTaskStatus.TO_CHECK_PAPER));
		canPaperEdit = canPaperEdit || paperTaskService.isCanBeEditedInFushen(taskId, curUser);
        task.getCourse().setQuesTypeList(questionTypeService.queryByCourseId(task.getCourse().getId()));
        // PagerConstruct sj = pagerConstructSerivce.generateBlankPaper(task,
        // getCurUser(session));//声明一个空试卷，手工组卷页面用得着
        PagerConstruct sj = pagerConstructSerivce.autoAdd(task, getCurUser(session), true);// 先抓取可用的题，其他的空题由命题教师自己处理
        result.addObject("task", task);
        result.addObject("sj", sj);
        result.addObject("canPaperEdit", canPaperEdit);
        return result;
    }
	
    /**
     * 浏览组好的试卷
     * <p>
     * </p>
     * 
     * @param request
     * @param session
     * @return
     */
    @RequestMapping(value = "/viewPapers")
    public ModelAndView viewPapers(int skeletion, String pcIdArrStr, HttpSession session) {
        String[] pcIdArr = pcIdArrStr.split(";");
        int[] pcIntIdArr = new int[pcIdArr.length];
        for (int i = 0; i < pcIdArr.length; i++) {
            pcIntIdArr[i] = Integer.parseInt(pcIdArr[i]);
        }
        PaperSkeleton pagerSkeleton = pagerSkeltionSerice.queryById(skeletion);

        ModelAndView result = new ModelAndView(BASE_JSP_PATH + "viewPapers");
        List<PagerConstruct> listSJ = zujuanService.getPaperListByIdArr(pcIntIdArr);

        result.addObject("pagerSkeleton", pagerSkeleton);
        result.addObject("listSJ", listSJ);
        return result;
    }

    @RequestMapping(value = "/queryAvailableQues")
    @ResponseBody
    public Map<String, Object> queryAvailableQues(AvailableQuesQueryParams queryParams) {
        Map<String, Object> result = new HashMap<String, Object>();
        List<Question> quesList = null;
        if (queryParams.getPcqtId() != null) {
            quesList = pagerConstructSerivce.queryAvailableQues(queryParams);
        } else {
            quesList = new ArrayList<Question>();
        }
        result.put("rows", quesList);
        result.put("total", queryParams.getTotalNum());
        return result;
    }

    @RequestMapping(value = "/randomQues")
    @ResponseBody
    public Map<String, Object> randomQues(int pcqtId, int detailId, String curQuesIdListStr, String rndListStr) {
        Map<String, Object> result = null;
        try {
            Question ques = pagerConstructSerivce.randomQues(pcqtId, detailId, curQuesIdListStr, rndListStr);
            result = successResult(null);
            result.put("ques", ques);
        } catch (Exception e) {
            log.error("随机换题失败[pcqtId=" + pcqtId + ",detailId=" + detailId + ",curQuesIdListStr=" + curQuesIdListStr
                    + ",rndListStr=" + rndListStr + "]，原因:" + e.getMessage(), e);
            result = failedResult("随机换题失败，请与管理员联系!");
        }
        return result;
    }

    // /**智能组卷校验公用方法
    // * @param ids
    // * @param session
    // * @return
    // */
    // @RequestMapping(value="/checkZJ")
    // @ResponseBody
    // public BaseExcetion checkZJ(@RequestParam String
    // skeletionId,@RequestParam String zjsl,@RequestParam String
    // sameCount,@RequestParam String oldCount,HttpSession session){
    // BaseExcetion
    // be=pagerConstructSerivce.checkZj(Integer.parseInt(skeletionId),
    // Integer.parseInt(zjsl),Integer.parseInt(sameCount),Integer.parseInt(oldCount));
    // return be;
    // }

    @RequestMapping(value = "/submitAudit")
    @ResponseBody
    public Map<String, Object> submitAudit(int paperId, HttpSession session) {
        try {
            User user = getCurUser(session);
            zujuanService.submitAudit(paperId, user.getId());
            Map<String, Object> resultMap = successResult("试卷提交审核成功");
            return resultMap;
        } catch (Exception e) {
            log.error("提交审核试卷[id=" + paperId + "]失败，原因：" + e.getMessage(), e);
            return failedResult("提交审核试卷失败");
        }
    }

    @RequestMapping(value = "/saveAudit")
    @ResponseBody
    public Map<String, Object> saveAudit(int paperId, int auditResult, String remark, HttpSession session) {
        try {
            User user = getCurUser(session);
            zujuanService.saveAudit(paperId, user.getId(), auditResult, remark);
            Map<String, Object> resultMap = successResult("保存试卷的审核结果成功");
            return resultMap;
        } catch (Exception e) {
            log.error("保存试卷[id=" + paperId + "]的审核结果失败，原因：" + e.getMessage(), e);
            return failedResult("提交试卷审核结果失败");
        }
    }

    @RequestMapping(value = "/getAuditLogs")
    @ResponseBody
    public Map<String, Object> getAuditLogs(int paperId) {
        try {
            Map<String, Object> resultMap = successResult("查询审核日志成功");
            resultMap.put("auditLogs", zujuanService.getAuditLogs(paperId));
            return resultMap;
        } catch (Exception e) {
            log.error("查询试卷[id=" + paperId + "]的审核日志失败，原因：" + e.getMessage(), e);
            return failedResult("查询审核日志失败");
        }
    }

    @RequestMapping(value = "/delete/{paperId}")
    @ResponseBody
    public Map<String, Object> delete(@PathVariable int paperId) {
        try {
            zujuanService.deletePaper(paperId);
            return successResult("删除试卷成功");
        } catch (Exception e) {
            log.error("删除试卷[id=" + paperId + "]失败，原因：" + e.getMessage(), e);
            return failedResult("删除试卷失败");
        }
    }

    @RequestMapping(value = "/list")
    public ModelAndView list(HttpServletRequest request) {
        return new ModelAndView(BASE_JSP_PATH + "list");
    }

    @RequestMapping(value = "/audit")
    public ModelAndView auditList(HttpServletRequest request) {
        return new ModelAndView(BASE_JSP_PATH + "list");
    }

    @RequestMapping(value = "/queryPagers")
    @ResponseBody
    public Map<String, Object> queryPagers(PagerQueryParams params) {
        Map<String, Object> result = new HashMap<String, Object>();
        List<PagerConstruct> rows = zujuanService.queryPagers(params);
        result.put("rows", rows);
        result.put("total", params.getTotalNum());
        return result;
    }

    @RequestMapping(value = "/previewPaper/{paperId}")
    @ResponseBody
    public Map<String, Object> previewPaper(@PathVariable int paperId, HttpSession session) {
        try {
            Attachment att = zujuanService.generalPaperFileIntoAtt(paperId, this.getCurUser(session));
            Map<String, Object> resultMap = successResult("生成试卷文件成功");
            resultMap.put("att", att);
            return resultMap;
        } catch (Exception e) {
            log.error("生成试卷[id=" + paperId + "]文件失败，原因：" + e.getMessage(), e);
            return failedResult("生成试卷文件失败");
        }
    }

    @RequestMapping(value = "/previewWangpingPaper/{paperId}")
    @ResponseBody
    public Map<String, Object> previewWangpingPaper(@PathVariable int paperId, HttpSession session) {
        try {
            Attachment att = zujuanService.generalWangpingPaperFileIntoAtt(paperId, this.getCurUser(session));
            Map<String, Object> resultMap = successResult("生成网评卷文件成功");
            resultMap.put("att", att);
            return resultMap;
        } catch (Exception e) {
            log.error("生成网评卷[id=" + paperId + "]文件失败，原因：" + e.getMessage(), e);
            return failedResult("生成网评卷文件失败");
        }
    }

    @RequestMapping(value = "/previewTika/{paperId}")
    @ResponseBody
    public Map<String, Object> previewTika(@PathVariable int paperId, HttpSession session) {
        try {
            Attachment att = zujuanService.generalTikaFileIntoAtt(paperId, this.getCurUser(session));
            Map<String, Object> resultMap = successResult("生成题卡文件成功");
            resultMap.put("att", att);
            return resultMap;
        } catch (Exception e) {
            log.error("生成题卡[id=" + paperId + "]文件失败，原因：" + e.getMessage(), e);
            return failedResult("生成题卡文件失败");
        }
    }

    @RequestMapping(value = "/previewAnswer/{paperId}")
    @ResponseBody
    public Map<String, Object> previewAnswer(@PathVariable int paperId, HttpSession session) {
        try {
            Attachment att = zujuanService.generalAnswerFileIntoAtt(paperId, this.getCurUser(session));
            Map<String, Object> resultMap = successResult("生成试卷答案文件成功");
            resultMap.put("att", att);
            return resultMap;
        } catch (Exception e) {
            log.error("生成试卷答案[id=" + paperId + "]文件失败，原因：" + e.getMessage(), e);
            return failedResult("生成试卷答案文件失败");
        }
    }

    @RequestMapping(value = "/questionStat")
    @ResponseBody
    public Map<String, Object> questionStat(int paperId, int questionId) {
        try {
            Map<String, Object> statResult = pagerConstructSerivce.questionStat(paperId, questionId);
            Map<String, Object> resultMap = successResult("获取试题统计数据成功");
            resultMap.put("statResult", statResult);
            return resultMap;
        } catch (Exception e) {
            log.error("获取试题[paperId=" + paperId + ",questionId=" + questionId + "]统计数据失败，原因：" + e.getMessage(), e);
            return failedResult("获取试题统计数据失败");
        }
    }

    @RequestMapping(value = "/questionListForZj")
    public ModelAndView questionListForZj() {
        List<Code> codes = codeSerivce.getAllCode();
        return new ModelAndView(BASE_JSP_PATH + "questionList", "codes", codes);
    }

    @RequestMapping(value = "/questionForZj")
    public ModelAndView questionAddForZj() {
        List<Code> codes = codeSerivce.getAllCode();
        return new ModelAndView(BASE_JSP_PATH + "question", "codes", codes);
    }

    /**
     * 查询试卷的预估难度表
     * @param paperId 试卷记录ID
     **/
    @RequestMapping(value = "/getDifficultyEstimate/{paperId}")
    @ResponseBody
    public List<PaperDifficultyEstimateDetail> getDifficultyEstimate(HttpSession session, @PathVariable int paperId) {
        return paperDifficultyEstimateService.getByPaperId(paperId);
    }

    /**
     * 查询试卷的预估难度表，用于对外访问：自考成绩分析，接口人：舒东辉。
     * @version 2017-8-7。
     * @author 马涛
     * @param paperNo 试卷代码
     **/
    @RequestMapping(value = "/paperDifficultyEstimateDetails/{paperCode}")
    @ResponseBody
    public List<Map<String,Object>> paperDifficultyEstimateDetails(@PathVariable String paperCode) {
        return paperDifficultyEstimateService.getByPaperNo(paperCode);
    }

    @RequestMapping(value = "/createDifficultyEstimate/{paperId}")
    @ResponseBody
    public Map<String, Object> createDifficultyEstimate(HttpSession session, @PathVariable int paperId) {
        int curUserId = this.getCurUser(session).getId();
        paperDifficultyEstimateService.createDifficultyEstimate(curUserId, paperId);
        Map<String, Object> resultMap = successResult("操作成功");
        return resultMap;
    }

    @RequestMapping(value = "/deleteDifficultyEstimate/{paperId}")
    @ResponseBody
    public Map<String, Object> deleteDifficultyEstimate(HttpSession session, @PathVariable int paperId) {
        try {
            paperDifficultyEstimateService.deleteEstimateDifficultyByPaperId(paperId);
            return successResult("操作成功");
        } catch (Exception e) {
            return failedResult("操作失败！");
        }
    }

    @RequestMapping(value = "/sortSj/{paperId}")
    @ResponseBody
    public Map<String, Object> sortSj(@PathVariable int paperId, HttpSession session) {
        try {
            zujuanService.sortSj(paperId, this.getCurUser(session));
            Map<String, Object> resultMap = successResult("试卷排序成功");
            return resultMap;
        } catch (Exception e) {
            log.error("对试卷[id=" + paperId + "]进行排序失败，原因：" + e.getMessage(), e);
            return failedResult("试卷排序失败");
        }
    }

    @RequestMapping(value = "/setEstimateDifficulty")
    @ResponseBody
    public Map<String, Object> setEstimateDifficulty(@RequestBody List<PaperDifficultyEstimateDetail> list) {
        try {
            paperDifficultyEstimateService.updateEstimateDifficultyValue(list);
            return successResult("保存难度预估表成功");
        } catch (Exception e) {
            log.error("保存难度预估表失败!");
            return failedResult("保存难度预估表失败!");
        }
    }

    @RequestMapping(value = "/countBlankQuesNum/{paperId}")
    @ResponseBody
    public Map<String, Object> countBlankQuesNum(@PathVariable int paperId) {
        try {
            Map<String, Object> resultMap = successResult("查询试卷里面的空题成功");
            resultMap.put("blankQuesNum", pagerConstructSerivce.countBlankQuesNum(paperId));
            return resultMap;
        } catch (Exception e) {
            log.error("查询试卷里面的空题失败，原因：" + e.getMessage(), e);
            return failedResult("查询试卷里面的空题失败");
        }
    }

    @RequestMapping(value = "/isUsedByOtherPaper")
    @ResponseBody
    public Map<String, Object> isUsedByOtherPaper(int quesId, int paperId) {
        try {
            Map<String, Object> resultMap = successResult("查询试题是否已被其他试卷引用成功");
            resultMap.put("used", questionService.isUsedByOtherPaper(quesId, paperId));
            return resultMap;
        } catch (Exception e) {
            log.error("查询试题[quesId=" + quesId + "，paperId=" + paperId + "]是否已被其他试卷引用失败，原因：" + e.getMessage(), e);
            return failedResult("查询试题是否已被其他试卷引用失败");
        }
    }
    
    /**
     * 试卷启用入口方法
     * @param paperId
     * @param date  时间格式：yyyy－mm
     * @return
     */
    @RequestMapping(value = "/enablePaper")
    @ResponseBody
    public Map<String, Object> enablePaper(String paperCode,String date) {
        try {
        	if(date==null||"".equals(date)){
        		return failedResult("启用试卷失败,启用时间不能为空！格式：yyyy-mm");
        	}
            Map<String, Object> resultMap = successResult("启用试卷成功");
            pagerConstructSerivce.saveOpenPaper(paperCode, date);
            return resultMap;
        } catch (Exception e) {
            log.error("启用试卷失败，原因：" + e.getMessage(), e);
            return failedResult("启用试卷失败");
        }
    }
    
    /**
     * 检查题目相似度
     * @param paperId
     * @return
     */
    @RequestMapping(value = "/checkSimilarity")
    @ResponseBody
    public Map<String, Object> checkSimilarity(int paperId) {
        try {
            Map<String, Object> resultMap = successResult("检查题目相似度");
            resultMap.put("allSimilarQuestion", pagerConstructSerivce.checkSimilarity(paperId));
            return resultMap;
        } catch (Exception e) {
            log.error("检查题目相似度失败，原因：" + e.getMessage(), e);
            return failedResult("检查题目相似度失败");
        }
    }
    
    /**
     * 检查选项相似度
     * @param paperId
     * @return
     */
    @RequestMapping(value = "/checkSimilarityOption")
    @ResponseBody
    public Map<String, Object> checkSimilarityOption(int quesId) {
        try {
            Map<String, Object> resultMap = successResult("检查选项相似度");
            resultMap.put("allSimilarOption", pagerConstructSerivce.checkSimilarityOption(quesId));
            return resultMap;
        } catch (Exception e) {
            log.error("检查选项相似度失败，原因：" + e.getMessage(), e);
            return failedResult("检查选项相似度失败");
        }
    }
    
    /**
	 * 检查所有试卷相似度
	 * 
	 */
	@RequestMapping("/checkPaperSimilarity")
	@ResponseBody
	public Map<String, Object> checkSimilarity() {
		List<SimilarPaper> resultList = pagerConstructSerivce.checkSimilarity();
		List<SimilarPaperQuestion> resultQuestionList = new ArrayList<SimilarPaperQuestion>();
		for(SimilarPaper similarPaper: resultList){
			if(similarPaper.getSimilarPaperQuesList1()!=null && similarPaper.getSimilarPaperQuesList1().size() > 0){
				resultQuestionList.addAll(similarPaper.getSimilarPaperQuesList1());
			}
			if(similarPaper.getSimilarPaperQuesList2()!=null && similarPaper.getSimilarPaperQuesList2().size() > 0){
				resultQuestionList.addAll(similarPaper.getSimilarPaperQuesList2());
			}
		}
		Map<String, Object> result = new HashMap<String, Object>();
		pagerConstructSerivce.delAllPaperSimilarity();
		pagerConstructSerivce.delAllPaperQuestionSimilarity();
		if(resultList!=null && resultList.size() > 0){
			pagerConstructSerivce.addPaperSimilarity(resultList);
			pagerConstructSerivce.addPaperQuestionSimilarity(resultQuestionList);
		}
		result.put("flag", "success");
		return result;
	}
	
	@RequestMapping(value="/queryPaperSimilarity")
	@ResponseBody
	public Map<String, Object> queryPaperSimilarity(@RequestBody PaperSimilarityQueryParams params,HttpSession session){
		Map<String,Object> result = new HashMap<String, Object>();
		User user = getCurUser(session);
	    if(user.getUserTypeText().equals("命题教师")){
	    	params.setCreatedBy(user.getId());
	    }
		List<SimilarPaper> similarPaper = pagerConstructSerivce.queryPaperSimilarity(params);
		int total = pagerConstructSerivce.queryPaperSimilarityCount(params);
		result.put("rows", similarPaper);
		result.put("total", total);
		return result;
	}
	
	@RequestMapping(value="/queryPaperQuestionSimilarity/{similarPaperNo}/{whichQuestion}")
	@ResponseBody
	public Map<String, Object> queryPaperQuestionSimilarity(@PathVariable String similarPaperNo,@PathVariable String whichQuestion){
		Map<String,Object> result = new HashMap<String, Object>();
		List<Question> similarPaperQuestion = pagerConstructSerivce.queryPaperQuestionSimilarity(similarPaperNo, whichQuestion);
		result.put("paperquestion", similarPaperQuestion);
		return result;
	}
}
