package com.qmth.qrzk.repository.user.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import net.sf.json.JSONObject;

import org.apache.commons.io.IOUtils;
import org.apache.ibatis.annotations.DeleteProvider;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.RegionUtil;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.qmth.qrzk.repository.common.base.BaseDao;
import com.qmth.qrzk.repository.common.enumeration.QuestionStatusEnum;
import com.qmth.qrzk.repository.exception.BizException;
import com.qmth.qrzk.repository.pager.model.PagerConstruct;
import com.qmth.qrzk.repository.pager.model.PaperSkeleton;
import com.qmth.qrzk.repository.pager.service.PagerConstructService;
import com.qmth.qrzk.repository.pager.service.ZujuanService;
import com.qmth.qrzk.repository.service.query.QueryParams;
import com.qmth.qrzk.repository.service.query.TaskQueryParams;
import com.qmth.qrzk.repository.task.PaperTask;
import com.qmth.qrzk.repository.task.TaskBatch;
import com.qmth.qrzk.repository.task.TaskFlowLog;
import com.qmth.qrzk.repository.task.WordHistory;
import com.qmth.qrzk.repository.user.model.Attachment;
import com.qmth.qrzk.repository.user.model.Book;
import com.qmth.qrzk.repository.user.model.Course;
import com.qmth.qrzk.repository.user.model.ImportBean;
import com.qmth.qrzk.repository.user.model.OperLog;
import com.qmth.qrzk.repository.user.model.Question;
import com.qmth.qrzk.repository.user.model.User;
import com.qmth.qrzk.repository.utils.Consts;
import com.qmth.qrzk.repository.utils.Consts.PaperTaskStatus;
import com.qmth.qrzk.repository.utils.Consts.ReviewTaskStatus;
import com.qmth.qrzk.repository.utils.docx.DocxReader;
import com.qmth.qrzk.repository.utils.docx.ResourceInfo;
import com.qmth.qrzk.repository.utils.DateHelper;
import com.qmth.qrzk.repository.utils.General;
import com.qmth.qrzk.repository.utils.ParamUtils;
import com.qmth.qrzk.repository.utils.StringUtils;
import com.qmth.qrzk.repositry.utils.excel.ExcelOperate;

@Service
public class PaperTaskServiceImpl {
	
	private final static Logger log = Logger.getLogger(PaperTaskServiceImpl.class);
	
	@Autowired private BaseDao dao;
	@Autowired
	private CourseServiceImpl courseService;
	
	@Autowired
	private BookServiceImpl bookService;
	
	@Autowired
	private TaskBatchImpl taskBatchService;
	
	@Autowired
	private UserServiceImpl userService;
	
	@Autowired
	private ZujuanService zujuanService;
	
	@Autowired
	private PagerConstructService paperService;
	
	@Autowired 
	private MessageServiceImpl messageService;
	
	public List<PaperTask> queryPaperTask(QueryParams params){
		return dao.getPagerList("queryPaperTask", params);
	}
	
	public List<PaperTask> queryTodoPaperTasks(TaskQueryParams params){
		return dao.getPagerList("queryTodoPaperTasks", params);
	}
	
	public List<PaperTask> queryPaperTaskByParam(PaperTask params){
		return dao.getPagerList("getPaperTasksByParam", params);
	}
	
	public PagerConstruct queryPagerConstructByTaskId(int id){
		return dao.get("findPagerConstructByTaskId", id);
	}
	
	public List<PaperTask> queryReviewTask(QueryParams params){
		List<PaperTask> paperList = dao.getPagerList("queryPaperTask", params);
		List<PaperTask> resultList = new ArrayList<PaperTask>();
		for(PaperTask task : paperList){
			PagerConstruct pagerConstruct = queryPagerConstructByTaskId(task.getId());
			task.setPagerConstruct(pagerConstruct);
			resultList.add(task);
		}
		return resultList;
	}
	
	public List<WordHistory> getPaperWordHistories(int paperId, String attType){
		WordHistory param = new WordHistory();
		param.setPaperId(paperId);
		param.setAttType(attType);
		List<WordHistory> paperWordHistories = dao.getList("queryPaperWordHistorysByPaperId",param);
		return paperWordHistories;
	}
	
	/**
	 * 某入闱命题的试卷是否能被复审批次的当前处理人编辑
	 * @param taskId
	 * @param curUser
	 * @return
	 */
	public boolean isCanBeEditedInFushen(int taskId,User curUser){
		Map<String,Object> param = new HashMap<String, Object>();
		param.put("taskId", taskId);
		param.put("curUserId", curUser.getId());
		List<Integer> result = dao.getList("isCanBeEditedInFushen",param);
		return result.size() > 0;
	}
	
	public String getTikaType(int paperId){
		PagerConstruct pagerConstruct = dao.get("findPagerConstructById", paperId);
		if(pagerConstruct != null){
			return pagerConstruct.getTikaType();
		}
		return null;
	}
	
	public PaperTask getPaperTaskById(int taskId){
		PaperTask task = dao.get("getPaperTaskById", taskId);
		if(task != null && !task.getBatchType().equals(Consts.TaskBatchType.SHI_JUAN_FU_SHEN)){
			List<TaskFlowLog> flows = dao.getList("queryPaperTaskFlowLogsByTaskId", taskId);
			task.setFlows(flows);
			
			PaperSkeleton paperSkeleton = dao.get("getPaperSkeletonByTaskId", taskId);
			task.setPaperSkeleton(paperSkeleton);
			
			PagerConstruct pagerConstruct = dao.get("findPagerConstructByTaskId", taskId);
			task.setPagerConstruct(pagerConstruct);
			
			if(pagerConstruct != null){
				WordHistory param1 = new WordHistory();
				param1.setPaperId(pagerConstruct.getId());
				param1.setAttType(Consts.WordType.PAPER);
				List<WordHistory> paperWordHistories = dao.getList("queryPaperWordHistorysByPaperId",param1);
				pagerConstruct.setPaperWordHistories(paperWordHistories);
				
				WordHistory param2 = new WordHistory();
				param2.setPaperId(pagerConstruct.getId());
				param2.setAttType(Consts.WordType.WANGPING);
				List<WordHistory> wangpingWordHistories = dao.getList("queryPaperWordHistorysByPaperId",param2);
				pagerConstruct.setWangpingWordHistories(wangpingWordHistories);

				WordHistory param3 = new WordHistory();
				param3.setPaperId(pagerConstruct.getId());
				param3.setAttType(Consts.WordType.TIKA);
				List<WordHistory> tikaWordHistories = dao.getList("queryPaperWordHistorysByPaperId",param3);
				pagerConstruct.setTikaWordHistories(tikaWordHistories);
				
				WordHistory param4 = new WordHistory();
				param4.setPaperId(pagerConstruct.getId());
				param4.setAttType(Consts.WordType.ANSWER);
				List<WordHistory> answerWordHistories = dao.getList("queryPaperWordHistorysByPaperId",param4);
				pagerConstruct.setAnswerWordHistories(answerWordHistories);
				
				WordHistory param5 = new WordHistory();
				param5.setPaperId(pagerConstruct.getId());
				param5.setAttType(Consts.WordType.ZHUANYIN);
				List<WordHistory> zhuanyinHistories = dao.getList("queryPaperWordHistorysByPaperId",param5);
				pagerConstruct.setZhuanyinHistories(zhuanyinHistories);
			}

			String status = task.getStatus();
			if(!status.equals(Consts.PaperTaskStatus.ARCHIVED)){//获取下一个处理者列表
				List<User> nextDealers = new ArrayList<User>();
				User defaultNextDealer = null;
				if(status.equals(Consts.PaperTaskStatus.TO_CREATE_SKEL)){
					defaultNextDealer = task.getAuditTeacherBean();
					nextDealers.add(copyAuditTeacherBean(task));
					nextDealers.add(copyPrimarySecretaryBean(task));
				}else if(status.equals(Consts.PaperTaskStatus.TO_AUDIT_SKEL)){
					if(task.getCurDealer().equals(task.getAuditTeacher())){
						defaultNextDealer = task.getPrimarySecretaryBean();
						nextDealers.add(copyPrimarySecretaryBean(task));
					}else{
						defaultNextDealer = task.getPropositionTeacherBean();
						nextDealers.add(copyPropositionTeacherBean(task));
					}
				}else if(status.equals(Consts.PaperTaskStatus.GENERATE_PAPER)){
					defaultNextDealer = task.getTypesetterBean();
					nextDealers.add(copyAuditTeacherBean(task));
					nextDealers.add(copyPrimarySecretaryBean(task));
					//nextDealers.add(copyAssistantSecretaryBean(task));
					nextDealers.add(copyTypesetterBean(task));
				}else if(status.equals(Consts.PaperTaskStatus.TYPESET)){
					defaultNextDealer = task.getPropositionTeacherBean();
					nextDealers.add(copyPropositionTeacherBean(task));
					nextDealers.add(copyAuditTeacherBean(task));
					nextDealers.add(copyPrimarySecretaryBean(task));
					//nextDealers.add(copyAssistantSecretaryBean(task));
				}else if(status.equals(Consts.PaperTaskStatus.TO_AUDIT_PAPER)){
					if(task.getCurDealer().equals(task.getPropositionTeacher())){
						defaultNextDealer = task.getAuditTeacherBean();
						nextDealers.add(copyAuditTeacherBean(task));
						nextDealers.add(copyPrimarySecretaryBean(task));
						//nextDealers.add(copyAssistantSecretaryBean(task));
					}else if(task.getCurDealer().equals(task.getAuditTeacher())){
						defaultNextDealer = task.getPrimarySecretaryBean();
						nextDealers.add(copyPrimarySecretaryBean(task));
						//nextDealers.add(copyAssistantSecretaryBean(task));
					}else{
						//defaultNextDealer = task.getAssistantSecretaryBean();
						//nextDealers.add(copyAssistantSecretaryBean(task));
						defaultNextDealer = task.getPrimarySecretaryBean();
						nextDealers.add(copyPrimarySecretaryBean(task));
					}
				}else if(status.equals(Consts.PaperTaskStatus.TO_CHECK_PAPER)){
					if(task.getCurDealer().equals(task.getPrimarySecretary())){
						defaultNextDealer = task.getTypesetterBean();
						nextDealers.add(copyTypesetterBean(task));
					}else{
						defaultNextDealer = task.getPrimarySecretaryBean();
						nextDealers.add(copyPrimarySecretaryBean(task));
					}
				}else if(status.equals(Consts.PaperTaskStatus.FINAL_TYPESET)){
					defaultNextDealer = task.getPrimarySecretaryBean();
					nextDealers.add(copyPrimarySecretaryBean(task));
				}else if(status.equals(Consts.PaperTaskStatus.TO_ARCHIVE)){
					defaultNextDealer = task.getPrimarySecretaryBean();
					nextDealers.add(copyPrimarySecretaryBean(task));
				}
				if(defaultNextDealer == null || defaultNextDealer.getId() == null){
					task.setDefaultNextDealer(null);
				}else{
					task.setDefaultNextDealer(defaultNextDealer.getId());
				}
				task.setNextDealers(nextDealers);
			}
			
			{//获取上一个处理者列表，审核细目表或试卷时使用
				List<User> preDealers = new ArrayList<User>();
				if(status.equals(Consts.PaperTaskStatus.TO_AUDIT_SKEL)){
					if(task.getCurDealer().equals(task.getAuditTeacher())){
						preDealers.add(copyPropositionTeacherBean(task));
					}else{
						preDealers.add(copyPropositionTeacherBean(task));
						preDealers.add(copyAuditTeacherBean(task));
					}
				}else if(status.equals(Consts.PaperTaskStatus.TO_AUDIT_PAPER)){
					if(task.getCurDealer().equals(task.getAuditTeacher())){
						preDealers.add(copyPropositionTeacherBean(task));
						preDealers.add(copyTypesetterBean(task));
					}else{
						preDealers.add(copyPropositionTeacherBean(task));
						preDealers.add(copyAuditTeacherBean(task));
						preDealers.add(copyTypesetterBean(task));
					}
				}else if(status.equals(Consts.PaperTaskStatus.TO_CHECK_PAPER)){
					preDealers.add(copyPropositionTeacherBean(task));
					preDealers.add(copyAuditTeacherBean(task));
					preDealers.add(copyPrimarySecretaryBean(task));
					preDealers.add(copyTypesetterBean(task));
				}else if(status.equals(Consts.PaperTaskStatus.FINAL_TYPESET) || status.equals(Consts.PaperTaskStatus.TO_ARCHIVE)){
					preDealers.add(copyPropositionTeacherBean(task));
					preDealers.add(copyAuditTeacherBean(task));
					preDealers.add(copyPrimarySecretaryBean(task));
					preDealers.add(copyTypesetterBean(task));
				}
				for(User tmp:preDealers){
					if(tmp.getId().equals(task.getCurDealer())){
						preDealers.remove(tmp);
						break;
					}
				}
				task.setPreDealers(preDealers);
			}
		}
		return task;
	}
	
	/**
	 * 复审任务详情
	 * @param taskId
	 * @return
	 */
	public PaperTask getReviewTaskById(int taskId){
		PaperTask task = dao.get("getReviewTaskById", taskId);
		if(task != null){
			
			List<TaskFlowLog> flows = dao.getList("queryPaperTaskFlowLogsByTaskId", taskId);
			task.setFlows(flows);
			
			PagerConstruct pagerConstruct = dao.get("findPagerConstructByTaskId", taskId);
			task.setPagerConstruct(pagerConstruct);
			
			if(pagerConstruct != null){
				WordHistory param1 = new WordHistory();
				param1.setPaperId(pagerConstruct.getId());
				param1.setAttType(Consts.WordType.HJ);
				List<WordHistory> paperWordHistories = dao.getList("queryPaperWordHistorysByPaperId",param1);
				pagerConstruct.setPaperWordHistories(paperWordHistories);
				
				WordHistory param2 = new WordHistory();
				param2.setPaperId(pagerConstruct.getId());
				param2.setAttType(Consts.WordType.WPJ);
				List<WordHistory> wangpingWordHistories = dao.getList("queryPaperWordHistorysByPaperId",param2);
				pagerConstruct.setWangpingWordHistories(wangpingWordHistories);

				WordHistory param3 = new WordHistory();
				param3.setPaperId(pagerConstruct.getId());
				param3.setAttType(Consts.WordType.ZK);
				List<WordHistory> tikaWordHistories = dao.getList("queryPaperWordHistorysByPaperId",param3);
				pagerConstruct.setTikaWordHistories(tikaWordHistories);
				
				WordHistory param4 = new WordHistory();
				param4.setPaperId(pagerConstruct.getId());
				param4.setAttType(Consts.WordType.DA);
				List<WordHistory> answerWordHistories = dao.getList("queryPaperWordHistorysByPaperId",param4);
				pagerConstruct.setAnswerWordHistories(answerWordHistories);
			}
			
			String status = task.getStatus();
			if(!status.equals(Consts.ReviewTaskStatus.ARCHIVED)){//获取下一个处理者列表
				List<User> nextDealers = new ArrayList<User>();
				User defaultNextDealer = null;
				if(status.equals(Consts.ReviewTaskStatus.TO_AUDIT_PAPER)){
					if(task.getCurDealer() != task.getPrimarySecretary()){
						User user = task.getPrimarySecretaryBean();
						User primarySecretary = new User();
						primarySecretary.setId(user.getId());
						primarySecretary.setName("学科秘书：" + user.getName());
						
						nextDealers.add(primarySecretary);
						defaultNextDealer = primarySecretary;
					}
					
					if(task.getCurDealer() != task.getTypesetter()){
						User user = task.getTypesetterBean();
						User Typesetter = new User();
						Typesetter.setId(user.getId());
						Typesetter.setName("排版员：" + user.getName());
						
						nextDealers.add(Typesetter);
						defaultNextDealer = Typesetter;
					}
					
					if(task.getCurDealer() != task.getAuditTeacher()){
						User user = task.getAuditTeacherBean();
						User auditTeacher = new User();
						auditTeacher.setId(user.getId());
						auditTeacher.setName("命题教师：" + user.getName());
						
						nextDealers.add(auditTeacher);
						defaultNextDealer = auditTeacher;
					}
					
//					User user2 = task.getTypesetterBean();
//					User Typesetter = new User();
//					Typesetter.setId(user1.getId());
//					Typesetter.setName("排版员：" + user1.getName());
//					nextDealers.add(Typesetter);
//					defaultNextDealer = Typesetter;
				}
//				else if(status.equals(Consts.ReviewTaskStatus.TO_ARCHIVE)){
					
					
//				}
				task.setDefaultNextDealer(defaultNextDealer.getId());
				task.setNextDealers(nextDealers);
			}
			
			{//获取上一个处理者列表
				List<User> preDealers = new ArrayList<User>();
//				if(status.equals(Consts.ReviewTaskStatus.TO_ARCHIVE)){
//					User user = task.getPrimarySecretaryBean();
//					User primarySecretary = new User();
//					primarySecretary.setId(user.getId());
//					primarySecretary.setName("学科秘书：" + user.getName());
//					
//					preDealers.add(primarySecretary);
//				}
				task.setPreDealers(preDealers);
			}
		}
		return task;
	}
	
	private User copyPropositionTeacherBean(PaperTask task){
		User user = task.getPropositionTeacherBean();
		User propositionTeacher = new User();
		propositionTeacher.setId(user.getId());
		propositionTeacher.setName("命题教师1：" + user.getName());
		return propositionTeacher;
	}
	
