package com.qmth.qrzk.web.controller;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.qmth.qrzk.repository.pager.model.PagerConstruct;
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.PaperTaskVO;
import com.qmth.qrzk.repository.task.ReviewTaskVo;
import com.qmth.qrzk.repository.task.TaskBatch;
import com.qmth.qrzk.repository.task.WordHistory;
import com.qmth.qrzk.repository.user.model.Attachment;
import com.qmth.qrzk.repository.user.model.AuditQuesTask;
import com.qmth.qrzk.repository.user.model.AuditQuesTaskUserLink;
import com.qmth.qrzk.repository.user.model.Course;
import com.qmth.qrzk.repository.user.model.InputQuesTask;
import com.qmth.qrzk.repository.user.model.InputQuesTaskUserLink;
import com.qmth.qrzk.repository.user.model.TkjsTask;
import com.qmth.qrzk.repository.user.model.TkjsTaskUserLink;
import com.qmth.qrzk.repository.user.model.User;
import com.qmth.qrzk.repository.user.service.impl.AttachmentService;
import com.qmth.qrzk.repository.user.service.impl.AuditQuesTaskServiceImpl;
import com.qmth.qrzk.repository.user.service.impl.BookServiceImpl;
import com.qmth.qrzk.repository.user.service.impl.CourseServiceImpl;
import com.qmth.qrzk.repository.user.service.impl.InputQuesTaskServiceImpl;
import com.qmth.qrzk.repository.user.service.impl.PaperTaskServiceImpl;
import com.qmth.qrzk.repository.user.service.impl.TaskBatchImpl;
import com.qmth.qrzk.repository.user.service.impl.TkjsTaskServiceImpl;
import com.qmth.qrzk.repository.user.service.impl.UserServiceImpl;
import com.qmth.qrzk.repository.utils.Consts;
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.repositry.utils.excel.ExcelOperate;

@Controller
@RequestMapping("/business")
public class BusinessController extends BaseAjaxController{
	
	private static final String BASE_JSP_PATH = "business/";
	
	private static final Logger log=Logger.getLogger(TaskController.class);
	
	@Autowired
	private TaskBatchImpl taskBatchService;
	
	@Autowired
	private BookServiceImpl bookService;
	
	@Autowired
	private PaperTaskServiceImpl paperTaskSerivce;
	
	@Autowired
	private AuditQuesTaskServiceImpl auditQuesTaskSerivce;
	
	@Autowired
	private InputQuesTaskServiceImpl inputQuesTaskSerivce;
	
	@Autowired
	private TkjsTaskServiceImpl tkjsTaskSerivce;
	
	@Autowired
	private CourseServiceImpl courseService;
	
	@Autowired
	private UserServiceImpl userService;
	
	@Autowired
	private AttachmentService attachmentService;
	
	@RequestMapping("/addBatch")
	public ModelAndView addBatch(){
		ModelAndView mov = new ModelAndView(BASE_JSP_PATH + "addBatch");
		mov.addObject("taskBatchTypes", Consts.TaskBatchType.dicMap);
		return mov;
	}
	
	@RequestMapping("/paperTaskList/{batchId}")
	public ModelAndView taskList(@PathVariable int batchId){
		ModelAndView mov = new ModelAndView(BASE_JSP_PATH + "paperTaskList");
		mov.addObject("status", paperTaskSerivce.queryPaperTaskStatusByBatchId(batchId));
		mov.addObject("batchId", batchId);
		return mov;
	}
	
	@RequestMapping("/getTaskBatch/{batchId}")
	@ResponseBody
	public TaskBatch getTaskBatch(@PathVariable int batchId){
		return taskBatchService.findById(batchId);
	}
	
	@RequestMapping("/auditQuesTaskList/{batchId}")
	public ModelAndView auditQuesTaskList(@PathVariable int batchId){
		ModelAndView mov = new ModelAndView(BASE_JSP_PATH + "auditQuesTaskList");
		mov.addObject("batchId", batchId);
		mov.addObject("taskBatch",taskBatchService.findById(batchId));
		return mov;
	}
	
	/**
	 * 根据批次ID查询所有的审题任务单
	 * @return
	 */
	@RequestMapping("/allAuditQuesTasks/{batchId}")
	@ResponseBody
	public Map<String, Object> allAuditQuesTasks(@PathVariable int batchId){
		Map<String, Object> result = new HashMap<String, Object>();
		List<AuditQuesTask> tasks = auditQuesTaskSerivce.getAuditQuesTasksByBatchId(batchId);
		result.put("rows", tasks);
		result.put("total", tasks.size());
		return result;
	}
	
	/**
	 * 带有统计信息的根据批次ID查询所有的审题任务单
	 * @return
	 */
	@RequestMapping("/allAuditQuesTasksWithStat/{batchId}")
	@ResponseBody
	public Map<String, Object> allAuditQuesTasksWithStat(@PathVariable int batchId){
		Map<String, Object> result = new HashMap<String, Object>();
		List<AuditQuesTask> tasks = auditQuesTaskSerivce.getAuditQuesTasksWithStatByBatchId(batchId);
		result.put("rows", tasks);
		result.put("total", tasks.size());
		return result;
	}
	