	private User copyAuditTeacherBean(PaperTask task){
		User user = task.getAuditTeacherBean();
		User auditTeacher = new User();
		auditTeacher.setId(user.getId());
		auditTeacher.setName("命题教师2：" + user.getName());
		return auditTeacher;
	}
	
	private User copyPrimarySecretaryBean(PaperTask task){
		User user = task.getPrimarySecretaryBean();
		User primarySecretary = new User();
		primarySecretary.setId(user.getId());
		primarySecretary.setName("学科秘书1：" + user.getName());
		return primarySecretary;
	}
	
//	private User copyAssistantSecretaryBean(PaperTask task){
//		User user = task.getAssistantSecretaryBean();
//		User assistantSecretary = new User();
//		assistantSecretary.setId(user.getId());
//		assistantSecretary.setName("学科秘书2：" + user.getName());
//		return assistantSecretary;
//	}

	private User copyTypesetterBean(PaperTask task){
		User user = task.getTypesetterBean();
		User typesetter = new User();
		typesetter.setId(user.getId());
		typesetter.setName("排版员：" + user.getName());
		return typesetter;
	}
	
	public int addPaperTask(PaperTask pt){
		return dao.insert("addPaperTask", pt);
	}
	
	public int addReviewTask(PaperTask pt){
		return dao.insert("addReviewTask", pt);
	}
	
	public Map<String, Object> addPaperTask(int batchId, Course course, List<User> users, User curUser){
		Map<String, Object> result = new HashMap<String, Object>();
		
		PaperTask paperTaskA = new PaperTask();
		PaperTask paperTaskB = new PaperTask();
		//设置课程
		paperTaskA.setCourseId(course.getId());
		paperTaskB.setCourseId(course.getId());
		//设置教材
		List<Book> books=bookService.findBooks(course.getCode());
		if(books.size() > 1){
			result.put("flag", "failed");
			result.put("msg", "当前课程有多个启用的教材，保存失败！");
			return result;
		}else if(books.size() < 1){
			result.put("flag", "failed");
			result.put("msg", "当前课程没有教材！");
			return result;
		}else if(books.size() == 1){
			Book book = books.get(0);
			paperTaskA.setBookId(book.getId());
			paperTaskB.setBookId(book.getId());
		}
		
		TaskBatch taskBatch = taskBatchService.findById(batchId);
		//设置批次信息
		paperTaskA.setBatchId(batchId);
		paperTaskA.setPlanStartTime(taskBatch.getPlanStartTime());
		paperTaskA.setPlanEndTime(taskBatch.getPlanEndTime());
		paperTaskB.setBatchId(batchId);
		paperTaskB.setPlanStartTime(taskBatch.getPlanStartTime());
		paperTaskB.setPlanEndTime(taskBatch.getPlanEndTime());
		
				
		//设置任务编号		
		String taskNoA = course.getCode() + taskBatch.getName() + "A";
		String taskNoB = course.getCode() + taskBatch.getName() + "B";
		paperTaskA.setTaskNo(taskNoA);
		paperTaskA.setTitle(taskNoA);
		paperTaskA.setPaperName(taskNoA);
		paperTaskB.setTaskNo(taskNoB);
		paperTaskB.setTitle(taskNoB);
		paperTaskB.setPaperName(taskNoB);
		
		
		//设置A卷相关人员
		paperTaskA.setPropositionTeacher(users.get(0).getId());
		paperTaskA.setPropositionLoginName(users.get(0).getLoginName());
		paperTaskA.setAuditTeacher(users.get(1).getId());
		paperTaskA.setAuditTeacherLoginName(users.get(1).getLoginName());
		paperTaskA.setPrimarySecretary(users.get(2).getId());
		paperTaskA.setPrimarySecretaryLoginName(users.get(2).getLoginName());
		//paperTaskA.setAssistantSecretary(users.get(3).getId());
		//paperTaskA.setAssistantSecretaryLoginName(users.get(3).getLoginName());
		paperTaskA.setTypesetter(users.get(4).getId());
		paperTaskA.setTypesetterLoginName(users.get(4).getLoginName());
		//设置B卷相关人员		
		paperTaskB.setPropositionTeacher(users.get(1).getId());
		paperTaskB.setPropositionLoginName(users.get(1).getLoginName());
		paperTaskB.setAuditTeacher(users.get(0).getId());
		paperTaskB.setAuditTeacherLoginName(users.get(0).getLoginName());
		paperTaskB.setPrimarySecretary(users.get(2).getId());
		paperTaskB.setPrimarySecretaryLoginName(users.get(2).getLoginName());
		//paperTaskB.setAssistantSecretary(users.get(2).getId());
		//paperTaskB.setAssistantSecretaryLoginName(users.get(2).getLoginName());
		paperTaskB.setTypesetter(users.get(4).getId());
		paperTaskB.setTypesetterLoginName(users.get(4).getLoginName());
		
		//设置状态等
		paperTaskA.setStatus(PaperTaskStatus.TO_CREATE_SKEL);
		paperTaskA.setCreatedBy(curUser.getId());
		paperTaskA.setCreatedTime(new Date());
		paperTaskA.setUpdatedBy(curUser.getId());
		paperTaskA.setUpdatedTime(new Date());
		paperTaskA.setCurDealer(paperTaskA.getPropositionTeacher());
		paperTaskB.setStatus(PaperTaskStatus.TO_CREATE_SKEL);
		paperTaskB.setCreatedBy(curUser.getId());
		paperTaskB.setCreatedTime(new Date());
		paperTaskB.setUpdatedBy(curUser.getId());
		paperTaskB.setUpdatedTime(new Date());
		paperTaskB.setCurDealer(paperTaskB.getPropositionTeacher());
		
		dao.insert("addPaperTask", paperTaskA);
		messageService.saveMessage(paperTaskA.getId(), paperTaskA.getPropositionTeacher(), curUser);
		dao.insert("addPaperTask", paperTaskB);
		messageService.saveMessage(paperTaskB.getId(), paperTaskB.getPropositionTeacher(), curUser);
		
		return result;
	}
	
	/**
	 * 新建复审任务
	 * @param batchId
	 * @param taskNo
	 * @param users
	 * @param curUser
	 * @return
	 */
	public Map<String, Object> addReviewTask(int batchId, String taskNo, List<User> users, User curUser){
		Map<String, Object> result = new HashMap<String, Object>();
		
		PaperTask paperTask = new PaperTask();
		
		TaskBatch taskBatch = taskBatchService.findById(batchId);
		//设置批次信息
		paperTask.setBatchId(batchId);
		paperTask.setPlanStartTime(taskBatch.getPlanStartTime());
		paperTask.setPlanEndTime(taskBatch.getPlanEndTime());
		paperTask.setBatchId(batchId);
		paperTask.setPlanStartTime(taskBatch.getPlanStartTime());
		paperTask.setPlanEndTime(taskBatch.getPlanEndTime());
		
				
		//设置任务编号		
		paperTask.setTaskNo(taskNo);
		paperTask.setTitle(taskNo);
		paperTask.setPaperName(taskNo);
		
		//设置相关人员
//		paperTaskA.setPropositionTeacher(users.get(0).getId());
//		paperTaskA.setPropositionLoginName(users.get(0).getLoginName());
		paperTask.setAuditTeacher(users.get(0).getId());
		paperTask.setAuditTeacherLoginName(users.get(0).getLoginName());
		paperTask.setPrimarySecretary(users.get(1).getId());
		paperTask.setPrimarySecretaryLoginName(users.get(1).getLoginName());
//		paperTaskA.setAssistantSecretary(users.get(3).getId());
//		paperTaskA.setAssistantSecretaryLoginName(users.get(3).getLoginName());
		paperTask.setTypesetter(users.get(2).getId());
		paperTask.setTypesetterLoginName(users.get(2).getLoginName());
		
		//设置状态等
		paperTask.setStatus(ReviewTaskStatus.TO_AUDIT_PAPER);
		paperTask.setCreatedBy(curUser.getId());
		paperTask.setCreatedTime(new Date());
		paperTask.setUpdatedBy(curUser.getId());
		paperTask.setUpdatedTime(new Date());
		paperTask.setCurDealer(users.get(0).getId());
		
		dao.insert("addReviewTask", paperTask);
		messageService.saveMessage(paperTask.getId(), users.get(0).getId(), curUser);
		
		PagerConstruct pager = new PagerConstruct();

		//获取入闱命题批次的试卷信息
		PaperTask paperParam = new PaperTask();
		paperParam.setBatchType("RU_WEI_MING_TI");
		paperParam.setTaskNo(paperTask.getTaskNo());
		List<PaperTask> tempTasks = queryPaperTaskByParam(paperParam);
		PagerConstruct tempPaper = queryPagerConstructByTaskId(tempTasks.get(0).getId());

    	pager.setTaskId(paperTask.getId());
    	pager.setName(paperTask.getTaskNo());
    	String head = Consts.DEFAULT_HEAD.replace("XXXX", DateHelper.formatDate(new Date(),"yyyy")).replace("XX", DateHelper.formatDate(new Date(),"M"));
    	pager.setHead(head);
//    	pager.setSkeletonId(skel.getId());
    	pager.setResourse(2);//智能组卷
    	pager.setStatus(Consts.PaperStatus.DRAFT);//草稿
    	pager.setCreatedBy(curUser.getId());
		pager.setLastPaperWord(tempPaper.getLastPaperWord());
		pager.setLastAnswerWord(tempPaper.getLastAnswerWord());
		pager.setLastTikaWord(tempPaper.getLastTikaWord());
		pager.setLastWangpingWord(tempPaper.getLastWangpingWord());
		pager.setTikaType(tempPaper.getTikaType());
		pager.setLastZhuanyinWord(tempPaper.getLastZhuanyinWord());
    	
    	dao.insert("addPagerConstruct", pager);
		
		return result;
	}
	
	public void saveAuditResult(int taskId,int nextDealer,int auditResult,String remark,User curUser) throws BizException{
		PaperTask task = dao.get("getPaperTaskById", taskId);
		if(!task.getCurDealer().equals(curUser.getId())){
			throw new BizException("当前用户没有权限执行此操作");
		}
		if(task.getStatus().equals(Consts.PaperTaskStatus.TO_AUDIT_SKEL)){
			saveSkelAuditResult(task, nextDealer, auditResult, remark, curUser);
		}else if(task.getStatus().equals(Consts.PaperTaskStatus.TO_AUDIT_PAPER)){
			savePaperAuditResult(task, nextDealer, auditResult, remark, curUser);
		}else if(task.getStatus().equals(Consts.PaperTaskStatus.TO_CHECK_PAPER)){
			savePaperCheckResult(task, nextDealer, auditResult, remark, curUser);
		}else if(task.getStatus().equals(Consts.PaperTaskStatus.FINAL_TYPESET)){
			saveFinalTypesetCheckResult(task, nextDealer, auditResult, remark, curUser);
		}else if(task.getStatus().equals(Consts.PaperTaskStatus.TO_ARCHIVE)){
			saveArchiveCheckResult(task, nextDealer, auditResult, remark, curUser);
		}
	}

	public void saveSkelAuditResult(PaperTask task,int nextDealer,int auditResult,String remark,User curUser) throws BizException{
		if(auditResult == Consts.AuditStatus.APPROVE && (nextDealer != task.getPrimarySecretary() && nextDealer != task.getPropositionTeacher())){
			throw new BizException("当前流程不能流转到：" + Consts.UserMap.get(nextDealer).getName());
		}
		if(auditResult == Consts.AuditStatus.REFUSED && (nextDealer != task.getAuditTeacher() && nextDealer != task.getPropositionTeacher())){
			throw new BizException("当前流程不能流转到：" + Consts.UserMap.get(nextDealer).getName());
		}
		task.setCurDealer(nextDealer);
		if(auditResult == Consts.AuditStatus.APPROVE){
			if(nextDealer == task.getPrimarySecretary()){//如果下一位处理人是主学科秘书的话，那么状态还是 审核细目表
				task.setStatus(Consts.PaperTaskStatus.TO_AUDIT_SKEL);
			}else {//如果下一位处理人是命题教师的话，那么状态就是 组卷 了
				task.setStatus(Consts.PaperTaskStatus.GENERATE_PAPER);
			}
		}else{
			if(nextDealer == task.getAuditTeacher()){//如果下一位处理人是审题教师的话，那么状态还是 审核细目表
				task.setStatus(Consts.PaperTaskStatus.TO_AUDIT_SKEL);
			}else {//如果下一位处理人是命题教师的话，那么状态就是 提交细目表 了
				task.setStatus(Consts.PaperTaskStatus.TO_CREATE_SKEL);
			}
		}
		dao.update("updatePaperTask", task);
		
		TaskFlowLog flowLog = new TaskFlowLog();
		flowLog.setCreatedBy(curUser.getId());
		flowLog.setOperName("审核细目表，审核结果：" + Consts.AuditStatus.dicMap.get(auditResult) + "，下一位处理人：" + Consts.UserMap.get(nextDealer).getName());
		flowLog.setRemark(remark);
		flowLog.setTaskId(task.getId());
		flowLog.setTaskType(Consts.TaskBatchType.RU_WEI_MING_TI);
		dao.insert("addTaskFlowLog", flowLog);
	}

	/**
	 * 保存试卷审核结果
	 * @param task
	 * @param nextDealer
	 * @param auditResult
	 * @param remark
	 * @param curUser
	 * @throws BizException
	 */
	public void savePaperAuditResult(PaperTask task,int nextDealer,int auditResult,String remark,User curUser) throws BizException{
		if(auditResult == Consts.AuditStatus.APPROVE && (nextDealer == task.getTypesetter())){
			throw new BizException("当前流程不能流转到：" + Consts.UserMap.get(nextDealer).getName());
		}
		if(auditResult == Consts.AuditStatus.REFUSED && (nextDealer != task.getPropositionTeacher() && nextDealer != task.getAuditTeacher() && nextDealer != task.getTypesetter())){
			throw new BizException("当前流程不能流转到：" + Consts.UserMap.get(nextDealer).getName());
		}
		checkPaperFiles(task, curUser);
		task.setCurDealer(nextDealer);
		if(auditResult == Consts.AuditStatus.APPROVE){
//			if(nextDealer != task.getAssistantSecretary()){//如果下一位处理人不是辅学科秘书，那么状态就是 试卷审核
//				task.setStatus(Consts.PaperTaskStatus.TO_AUDIT_PAPER);
//			}else {//否则状态就是 试卷校对
				task.setStatus(Consts.PaperTaskStatus.TO_CHECK_PAPER);
//			}
		}else{
			if(nextDealer == task.getPropositionTeacher()){//如果下一位处理人是命题教师的话，那么状态就是 组卷
				task.setStatus(Consts.PaperTaskStatus.GENERATE_PAPER);
			}else if(nextDealer == task.getTypesetter()){//如果下一位处理人是排版员的话，那么状态就是 排版
				task.setStatus(Consts.PaperTaskStatus.TYPESET);
			}else {//否则状态还是 试卷审核
				task.setStatus(Consts.PaperTaskStatus.TO_AUDIT_PAPER);
			}
		}
		dao.update("updatePaperTask", task);
		
		TaskFlowLog flowLog = new TaskFlowLog();
		flowLog.setCreatedBy(curUser.getId());
		flowLog.setOperName("审核试卷，审核结果：" + Consts.AuditStatus.dicMap.get(auditResult) + "，下一位处理人：" + Consts.UserMap.get(nextDealer).getName());
		flowLog.setRemark(remark);
		flowLog.setTaskId(task.getId());
		flowLog.setTaskType(Consts.TaskBatchType.RU_WEI_MING_TI);
		dao.insert("addTaskFlowLog", flowLog);
	}
	
	/**
	 * 保存试卷校对结果
	 * @param task
	 * @param nextDealer
	 * @param auditResult
	 * @param remark
	 * @param curUser
	 * @throws BizException
	 */
	public void savePaperCheckResult(PaperTask task,int nextDealer,int auditResult,String remark,User curUser) throws BizException{
		if(auditResult == Consts.AuditStatus.APPROVE && (nextDealer != task.getTypesetter() && nextDealer != task.getPrimarySecretary())){
			throw new BizException("当前流程不能流转到：" + Consts.UserMap.get(nextDealer).getName());
		}
//		if(auditResult == Consts.AuditStatus.REFUSED && (nextDealer == task.getAssistantSecretary())){
//			throw new BizException("当前流程不能流转到：" + Consts.UserMap.get(nextDealer).getName());
//		}
		checkPaperFiles(task, curUser);
		task.setCurDealer(nextDealer);
		if(auditResult == Consts.AuditStatus.APPROVE){//如果是审核通过，那么状态变成 待归档
			if(task.getCurDealer().equals(task.getTypesetter())){
				task.setStatus(Consts.PaperTaskStatus.FINAL_TYPESET);
			}else{
				//do nothing
			}
		}else{
			if(nextDealer == task.getPropositionTeacher()){//如果下一位处理人是命题教师的话，那么状态就是 组卷
				task.setStatus(Consts.PaperTaskStatus.GENERATE_PAPER);
			}else if(nextDealer == task.getTypesetter()){//如果下一位处理人是排版员的话，那么状态就是 排版
				task.setStatus(Consts.PaperTaskStatus.TYPESET);
			}else {//否则状态还是 试卷审核
				task.setStatus(Consts.PaperTaskStatus.TO_AUDIT_PAPER);
			}
		}
		dao.update("updatePaperTask", task);
		
		TaskFlowLog flowLog = new TaskFlowLog();
		flowLog.setCreatedBy(curUser.getId());
		flowLog.setOperName("校对试卷，校对结果：" + Consts.AuditStatus.dicMap.get(auditResult) + "，下一位处理人：" + Consts.UserMap.get(nextDealer).getName());
		flowLog.setRemark(remark);
		flowLog.setTaskId(task.getId());
		flowLog.setTaskType(Consts.TaskBatchType.RU_WEI_MING_TI);
		dao.insert("addTaskFlowLog", flowLog);
	}