	@RequestMapping("/selectUsersByTaskId/{taskId}")
	@ResponseBody
	public Map<String, Object> selectUsersByTaskId(@PathVariable int taskId){
		Map<String, Object> result = new HashMap<String, Object>();
		AuditQuesTask task = auditQuesTaskSerivce.getAuditQuesTaskById(taskId);
		List<User> auditors = new ArrayList<User>();
		for(AuditQuesTaskUserLink ul:task.getAuditorLinks()){
			auditors.add(ul.getAuditor());
		}
		result.put("rows", auditors);
		result.put("total", auditors.size());
		return result;
	}
	
	@RequestMapping("/delTaskBatch/{batchId}")
	@ResponseBody
	public Map<String, Object> delTaskBatch(@PathVariable int batchId){
		try {
			taskBatchService.delTaskBatch(batchId);
			return this.successResult(null);
		} catch (Exception exp) {
			log.error("删除任务批次失败，原因:" + exp.getMessage(),exp);
			return this.failedResult("删除任务批次失败，原因：这不是空的任务批次。");
		}
	}
	
	@RequestMapping(value = "/saveLinkUsers/{taskId}")
	@ResponseBody
	public Map<String, Object> saveLinkUsers(@PathVariable int taskId, @RequestBody String[] links) {
		try {
			List<AuditQuesTaskUserLink> uls = new ArrayList<AuditQuesTaskUserLink>();
			if (links != null) {
				for (String link : links) {
					AuditQuesTaskUserLink ul = new AuditQuesTaskUserLink();
					ul.setAuditQuesTaskId(taskId);
					ul.setAuditorId(Integer.parseInt(link));
					uls.add(ul);
				}
			}
			AuditQuesTask task = new AuditQuesTask();
			task.setId(taskId);
			task.setAuditorLinks(uls);
			auditQuesTaskSerivce.updateAuditQuesTaskUserLinks(task);
			return this.successResult(null);
		} catch (Exception exp) {
			log.error("更新审题任务(id=" + taskId + ")关联的审题教师信息失败，原因:" + exp.getMessage(),exp);
			return this.failedResult(exp);
		}
	}
	
	@RequestMapping(value = "/delAuditQuesTasks")
	@ResponseBody
	public Map<String, Object> delAuditQuesTasks(@RequestParam(value = "taskIds[]", required = false) String[] taskIds) {
		try {
			if (taskIds != null) {
				int[] taskIdArr = new int[taskIds.length];
				for(int i=0;i<taskIds.length;i++){
					taskIdArr[i] = Integer.parseInt(taskIds[i]);
				}
				auditQuesTaskSerivce.deleteAuditQuesTasks(taskIdArr);
			}
			return this.successResult(null);
		} catch (Exception exp) {
			log.error("批量删除审题任务失败，原因:" + exp.getMessage(),exp);
			return this.failedResult(exp);
		}
	}
	
	@RequestMapping(value = "/addAuditQuesTask")
	@ResponseBody
	public Map<String, Object> addAuditQuesTask(HttpSession session, @RequestBody AuditQuesTask task) {
		try {
			AuditQuesTask t = auditQuesTaskSerivce.addAuditQuesTask(task,this.getCurUser(session));
			t.setCourseCode(t.getCourse().getCode());
			t.setCourseName(t.getCourse().getName());
			Map<String,Object> resultMap = this.successResult(null);
			resultMap.put("task", t);
			return resultMap;
		} catch (Exception exp) {
			log.error("添加审题任务失败，原因:" + exp.getMessage(),exp);
			return this.failedResult(exp);
		}
	}
	
	/**
	 * 查询批次信息
	 * @return
	 */
	@RequestMapping(value = "/queryBatch")
	@ResponseBody
	public Map<String, Object> queryBatch(@RequestBody QueryParams params){
		Map<String, Object> result = new HashMap<String, Object>();
		List<TaskBatch> ls=taskBatchService.queryTaskBatchs(params);
		result.put("rows", ls);
		result.put("total", params.getTotalNum());
		return result;
	}
	
	/**
	 * 查询批次信息
	 * @return
	 */
	@RequestMapping("/queryBatchById/{batchId}")
	@ResponseBody
	public TaskBatch queryBatchById(@PathVariable Integer batchId){
		if(batchId != null){
			return taskBatchService.findById(batchId);
		}
		return null;
	}
	
	@RequestMapping("/queryPaperTask")
	@ResponseBody
	public Map<String, Object> queryPaperTask(@RequestBody TaskQueryParams params){
		Map<String, Object> result = new HashMap<String, Object>();
		List<PaperTask> list=paperTaskSerivce.queryPaperTask(params);
		result.put("rows", list);
		result.put("total", params.getTotalNum());
		return result;
	}
	
	/**
	 * 新建任务批次
	 * @param session
	 * @param taskBatch
	 * @return
	 */
	@RequestMapping(value="/addTaskBatch",method={RequestMethod.POST})
	@ResponseBody
	public Map<String,Object> addTaskBatch(HttpSession session,@RequestBody TaskBatch taskBatch){
		try{
			User user = this.getCurUser(session);
			taskBatch.setCreatedBy(user.getId());
			taskBatch.setCreatedTime(new Date());
			taskBatchService.addTaskBatch(taskBatch);
			return this.successResult(null);
		}catch(Exception e){
			log.error("新建任务批次失败，原因：" + e.getMessage(),e);
			return this.failedResult(e);
		}
	}
	
	//修改任务批次
	@RequestMapping(value="/updateTaskBatch",method={RequestMethod.POST})
	@ResponseBody
	public Map<String,Object> updateTaskBatch(HttpSession session,TaskBatch taskBatch){
		try{
			User user = this.getCurUser(session);
			taskBatch.setCreatedBy(user.getId());
			taskBatch.setCreatedTime(new Date());
			taskBatchService.updateTaskBatch(taskBatch);
			return this.successResult(null);
		}catch(Exception e){
			log.error("新建任务批次失败!",e);
		}
		return null;
	}
	
	
	/**
	 * 验证任务是否能修改或删除  
	 * @param id  任务批次id
	 * @return
	 */
	@RequestMapping(value="/validateChange",method={RequestMethod.POST})
	@ResponseBody
	public Map<String,Object> validateChange(int id){
		try{
			int result=paperTaskSerivce.taskValidateChange(id);
			if(result>0){
				return this.successResult(null);
			}else{
				return this.failedResult("验证任务单是否开启失败");
			}
		}catch(Exception e){
			log.error("验证任务单是否开启失败!",e);
		}
		return null;
	}
	
	@RequestMapping(value="/deleteReviewTask",method={RequestMethod.POST})
	@ResponseBody
	public Map<String,Object> deleteReviewTask(int id){
		try{
			PagerConstruct pagerConstruct = paperTaskSerivce.queryPagerConstructByTaskId(id);
			if(pagerConstruct != null && pagerConstruct.getId() != null){
				List<WordHistory> wordList = paperTaskSerivce.getPaperWordHistories(pagerConstruct.getId(), null);
				for(WordHistory wordHistory : wordList){
					attachmentService.changeAttStatus(wordHistory.getAttId(), Consts.AttachmentStatus.DRAFT);
				}
				paperTaskSerivce.deleteWordHistoryByTaskId(pagerConstruct.getId());
			}
			paperTaskSerivce.deletePagerConstructByTaskId(id);
			int result = paperTaskSerivce.deletePaperTaskById(id);
			if(result>0){
				return this.successResult(null);
			}else{
				return this.failedResult("验证任务单是否开启失败");
			}
		}catch(Exception e){
			log.error("验证任务单是否开启失败!",e);
		}
		return null;
	}
	
	@RequestMapping(value="/deleteTask",method={RequestMethod.POST})
	@ResponseBody
	public Map<String,Object> deleteTask(int id){
		try{
			paperTaskSerivce.deletePagerConstructByTaskId(id);
			int result = paperTaskSerivce.deletePaperTaskById(id);
			if(result>0){
				return this.successResult(null);
			}else{
				return this.failedResult("验证任务单是否开启失败");
			}
		}catch(Exception e){
			log.error("验证任务单是否开启失败!",e);
		}
		return null;
	}
	
	/**
	 * 修改任务单相关人员
	 * @param session
	 * @param request
	 * @param response
	 * @param id	paper_taskID
	 * @param oldId	需要修改人员的ID
	 * @param newId	更换新人员的ID
	 * @return
	 */
	@RequestMapping(value="/updatePaperTask",method={RequestMethod.POST})
	@ResponseBody
	public Map<String,Object> updatePaperTask(@RequestBody PaperTask task){
		try{
			//更新当前处理人
			PaperTask dbPaperTask = paperTaskSerivce.getPaperTaskById(task.getId());
			if(dbPaperTask.getCurDealer().equals(dbPaperTask.getPropositionTeacher())){
				task.setCurDealer(task.getPropositionTeacher());
			}else if(dbPaperTask.getCurDealer().equals(dbPaperTask.getAuditTeacher())){
				task.setCurDealer(task.getAuditTeacher());
			}else if(dbPaperTask.getCurDealer().equals(dbPaperTask.getPrimarySecretary())){
				task.setCurDealer(task.getPrimarySecretary());
			}else if(dbPaperTask.getCurDealer().equals(dbPaperTask.getAssistantSecretary())){
				task.setCurDealer(task.getAssistantSecretary());
			}else if(dbPaperTask.getCurDealer().equals(dbPaperTask.getTypesetter())){
				task.setCurDealer(task.getTypesetter());
			}
			
			int result=paperTaskSerivce.updatePaperTask(task);
			if(result>0){
				return this.successResult(null);
			}else{
				return this.failedResult("修改任务单人员失败!");
			}
		}catch(Exception e){
			log.error("修改任务单人员失败!",e);
		}
		return null;
	}
	
	/**
	 * 修改复审任务单相关人员
	 * @param task
	 * @return
	 */
	@RequestMapping(value="/updateReviewTask",method={RequestMethod.POST})
	@ResponseBody
	public Map<String,Object> updateReviewTask(@RequestBody PaperTask task){
		try{
			//更新当前处理人
			PaperTask dbPaperTask = paperTaskSerivce.getPaperTaskById(task.getId());
			if(dbPaperTask.getCurDealer() == null){
				task.setCurDealer(task.getAuditTeacher());
			}else{
				if(dbPaperTask.getCurDealer().equals(dbPaperTask.getAuditTeacher())){
					task.setCurDealer(task.getAuditTeacher());
				}else if(dbPaperTask.getCurDealer().equals(dbPaperTask.getPrimarySecretary())){
					task.setCurDealer(task.getPrimarySecretary());
				}else if(dbPaperTask.getCurDealer().equals(dbPaperTask.getTypesetter())){
					task.setCurDealer(task.getTypesetter());
				}				
			}
			
			int result = paperTaskSerivce.updatePaperTask(task);
			if(result>0){
				return this.successResult(null);
			}else{
				return this.failedResult("修改任务单人员失败!");
			}
		}catch(Exception e){
			log.error("修改任务单人员失败!",e);
		}
		return null;
	}
	