	/**
	 * 保存试卷终排版审核结果
	 * @param task
	 * @param nextDealer
	 * @param auditResult
	 * @param remark
	 * @param curUser
	 * @throws BizException
	 */
	public void saveFinalTypesetCheckResult(PaperTask task,int nextDealer,int auditResult,String remark,User curUser) throws BizException{
		if(auditResult == Consts.AuditStatus.APPROVE && nextDealer != task.getPrimarySecretary()){
			throw new BizException("当前流程不能流转到：" + Consts.UserMap.get(nextDealer).getName());
		}
		checkPaperFiles(task, curUser);
		task.setCurDealer(nextDealer);
		if(auditResult == Consts.AuditStatus.APPROVE){//如果是审核通过，那么状态变成 待归档
			task.setStatus(Consts.PaperTaskStatus.TO_ARCHIVE);
		}else{
			if(nextDealer == task.getPropositionTeacher()){//如果下一位处理人是命题教师1的话，那么状态就是 试卷审核
				task.setStatus(Consts.PaperTaskStatus.TO_AUDIT_PAPER);
			}else if(nextDealer == task.getAuditTeacher() || nextDealer == task.getPrimarySecretary()){//如果下一位处理人是命题教师2或者学科秘书1的话，那么状态就是 试卷校对
				task.setStatus(Consts.PaperTaskStatus.TO_CHECK_PAPER);
			}else {//否则状态还是 终排版
				task.setStatus(Consts.PaperTaskStatus.FINAL_TYPESET);
			}
		}
		dao.update("updatePaperTask", task);
		
		TaskFlowLog flowLog = new TaskFlowLog();
		flowLog.setCreatedBy(curUser.getId());
		flowLog.setOperName("终排版审核，审核结果：" + Consts.AuditStatus.dicMap.get(auditResult) + "，下一位处理人：" + Consts.UserMap.get(nextDealer).getName());
		flowLog.setRemark(remark);
		flowLog.setTaskId(task.getId());
		flowLog.setTaskType(Consts.TaskBatchType.RU_WEI_MING_TI);
		dao.insert("addTaskFlowLog", flowLog);
	}

	/**
	 * 保存试卷待归档审核结果
	 * @param task
	 * @param nextDealer
	 * @param auditResult
	 * @param remark
	 * @param curUser
	 * @throws BizException
	 */
	public void saveArchiveCheckResult(PaperTask task,int nextDealer,int auditResult,String remark,User curUser) throws BizException{
		if(auditResult == Consts.AuditStatus.APPROVE){
			saveArchiveResult(task.getId(), remark, curUser);
			return;
		}
		checkPaperFiles(task, curUser);
		task.setCurDealer(nextDealer);
		{//处理审核不通过的情况
			if(nextDealer == task.getPropositionTeacher()){//如果下一位处理人是命题教师1的话，那么状态就是 试卷审核
				task.setStatus(Consts.PaperTaskStatus.TO_AUDIT_PAPER);
			}else if(nextDealer == task.getAuditTeacher() || nextDealer == task.getPrimarySecretary()){//如果下一位处理人是命题教师2或者学科秘书1的话，那么状态就是 试卷校对
				task.setStatus(Consts.PaperTaskStatus.TO_CHECK_PAPER);
			}else {//否则状态还是 终排版
				task.setStatus(Consts.PaperTaskStatus.FINAL_TYPESET);
			}
		}
		dao.update("updatePaperTask", task);
		
		TaskFlowLog flowLog = new TaskFlowLog();
		flowLog.setCreatedBy(curUser.getId());
		flowLog.setOperName("待归档审核，审核结果：" + Consts.AuditStatus.dicMap.get(auditResult) + "，下一位处理人：" + Consts.UserMap.get(nextDealer).getName());
		flowLog.setRemark(remark);
		flowLog.setTaskId(task.getId());
		flowLog.setTaskType(Consts.TaskBatchType.RU_WEI_MING_TI);
		dao.insert("addTaskFlowLog", flowLog);
	}

	public void normalSubmit(int taskId,int nextDealer,String remark,User curUser) throws BizException{
		PaperTask task = dao.get("getPaperTaskById", taskId);
		if(!task.getCurDealer().equals(curUser.getId())){
			throw new BizException("当前用户没有权限执行此操作");
		}
		if(task.getStatus().equals(Consts.PaperTaskStatus.TO_CREATE_SKEL)){
			submitSkelToAudit(task, nextDealer, remark, curUser);
		}else if(task.getStatus().equals(Consts.PaperTaskStatus.GENERATE_PAPER)
				|| task.getStatus().equals(Consts.PaperTaskStatus.TYPESET)
				|| task.getStatus().equals(Consts.PaperTaskStatus.FINAL_TYPESET)){
			submitPaperToTypesetOrAudit(task, nextDealer, remark, curUser);
		}
	}
	
	/**
	 * 复审提交
	 * @param taskId
	 * @param nextDealer
	 * @param remark
	 * @param curUser
	 * @throws BizException
	 */
	public void reviewSubmit(int taskId,int nextDealer,String remark,User curUser) throws BizException{
		PaperTask task = dao.get("getPaperTaskById", taskId);
		if(!task.getCurDealer().equals(curUser.getId())){
			throw new BizException("当前用户没有权限执行此操作");
		}
		submitReviewTash(task, nextDealer, remark, curUser);
	}

	public void submitSkelToAudit(PaperTask task,int nextDealer,String remark,User curUser) throws BizException{
		if(nextDealer != task.getAuditTeacher() && nextDealer != task.getPrimarySecretary()){
			throw new BizException("当前流程不能流转到：" + Consts.UserMap.get(nextDealer).getName());
		}
		task.setCurDealer(nextDealer);
		task.setStatus(Consts.PaperTaskStatus.TO_AUDIT_SKEL);
		dao.update("updatePaperTask", task);
		
		TaskFlowLog flowLog = new TaskFlowLog();
		flowLog.setCreatedBy(curUser.getId());
		flowLog.setOperName("提交细目表给" + Consts.UserMap.get(nextDealer).getName());
		flowLog.setRemark(remark);
		flowLog.setTaskId(task.getId());
		flowLog.setTaskType(Consts.TaskBatchType.RU_WEI_MING_TI);
		dao.insert("addTaskFlowLog", flowLog);
	}
	
	/**
	 * 提交复审任务
	 * @param task
	 * @param nextDealer
	 * @param remark
	 * @param curUser
	 * @throws BizException
	 */
	public void submitReviewTash(PaperTask task,int nextDealer,String remark,User curUser) throws BizException{
		task.setCurDealer(nextDealer);
//		if(nextDealer == task.getPrimarySecretary()){
//			task.setStatus(Consts.ReviewTaskStatus.TO_ARCHIVE);
//		}else 
//		if(nextDealer == task.getTypesetter()){
//			task.setStatus(Consts.ReviewTaskStatus.ARCHIVED);
//		}else if(nextDealer == task.getAuditTeacher()){
//			task.setStatus(Consts.ReviewTaskStatus.TO_AUDIT_PAPER);
//		}
		dao.update("updatePaperTask", task);
		
		TaskFlowLog flowLog = new TaskFlowLog();
		flowLog.setCreatedBy(curUser.getId());
		flowLog.setOperName("提交审核任务给" + Consts.UserMap.get(nextDealer).getName());
		flowLog.setRemark(remark);
		flowLog.setTaskId(task.getId());
		flowLog.setTaskType(Consts.TaskBatchType.SHI_JUAN_FU_SHEN);
		dao.insert("addTaskFlowLog", flowLog);
	}
	
	private void checkPaperFiles(PaperTask task,User curUser) throws BizException{
		{//处理试卷Word
			PagerConstruct pager = dao.get("findPagerConstructByTaskId", task.getId());
			pager = zujuanService.getOriginalWholePaperInfo(pager.getId());
			/**
			if(pager.getLastPaperWord() == null || pager.getLastPaperWord()-0 == 0){//如果之前没有生成Word，现在自动生成
				try {
					File paperFile = zujuanService.generalPaperFile(pager);
					File newFile = General.newAttFile();
					paperFile.renameTo(newFile);
					Attachment att = new Attachment();
					att.setCreatedBy(curUser.getId());
					att.setOriginalName(task.getTaskNo() + ".docx");
					att.setCurName(newFile.getName());
					att.setFileLength(newFile.length());
					att.setStorePath(newFile.getAbsolutePath());
					att.setStatus(Consts.AttachmentStatus.USING);
					dao.insert("addAttachment", att);
					pager.setLastPaperWord(att.getId());
					dao.update("updatePagerConstruct", pager);
					addWordHistory(pager.getId(), att.getId(), curUser, Consts.WordType.PAPER);
				} catch (Exception e) {
					throw new BizException("生成Word试卷失败，请与管理员联系。", e);
				}
			}
			**/
			if(pager.getLastWangpingWord() == null || pager.getLastWangpingWord()-0 == 0){//如果之前没有生成Word，现在自动生成
				try {
					File paperFile = zujuanService.generalWangPingPaperFile(pager);
					File newFile = General.newAttFile();
					paperFile.renameTo(newFile);
					Attachment att = new Attachment();
					att.setCreatedBy(curUser.getId());
					att.setOriginalName(task.getTaskNo() + "网评卷.docx");
					att.setCurName(newFile.getName());
					att.setFileLength(newFile.length());
					att.setStorePath(newFile.getAbsolutePath());
					att.setStatus(Consts.AttachmentStatus.USING);
					dao.insert("addAttachment", att);
					pager.setLastWangpingWord(att.getId());
					dao.update("updatePagerConstruct", pager);
					addWordHistory(pager.getId(), att.getId(), curUser, Consts.WordType.WANGPING);
				} catch (Exception e) {
					throw new BizException("生成Word网评卷失败，请与管理员联系。", e);
				}
			}
			if(pager.getLastTikaWord() == null || pager.getLastTikaWord()-0 == 0){//如果之前没有生成Word，现在自动生成
				try {
					File paperFile = zujuanService.generalTikaFile(pager);
					File newFile = General.newAttFile();
					paperFile.renameTo(newFile);
					Attachment att = new Attachment();
					att.setCreatedBy(curUser.getId());
					att.setOriginalName(task.getTaskNo() + "题卡.docx");
					att.setCurName(newFile.getName());
					att.setFileLength(newFile.length());
					att.setStorePath(newFile.getAbsolutePath());
					att.setStatus(Consts.AttachmentStatus.USING);
					dao.insert("addAttachment", att);
					pager.setLastTikaWord(att.getId());
					dao.update("updatePagerConstruct", pager);
					addWordHistory(pager.getId(), att.getId(), curUser, Consts.WordType.TIKA);
				} catch (Exception e) {
					throw new BizException("生成Word网评卷失败，请与管理员联系。", e);
				}
			}
			if(pager.getLastAnswerWord() == null || pager.getLastAnswerWord()-0 == 0){//如果之前没有生成Word，现在自动生成
				try {
					File answerFile = zujuanService.generalAnswerFile(pager);
					File newFile = General.newAttFile();
					answerFile.renameTo(newFile);
					Attachment att = new Attachment();
					att.setCreatedBy(curUser.getId());
					att.setOriginalName(task.getTaskNo() + "AN.docx");
					att.setCurName(newFile.getName());
					att.setFileLength(newFile.length());
					att.setStorePath(newFile.getAbsolutePath());
					att.setStatus(Consts.AttachmentStatus.USING);
					dao.insert("addAttachment", att);
					pager.setLastAnswerWord(att.getId());
					dao.update("updatePagerConstruct", pager);
					addWordHistory(pager.getId(), att.getId(), curUser, Consts.WordType.ANSWER);
				} catch (Exception e) {
					throw new BizException("生成Word试卷失败，请与管理员联系。", e);
				}
			}
		}
	}

	public void submitPaperToTypesetOrAudit(PaperTask task,int nextDealer,String remark,User curUser) throws BizException{
		checkPaperFiles(task, curUser);
		task.setCurDealer(nextDealer);
		if(nextDealer == task.getTypesetter()){
			task.setStatus(Consts.PaperTaskStatus.TYPESET);
		}else if(nextDealer == task.getPropositionTeacher() || nextDealer == task.getAuditTeacher()){
			task.setStatus(Consts.PaperTaskStatus.TO_AUDIT_PAPER);
		}else if(nextDealer == task.getPrimarySecretary()){
			if(Consts.PaperTaskStatus.FINAL_TYPESET.equals(task.getStatus())){
				task.setStatus(Consts.PaperTaskStatus.TO_ARCHIVE);
			}else{
				task.setStatus(Consts.PaperTaskStatus.TO_AUDIT_PAPER);
			}
		}/*else if(nextDealer == task.getAssistantSecretary()){
			task.setStatus(Consts.PaperTaskStatus.TO_CHECK_PAPER);
		}*/else{
			throw new BizException("当前流程不能流转到：" + Consts.UserMap.get(nextDealer).getName());
		}
		dao.update("updatePaperTask", task);
		
		TaskFlowLog flowLog = new TaskFlowLog();
		flowLog.setCreatedBy(curUser.getId());
		flowLog.setOperName("提交试卷给" + Consts.UserMap.get(nextDealer).getName());
		flowLog.setRemark(remark);
		flowLog.setTaskId(task.getId());
		flowLog.setTaskType(Consts.TaskBatchType.RU_WEI_MING_TI);
		dao.insert("addTaskFlowLog", flowLog);
	}
	
	public void saveArchiveResult(int taskId,String remark,User curUser) throws BizException{
		PaperTask task = dao.get("getPaperTaskById", taskId);
		if(!task.getCurDealer().equals(curUser.getId())){
			throw new BizException("当前用户没有权限执行此操作");
		}
		if(task.getBatchType().equals(Consts.TaskBatchType.RU_WEI_MING_TI)){
			if(!task.getStatus().equals(Consts.PaperTaskStatus.TO_ARCHIVE)){
				throw new BizException("当前任务不能被归档");
			}
		}
		String batchType = task.getBatchType();
		if(Consts.TaskBatchType.SHI_JUAN_FU_SHEN.equals(batchType)){
			task.setStatus(Consts.ReviewTaskStatus.ARCHIVED);
		}else if(Consts.TaskBatchType.RU_WEI_MING_TI.equals(batchType)){
			task.setStatus(Consts.PaperTaskStatus.ARCHIVED);
		}
		task.setRealEndTime(new Date());
		dao.update("updatePaperTask", task);
		
		if(Consts.TaskBatchType.RU_WEI_MING_TI.equals(task.getBatchType())){
			List<Question> drafts = dao.getList("queryDraftQuesInPaperTask", taskId);
			if(drafts != null && drafts.size() > 0){
				for(Question q:drafts){
					
					OperLog ol = new OperLog();
					ol.setObjId(q.getId());
					ol.setObjType(Consts.OperLogObjType.Question);
					ol.setOperCode("归档试卷");
					ol.setRemark("归档试卷" + task.getPaperName() + "时，试题状态自动由“" + q.getStatusName() + "”变成“" + QuestionStatusEnum.QUESTION_APPROVED.getValue() + "”");
					ol.setCreatedBy(curUser.getId());
					dao.insert("addOperLog", ol);
					
					q.setStatusCode(QuestionStatusEnum.QUESTION_APPROVED.getKey());
					q.setUpdatedBy(curUser.getId());
					q.setUpdatedTime(new Date());
					dao.update("updateQuestion", q);
				}
			}
		}
		
		TaskFlowLog flowLog = new TaskFlowLog();
		flowLog.setCreatedBy(curUser.getId());
		flowLog.setOperName("归档");
		flowLog.setRemark(remark);
		flowLog.setTaskId(task.getId());
		flowLog.setTaskType(batchType);
		dao.insert("addTaskFlowLog", flowLog);
	}

    public void submitCurWord(int taskId, int paperId, int attId, String wordType,User curUser){
    	addWordHistory(paperId, attId, curUser, wordType);
    	
    	TaskFlowLog flowLog = new TaskFlowLog();
		flowLog.setCreatedBy(curUser.getId());
    	
    	PagerConstruct paper = new PagerConstruct();
    	paper.setId(paperId);
    	if(Consts.WordType.PAPER.equals(wordType)){
    		paper.setLastPaperWord(attId);
    		flowLog.setOperName("上传最新Word试卷");
    	}else if(Consts.WordType.WANGPING.equals(wordType)){
    		paper.setLastWangpingWord(attId);
    		flowLog.setOperName("上传最新Word网评卷");
    	}else if(Consts.WordType.TIKA.equals(wordType)){
    		paper.setLastTikaWord(attId);
    		flowLog.setOperName("上传最新Word题卡");
    	}else{
    		paper.setLastAnswerWord(attId);
    		flowLog.setOperName("上传最新Word答案");
    	}
    	paper.setUpdatedBy(curUser.getId());
    	dao.update("updatePagerConstruct", paper);
    	
    	Attachment att = dao.get("getAttachmentById", attId);
    	if(ParamUtils.NeedCheckWordVersion){
	    	File attFile = new File(att.getStorePath());
	    	General.setDocxDefinedAttr(attFile, Consts.DOCX_VERSION, "QMTH" + System.currentTimeMillis());//往新上传的Word里面打个版本号：当前时间
	    	att.setFileLength(attFile.length());
    	}
    	att.setStatus(Consts.AttachmentStatus.USING);
    	att.setUpdatedBy(curUser.getId());
    	dao.update("updateAttachment", att);
    	
//		flowLog.setRemark("无");
		flowLog.setTaskId(taskId);
		flowLog.setTaskType(Consts.TaskBatchType.RU_WEI_MING_TI);
		dao.insert("addTaskFlowLog", flowLog);
    }
    