	@RequestMapping(value="/addPaperTask/{batchId}")
	@ResponseBody
	public Map<String,Object> addPaperTask(HttpSession session, @PathVariable Integer batchId, @RequestBody PaperTaskVO vo){
		Course course = vo.getCourse();
		
		List<User> users = new ArrayList<User>();
		users.add(vo.getTeacher1());
		users.add(vo.getTeacher2());
		users.add(vo.getSecretary1());
		users.add(vo.getSecretary2());
		users.add(vo.getInputer());
		 
		try {
			return paperTaskSerivce.addPaperTask(batchId, course, users, this.getCurUser(session));
		} catch (Exception e) {
			e.printStackTrace();
			return this.failedResult("操作失败，请与管理员联系!");
		}
	}
	
	/**
	 * 新增复审任务
	 * @param session
	 * @param batchId
	 * @param vo
	 * @return
	 */
	@RequestMapping(value="/addReviewTask/{batchId}")
	@ResponseBody
	public Map<String,Object> addReviewTask(HttpSession session, @PathVariable Integer batchId, @RequestBody ReviewTaskVo vo){
		List<User> users = new ArrayList<User>();
		users.add(vo.getTeacher());
		users.add(vo.getSecretary());
		users.add(vo.getInputer());
		 
		try {
			return paperTaskSerivce.addReviewTask(batchId, vo.getTaskNo(), users, this.getCurUser(session));
		} catch (Exception e) {
			e.printStackTrace();
			return this.failedResult("操作失败，请与管理员联系!");
		}
	}
	