    /**
     * 提交复审附件
     * @param taskId
     * @param paperId
     * @param attId
     * @param wordType
     * @param curUser
     */
    public void submitReviewAtt(int taskId, int paperId, int attId, String wordType,User curUser){
    	addWordHistory(paperId, attId, curUser, wordType);
    	
    	TaskFlowLog flowLog = new TaskFlowLog();
		flowLog.setCreatedBy(curUser.getId());
    	
    	PagerConstruct paper = new PagerConstruct();
    	paper.setId(paperId);
    	if(Consts.WordType.HJ.equals(wordType)){
    		paper.setLastPaperWord(attId);
    		flowLog.setOperName("上传最新试卷");
    	}else if(Consts.WordType.DA.equals(wordType)){
    		paper.setLastAnswerWord(attId);
    		flowLog.setOperName("上传最新答题卷");
    	}else if(Consts.WordType.WPJ.equals(wordType)){
    		paper.setLastWangpingWord(attId);
    		flowLog.setOperName("上传最新网评卷");
    	}else if(Consts.WordType.ZK.equals(wordType)){
    		paper.setLastTikaWord(attId);
    		flowLog.setOperName("上传最新专卡");
    	}
    	paper.setUpdatedBy(curUser.getId());
    	dao.update("updatePagerConstruct", paper);
    	
    	Attachment att = dao.get("getAttachmentById", attId);
    	if(ParamUtils.NeedCheckWordVersion){
	    	File attFile = new File(att.getStorePath());
	    	General.setDocxDefinedAttr(attFile, Consts.DOCX_VERSION, "QMTH" + System.currentTimeMillis());//往新上传的Word里面打个版本号：当前时间
	    	att.setFileLength(attFile.length());
    	}
    	att.setStatus(Consts.AttachmentStatus.USING);
    	att.setUpdatedBy(curUser.getId());
    	dao.update("updateAttachment", att);
    	
//		flowLog.setRemark("无");
		flowLog.setTaskId(taskId);
		flowLog.setTaskType(Consts.TaskBatchType.SHI_JUAN_FU_SHEN);
		dao.insert("addTaskFlowLog", flowLog);
    }
    
    public void addWordHistory(int paperId, int attId,User curUser,String attType){
    	WordHistory wh = new WordHistory();
    	wh.setAttId(attId);
    	wh.setCreatedBy(curUser.getId());
    	wh.setAttType(attType);
    	wh.setPaperId(paperId);
    	dao.insert("addWordHistory", wh);
    }

    public boolean checkWordVersion(int paperId,int comparedAttId,String wordType){
    	if(!ParamUtils.NeedCheckWordVersion){
    		return true;
    	}
    	PagerConstruct paper = dao.get("findPagerConstructById", paperId);
    	
    	Integer attId = Consts.WordType.PAPER.equals(wordType) ? paper.getLastPaperWord() : paper.getLastAnswerWord();
    	if(attId == null){
    		throw new RuntimeException("试卷[" + paperId + "]中没有最新Word" + (Consts.WordType.PAPER.equals(wordType) ? "试卷" : "答案"));
    	}
    	Attachment att = dao.get("getAttachmentById", attId);
    	String curAttVersion = General.getDocxDefinedAttr(new File(att.getStorePath()), Consts.DOCX_VERSION);
    	if(curAttVersion == null){
    		throw new RuntimeException("试卷[" + paperId + "]中的最新Word" + (Consts.WordType.PAPER.equals(wordType) ? "试卷" : "答案") + "里面没有版本号，请与管理员联系");
    	}
    	log.info("Docx文件[" + att.getStorePath() + "]的版本号：" + curAttVersion);
    	try{
    		Attachment comparedAtt = dao.get("getAttachmentById", comparedAttId);
	    	String comparedAttVersion = General.getDocxDefinedAttr(new File(comparedAtt.getStorePath()), Consts.DOCX_VERSION);
    		log.info("Docx文件[" + comparedAtt.getStorePath() + "]的版本号：" + curAttVersion);
	    	if(comparedAttVersion == null){
	    		return false;
	    	}
	    	return curAttVersion.equals(comparedAttVersion);
    	}catch(Exception e){
    		log.warn("不能解析出上传的附件[" + comparedAttId + "]版本号");
    		return false;
    	}
    }
	
	public int taskValidateChange(int id){
		return dao.get("taskValidateChange", id);
	}
	
	public int deleteWordHistoryByTaskId(int id){
		return dao.delete("deleteWordHistoryByTaskId", id);
	}
	
	public int deletePagerConstructByTaskId(int id){
		return dao.delete("deletePagerConstructByTaskId", id);
	}
	
	public int deletePaperTaskById(int id){//TODO 建议加上校验：已经开始的任务不能删除
		return dao.delete("deletePaperTaskById", id);
	}
	
	public int updatePaperTask(PaperTask task){
		return dao.update("updatePaperTask", task);
	}
	
	public List<HashMap<String, Object>> queryTodoPaperTaskStatus(int curDealer){
		List<HashMap<String, Object>> result = dao.getList("queryTodoPaperTaskStatus", curDealer);
		
		return addStatusNameToMap(result); 
	}
	
	private List<HashMap<String, Object>> addStatusNameToMap(List<HashMap<String, Object>> result){
		HashMap<String, Object> sum = new HashMap<String, Object>();
		sum.put("status", "");
		sum.put("statusName", "所有状态");
		int total = 0;
		if(result.size() > 0){
			for(HashMap<String, Object> map : result){
				map.put("statusName", Consts.PaperTaskStatus.dicMap.get(map.get("status")));
				total += (Long)map.get("count");
			}
		}
		
		sum.put("count", total);
		result.add(0, sum);
		
		return result;		
	}
	
	public List<HashMap<String, Object>> queryRelatedPaperTaskStatus(int curDealer){
		List<HashMap<String, Object>> result = dao.getList("queryRelatedPaperTaskStatus", curDealer);
		
		return addStatusNameToMap(result); 
	}
	
	public List<PaperTask> queryRelatedPaperTasks(TaskQueryParams params){
		return dao.getPagerList("queryRelatedPaperTasks", params);
	}
	
	public List<HashMap<String, Object>> queryPaperTaskStatusByBatchId(int batchId){
		List<HashMap<String, Object>> result = dao.getList("queryPaperTaskStatusByBatchId", batchId);
		
		return addStatusNameToMap(result); 
	}
	
	public void saveImportData(int batchId,List<PaperTask> list,JSONObject object,User curUser){
		TaskBatch taskBatch = taskBatchService.findById(batchId);
		String name = taskBatch.getName();
		List<String> loginList=new ArrayList<String>();
		Map<String,User> tempMap=new HashMap<String,User>();
		for(Map.Entry<Integer, User> entry : Consts.UserMap.entrySet()){
			tempMap.put(entry.getValue().getName(), entry.getValue());
			loginList.add(entry.getValue().getName());
		}
		boolean existsCourseCode=true;
		boolean isSameCourseCode=false;
		boolean isTaskNo=false;
		int i=1;
		Map<String,String> map=new HashMap<String,String>();
		
		PaperTask paperTask=new PaperTask();
		paperTask.setBatchId(batchId);
		
		List<PaperTask> paperTasks = queryPaperTask(paperTask);
		
		//把当前批次下所有的课程代码和任务单编号放到map里面
		for(PaperTask pp:paperTasks){
			Course course=courseService.findById(pp.getCourseId());
			map.put(course.getCode(), pp.getTaskNo());
		}
		
		for(PaperTask pt:list){
			
			Course course=courseService.findByCode(pt.getCourseCode());
			//校验课程代码是否在系统中存在
			if(course==null){
				existsCourseCode=false;
				break;
			}
			//校验课程代码是否在批次中存在
			if(map.containsKey(pt.getCourseCode())){
				isSameCourseCode=true;
				break;
			}
			
			if(!loginList.contains(pt.getPropositionLoginName())){
				//返回前端用户登录名不存在
				object.put("result", "fail");
				object.put("lineNum",i );
				object.put("msg", "命题教师1[" + pt.getPropositionLoginName() + "]用户信息不存在");
				return;
			}
			
			if(!loginList.contains(pt.getAuditTeacherLoginName())){
				//返回前端用户登录名不存在
				object.put("result", "fail");
				object.put("lineNum",i );
				object.put("msg", "命题教师2[" + pt.getAuditTeacherLoginName() + "]用户信息不存在");
				return;
			}
			
			if(!loginList.contains(pt.getPrimarySecretaryLoginName())){
				//返回前端用户登录名不存在
				object.put("result", "fail");
				object.put("lineNum",i );
				object.put("msg", "学科秘书[" + pt.getPrimarySecretaryLoginName() + "]用户信息不存在");
				return;
			}
			
//			if(!loginList.contains(pt.getAssistantSecretaryLoginName())){
//				//返回前端用户登录名不存在
//				object.put("result", "fail");
//				object.put("lineNum",i );
//				object.put("msg", "学科秘书2[" + pt.getAssistantSecretaryLoginName() + "]用户信息不存在");
//				return;
//			}
			
			if(!loginList.contains(pt.getTypesetterLoginName())){
				//返回前端用户登录名不存在
				object.put("result", "fail");
				object.put("lineNum",i );
				object.put("msg", "排版员[" + pt.getTypesetterLoginName() + "]用户信息不存在");
				return;
			}
			
			i++;
		}
		
		if(!existsCourseCode){
			object.put("result", "fail");
			object.put("lineNum",i);
			object.put("msg", "导入的课程代码在基础库中不存在");
		}else if(isSameCourseCode){	//导入的信息中存在相同的courseCode
			object.put("result", "fail");
			object.put("lineNum",i);
			object.put("msg", "导入的文件该批次下存在相同的课程编号");
		}else if(isTaskNo){
			object.put("result", "fail");
			object.put("lineNum",i);
			object.put("msg", "导入的文件任务单编号已经在数据库中存在!");
		}else{
			int j=1;
			for(PaperTask pt:list){
				pt.setPropositionTeacher(tempMap.get(pt.getPropositionLoginName()).getId());
				pt.setAuditTeacher(tempMap.get(pt.getAuditTeacherLoginName()).getId());
				pt.setPrimarySecretary(tempMap.get(pt.getPrimarySecretaryLoginName()).getId());
				//pt.setAssistantSecretary(tempMap.get(pt.getAssistantSecretaryLoginName()).getId());
				pt.setTypesetter(tempMap.get(pt.getTypesetterLoginName()).getId());
				
				List<Book> ls=bookService.findBooks(pt.getCourseCode());
				Course course=courseService.findByCode(pt.getCourseCode());
				
				pt.setCourseId(course.getId());
				if(ls.size()>1){
					//提示选择课程id 对应有多门教材
					object.put("result", "fail");
					object.put("lineNum",j);
					object.put("msg", "导入的课程代码有多个启用的教材!");
					return;
				}else if(ls.size()==1){
					int bookId=ls.get(0).getId();
					
					String taskNo=pt.getCourseCode();
					if(name.length()==6 && StringUtils.isNumeric(name)){
						taskNo+=name;
					}else{
						//任务单编号 = 课程代码+批次名称
						taskNo+=taskBatch.getName();
					}
					pt.setTaskNo(taskNo);
					pt.setTitle(taskNo);
					pt.setPaperName(taskNo);
					pt.setBatchId(batchId);
					pt.setBookId(bookId);
					pt.setPlanStartTime(taskBatch.getPlanStartTime());
					pt.setPlanEndTime(taskBatch.getPlanEndTime());
					
					pt.setStatus(PaperTaskStatus.TO_CREATE_SKEL);
					pt.setCreatedBy(curUser.getId());
					pt.setCreatedTime(new Date());
					pt.setUpdatedBy(curUser.getId());
					pt.setUpdatedTime(new Date());
				}else{
					object.put("result", "fail");
					object.put("lineNum",j);
					object.put("msg", "导入的课程代码没有对应的教材!");
					return;
				}
				j++;
			}
			int k=0;
			for(PaperTask pt:list){
				
				String taskNo=pt.getTaskNo();
				pt.setCurDealer(pt.getPropositionTeacher());
				pt.setTaskNo(taskNo+"A");
				pt.setTitle(taskNo+"A");
				pt.setPaperName(taskNo+"A");
				addPaperTask(pt);
				
				int teacher1=pt.getPropositionTeacher();
				int teacher2=pt.getAuditTeacher();
				
				pt.setAuditTeacher(teacher1);
				pt.setTaskNo(taskNo+"B");
				pt.setTitle(taskNo+"B");
				pt.setPaperName(taskNo+"B");
				pt.setPropositionTeacher(teacher2);
				pt.setCurDealer(teacher2);
				addPaperTask(pt);
				k+=2;
			}
			if(object.isEmpty()){
				object.put("result", "success");
				object.put("successNum", k);
				object.put("msg", "导入成功!");
			}
		}
	}
	
	public void setTeachersEnable(int taskId,int isEnabled){
		PaperTask task = dao.get("getPaperTaskById", taskId);
		User propositionTeacher = new User();
		propositionTeacher.setId(task.getPropositionTeacher());
		propositionTeacher.setIsEnabled(isEnabled);
		User auditTeacher = new User();
		auditTeacher.setId(task.getAuditTeacher());
		auditTeacher.setIsEnabled(isEnabled);
		dao.update("updateWholeUser", propositionTeacher);
		dao.update("updateWholeUser", auditTeacher);
		userService.initUserInfo();
	}
	
	public Attachment exportAllFiles(int batchId,User curUser){
		TaskBatch tb = dao.get("findTaskBatchById", batchId);
		if(tb == null){
			throw new RuntimeException("任务批次信息不存在");
		}
		Attachment expAtt = new Attachment();
		List<Map<String,Object>> allPaperInfos = dao.getList("findAllPaperFilesByBatchId",batchId);
		FileOutputStream fos = null;
		ZipOutputStream zos = null;
		try{
			File newFile = General.newTmpFile();
            fos = new FileOutputStream(newFile);
            zos = new ZipOutputStream(fos);
			for(Map<String,Object> info:allPaperInfos){
				String paperName = (String)info.get("paperName");
				int paperWord = General.toInteger(info.get("paperWord"), 0);
				int wangpingWord = General.toInteger(info.get("wangpingWord"), 0);
				int answerWord = General.toInteger(info.get("answerWord"), 0);
				String tikaType = (String)info.get("tikaType");
				int lastZhuanyinWord = General.toInteger(info.get("lastZhuanyinWord"), 0);
				if(paperWord != 0){
					Attachment att = dao.get("getAttachmentById", paperWord);
					if(att != null){
						File file = new File(att.getStorePath());
		            	FileInputStream fis = null;
		            	if(file.exists()){
		            		try{
		    					fis = new FileInputStream(file);
		    					String fileName = att.getOriginalName();
		    					if(fileName.contains(".")){
		    						fileName = paperName + fileName.substring(fileName.lastIndexOf('.'));
		    					}else{
		    						fileName = paperName + ".docx";
		    					}
		                		zos.putNextEntry(new ZipEntry(fileName));
		    					IOUtils.copyLarge(fis, zos);
								zos.flush();
		    				}finally{
		    					General.close(fis);
		    				}
		            	}
					}
				}
				if(wangpingWord != 0){
					Attachment att = dao.get("getAttachmentById", wangpingWord);
					if(att != null){
						File file = new File(att.getStorePath());
		            	FileInputStream fis = null;
		            	if(file.exists()){
		            		try{
		    					fis = new FileInputStream(file);
		    					String fileName = att.getOriginalName();
		    					if(fileName.contains(".")){
		    						fileName = paperName + "W" + fileName.substring(fileName.lastIndexOf('.'));
		    					}else{
		    						fileName = paperName + "W.docx";
		    					}
		                		zos.putNextEntry(new ZipEntry(fileName));
		    					IOUtils.copyLarge(fis, zos);
								zos.flush();
		    				}finally{
		    					General.close(fis);
		    				}
		            	}
					}
				}
				if(answerWord != 0){
					Attachment att = dao.get("getAttachmentById", answerWord);
					if(att != null){
						File file = new File(att.getStorePath());
		            	FileInputStream fis = null;
		            	if(file.exists()){
		            		try{
		    					fis = new FileInputStream(file);
		    					String fileName = att.getOriginalName();
		    					if(fileName.contains(".")){
		    						fileName = paperName + 'N' + fileName.substring(fileName.lastIndexOf('.'));
		    					}else{
		    						fileName = paperName + "N.docx";
		    					}
		                		zos.putNextEntry(new ZipEntry(fileName));
		    					IOUtils.copyLarge(fis, zos);
								zos.flush();
		    				}finally{
		    					General.close(fis);
		    				}
		            	}
					}
				}
				if(Consts.TikaType.SPECIAL.equals(tikaType) && lastZhuanyinWord != 0){
					Attachment att = dao.get("getAttachmentById", lastZhuanyinWord);
					if(att != null){
						File file = new File(att.getStorePath());
		            	FileInputStream fis = null;
		            	if(file.exists()){
		            		try{
		    					fis = new FileInputStream(file);
		    					String fileName = att.getOriginalName();
		    					if(fileName.contains(".")){
		    						fileName = paperName + "ZY" + fileName.substring(fileName.lastIndexOf('.'));
		    					}else{
		    						fileName = paperName + "ZY.docx";
		    					}
		                		zos.putNextEntry(new ZipEntry(fileName));
		    					IOUtils.copyLarge(fis, zos);
								zos.flush();
		    				}finally{
		    					General.close(fis);
		    				}
		            	}
					}
				}
			}
			zos.closeEntry();
        	General.close(zos);
        	General.close(fos);
        	
        	File destFile = General.newAttFile();
        	newFile.renameTo(destFile);
        	expAtt.setCreatedBy(curUser.getId());
        	expAtt.setOriginalName(tb.getName() + ".zip");
        	expAtt.setCurName(destFile.getName());
        	expAtt.setFileLength(destFile.length());
        	expAtt.setStorePath(destFile.getAbsolutePath());
        	expAtt.setStatus(Consts.AttachmentStatus.DRAFT);
			dao.insert("addAttachment", expAtt);
            
			return expAtt;
        } catch (Exception e) {
        	throw new RuntimeException("网评卷、答案、转印说明Word文件写入zip压缩文件失败，原因：" + e.getMessage(), e);
        } finally{
        	General.close(zos);
        	General.close(fos);
        }
	}
	