	/**
	 * 导入任务信息
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/importTask/{id}", method = RequestMethod.POST)
	public void importTask(HttpSession session,HttpServletRequest request,HttpServletResponse response, @PathVariable Integer id){
		JSONObject object=new JSONObject();
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("file");
		InputStream stream = null;
		try{
			stream = file.getInputStream();
			String fileName = file.getOriginalFilename();
			fileName = new String(fileName.getBytes(), "utf-8");
			TaskBatch taskBatch = taskBatchService.findById(id);
			if(Consts.TaskBatchType.RU_WEI_MING_TI.equals(taskBatch.getBatchType())){
				//1.根据上传的excel得到所有paperTask信息
				List<PaperTask> list=new ExcelOperate().readPaperTaskExcel(stream, fileName, object);
				
				if(!object.has("result") || !"fail".equals(object.getString("result"))){
					//2.验证上传的命题教师、学科秘书、排版员是否都存在
					if(list!=null && list.size()!=0){
						paperTaskSerivce.saveImportData(id, list, object,this.getCurUser(session));
					}else{
						object.put("result", "error");
						object.put("msg", "导入的Excel里面没有任务!");
					}
				}
			}else if(Consts.TaskBatchType.SHEN_TI.equals(taskBatch.getBatchType())){
				//1.根据上传的excel得到所有paperTask信息
				List<AuditQuesTask> list=new ExcelOperate().readAuditQuesTaskExcel(stream, fileName, object);
				
				if(!object.has("result") || !"fail".equals(object.getString("result"))){
					//2.验证上传的审题教师是否都存在
					if(list!=null && list.size()!=0){
						auditQuesTaskSerivce.saveImportData(id, list, object,this.getCurUser(session));
					}else{
						object.put("result", "error");
						object.put("msg", "导入的Excel里面没有任务!");
					}
				}
			}else if(Consts.TaskBatchType.SHI_JUAN_FU_SHEN.equals(taskBatch.getBatchType())){
				//1.根据上传的excel得到所有paperTask信息
				List<PaperTask> list=new ExcelOperate().readReviewTaskExcel(stream, fileName, object);
				
				if(!object.has("result") || !"fail".equals(object.getString("result"))){
					//2.验证上传的命题教师、学科秘书、排版员是否都存在
					if(list!=null && list.size()!=0){
						//原始方法，修改【导入复审任务】，导入不成功。题
						//paperTaskSerivce.saveReviewImportData(id, list, object,this.getCurUser(session));
						//修改导入复审任务，新方法
						paperTaskSerivce.saveReviewImportDataNew(id, list, object,this.getCurUser(session));
					}else{
						object.put("result", "error");
						object.put("msg", "导入的Excel里面没有任务!");
					}
				}
			}
		}catch(Exception e){
			log.error("导入任务失败，原因：" + e.getMessage(),e);
		}finally{
			this.outJsonString(response, object.toString());
		}
	}
	
	@RequestMapping("/taskReport")
	public ModelAndView taskReport(String batchName){
		ModelAndView mov = new ModelAndView(BASE_JSP_PATH + "taskReport");
		TaskBatch batch;
		if(null == batchName || "".equals(batchName)){
			batch = taskBatchService.findLatestTaskBatch();
		}else{
			batch = taskBatchService.findByName(batchName);
		}
		
		if(batch != null){
			mov.addObject("statusReport", paperTaskSerivce.queryPaperTaskStatusByBatchId(batch.getId()));
			mov.addObject("batch", batch);
		}
		
		return mov;
	}
	
	@RequestMapping("/expTkjsForClient/{batchId}")
	@ResponseBody
	public Map<String,Object> expTkjsForClient(@PathVariable int batchId,HttpSession session){
		try {
			Map<String,Object>	result = this.successResult("生成客户端导出文件成功。");
			result.put("attId", taskBatchService.expTkjsForClient(batchId,this.getCurUser(session)).getId());
			return result;
		}catch(Exception e){
			log.error("生成客户端导出批次[id=" + batchId + "]文件失败，原因:" + e.getMessage(), e);
			return this.failedResult("生成客户端导出文件失败，请与管理员联系!");
		}
	}
	
	@RequestMapping("/exportTask/{batchId}")
	@ResponseBody
	public Map<String,Object> exportTask(@PathVariable int batchId,HttpSession session){
		try {
			Map<String,Object>	result = this.successResult("生成导出批次数据成功。");
			result.put("attId", taskBatchService.exportTask(batchId,this.getCurUser(session)).getId());
			return result;
		}catch(Exception e){
			log.error("生成导出批次[id=" + batchId + "]数据失败，原因:" + e.getMessage(), e);
			return this.failedResult("生成导出批次数据失败，请与管理员联系!");
		}
	}
	
	@RequestMapping("/revertTask/{attId}")
	@ResponseBody
	public Map<String,Object> revertTask(@PathVariable int attId,HttpSession session){
		try {
			Map<String,Object>	result = this.successResult("还原任务批次的备份数据成功。");
			taskBatchService.revertTask(attId,this.getCurUser(session));
			userService.initUserInfo();
			return result;
		}catch(Exception e){
			log.error("还原任务批次的备份数据[attId=" + attId + "]失败，原因:" + e.getMessage(), e);
			return this.failedResult("还原任务批次的备份数据失败，请与管理员联系!");
		}
	}
	
	@RequestMapping(value="/statBatchAuditorJob/{batchId}")
	@ResponseBody
	public Map<String,Object> statBatchAuditorJob(@PathVariable Integer batchId){
		try{
			Map<String,Object> resultMap = new HashMap<String, Object>();
			resultMap.put("auditorJob",auditQuesTaskSerivce.statBatchAuditorJob(batchId));
			return resultMap;
		}catch(Exception e){
			log.error("统计任务批次[id=" + batchId + "]下所有人的审核数据失败，原因：" + e.getMessage(), e);
			return failedResult("统计任务批次下所有人的审核数据失败");
		}
	}
	
	@RequestMapping(value="/emptyData")
	@ResponseBody
	public Map<String,Object> emptyData(HttpSession session){
		User user = this.getCurUser(session);
		try{
			log.warn("用户：" + user.getName() + "(" + user.getId() +")正在清空数据...");
			taskBatchService.emptyData();
			log.warn("用户：" + user.getName() + "(" + user.getId() +")清空数据完成.");
			return successResult("清空数据成功");
		}catch(Exception e){
			log.error("用户：" + user.getName() + "(" + user.getId() +")清空数据失败，原因：" + e.getMessage(), e);
			return failedResult("清空数据失败，原因：" + e.getMessage());
		}
	}
	
	/**
	 * 根据批次ID查询所有的录题任务单
	 * @return
	 */
	@RequestMapping("/allInputQuesTasks/{batchId}")
	@ResponseBody
	public Map<String, Object> allInputQuesTasks(@PathVariable int batchId){
		Map<String, Object> result = new HashMap<String, Object>();
		List<InputQuesTask> tasks = inputQuesTaskSerivce.getInputQuesTasksWithStatByBatchId(batchId);
		result.put("rows", tasks);
		result.put("total", tasks.size());
		return result;
	}
	
	@RequestMapping(value = "/addInputQuesTask")
	@ResponseBody
	public Map<String, Object> addInputQuesTask(HttpSession session, @RequestBody InputQuesTask task) {
		try {
			InputQuesTask t = inputQuesTaskSerivce.addInputQuesTask(task,this.getCurUser(session));
			t.setCourseCode(t.getCourse().getCode());
			t.setCourseName(t.getCourse().getName());
			Map<String,Object> resultMap = this.successResult(null);
			resultMap.put("task", t);
			return resultMap;
		} catch (Exception exp) {
			log.error("添加录题任务失败，原因:" + exp.getMessage(),exp);
			return this.failedResult(exp);
		}
	}
	
	@RequestMapping(value = "/delInputQuesTasks/{taskId}")
	@ResponseBody
	public Map<String, Object> delInputQuesTasks(@PathVariable Integer taskId) {
		try {
			if (taskId != null) {
				int[] taskIdArr = new int[1];
				taskIdArr[0] = taskId.intValue();
				inputQuesTaskSerivce.deleteInputQuesTasks(taskIdArr);
			}
			return this.successResult(null);
		} catch (Exception exp) {
			log.error("删除录题任务失败，原因:" + exp.getMessage(),exp);
			return this.failedResult(exp);
		}
	}
	
	@RequestMapping(value = "/saveLinkInputers/{taskId}")
	@ResponseBody
	public Map<String, Object> saveLinkInputers(@PathVariable Integer taskId, @RequestBody String[] links) {
		try {
			List<InputQuesTaskUserLink> uls = new ArrayList<InputQuesTaskUserLink>();
			if (links != null) {
				for (String link : links) {
					InputQuesTaskUserLink ul = new InputQuesTaskUserLink();
					ul.setInputQuesTaskId(taskId);
					ul.setInputerId(Integer.parseInt(link));
					uls.add(ul);
				}
			}
			InputQuesTask task = new InputQuesTask();
			task.setId(taskId);
			task.setInputerLinks(uls);
			inputQuesTaskSerivce.updateInputQuesTaskUserLinks(task);
			return this.successResult(null);
		} catch (Exception exp) {
			log.error("更新录题任务(id=" + taskId + ")关联的录入员信息失败，原因:" + exp.getMessage(),exp);
			return this.failedResult(exp);
		}
	}
	
	/**
	 * 根据批次ID查询所有的题库建设任务单
	 * @return
	 */
	@RequestMapping("/allTkjsTasks/{batchId}")
	@ResponseBody
	public Map<String, Object> allTkjsTasks(@PathVariable int batchId){
		Map<String, Object> result = new HashMap<String, Object>();
		List<TkjsTask> tasks = tkjsTaskSerivce.getTkjsTasksWithStatByBatchId(batchId);
		result.put("rows", tasks);
		result.put("total", tasks.size());
		return result;
	}
	
	@RequestMapping(value = "/addTkjsTask")
	@ResponseBody
	public Map<String, Object> addTkjsTask(HttpSession session, @RequestBody TkjsTask task) {
		try {
			TkjsTask t = tkjsTaskSerivce.addTkjsTask(task,this.getCurUser(session));
			t.setCourseCode(t.getCourse().getCode());
			t.setCourseName(t.getCourse().getName());
			Map<String,Object> resultMap = this.successResult(null);
			resultMap.put("task", t);
			return resultMap;
		} catch (Exception exp) {
			log.error("添加题库建设任务失败，原因:" + exp.getMessage(),exp);
			return this.failedResult(exp);
		}
	}
	
	@RequestMapping(value = "/delTkjsTasks/{taskId}")
	@ResponseBody
	public Map<String, Object> delTkjsTasks(@PathVariable Integer taskId) {
		try {
			if (taskId != null) {
				int[] taskIdArr = new int[1];
				taskIdArr[0] = taskId.intValue();
				tkjsTaskSerivce.deleteTkjsTasks(taskIdArr);
			}
			return this.successResult(null);
		} catch (Exception exp) {
			log.error("删除题库建设任务失败，原因:" + exp.getMessage(),exp);
			return this.failedResult(exp);
		}
	}
	
	/**
	 * 关联命题教师到题库建设任务上
	 * @param taskId
	 * @param links
	 * @return
	 */
	@RequestMapping(value = "/saveLinkTeachers/{taskId}")
	@ResponseBody
	public Map<String, Object> saveLinkTeachers(@PathVariable Integer taskId, @RequestBody String[] links) {
		try {
			List<TkjsTaskUserLink> uls = new ArrayList<TkjsTaskUserLink>();
			if (links != null) {
				for (String link : links) {
					TkjsTaskUserLink ul = new TkjsTaskUserLink();
					ul.setTkjsTaskId(taskId);
					ul.setTeacherId(Integer.parseInt(link));
					uls.add(ul);
				}
			}
			TkjsTask task = new TkjsTask();
			task.setId(taskId);
			task.setTeacherLinks(uls);
			tkjsTaskSerivce.updateTkjsTaskUserLinks(task);
			return this.successResult(null);
		} catch (Exception exp) {
			log.error("更新题库建设任务(id=" + taskId + ")关联的命题教师信息失败，原因:" + exp.getMessage(),exp);
			return this.failedResult(exp);
		}
	}
	
	@RequestMapping(value ="/save")
	@ResponseBody
	public Map<String,Object> save(HttpSession session,  @RequestBody TaskBatch taskBatch){
		try{
			if(taskBatch.getId() != null){
				taskBatch.setUpdatedBy(this.getCurUser(session).getId());
				taskBatchService.updateTaskBatch(taskBatch);
			}else{
				taskBatch.setCreatedBy(this.getCurUser(session).getId());
				taskBatchService.addTaskBatch(taskBatch);
			}
			return this.successResult(null);
		}catch(Exception exp){
			log.error("保存批次信息失败，原因:" + exp.getMessage(), exp);
			return this.failedResult(exp);
		}
	}
	
	@RequestMapping(value = "/getById/{id}")
	@ResponseBody
	public TaskBatch getById(@PathVariable Integer id){
		return taskBatchService.findById(id);
	}
	
	@RequestMapping("/inputStat")
	public ModelAndView inputStat(String startTime,String endTime){
		ModelAndView mov = new ModelAndView(BASE_JSP_PATH + "inputStat");
		if(General.isNotEmpty(startTime) && General.isNotEmpty(endTime)){
			Date startDate = DateHelper.parseLongString(startTime + " 0:0:0");
			Date endDate = DateHelper.parseLongString(endTime + " 23:59:59");
			mov.addObject("statInputQuestByCourse",inputQuesTaskSerivce.statInputQuestByCourse(startDate, endDate));
			mov.addObject("statInputQuestByInputer",inputQuesTaskSerivce.statInputQuestByInputer(startDate, endDate));
		}
		return mov;
	}
	