	/**
	 * 导出入库数据
	 * @param batchId
	 * @param curUser
	 * @return
	 */
	public Attachment exportRkData(int batchId,User curUser){
		HSSFWorkbook workbook = new HSSFWorkbook();
		// 生成一个字体
	    HSSFFont normalFont1 = workbook.createFont();
	    normalFont1.setColor(HSSFColor.BLACK.index);
		
		// 生成一个字体
	    HSSFFont normalFont2 = workbook.createFont();
	    normalFont2.setColor(HSSFColor.BLACK.index);
	    normalFont2.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
	    
	    //标题边框，粗体，居中对齐，不可换行
  		HSSFCellStyle border_th = workbook.createCellStyle();
  		border_th.setBorderTop(HSSFCellStyle.BORDER_THIN);
  		border_th.setBorderBottom(HSSFCellStyle.BORDER_THIN);
  		border_th.setBorderLeft(HSSFCellStyle.BORDER_THIN);
  		border_th.setBorderRight(HSSFCellStyle.BORDER_THIN);
  		border_th.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  		border_th.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
  		border_th.setWrapText(false);
  		border_th.setFont(normalFont2);
	    
	    //普通字符边框，居左对齐，可换行
  		HSSFCellStyle border_str = workbook.createCellStyle();
  		border_str.setBorderTop(HSSFCellStyle.BORDER_THIN);
  		border_str.setBorderBottom(HSSFCellStyle.BORDER_THIN);
  		border_str.setBorderLeft(HSSFCellStyle.BORDER_THIN);
  		border_str.setBorderRight(HSSFCellStyle.BORDER_THIN);
  		border_str.setAlignment(HSSFCellStyle.ALIGN_LEFT);
  		border_str.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
  		border_str.setWrapText(true);
  		border_str.setFont(normalFont1);
	    
  		{
			HSSFSheet sheetByCourse = workbook.createSheet("入库导入数据");
			sheetByCourse.setColumnWidth(0, 4000);
			sheetByCourse.setColumnWidth(1, 3000);
			sheetByCourse.setColumnWidth(2, 3000);
			sheetByCourse.setColumnWidth(3, 5000);
			sheetByCourse.setColumnWidth(4, 5000);
			sheetByCourse.setColumnWidth(5, 3000);
			sheetByCourse.setColumnWidth(6, 3000);
			sheetByCourse.setColumnWidth(7, 3000);
			sheetByCourse.setColumnWidth(8, 3000);
			sheetByCourse.setColumnWidth(9, 3000);
			{
				HSSFRow row0 = sheetByCourse.createRow(0);
//				row1.setHeight((short)300);
				HSSFCell ce0 = row0.createCell(0);
		        ce0.setCellValue("SJBH");
		        ce0.setCellStyle(border_th);
				HSSFCell ce1 = row0.createCell(1);
		        ce1.setCellValue("QY");
		        ce1.setCellStyle(border_th);
				HSSFCell ce2 = row0.createCell(2);
		        ce2.setCellValue("KCDM");
		        ce2.setCellStyle(border_th);
				HSSFCell ce3 = row0.createCell(3);
		        ce3.setCellValue("KCMC");
		        ce3.setCellStyle(border_th);
				HSSFCell ce4 = row0.createCell(4);
		        ce4.setCellValue("JC");
		        ce4.setCellStyle(border_th);
				HSSFCell ce5 = row0.createCell(5);
		        ce5.setCellValue("BZ");
		        ce5.setCellStyle(border_th);
				HSSFCell ce6 = row0.createCell(6);
		        ce6.setCellValue("CBS");
		        ce6.setCellStyle(border_th);
				HSSFCell ce7 = row0.createCell(7);
		        ce7.setCellValue("BC");
		        ce7.setCellStyle(border_th);
				HSSFCell ce8 = row0.createCell(8);
		        ce8.setCellValue("XXMC");
		        ce8.setCellStyle(border_th);
				HSSFCell ce9 = row0.createCell(9);
		        ce9.setCellValue("ZK");
		        ce9.setCellStyle(border_th);
			}
			{
				List<Map<String,Object>> dataList = dao.getList("getRkDataList", batchId);
				for(int i=0;i<dataList.size();i++){
					Map<String,Object> data = dataList.get(i);
					HSSFRow row = sheetByCourse.createRow(1 + i);
					HSSFCell ce0 = row.createCell(0);
					HSSFCell ce1 = row.createCell(1);
					HSSFCell ce2 = row.createCell(2);
					HSSFCell ce3 = row.createCell(3);
					HSSFCell ce4 = row.createCell(4);
					HSSFCell ce5 = row.createCell(5);
					HSSFCell ce6 = row.createCell(6);
					HSSFCell ce7 = row.createCell(7);
					HSSFCell ce8 = row.createCell(8);
					HSSFCell ce9 = row.createCell(9);
					
					ce0.setCellStyle(border_str);
			        ce1.setCellStyle(border_str);
			        ce2.setCellStyle(border_str);
			        ce3.setCellStyle(border_str);
			        ce4.setCellStyle(border_str);
			        ce5.setCellStyle(border_str);
			        ce6.setCellStyle(border_str);
			        ce7.setCellStyle(border_str);
			        ce8.setCellStyle(border_str);
			        ce9.setCellStyle(border_str);
			        
			        ce0.setCellValue(General.null2String(data.get("SJBH")));
			        ce1.setCellValue(General.null2String(data.get("QY")));
			        ce2.setCellValue(General.null2String(data.get("KCDM")));
					ce3.setCellValue(General.null2String(data.get("KCMC")));
					ce4.setCellValue(General.null2String(data.get("JC")));
					ce5.setCellValue(General.null2String(data.get("BZ")));
					ce6.setCellValue(General.null2String(data.get("CBS")));
					ce7.setCellValue(General.null2String(data.get("BC")));
					ce8.setCellValue(General.null2String(data.get("XXMC")));
					ce9.setCellValue(General.null2String(data.get("ZK")));
				}
			}
  		}
  		
		File xlsFile = General.newTmpFile();
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(xlsFile);
			workbook.write(fos);
		} catch (Exception e) {
			throw new RuntimeException("写入Excel数据到临时文件：" + xlsFile.getAbsolutePath() + "中失败，原因：" + e.getMessage(), e);
		} finally{
			General.close(fos);
		}
		File newFile = General.newAttFile();
		xlsFile.renameTo(newFile);
		Attachment att = new Attachment();
		att.setCreatedBy(curUser.getId());
		att.setOriginalName("卷库入库_" + DateHelper.getNow(DateHelper.shortSimpleDateFormatWithoutSplit) + ".xls");
		att.setCurName(newFile.getName());
		att.setFileLength(newFile.length());
		att.setStorePath(newFile.getAbsolutePath());
		att.setStatus(Consts.AttachmentStatus.DRAFT);
		dao.insert("addAttachment", att);
		return att;
	}
	
	/**
	 * 导出命题教师签到表
	 * @param batchId
	 * @param curUser
	 * @return
	 */
	public Attachment exportMTJSQD(int batchId, User curUser){
		XSSFWorkbook workbook = new XSSFWorkbook();
		TaskBatch batch = this.taskBatchService.findById(batchId);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月");
		// 生成一个字体
		XSSFFont tittleFont = workbook.createFont();
	    tittleFont.setColor(HSSFColor.BLACK.index);
	    tittleFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
	    tittleFont.setFontHeightInPoints((short)16);
	    // 生成一个字体
	    XSSFFont normalFont1 = workbook.createFont();
	    normalFont1.setColor(HSSFColor.BLACK.index);
		
		// 生成一个字体
	    XSSFFont normalFont2 = workbook.createFont();
	    normalFont2.setColor(HSSFColor.BLACK.index);
	    normalFont2.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
	    
	    //标题
  		XSSFCellStyle tittleStyle = workbook.createCellStyle();
  		tittleStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
  		tittleStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
  		tittleStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
  		tittleStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
  		tittleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  		tittleStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
  		tittleStyle.setWrapText(false);
  		tittleStyle.setFont(tittleFont);
	    
	    //标题边框，粗体，居中对齐，不可换行
  		XSSFCellStyle border_th = workbook.createCellStyle();
  		border_th.setBorderTop(HSSFCellStyle.BORDER_THIN);
  		border_th.setBorderBottom(HSSFCellStyle.BORDER_THIN);
  		border_th.setBorderLeft(HSSFCellStyle.BORDER_THIN);
  		border_th.setBorderRight(HSSFCellStyle.BORDER_THIN);
  		border_th.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  		border_th.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
  		border_th.setWrapText(false);
  		border_th.setFont(normalFont2);
	    
	    //普通字符边框，居左对齐，可换行
  		XSSFCellStyle border_str = workbook.createCellStyle();
  		border_str.setBorderTop(HSSFCellStyle.BORDER_THIN);
  		border_str.setBorderBottom(HSSFCellStyle.BORDER_THIN);
  		border_str.setBorderLeft(HSSFCellStyle.BORDER_THIN);
  		border_str.setBorderRight(HSSFCellStyle.BORDER_THIN);
  		border_str.setAlignment(HSSFCellStyle.ALIGN_LEFT);
  		border_str.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
  		border_str.setWrapText(true);
  		border_str.setFont(normalFont1);
	    
  		{
  			XSSFSheet sheetByCourse = workbook.createSheet("命题教师签到");
			sheetByCourse.setColumnWidth(0, 1000);
			sheetByCourse.setColumnWidth(1, 3000);
			sheetByCourse.setColumnWidth(2, 3000);
			sheetByCourse.setColumnWidth(3, 5000);
			sheetByCourse.setColumnWidth(4, 5000);
			sheetByCourse.setColumnWidth(5, 3000);
			sheetByCourse.setColumnWidth(6, 3000);
			sheetByCourse.setColumnWidth(7, 3000);
			sheetByCourse.setColumnWidth(8, 3000);
			{
				XSSFRow row0 = sheetByCourse.createRow(0);
				XSSFCell cell_tittle = row0.createCell(0);
		        String dateStr = sdf.format(batch.getPlanStartTime());
				cell_tittle.setCellValue(dateStr + "自考统考课程入闱命题教师签到表");
				cell_tittle.setCellStyle(tittleStyle);
				CellRangeAddress range1 = new CellRangeAddress(0, 0, 0, 8);
				sheetByCourse.addMergedRegion(range1);
				
				XSSFRow row1 = sheetByCourse.createRow(1);
				XSSFCell ce0 = row1.createCell(0);
		        ce0.setCellValue("序号");
		        ce0.setCellStyle(border_th);
		        XSSFCell ce1 = row1.createCell(1);
		        ce1.setCellValue("课程");
		        ce1.setCellStyle(border_th);
		        XSSFCell ce2 = row1.createCell(2);
		        ce2.setCellValue("课程名称");
		        ce2.setCellStyle(border_th);
		        XSSFCell ce3 = row1.createCell(3);
		        ce3.setCellValue("姓名");
		        ce3.setCellStyle(border_th);
		        XSSFCell ce4 = row1.createCell(4);
		        ce4.setCellValue("单位");
		        ce4.setCellStyle(border_th);
		        XSSFCell ce5 = row1.createCell(5);
		        ce5.setCellValue("联系方式");
		        ce5.setCellStyle(border_th);
		        XSSFCell ce6 = row1.createCell(6);
		        ce6.setCellValue("身份证号");
		        ce6.setCellStyle(border_th);
		        XSSFCell ce7 = row1.createCell(7);
		        ce7.setCellValue("银行卡号");
		        ce7.setCellStyle(border_th);
		        XSSFCell ce8 = row1.createCell(8);
		        ce8.setCellValue("签字");
		        ce8.setCellStyle(border_th);
			}
			{
				List<Map<String,Object>> dataList = dao.getList("getMTJSQDList", batchId);
				List<MergeInfo> mergeList = builQDBGroupByList(dataList);
				for(int i=0;i<dataList.size();i++){
					Map<String,Object> data = dataList.get(i);
					XSSFRow row = sheetByCourse.createRow(2 + i);
					XSSFCell ce0 = row.createCell(0);
					XSSFCell ce1 = row.createCell(1);
					XSSFCell ce2 = row.createCell(2);
					XSSFCell ce3 = row.createCell(3);
					XSSFCell ce4 = row.createCell(4);
					XSSFCell ce5 = row.createCell(5);
					XSSFCell ce6 = row.createCell(6);
					XSSFCell ce7 = row.createCell(7);
					XSSFCell ce8 = row.createCell(8);
					
					ce0.setCellStyle(border_str);
			        ce1.setCellStyle(border_str);
			        ce2.setCellStyle(border_str);
			        ce3.setCellStyle(border_str);
			        ce4.setCellStyle(border_str);
			        ce5.setCellStyle(border_str);
			        ce6.setCellStyle(border_str);
			        ce7.setCellStyle(border_str);
			        ce8.setCellStyle(border_str);
			        
			        ce0.setCellValue(General.null2String(i + 1));
			        ce1.setCellValue(General.null2String(data.get("kcdm")));
			        ce2.setCellValue(General.null2String(data.get("kcmc")));
					ce3.setCellValue(General.null2String(data.get("teacher_name")));
					ce4.setCellValue(General.null2String(data.get("school")));
					ce5.setCellValue(General.null2String(data.get("phone")));
					ce6.setCellValue(General.null2String(data.get("certino")));
					ce7.setCellValue(General.null2String(data.get("bankno")));
					ce8.setCellValue("");
				}
				//合并
				for (MergeInfo merge : mergeList) {
					System.err.println(merge.getType() + " , " + merge.getName() + " , " + merge.getFirst_row() + " , " + merge.getLast_row() + " , " + merge.getFirst_col() + " , " + merge.getLast_col());
					CellRangeAddress range1 = new CellRangeAddress(merge.getFirst_row(), merge.getLast_row(), merge.getFirst_col(), merge.getLast_col());
					sheetByCourse.addMergedRegion(range1);
				}
			}
  		}
  		
		File xlsFile = General.newTmpFile();
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(xlsFile);
			workbook.write(fos);
		} catch (Exception e) {
			throw new RuntimeException("写入Excel数据到临时文件：" + xlsFile.getAbsolutePath() + "中失败，原因：" + e.getMessage(), e);
		} finally{
			General.close(fos);
		}
		File newFile = General.newAttFile();
		xlsFile.renameTo(newFile);
		Attachment att = new Attachment();
		att.setCreatedBy(curUser.getId());
		att.setOriginalName("命题教师签到_" + DateHelper.getNow(DateHelper.shortSimpleDateFormatWithoutSplit) + ".xls");
		att.setCurName(newFile.getName());
		att.setFileLength(newFile.length());
		att.setStorePath(newFile.getAbsolutePath());
		att.setStatus(Consts.AttachmentStatus.DRAFT);
		dao.insert("addAttachment", att);
		return att;
	}
	
	/**
	 * 导出命题审题学科联系人分工表
	 * @param batchId
	 * @param curUser
	 * @return
	 */
	public Attachment exportMTSTFGB(int batchId, User curUser){
		XSSFWorkbook workbook = new XSSFWorkbook();
		TaskBatch batch = this.taskBatchService.findById(batchId);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月");
		// 生成一个字体
		XSSFFont tittleFont = workbook.createFont();
	    tittleFont.setColor(HSSFColor.BLACK.index);
	    tittleFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
	    tittleFont.setFontHeightInPoints((short)16);
	    // 生成一个字体
	    XSSFFont normalFont1 = workbook.createFont();
	    normalFont1.setColor(HSSFColor.BLACK.index);
		
		// 生成一个字体
	    XSSFFont normalFont2 = workbook.createFont();
	    normalFont2.setColor(HSSFColor.BLACK.index);
	    normalFont2.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
	    
	    //标题
  		XSSFCellStyle tittleStyle = workbook.createCellStyle();
  		tittleStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
  		tittleStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
  		tittleStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
  		tittleStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
  		tittleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  		tittleStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
  		tittleStyle.setWrapText(false);
  		tittleStyle.setFont(tittleFont);
	    
	    //标题边框，粗体，居中对齐，不可换行
  		XSSFCellStyle border_th = workbook.createCellStyle();
  		border_th.setBorderTop(HSSFCellStyle.BORDER_THIN);
  		border_th.setBorderBottom(HSSFCellStyle.BORDER_THIN);
  		border_th.setBorderLeft(HSSFCellStyle.BORDER_THIN);
  		border_th.setBorderRight(HSSFCellStyle.BORDER_THIN);
  		border_th.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  		border_th.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
  		border_th.setWrapText(false);
  		border_th.setFont(normalFont2);
	    
	    //普通字符边框，居左对齐，可换行
  		XSSFCellStyle border_str = workbook.createCellStyle();
  		border_str.setBorderTop(HSSFCellStyle.BORDER_THIN);
  		border_str.setBorderBottom(HSSFCellStyle.BORDER_THIN);
  		border_str.setBorderLeft(HSSFCellStyle.BORDER_THIN);
  		border_str.setBorderRight(HSSFCellStyle.BORDER_THIN);
  		border_str.setAlignment(HSSFCellStyle.ALIGN_LEFT);
  		border_str.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
  		border_str.setWrapText(true);
  		border_str.setFont(normalFont1);
	    
  		{
  			XSSFSheet sheetByCourse = workbook.createSheet("联系人分工表");
			sheetByCourse.setColumnWidth(0, 1000);
			sheetByCourse.setColumnWidth(1, 3000);
			sheetByCourse.setColumnWidth(2, 3000);
			sheetByCourse.setColumnWidth(3, 5000);
			sheetByCourse.setColumnWidth(4, 5000);
			sheetByCourse.setColumnWidth(5, 3000);
			sheetByCourse.setColumnWidth(6, 3000);
			{
				XSSFRow row0 = sheetByCourse.createRow(0);
				XSSFCell cell_tittle = row0.createCell(0);
		        String dateStr = sdf.format(batch.getPlanStartTime());
				cell_tittle.setCellValue(dateStr + "自考全国统考课程命审题分工表");
				cell_tittle.setCellStyle(tittleStyle);
				CellRangeAddress range1 = new CellRangeAddress(0, 0, 0, 6);
				sheetByCourse.addMergedRegion(range1);
				
				XSSFRow row1 = sheetByCourse.createRow(1);
				XSSFCell ce0 = row1.createCell(0);
		        ce0.setCellValue("序号");
		        ce0.setCellStyle(border_th);
		        XSSFCell ce1 = row1.createCell(1);
		        ce1.setCellValue("课程代码");
		        ce1.setCellStyle(border_th);
		        XSSFCell ce2 = row1.createCell(2);
		        ce2.setCellValue("课程名称");
		        ce2.setCellStyle(border_th);
		        XSSFCell ce3 = row1.createCell(3);
		        ce3.setCellValue("命题教师");
		        ce3.setCellStyle(border_th);
		        XSSFCell ce4 = row1.createCell(4);
		        ce4.setCellValue("学科联系人");
		        ce4.setCellStyle(border_th);
		        XSSFCell ce5 = row1.createCell(5);
		        ce5.setCellValue("互校人");
		        ce5.setCellStyle(border_th);
		        XSSFCell ce6 = row1.createCell(6);
		        ce6.setCellValue("排版人");
		        ce6.setCellStyle(border_th);
			}
			{
				List<Map<String,Object>> dataList = dao.getList("getMTSTFGBList", batchId);
				List<MergeInfo> mergeList = buildFGBGroupByList(dataList);
				for(int i=0;i<dataList.size();i++){
					Map<String,Object> data = dataList.get(i);
					XSSFRow row = sheetByCourse.createRow(2 + i);
					XSSFCell ce0 = row.createCell(0);
					XSSFCell ce1 = row.createCell(1);
					XSSFCell ce2 = row.createCell(2);
					XSSFCell ce3 = row.createCell(3);
					XSSFCell ce4 = row.createCell(4);
					XSSFCell ce5 = row.createCell(5);
					XSSFCell ce6 = row.createCell(6);
					
					ce0.setCellStyle(border_str);
			        ce1.setCellStyle(border_str);
			        ce2.setCellStyle(border_str);
			        ce3.setCellStyle(border_str);
			        ce4.setCellStyle(border_str);
			        ce5.setCellStyle(border_str);
			        ce6.setCellStyle(border_str);
			        
			        ce0.setCellValue(General.null2String(i + 1));
			        ce1.setCellValue(General.null2String(data.get("kcdm")));
			        ce2.setCellValue(General.null2String(data.get("kcmc")));
					ce3.setCellValue(General.null2String(data.get("proposition_teacher")));//命题教师
					ce4.setCellValue(General.null2String(data.get("assistant_secretary")));//学科联系人 
					ce5.setCellValue(General.null2String(data.get("primary_secretary")));//互校人
					ce6.setCellValue(General.null2String(data.get("typesetter")));//排版人
				}
				//合并
				for (MergeInfo merge : mergeList) {
					System.err.println(merge.getType() + " , " + merge.getName() + " , " + merge.getFirst_row() + " , " + merge.getLast_row() + " , " + merge.getFirst_col() + " , " + merge.getLast_col());
					CellRangeAddress range1 = new CellRangeAddress(merge.getFirst_row(), merge.getLast_row(), merge.getFirst_col(), merge.getLast_col());
					sheetByCourse.addMergedRegion(range1);
				}
			}
  		}
  		
		File xlsFile = General.newTmpFile();
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(xlsFile);
			workbook.write(fos);
		} catch (Exception e) {
			throw new RuntimeException("写入Excel数据到临时文件：" + xlsFile.getAbsolutePath() + "中失败，原因：" + e.getMessage(), e);
		} finally{
			General.close(fos);
		}
		File newFile = General.newAttFile();
		xlsFile.renameTo(newFile);
		Attachment att = new Attachment();
		att.setCreatedBy(curUser.getId());
		att.setOriginalName("命题学科联系人分工表_" + DateHelper.getNow(DateHelper.shortSimpleDateFormatWithoutSplit) + ".xls");
		att.setCurName(newFile.getName());
		att.setFileLength(newFile.length());
		att.setStorePath(newFile.getAbsolutePath());
		att.setStatus(Consts.AttachmentStatus.DRAFT);
		dao.insert("addAttachment", att);
		return att;
	}
	
	/**
	 * 导出复审任务附件
	 * @param batchId
	 * @param curUser
	 * @return
	 */
	public Attachment exportReviewFiles(int batchId,User curUser){
		TaskBatch tb = dao.get("findTaskBatchById", batchId);
		if(tb == null){
			throw new RuntimeException("任务批次信息不存在");
		}
		Attachment expAtt = new Attachment();
		List<Map<String,Object>> allPaperInfos = dao.getList("findAllPaperFilesByBatchId",batchId);
		OutputStream fos = null;
		ZipOutputStream zos = null;
		try{
			File newFile = General.newTmpFile();
            fos = new FileOutputStream(newFile);
            zos = new ZipOutputStream(fos);
			for(Map<String,Object> info:allPaperInfos){
				String paperName = (String)info.get("paperName");
//				int paperWord = General.toInteger(info.get("paperWord"), 0);
				int answerWord = General.toInteger(info.get("answerWord"), 0);
				int wangpingWord = General.toInteger(info.get("wangpingWord"), 0);
//				int tikaWord = General.toInteger(info.get("tikaWord"), 0);
				String tikaType = (String)info.get("tikaType");
				int lastZhuanyinWord = General.toInteger(info.get("lastZhuanyinWord"), 0);
				if(answerWord != 0){
					Attachment att = dao.get("getAttachmentById", answerWord);
					if(att != null){
						File file = new File(att.getStorePath());
		            	FileInputStream fis = null;
		            	if(file.exists()){
		            		try{
		    					fis = new FileInputStream(file);
		    					String fileName = att.getOriginalName();
		    					if(fileName.contains(".")){
		    						fileName = paperName + 'N' + fileName.substring(fileName.lastIndexOf('.'));
		    					}else{
		    						fileName = paperName + "N.docx";
		    					}
		                		zos.putNextEntry(new ZipEntry(paperName + "/" + fileName));
		    					IOUtils.copyLarge(fis, zos);
								zos.flush();
		    				}finally{
		    					General.close(fis);
		    				}
		            	}
					}
				}
				if(wangpingWord != 0){
					Attachment att = dao.get("getAttachmentById", wangpingWord);
					if(att != null){
						File file = new File(att.getStorePath());
						FileInputStream fis = null;
						if(file.exists()){
							try{
								fis = new FileInputStream(file);
								String fileName = att.getOriginalName();
								if(fileName.contains(".")){
									fileName = paperName + 'W' + fileName.substring(fileName.lastIndexOf('.'));
								}else{
									fileName = paperName + "W.docx";
								}
								zos.putNextEntry(new ZipEntry(paperName + "/" + fileName));
								IOUtils.copyLarge(fis, zos);
								zos.flush();
							}finally{
								General.close(fis);
							}
						}
					}
				}
				/**
				if(tikaWord != 0){
					Attachment att = dao.get("getAttachmentById", tikaWord);
					if(att != null){
						File file = new File(att.getStorePath());
						FileInputStream fis = null;
						if(file.exists()){
							try{
								fis = new FileInputStream(file);
								String fileName = att.getOriginalName();
								if(fileName.contains(".")){
									fileName = paperName +"TK"+fileName.substring(fileName.lastIndexOf('.'));
								}else{
									fileName = paperName + ".cdr";
								}
								zos.putNextEntry(new ZipEntry(paperName + "/" + fileName));
								IOUtils.copyLarge(fis, zos);
								zos.flush();
							}finally{
								General.close(fis);
							}
						}
					}
				}
				**/
				if(Consts.TikaType.SPECIAL.equals(tikaType) && lastZhuanyinWord != 0){
					Attachment att = dao.get("getAttachmentById", lastZhuanyinWord);
					if(att != null){
						File file = new File(att.getStorePath());
		            	FileInputStream fis = null;
		            	if(file.exists()){
		            		try{
		    					fis = new FileInputStream(file);
		    					String fileName = att.getOriginalName();
		    					if(fileName.contains(".")){
		    						fileName = paperName + "ZY" + fileName.substring(fileName.lastIndexOf('.'));
		    					}else{
		    						fileName = paperName + "ZY.docx";
		    					}
		                		zos.putNextEntry(new ZipEntry(paperName + "/" + fileName));
		    					IOUtils.copyLarge(fis, zos);
								zos.flush();
		    				}finally{
		    					General.close(fis);
		    				}
		            	}
					}
				}
			}
			zos.closeEntry();
        	General.close(zos);
        	General.close(fos);
        	
        	File destFile = General.newAttFile();
        	newFile.renameTo(destFile);
        	expAtt.setCreatedBy(curUser.getId());
        	expAtt.setOriginalName(tb.getName() + ".zip");
        	expAtt.setCurName(destFile.getName());
        	expAtt.setFileLength(destFile.length());
        	expAtt.setStorePath(destFile.getAbsolutePath());
        	expAtt.setStatus(Consts.AttachmentStatus.DRAFT);
			dao.insert("addAttachment", expAtt);
            
			return expAtt;
        } catch (Exception e) {
        	throw new RuntimeException("附件写入zip压缩文件失败，原因：" + e.getMessage(), e);
        } finally{
        	General.close(zos);
        	General.close(fos);
        }
	}
	
	/**
	 * 保存复审任务数据(原始方法)
	 * @param batchId
	 * @param list
	 * @param object
	 * @param curUser
	 */
	public void saveReviewImportData(int batchId,List<PaperTask> list,JSONObject object,User curUser){
//		TaskBatch taskBatch = taskBatchService.findById(batchId);
//		String name = taskBatch.getName();
		List<String> loginList=new ArrayList<String>();
		Map<String,User> tempMap=new HashMap<String,User>();
		for(Map.Entry<Integer, User> entry : Consts.UserMap.entrySet()){
			tempMap.put(entry.getValue().getName(), entry.getValue());
			loginList.add(entry.getValue().getName());
		}
		boolean isTaskNo = false;
		String taskNoError = "";
		int i=1;
		
		PaperTask paperTask=new PaperTask();
		paperTask.setBatchId(batchId);
		
		List<PaperTask> taskList = new ArrayList<PaperTask>();
		for(PaperTask pt : list){
			pt.setBatchId(batchId);
			List<PaperTask> paperTasks = dao.getList("getPaperTasksByParam", pt);
			if(paperTasks == null || paperTasks.size() == 0){
				isTaskNo = true;
				taskNoError = pt.getTaskNo();
				break;
			}
			
			pt.setId(paperTasks.get(0).getId());
			
			if(!loginList.contains(pt.getAuditTeacherLoginName())){
				//返回前端用户登录名不存在
				object.put("result", "fail");
				object.put("lineNum",i );
				object.put("msg", "命题教师[" + pt.getAuditTeacherLoginName() + "]用户信息不存在");
				return;
			}
			
			if(!loginList.contains(pt.getPrimarySecretaryLoginName())){
				//返回前端用户登录名不存在
				object.put("result", "fail");
				object.put("lineNum",i );
				object.put("msg", "学科秘书[" + pt.getPrimarySecretaryLoginName() + "]用户信息不存在");
				return;
			}
			
			if(!loginList.contains(pt.getTypesetterLoginName())){
				//返回前端用户登录名不存在
				object.put("result", "fail");
				object.put("lineNum",i );
				object.put("msg", "排版员[" + pt.getTypesetterLoginName() + "]用户信息不存在");
				return;
			}
			
			taskList.add(pt);
			
			i++;
		}
		
		if(isTaskNo){
			object.put("result", "fail");
			object.put("lineNum",i);
			object.put("msg", "导入的文件任务单编号" + taskNoError + "不存在!");
		}else{
			int j = 0;
			for(PaperTask pt:list){
//				pt.setPropositionTeacher(tempMap.get(pt.getPropositionLoginName()).getId());
				pt.setAuditTeacher(tempMap.get(pt.getAuditTeacherLoginName()).getId());
				pt.setPrimarySecretary(tempMap.get(pt.getPrimarySecretaryLoginName()).getId());
//				pt.setAssistantSecretary(tempMap.get(pt.getAssistantSecretaryLoginName()).getId());
				pt.setTypesetter(tempMap.get(pt.getTypesetterLoginName()).getId());
				
//				String taskNo = pt.getTaskNo();
//				pt.setTaskNo(taskNo);
//				pt.setTitle(taskNo);
//				pt.setPaperName(taskNo);
//				pt.setBatchId(batchId);
////				pt.setBookId(bookId);
//				pt.setPlanStartTime(taskBatch.getPlanStartTime());
//				pt.setPlanEndTime(taskBatch.getPlanEndTime());
				
				pt.setStatus(ReviewTaskStatus.TO_AUDIT_PAPER);
				pt.setCreatedBy(curUser.getId());
				pt.setCreatedTime(new Date());
				pt.setUpdatedBy(curUser.getId());
				pt.setUpdatedTime(new Date());
				
				pt.setCurDealer(tempMap.get(pt.getAuditTeacherLoginName()).getId());				
//				List<Book> ls=bookService.findBooks(pt.getCourseCode());
//				Course course=courseService.findByCode(pt.getCourseCode());
				
//				pt.setCourseId(course.getId());
//				addReviewTask(pt);
				dao.update("updatePaperTask", pt);
				messageService.saveMessage(pt.getId(), pt.getAuditTeacher(), curUser);
				
//				PagerConstruct pager = new PagerConstruct();
//		    	pager.setTaskId(paperTask.getId());
//		    	pager.setName(paperTask.getTaskNo());
//		    	String head = Consts.DEFAULT_HEAD.replace("XXXX", DateHelper.formatDate(new Date(),"yyyy")).replace("XX", DateHelper.formatDate(new Date(),"M"));
//		    	pager.setHead(head);
////		    	pager.setSkeletonId(skel.getId());
//		    	pager.setResourse(2);//智能组卷
//		    	pager.setStatus(Consts.PaperStatus.DRAFT);//草稿
//		    	pager.setCreatedBy(curUser.getId());
		    	
//		    	dao.insert("addPagerConstruct", pager);
				
				j ++;
			}
			if(object.isEmpty()){
				object.put("result", "success");
				object.put("successNum", j);
				object.put("msg", "导入成功!");
			}
		}
	}
	
	/**
	 * 保存复审任务数据
	 * @param batchId
	 * @param list
	 * @param object
	 * @param curUser
	 */
	public void saveReviewImportDataNew(int batchId,List<PaperTask> list,JSONObject object,User curUser){
//		TaskBatch taskBatch = taskBatchService.findById(batchId);
//		String name = taskBatch.getName();
		List<String> loginList=new ArrayList<String>();
		Map<String,User> tempMap=new HashMap<String,User>();
		for(Map.Entry<Integer, User> entry : Consts.UserMap.entrySet()){
			tempMap.put(entry.getValue().getName(), entry.getValue());
			loginList.add(entry.getValue().getName());
		}
		boolean isTaskNo = false;
		//flag用于判断新增、修改，flag=true，则新增，flag=false 则修改；
		boolean flag = false; 
		String taskNoError = "";
		int i=1;
		
		PaperTask paperTask=new PaperTask();
		paperTask.setBatchId(batchId);
		
		List<PaperTask> taskList = new ArrayList<PaperTask>();
		for(PaperTask pt : list){
			pt.setBatchId(batchId);
			//查询该批次是否存在对应数据     
			List<PaperTask> paperTasks = dao.getList("getPaperTasksByParam", pt);
			if(paperTasks == null || paperTasks.size() == 0){
				PaperTask pTask = new PaperTask();
				pTask.setTaskNo(pt.getTaskNo());
				pTask.setStatus(Consts.PaperTaskStatus.ARCHIVED); //试卷状态为【归档】
				//通过试卷编号和试卷归档状态查询试卷是否存在,不存在则返回到前端 ,存在则新增 
				List<PaperTask> paperTasksTaskNo = dao.getList("getPaperTasksByParam", pTask);
				if(paperTasksTaskNo == null || paperTasksTaskNo.size() == 0) {
					isTaskNo = true;
					taskNoError = pt.getTaskNo();
					break;
				}else {
					flag = true; 
				}
			}else {
				pt.setId(paperTasks.get(0).getId());
			}
			
			
			if(!loginList.contains(pt.getAuditTeacherLoginName())){
				//返回前端用户登录名不存在
				object.put("result", "fail");
				object.put("lineNum",i );
				object.put("msg", "命题教师[" + pt.getAuditTeacherLoginName() + "]用户信息不存在");
				return;
			}
			
			if(!loginList.contains(pt.getPrimarySecretaryLoginName())){
				//返回前端用户登录名不存在
				object.put("result", "fail");
				object.put("lineNum",i );
				object.put("msg", "学科秘书[" + pt.getPrimarySecretaryLoginName() + "]用户信息不存在");
				return;
			}
			
			if(!loginList.contains(pt.getTypesetterLoginName())){
				//返回前端用户登录名不存在
				object.put("result", "fail");
				object.put("lineNum",i );
				object.put("msg", "排版员[" + pt.getTypesetterLoginName() + "]用户信息不存在");
				return;
			}
			
			taskList.add(pt);
			
			i++;
		}
		
		if(isTaskNo){
			object.put("result", "fail");
			object.put("lineNum",i);
			object.put("msg", "导入的文件任务单编号" + taskNoError + "不存在或者未归档!");
		}else{
			int j = 0;
			for(PaperTask pt:list){
//				pt.setPropositionTeacher(tempMap.get(pt.getPropositionLoginName()).getId());
				pt.setAuditTeacher(tempMap.get(pt.getAuditTeacherLoginName()).getId());
				pt.setPrimarySecretary(tempMap.get(pt.getPrimarySecretaryLoginName()).getId());
//				pt.setAssistantSecretary(tempMap.get(pt.getAssistantSecretaryLoginName()).getId());
				pt.setTypesetter(tempMap.get(pt.getTypesetterLoginName()).getId());
				
//				String taskNo = pt.getTaskNo();
//				pt.setTaskNo(taskNo);
//				pt.setTitle(taskNo);
//				pt.setPaperName(taskNo);
//				pt.setBatchId(batchId);
////				pt.setBookId(bookId);
//				pt.setPlanStartTime(taskBatch.getPlanStartTime());
//				pt.setPlanEndTime(taskBatch.getPlanEndTime());
				
				pt.setStatus(ReviewTaskStatus.TO_AUDIT_PAPER);
				pt.setCreatedBy(curUser.getId());
				pt.setCreatedTime(new Date());
				pt.setUpdatedBy(curUser.getId());
				pt.setUpdatedTime(new Date());
				
				pt.setCurDealer(tempMap.get(pt.getAuditTeacherLoginName()).getId());				
//				List<Book> ls=bookService.findBooks(pt.getCourseCode());
//				Course course=courseService.findByCode(pt.getCourseCode());
				
//				pt.setCourseId(course.getId());
//				addReviewTask(pt);
				if(flag) {
					List<User> usersList = new ArrayList<User>();
					
					User user1 = tempMap.get(pt.getAuditTeacherLoginName());
					User user2 = tempMap.get(pt.getPrimarySecretaryLoginName());
					User user3 = tempMap.get(pt.getTypesetterLoginName());
					usersList.add(user1);
					usersList.add(user2);
					usersList.add(user3);
					
					addReviewTaskTwo(batchId,pt.getTaskNo(),usersList,curUser);
					
				}else {
					dao.update("updatePaperTask", pt);
					messageService.saveMessage(pt.getId(), pt.getAuditTeacher(), curUser);
				}
				
				
				
//				PagerConstruct pager = new PagerConstruct();
//		    	pager.setTaskId(paperTask.getId());
//		    	pager.setName(paperTask.getTaskNo());
//		    	String head = Consts.DEFAULT_HEAD.replace("XXXX", DateHelper.formatDate(new Date(),"yyyy")).replace("XX", DateHelper.formatDate(new Date(),"M"));
//		    	pager.setHead(head);
////		    	pager.setSkeletonId(skel.getId());
//		    	pager.setResourse(2);//智能组卷
//		    	pager.setStatus(Consts.PaperStatus.DRAFT);//草稿
//		    	pager.setCreatedBy(curUser.getId());
		    	
//		    	dao.insert("addPagerConstruct", pager);
				
				j ++;
			}
			if(object.isEmpty()){
				object.put("result", "success");
				object.put("successNum", j);
				object.put("msg", "导入成功!");
			}
		}
	}
	
	/**
	 *   导入试卷复审任务
	 * @param batchId
	 * @param taskNo
	 * @param users
	 * @param curUser
	 * @return
	 */
	public Map<String, Object> addReviewTaskTwo(int batchId, String taskNo, List<User> users, User curUser){
		Map<String, Object> result = new HashMap<String, Object>();
		
		PaperTask paperTask = new PaperTask();
		
		TaskBatch taskBatch = taskBatchService.findById(batchId);
		//设置批次信息
		paperTask.setBatchId(batchId);
		paperTask.setPlanStartTime(taskBatch.getPlanStartTime());
		paperTask.setPlanEndTime(taskBatch.getPlanEndTime());
		paperTask.setBatchId(batchId);
		paperTask.setPlanStartTime(taskBatch.getPlanStartTime());
		paperTask.setPlanEndTime(taskBatch.getPlanEndTime());
		
				
		//设置任务编号		
		paperTask.setTaskNo(taskNo);
		paperTask.setTitle(taskNo);
		paperTask.setPaperName(taskNo);
		
		//设置相关人员
//		paperTaskA.setPropositionTeacher(users.get(0).getId());
//		paperTaskA.setPropositionLoginName(users.get(0).getLoginName());
		paperTask.setAuditTeacher(users.get(0).getId());
		paperTask.setAuditTeacherLoginName(users.get(0).getLoginName());
		paperTask.setPrimarySecretary(users.get(1).getId());
		paperTask.setPrimarySecretaryLoginName(users.get(1).getLoginName());
//		paperTaskA.setAssistantSecretary(users.get(3).getId());
//		paperTaskA.setAssistantSecretaryLoginName(users.get(3).getLoginName());
		paperTask.setTypesetter(users.get(2).getId());
		paperTask.setTypesetterLoginName(users.get(2).getLoginName());
		
		//设置状态等
		paperTask.setStatus(ReviewTaskStatus.TO_AUDIT_PAPER);
		paperTask.setCreatedBy(curUser.getId());
		paperTask.setCreatedTime(new Date());
		paperTask.setUpdatedBy(curUser.getId());
		paperTask.setUpdatedTime(new Date());
		paperTask.setCurDealer(users.get(0).getId());
		
		dao.insert("addReviewTask", paperTask);
		messageService.saveMessage(paperTask.getId(), users.get(0).getId(), curUser);
		
		PagerConstruct pager = new PagerConstruct();

		//获取入闱命题批次的试卷信息
		PaperTask paperParam = new PaperTask();
		paperParam.setBatchType("RU_WEI_MING_TI");
		paperParam.setTaskNo(paperTask.getTaskNo());
		List<PaperTask> tempTasks = queryPaperTaskByParam(paperParam);
		PagerConstruct tempPaper = queryPagerConstructByTaskId(tempTasks.get(0).getId());

    	pager.setTaskId(paperTask.getId());
    	pager.setName(paperTask.getTaskNo());
    	String head = Consts.DEFAULT_HEAD.replace("XXXX", DateHelper.formatDate(new Date(),"yyyy")).replace("XX", DateHelper.formatDate(new Date(),"M"));
    	pager.setHead(head);
//    	pager.setSkeletonId(skel.getId());
    	pager.setResourse(2);//智能组卷
    	pager.setStatus(Consts.PaperStatus.DRAFT);//草稿
    	pager.setCreatedBy(curUser.getId());
		pager.setLastPaperWord(tempPaper.getLastPaperWord());
		pager.setLastAnswerWord(tempPaper.getLastAnswerWord());
		pager.setLastTikaWord(tempPaper.getLastTikaWord());
		pager.setLastWangpingWord(tempPaper.getLastWangpingWord());
		pager.setTikaType(tempPaper.getTikaType());
		pager.setLastZhuanyinWord(tempPaper.getLastZhuanyinWord());
    	
    	dao.insert("addPagerConstruct", pager);
		
		return result;
	}
	
	/**
	 * 获取试卷中的转印说明AttId，如果没有，就使用转印说明模板，并保存到试卷信息里面
	 * @param index
	 * @param taskId
	 * @param paperId
	 * @param curUser
	 */
    public Integer getZhuanyinAtt(int index, int taskId, User curUser){
    	PaperTask task = dao.get("getPaperTaskById", taskId);
    	PagerConstruct paper = dao.get("findPagerConstructByTaskId", taskId);
    	if (index == 1) {
    		saveZhuanyinAtt1(task, paper, curUser);
    		return paper.getLastZhuanyinWord();
    	} else if (index == 2) {
    		saveZhuanyinAtt2(task, paper, curUser);
    		return paper.getLastZhuanyinWord2();
    	}
    	return 0;
    }
    
    //转印附件一
    private void saveZhuanyinAtt1(final PaperTask task, final PagerConstruct paper, final User curUser) {
    	if(paper.getLastZhuanyinWord() == null){
    		//zhuanyinTmp.docx
    		File newFile = General.newAttFile();
    		FileOutputStream docxFos = null;
    		InputStream contentIs = null;
    		FileOutputStream contentFos = null;
    		DocxReader templetDocxReader = null;
    		Map<String, ResourceInfo> needToUpdate = new HashMap<String, ResourceInfo>();
    		try {
    			docxFos = new FileOutputStream(newFile);
    			IOUtils.copyLarge(PaperTaskServiceImpl.class.getResourceAsStream("/paperTmps/zhuanyinTmp.docx"), docxFos);
    			docxFos.flush();
    			General.close(docxFos);
    			docxFos = null;
    			templetDocxReader = new DocxReader(newFile);
                templetDocxReader.doRead();
                File document = templetDocxReader.getDocumentInfo().getFile();
                contentIs = new FileInputStream(document);
                String docStr = IOUtils.toString(contentIs, "UTF-8");
                General.close(contentIs);
                contentIs = null;
                docStr = docStr.replace("courseCode", task.getCourse().getCode())
                				.replace("courseName", task.getCourse().getName());
                contentFos = new FileOutputStream(document, false);
                IOUtils.write(docStr, contentFos, "UTF-8");
                General.close(contentFos);
                contentFos = null;
                needToUpdate.put(templetDocxReader.getDocumentInfo().getPathInZip(),
                        templetDocxReader.getDocumentInfo());
                DocxReader.updateDocx(newFile, needToUpdate);
			} catch (Exception e) {
				log.error("读取转印说明模板附件一：/zhuanyinTmp.docx失败，原因：" + e.getMessage(),e);
				throw new RuntimeException("读取转印说明模板文件：/zhuanyinTmp.docx失败，原因：" + e.getMessage(),e);
			} finally{
				General.close(contentIs);
				General.close(contentFos);
				General.close(docxFos);
				General.release(templetDocxReader);
			}
    		Attachment att = new Attachment();
    		att.setCreatedBy(curUser.getId());
    		att.setOriginalName(task.getTaskNo() + "转印说明附件一.docx");
    		att.setCurName(newFile.getName());
    		att.setFileLength(newFile.length());
    		att.setStorePath(newFile.getAbsolutePath());
    		att.setStatus(Consts.AttachmentStatus.USING);
    		dao.insert("addAttachment", att);
    		
    		paper.setLastZhuanyinWord(att.getId());
    		dao.update("updateZhuanyin", paper);
    	}
    }
    //转印附件二
    @Deprecated
    private void saveZhuanyinAtt2(final PaperTask task, final PagerConstruct paper, final User curUser) {
    	if(paper.getLastZhuanyinWord2() == null){
    		//zhuanyinTmp.docx
    		File newFile = General.newAttFile();
    		FileOutputStream docxFos = null;
    		InputStream contentIs = null;
    		FileOutputStream contentFos = null;
    		DocxReader templetDocxReader = null;
    		Map<String, ResourceInfo> needToUpdate = new HashMap<String, ResourceInfo>();
    		try {
    			docxFos = new FileOutputStream(newFile);
    			IOUtils.copyLarge(PaperTaskServiceImpl.class.getResourceAsStream("/paperTmps/zhuanyinTmp2.docx"), docxFos);
    			docxFos.flush();
    			General.close(docxFos);
    			docxFos = null;
    			templetDocxReader = new DocxReader(newFile);
                templetDocxReader.doRead();
                File document = templetDocxReader.getDocumentInfo().getFile();
                contentIs = new FileInputStream(document);
                String docStr = IOUtils.toString(contentIs, "UTF-8");
                General.close(contentIs);
                contentIs = null;
                docStr = docStr.replace("courseCode", task.getCourse().getCode())
                				.replace("courseName", task.getCourse().getName());
                contentFos = new FileOutputStream(document, false);
                IOUtils.write(docStr, contentFos, "UTF-8");
                General.close(contentFos);
                contentFos = null;
                needToUpdate.put(templetDocxReader.getDocumentInfo().getPathInZip(),
                        templetDocxReader.getDocumentInfo());
                DocxReader.updateDocx(newFile, needToUpdate);
			} catch (Exception e) {
				log.error("读取转印说明模板附件二：/zhuanyinTmp2.docx失败，原因：" + e.getMessage(),e);
				throw new RuntimeException("读取转印说明模板文件：/zhuanyinTmp2.docx失败，原因：" + e.getMessage(),e);
			} finally{
				General.close(contentIs);
				General.close(contentFos);
				General.close(docxFos);
				General.release(templetDocxReader);
			}
    		Attachment att = new Attachment();
    		att.setCreatedBy(curUser.getId());
    		att.setOriginalName(task.getTaskNo() + "转印说明附件二.docx");
    		att.setCurName(newFile.getName());
    		att.setFileLength(newFile.length());
    		att.setStorePath(newFile.getAbsolutePath());
    		att.setStatus(Consts.AttachmentStatus.USING);
    		dao.insert("addAttachment", att);
    		
    		paper.setLastZhuanyinWord2(att.getId());
    		dao.update("updateZhuanyin", paper);
    	}
    }
    
    public void saveTikaCfg(int taskId,int paperId, String tikaType, User curUser){
    	TaskFlowLog flowLog = new TaskFlowLog();
		flowLog.setCreatedBy(curUser.getId());
    	
    	PagerConstruct paper = new PagerConstruct();
    	paper.setId(paperId);
    	paper.setTikaType(tikaType);
    	paper.setUpdatedBy(curUser.getId());
    	dao.update("updateTikaCfg", paper);
    	
    	if(Consts.TikaType.SPECIAL.equals(tikaType)){
    		flowLog.setOperName("设置题卡类型为专用题卡");
    		getZhuanyinAtt(0, taskId, curUser);
    	}else{
    		flowLog.setOperName("设置题卡类型为通用题卡");
    		paper.setLastZhuanyinWord(null);
    		dao.update("updateZhuanyin", paper);
    	}
		flowLog.setTaskId(taskId);
		flowLog.setTaskType(Consts.TaskBatchType.RU_WEI_MING_TI);
		dao.insert("addTaskFlowLog", flowLog);
    }
	
    /**
     * 查询已启用试卷的数据
     * @param params
     * @return
     */
	public List<Map<String,Object>> queryStartedPapers(QueryParams params){
		return dao.getPagerList("queryStartedPapers", params);
	}
	
	/**
	 * 导入试卷启用数据
	 * @param attId 上传的数据文件
	 * @param startTime 启用时间
	 * @return
	 */
	public StringBuffer impStartedPapers(int attId,String startTime){
		StringBuffer msg = new StringBuffer("");
		Attachment att = dao.get("getAttachmentById", attId);
		InputStream is = null;
		int successCount = 0;
		int faildCount = 0;
		try {
			is = new FileInputStream(att.getStorePath());
			List<ImportBean> list = new ExcelOperate().readStartedPaperExcel(is, att.getOriginalName());
			LinkedHashSet<String> paperCodeSet = new LinkedHashSet<String>();
			for(ImportBean bean:list){
				paperCodeSet.add(bean.getName());
			}
			for(String paperCode:paperCodeSet){
				List<PagerConstruct> paperList = dao.getList("getReviewPaperByPaperCode", paperCode);
				if(paperList == null || paperList.size() == 0){
					msg.append(paperCode + "不存在或者没有复审过；");
					faildCount++;
				}else if(paperList.get(0).getStartTime() != null) {
					msg.append(paperCode + "已启用过，不能重复启用；");
					faildCount++;
				}else{
					paperService.saveOpenPaper(paperCode, startTime);
					successCount++;
				}
			}
		} catch (Exception e) {
			log.error("导入试卷启用数据失败，原因：" + e.getMessage(),e);
			msg.append("导入试卷启用数据失败，原因：" + e.getMessage());
		} finally{
			General.close(is);
		}
		msg.append("加载完成，" + successCount + "条成功，" + faildCount + "条失败。");
		return msg;
	}
	
	public static void main(String[] args) {
		XSSFWorkbook workbook = new XSSFWorkbook();
		//TaskBatch batch = this.taskBatchService.findById(batchId);
		TaskBatch batch = new TaskBatch();batch.setPlanStartTime(new Date());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月");
		// 生成一个字体
		XSSFFont tittleFont = workbook.createFont();
	    tittleFont.setColor(HSSFColor.BLACK.index);
	    tittleFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
	    tittleFont.setFontHeightInPoints((short)16);
	    // 生成一个字体
	    XSSFFont normalFont1 = workbook.createFont();
	    normalFont1.setColor(HSSFColor.BLACK.index);
		
		// 生成一个字体
	    XSSFFont normalFont2 = workbook.createFont();
	    normalFont2.setColor(HSSFColor.BLACK.index);
	    normalFont2.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
	    
	    //标题
  		XSSFCellStyle tittleStyle = workbook.createCellStyle();
  		tittleStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
  		tittleStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
  		tittleStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
  		tittleStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
  		tittleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  		tittleStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
  		tittleStyle.setWrapText(false);
  		tittleStyle.setFont(tittleFont);
	    
	    //标题边框，粗体，居中对齐，不可换行
  		XSSFCellStyle border_th = workbook.createCellStyle();
  		border_th.setBorderTop(HSSFCellStyle.BORDER_THIN);
  		border_th.setBorderBottom(HSSFCellStyle.BORDER_THIN);
  		border_th.setBorderLeft(HSSFCellStyle.BORDER_THIN);
  		border_th.setBorderRight(HSSFCellStyle.BORDER_THIN);
  		border_th.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  		border_th.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
  		border_th.setWrapText(false);
  		border_th.setFont(normalFont2);
	    
	    //普通字符边框，居左对齐，可换行
  		XSSFCellStyle border_str = workbook.createCellStyle();
  		border_str.setBorderTop(HSSFCellStyle.BORDER_THIN);
  		border_str.setBorderBottom(HSSFCellStyle.BORDER_THIN);
  		border_str.setBorderLeft(HSSFCellStyle.BORDER_THIN);
  		border_str.setBorderRight(HSSFCellStyle.BORDER_THIN);
  		border_str.setAlignment(HSSFCellStyle.ALIGN_LEFT);
  		border_str.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
  		border_str.setWrapText(true);
  		border_str.setFont(normalFont1);
	    
  		{
  			XSSFSheet sheetByCourse = workbook.createSheet("联系人分工表");
			sheetByCourse.setColumnWidth(0, 1000);
			sheetByCourse.setColumnWidth(1, 3000);
			sheetByCourse.setColumnWidth(2, 3000);
			sheetByCourse.setColumnWidth(3, 5000);
			sheetByCourse.setColumnWidth(4, 5000);
			sheetByCourse.setColumnWidth(5, 3000);
			sheetByCourse.setColumnWidth(6, 3000);
			{
				XSSFRow row0 = sheetByCourse.createRow(0);
				XSSFCell cell_tittle = row0.createCell(0);
		        String dateStr = sdf.format(batch.getPlanStartTime());
				cell_tittle.setCellValue(dateStr + "自考全国统考课程命审题分工表");
				cell_tittle.setCellStyle(tittleStyle);
				CellRangeAddress range1 = new CellRangeAddress(0, 0, 0, 6);
				sheetByCourse.addMergedRegion(range1);
				
				XSSFRow row1 = sheetByCourse.createRow(1);
				XSSFCell ce0 = row1.createCell(0);
		        ce0.setCellValue("序号");
		        ce0.setCellStyle(border_th);
		        XSSFCell ce1 = row1.createCell(1);
		        ce1.setCellValue("课程代码");
		        ce1.setCellStyle(border_th);
		        XSSFCell ce2 = row1.createCell(2);
		        ce2.setCellValue("课程名称");
		        ce2.setCellStyle(border_th);
		        XSSFCell ce3 = row1.createCell(3);
		        ce3.setCellValue("命题教师");
		        ce3.setCellStyle(border_th);
		        XSSFCell ce4 = row1.createCell(4);
		        ce4.setCellValue("学科联系人");
		        ce4.setCellStyle(border_th);
		        XSSFCell ce5 = row1.createCell(5);
		        ce5.setCellValue("互校人");
		        ce5.setCellStyle(border_th);
		        XSSFCell ce6 = row1.createCell(6);
		        ce6.setCellValue("排版人");
		        ce6.setCellStyle(border_th);
			}
			{
				//List<Map<String,Object>> dataList = dao.getList("getMTSTFGBList", batchId);
				List<Map<String,Object>> dataList = new ArrayList<Map<String,Object>>();
				Map<String, Object> map1 = new HashMap<String, Object>();
				map1.put("kcdm", "02158");
				map1.put("kcmc", "市场营销");
				map1.put("proposition_teacher", "严奉志1");//命题教师
				map1.put("assistant_secretary", "杨武");//学科联系人
				map1.put("primary_secretary", "梁玉笛");//互校人
				map1.put("typesetter", "周鑫");//排版人
				
				Map<String, Object> map2 = new HashMap<String, Object>();
				map2.put("kcdm", "02158");
				map2.put("kcmc", "市场营销");
				map2.put("proposition_teacher", "严奉志2");//命题教师
				map2.put("assistant_secretary", "杨武");//学科联系人
				map2.put("primary_secretary", "梁玉笛");//互校人
				map2.put("typesetter", "周鑫");//排版人
				
				Map<String, Object> map3 = new HashMap<String, Object>();
				map3.put("kcdm", "07310");
				map3.put("kcmc", "外交技巧");
				map3.put("proposition_teacher", "严奉志3");//命题教师
				map3.put("assistant_secretary", "杨武");//学科联系人
				map3.put("primary_secretary", "梁玉笛");//互校人
				map3.put("typesetter", "周鑫");//排版人
				
				Map<String, Object> map4 = new HashMap<String, Object>();
				map4.put("kcdm", "07310");
				map4.put("kcmc", "外交技巧");
				map4.put("proposition_teacher", "严奉志4");//命题教师
				map4.put("assistant_secretary", "杨武");//学科联系人
				map4.put("primary_secretary", "梁玉笛");//互校人
				map4.put("typesetter", "周鑫");//排版人
				
				Map<String, Object> map41 = new HashMap<String, Object>();
				map41.put("kcdm", "07310");
				map41.put("kcmc", "外交技巧");
				map41.put("proposition_teacher", "严奉志41");//命题教师
				map41.put("assistant_secretary", "杨武");//学科联系人
				map41.put("primary_secretary", "梁玉笛");//互校人
				map41.put("typesetter", "周鑫");//排版人
				
				Map<String, Object> map5 = new HashMap<String, Object>();
				map5.put("kcdm", "09667");
				map5.put("kcmc", "高等数学");
				map5.put("proposition_teacher", "严奉志5");//命题教师
				map5.put("assistant_secretary", "柳佳崎");//学科联系人
				map5.put("primary_secretary", "杨威");//互校人
				map5.put("typesetter", "周鑫");//排版人
				
				Map<String, Object> map6 = new HashMap<String, Object>();
				map6.put("kcdm", "09667");
				map6.put("kcmc", "高等数学");
				map6.put("proposition_teacher", "严奉志6");//命题教师
				map6.put("assistant_secretary", "柳佳崎");//学科联系人
				map6.put("primary_secretary", "杨威");//互校人
				map6.put("typesetter", "周鑫");//排版人
				
				dataList.add(map1);dataList.add(map2);dataList.add(map3);dataList.add(map4);dataList.add(map41);
				dataList.add(map5);dataList.add(map6);
				List<MergeInfo> mergeList = buildFGBGroupByList(dataList);
				for(int i=0;i<dataList.size();i++){
					Map<String,Object> data = dataList.get(i);
					XSSFRow row = sheetByCourse.createRow(2 + i);
					XSSFCell ce0 = row.createCell(0);
					XSSFCell ce1 = row.createCell(1);
					XSSFCell ce2 = row.createCell(2);
					XSSFCell ce3 = row.createCell(3);
					XSSFCell ce4 = row.createCell(4);
					XSSFCell ce5 = row.createCell(5);
					XSSFCell ce6 = row.createCell(6);
					
					ce0.setCellStyle(border_str);
			        ce1.setCellStyle(border_str);
			        ce2.setCellStyle(border_str);
			        ce3.setCellStyle(border_str);
			        ce4.setCellStyle(border_str);
			        ce5.setCellStyle(border_str);
			        ce6.setCellStyle(border_str);
			        
			        ce0.setCellValue(General.null2String(i + 1));
			        ce1.setCellValue(General.null2String(data.get("kcdm")));
			        ce2.setCellValue(General.null2String(data.get("kcmc")));
					ce3.setCellValue(General.null2String(data.get("proposition_teacher")));//命题教师
					ce4.setCellValue(General.null2String(data.get("assistant_secretary")));//学科联系人 
					ce5.setCellValue(General.null2String(data.get("primary_secretary")));//互校人
					ce6.setCellValue(General.null2String(data.get("typesetter")));//排版人
				}
				//合并
				for (MergeInfo merge : mergeList) {
					System.err.println(merge.getType() + " , " + merge.getName() + " , " + merge.getFirst_row() + " , " + merge.getLast_row() + " , " + merge.getFirst_col() + " , " + merge.getLast_col());
					CellRangeAddress range1 = new CellRangeAddress(merge.getFirst_row(), merge.getLast_row(), merge.getFirst_col(), merge.getLast_col());
					sheetByCourse.addMergedRegion(range1);
				}
			}
  		}
  		
		File xlsFile = new File("C:\\Users\\hm\\Desktop\\1.xlsx");
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(xlsFile);
			workbook.write(fos);
		} catch (Exception e) {
			throw new RuntimeException("写入Excel数据到临时文件：" + xlsFile.getAbsolutePath() + "中失败，原因：" + e.getMessage(), e);
		} finally{
			General.close(fos);
		}

	
	}
	//签到表合并
	private static List<MergeInfo> builQDBGroupByList(List<Map<String, Object>> dataList) {
		int kcdm_cnt = 1;//课程
		int xklxr_cnt = 1;//学科联系人
		int hjr_cnt = 1;//互校
		int pb_cnt = 1;//排版
		int skiprows = 2;
		List<MergeInfo> mergeList = new ArrayList<MergeInfo>();
		for (int i=0;i<dataList.size();i++) {
			Map<String, Object> data = dataList.get(i);
			if (i >= 1) {
				Map<String, Object> data_pre = dataList.get(i-1);
				//课程代码、课程名称
				if (data_pre.get("kcdm").equals(data.get("kcdm"))) {
					kcdm_cnt ++;
				} else {
					MergeInfo merge = new MergeInfo("kcdm", data_pre.get("kcdm").toString(),
							i - kcdm_cnt + skiprows, i - 1 + skiprows, 1, 1);
					MergeInfo merge2 = new MergeInfo("kcmc", data_pre.get("kcmc").toString(),
							i - kcdm_cnt + skiprows, i - 1 + skiprows, 2, 2);
					mergeList.add(merge);
					mergeList.add(merge2);
					kcdm_cnt = 1;
				}
				//最后一行处理
				if (i == dataList.size() - 1) {
					//课程
					if (kcdm_cnt > 1) {
						MergeInfo merge = new MergeInfo("kcdm", data_pre.get("kcdm").toString(),
								i-kcdm_cnt + 1 + skiprows, i + skiprows, 1, 1);
						MergeInfo merge2 = new MergeInfo("kcmc", data_pre.get("kcmc").toString(),
								i-kcdm_cnt + 1 + skiprows, i + skiprows, 2, 2);
						mergeList.add(merge);
						mergeList.add(merge2);
					}
				}
			}
		}
		return mergeList;
	}
	//分工表合并
	private static List<MergeInfo> buildFGBGroupByList(List<Map<String, Object>> dataList) {
		int kcdm_cnt = 1;//课程
		int xklxr_cnt = 1;//学科联系人
		int hjr_cnt = 1;//互校
		int pb_cnt = 1;//排版
		int skiprows = 2;
		List<MergeInfo> mergeList = new ArrayList<MergeInfo>();
		for (int i=0;i<dataList.size();i++) {
			Map<String, Object> data = dataList.get(i);
			if (i >= 1) {
				Map<String, Object> data_pre = dataList.get(i-1);
				//课程代码、课程名称
				if (data_pre.get("kcdm").equals(data.get("kcdm"))) {
					kcdm_cnt ++;
				} else {
					MergeInfo merge = new MergeInfo("kcdm", data_pre.get("kcdm").toString(),
							i - kcdm_cnt + skiprows, i - 1 + skiprows, 1, 1);
					MergeInfo merge2 = new MergeInfo("kcmc", data_pre.get("kcmc").toString(),
							i - kcdm_cnt + skiprows, i - 1 + skiprows, 2, 2);
					mergeList.add(merge);
					mergeList.add(merge2);
					kcdm_cnt = 1;
				}
				//学科联系人
				if (data_pre.get("assistant_secretary") != null) {
					if (data_pre.get("assistant_secretary").equals(data.get("assistant_secretary"))) {
						xklxr_cnt ++;
					} else {
						MergeInfo merge = new MergeInfo("assistant_secretary", data_pre.get("assistant_secretary").toString(),
								i-xklxr_cnt + skiprows, i-1 + skiprows, 4, 4);
						mergeList.add(merge);
						xklxr_cnt = 1;
					}
				}
				
				//互校人
				if (data_pre.get("primary_secretary") != null) {
					if (data_pre.get("primary_secretary").equals(data.get("primary_secretary"))) {
						hjr_cnt ++;
					} else {
						MergeInfo merge = new MergeInfo("primary_secretary", data_pre.get("primary_secretary").toString(),
								i-hjr_cnt + skiprows, i-1 + skiprows, 5, 5);
						mergeList.add(merge);
						hjr_cnt = 1;
					}
				}
				
				//排版
				if (data_pre.get("typesetter") != null) {
					if (data_pre.get("typesetter").equals(data.get("typesetter"))) {
						pb_cnt ++;
					} else {
						MergeInfo merge = new MergeInfo("typesetter", data_pre.get("typesetter").toString(),
								i-pb_cnt + skiprows, i-1 + skiprows, 6, 6);
						mergeList.add(merge);
						pb_cnt = 1;
					}
				}
				
				//最后一行处理
				if (i == dataList.size() - 1) {
					//课程
					if (kcdm_cnt > 1) {
						MergeInfo merge = new MergeInfo("kcdm", data_pre.get("kcdm").toString(),
								i-kcdm_cnt + 1 + skiprows, i + skiprows, 1, 1);
						MergeInfo merge2 = new MergeInfo("kcmc", data_pre.get("kcmc").toString(),
								i-kcdm_cnt + 1 + skiprows, i + skiprows, 2, 2);
						mergeList.add(merge);
						mergeList.add(merge2);
					}
					//学科联系人
					if (xklxr_cnt > 1) {
						MergeInfo merge3 = new MergeInfo("assistant_secretary", data_pre.get("assistant_secretary").toString(),
								i-xklxr_cnt + 1 + skiprows, i + skiprows, 4, 4);
						mergeList.add(merge3);
					}
					//互校人
					if (hjr_cnt > 1) {
						MergeInfo merge4 = new MergeInfo("primary_secretary", data_pre.get("primary_secretary").toString(),
								i-hjr_cnt + 1 + skiprows, i + skiprows, 5, 5);
						mergeList.add(merge4);
					}
					//排版
					if (pb_cnt > 1) {
						MergeInfo merge5 = new MergeInfo("typesetter", data_pre.get("typesetter").toString(),
								i-pb_cnt + 1 + skiprows, i + skiprows, 6, 6);
						mergeList.add(merge5);
					}
				}
			}
		}
		return mergeList;
	}
	
	public static class MergeInfo {
		String type;//课程代码、课程名称、学科联系人、互校人、排版
		String name;
		int first_row;
		int last_row;
		int first_col;
		int last_col;
		public MergeInfo(String type, String name, int first_row, int last_row, int first_col, int last_col) {
			this.type = type;
			this.name = name;
			this.first_row = first_row;
			this.last_row = last_row;
			this.first_col = first_col;
			this.last_col = last_col;
		}
		public String getType() {
			return type;
		}
		public String getName() {
			return name;
		}
		public int getFirst_row() {
			return first_row;
		}
		public int getLast_row() {
			return last_row;
		}
		public int getFirst_col() {
			return first_col;
		}
		public int getLast_col() {
			return last_col;
		}
		public void setType(String type) {
			this.type = type;
		}
		public void setName(String name) {
			this.name = name;
		}
		public void setFirst_row(int first_row) {
			this.first_row = first_row;
		}
		public void setLast_row(int last_row) {
			this.last_row = last_row;
		}
		public void setFirst_col(int first_col) {
			this.first_col = first_col;
		}
		public void setLast_col(int last_col) {
			this.last_col = last_col;
		}
		
	}
}