	@RequestMapping(value ="/exportInputStat")
	@ResponseBody
	public Map<String,Object> exportInputStat(HttpSession session, String startTime,String endTime){
		try{
			Date startDate = DateHelper.parseLongString(startTime + " 0:0:0");
			Date endDate = DateHelper.parseLongString(endTime + " 23:59:59");
			Attachment att = inputQuesTaskSerivce.exportInputStat(startDate, endDate, this.getCurUser(session));
			Map<String,Object> resultMap = successResult("生成报表文件成功");
			resultMap.put("att", att);
			return resultMap;
		}catch(Exception exp){
			log.error("生成报表文件失败，原因:" + exp.getMessage(), exp);
			return this.failedResult(exp);
		}
	}
	
	@RequestMapping(value ="/enableTeachers/{taskId}")
	@ResponseBody
	public Map<String,Object> enableTeachers(HttpSession session,@PathVariable int taskId){
		try{
			paperTaskSerivce.setTeachersEnable(taskId, 1);
			return successResult("启用命题教师账号成功");
		}catch(Exception exp){
			log.error("启用命题教师账号失败，原因:" + exp.getMessage(), exp);
			return this.failedResult(exp);
		}
	}
	
	@RequestMapping(value ="/disableTeachers/{taskId}")
	@ResponseBody
	public Map<String,Object> disableTeachers(HttpSession session,@PathVariable int taskId){
		try{
			paperTaskSerivce.setTeachersEnable(taskId, 0);
			return successResult("禁用命题教师账号成功");
		}catch(Exception exp){
			log.error("禁用命题教师账号失败，原因:" + exp.getMessage(), exp);
			return this.failedResult(exp);
		}
	}
	
	@RequestMapping(value ="/exportAllFiles/{batchId}")
	@ResponseBody
	public Map<String,Object> exportAllFiles(HttpSession session,@PathVariable int batchId){
		try{
			Map<String,Object> result = successResult("生成试卷Zip文件成功");
			Attachment att = paperTaskSerivce.exportAllFiles(batchId, this.getCurUser(session));
			result.put("att", att);
			return result;
		}catch(Exception exp){
			log.error("生成试卷Zip文件[batchId=" + batchId + "]失败，原因:" + exp.getMessage(), exp);
			return this.failedResult(exp);
		}
	}
	
	@RequestMapping(value ="/exportRkData/{batchId}")
	@ResponseBody
	public Map<String,Object> exportRkData(HttpSession session,@PathVariable int batchId){
		try{
			Map<String,Object> result = successResult("生成卷库入库xls文件成功");
			Attachment att = paperTaskSerivce.exportRkData(batchId, this.getCurUser(session));
			result.put("att", att);
			return result;
		}catch(Exception exp){
			log.error("生成卷库入库xls文件[batchId=" + batchId + "]失败，原因:" + exp.getMessage(), exp);
			return this.failedResult(exp);
		}
	}
	
	//导出命题教师签到表-新加
	@RequestMapping(value ="/exportMTJSQD/{batchId}")
	@ResponseBody
	public Map<String,Object> exportMTJSQD(HttpSession session, @PathVariable int batchId) {
		try{
			Map<String,Object> result = successResult("生成命题教师签到xls文件成功");
			Attachment att = paperTaskSerivce.exportMTJSQD(batchId, this.getCurUser(session));
			result.put("att", att);
			return result;
		} catch(Exception exp) {
			log.error("生成命题教师签到xls文件[batchId=" + batchId + "]失败，原因:" + exp.getMessage(), exp);
			return this.failedResult(exp);
		}
	}
	
	//导出命题、审题分工表-新加
	@RequestMapping(value ="/exportMTSTFGB/{batchId}")
	@ResponseBody
	public Map<String,Object> exportMTSTFGB(HttpSession session, @PathVariable int batchId) {
		try{
			Map<String,Object> result = successResult("生成命题学科联系人分工表");
			Attachment att = paperTaskSerivce.exportMTSTFGB(batchId, this.getCurUser(session));
			result.put("att", att);
			return result;
		} catch(Exception exp) {
			log.error("生成命题学科联系人分工xls文件[batchId=" + batchId + "]失败，原因:" + exp.getMessage(), exp);
			return this.failedResult(exp);
		}
	}
	
	/**
	 * 导出复审任务附件
	 * @param session
	 * @param batchId
	 * @return
	 */
	@RequestMapping(value ="/exportReviewFiles/{batchId}")
	@ResponseBody
	public Map<String,Object> exportReviewFiles(HttpSession session,@PathVariable int batchId){
		try{
			Map<String,Object> result = successResult("生成试卷Zip文件成功");
			Attachment att = paperTaskSerivce.exportReviewFiles(batchId, this.getCurUser(session));
			result.put("att", att);
			return result;
		}catch(Exception exp){
			log.error("生成试卷Zip文件[batchId=" + batchId + "]失败，原因:" + exp.getMessage(), exp);
			return this.failedResult(exp);
		}
	}
	
	/**
	 * 根据批次ID查询所有的复审任务单
	 * @return
	 */
	@RequestMapping("/allReviewTasks")
	@ResponseBody
	public Map<String, Object> allReviewTasks(@RequestBody TaskQueryParams params){
		Map<String, Object> result = new HashMap<String, Object>();
		List<PaperTask> list = paperTaskSerivce.queryReviewTask(params);
		result.put("rows", list);
		result.put("total", params.getTotalNum());
		return result;
	}
	
	/**
	 * 根据复审任务名称查询试卷
	 * @return
	 */
	@RequestMapping("/queryTaskByTaskNo/{taskNo}")
	@ResponseBody
	public Map<String, Object> queryTaskByTaskNo(HttpServletRequest request, @PathVariable String taskNo){
		Map<String, Object> result = new HashMap<String, Object>();
		PaperTask task = new PaperTask();
		String batchType = request.getParameter("batchType");
		if(General.isNotEmpty(batchType)){
			task.setBatchType(batchType);
		}
		task.setTaskNo(taskNo);
		String batchId = request.getParameter("batchId");
		if(General.isNotEmpty(batchId)){
			task.setBatchId(Integer.parseInt(batchId));
		}
		List<PaperTask> list = paperTaskSerivce.queryPaperTaskByParam(task);
		result.put("rows", list);
		return result;
	}
	
	/**
	 * 获取word打开方式
	 * @return
	 */
	@RequestMapping("/getOpenWordType")
	@ResponseBody
	public Map<String, Object> getOpenWordType(){
		Map<String, Object> result = new HashMap<String, Object>();
		String type = ParamUtils.OpenWordType;
		result.put("type", type);
		return result;
	}
	
	@RequestMapping("/queryStartedPapers")
	@ResponseBody
	public Map<String, Object> queryStartedPapers(@RequestBody QueryParams params){
		Map<String, Object> result = new HashMap<String, Object>();
		List<Map<String, Object>> list=paperTaskSerivce.queryStartedPapers(params);
		result.put("rows", list);
		result.put("total", params.getTotalNum());
		return result;
	}
	
	/**
	 * 导入试卷启用数据
	 * @param session
	 * @param batchId
	 * @return
	 */
	@RequestMapping(value ="/impStartedPapers/{attId}")
	@ResponseBody
	public Map<String,Object> impStartedPapers(HttpSession session,@PathVariable int attId,String startTime){
		try{
			Map<String,Object> result = successResult("导入成功。");
			StringBuffer msg = paperTaskSerivce.impStartedPapers(attId, startTime);
			result.put("log", msg);
			return result;
		}catch(Exception exp){
			log.error("导入试卷启用数据失败，原因:" + exp.getMessage(), exp);
			return this.failedResult(exp);
		}
	}
	
	/**
	 * 获取试卷的题卡类型
	 * @param session
	 * @param batchId
	 * @return
	 */
	@RequestMapping(value ="/getTikaType/{paperId}")
	@ResponseBody
	public Map<String,Object> getTikaType(@PathVariable int paperId){
		try{
			Map<String,Object> result = successResult("获取题卡类型成功。");
			String tikaType = paperTaskSerivce.getTikaType(paperId);
			result.put("tikaType", tikaType);
			return result;
		}catch(Exception exp){
			log.error("获取题卡类型失败，原因:" + exp.getMessage(), exp);
			return this.failedResult(exp);
		}
	}
	
	@RequestMapping(value ="/expInputTaskQuestions/{batchId}")
	@ResponseBody
	public Map<String,Object> expInputTaskQuestions(HttpSession session,@PathVariable int batchId){
		try{
			Map<String,Object> result = successResult("生成录入批次的题卡文件成功");
			Attachment att = inputQuesTaskSerivce.expInputTaskQuestions(batchId, this.getCurUser(session));
			result.put("att", att);
			return result;
		}catch(Exception exp){
			log.error("生成录入批次的题卡文件[batchId=" + batchId + "]失败，原因:" + exp.getMessage(), exp);
			return this.failedResult(exp);
		}
	}
	
	@RequestMapping(value = "/impInputTaskQuestions/{attId}")
	@ResponseBody
	public Map<String,Object> impInputTaskQuestions(@PathVariable int attId,HttpSession session){
		try {
			Map<String,Object>	result = this.successResult("导入录入批次的题卡文件成功。");
			result.putAll(inputQuesTaskSerivce.revertInputTaskQuestions(attId,this.getCurUser(session)));
			return result;
		}catch(Exception e){
			log.error("导入录入批次的题卡文件[attId=" + attId + "]失败，原因:" + e.getMessage(), e);
			return this.failedResult("导入录入批次的题卡文件失败，请与管理员联系!");
		}
	}
	
	/**
	 * 删除试卷任务细目表 
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/deleteDetailTask",method={RequestMethod.POST})
	@ResponseBody
	public Map<String,Object> deleteDetailTask(int id){
		try{
			int result = paperTaskSerivce.deletePaperTaskById(id);
			if(result>0){
				return this.successResult(null);
			}else{
				return this.failedResult("删除试卷细目表错误!");
			}
		}catch(Exception e){
			log.error("删除试卷细目表错误!",e);
		}
		return null;
	}

	@RequestMapping(value = "/queryAllBatch")
	@ResponseBody
	public List<TaskBatch> queryAllCourses() {
		List<TaskBatch> taskBatchs = taskBatchService.queryAllBatchs();
		return taskBatchs;
	}
}
