package com.qmth.qrzk.web.controller;

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

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

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

import com.qmth.qrzk.repository.exception.BizException;
import com.qmth.qrzk.repository.service.query.TaskQueryParams;
import com.qmth.qrzk.repository.task.PaperTask;
import com.qmth.qrzk.repository.user.service.impl.MessageServiceImpl;
import com.qmth.qrzk.repository.user.service.impl.PaperTaskServiceImpl;
import com.qmth.qrzk.repository.utils.Consts;
import com.qmth.qrzk.repository.utils.General;

@Controller
@RequestMapping("/taskCenter")
public class TaskController extends BaseAjaxController{
	
	private static final String BASE_JSP_PATH = "taskCenter/";
	
	private static final Logger log = Logger.getLogger(TaskController.class);
	
	@Autowired 
	private PaperTaskServiceImpl paperTaskService;
	
	@Autowired 
	private MessageServiceImpl messageService;
	
	@RequestMapping("/pending")
	public ModelAndView pending(HttpSession session){
		ModelAndView mov = new ModelAndView(BASE_JSP_PATH + "pending");
		mov.addObject("status", paperTaskService.queryTodoPaperTaskStatus(this.getCurUser(session).getId()));
		
		return mov;
	}
	
	@RequestMapping(value="/queryTodoPaperTasks")
	@ResponseBody
	public Map<String, Object> queryTodoPaperTasks(HttpSession session, TaskQueryParams params){
		Map<String,Object> result = new HashMap<String, Object>();
		params.setCurDealer(this.getCurUser(session).getId());
		List<PaperTask> rows = paperTaskService.queryTodoPaperTasks(params);
		result.put("rows", rows);
		result.put("total", params.getTotalNum());
		return result;
	}
	
	@RequestMapping("/viewTaskCenterDetail/{id}")
    public ModelAndView viewTaskCenterDetail(HttpSession session,@PathVariable Integer id) {
		ModelAndView modelAndView = new ModelAndView(BASE_JSP_PATH + "paperTask");
		PaperTask task = paperTaskService.getPaperTaskById(id);
	    modelAndView.addObject("task", task);
        return modelAndView;
    }
	
	@RequestMapping("/updateMsgStatus/{id}")
	@ResponseBody
	public Map<String,Object> updateMsgStatus(@PathVariable Integer id, HttpSession session) {
		messageService.updateMsgStatus(id, this.getCurUser(session).getId());
		return null;
	}
	
	@RequestMapping("/getPaperTask/{id}")
	@ResponseBody
	public PaperTask getPaperTask(@PathVariable Integer id) {
		return paperTaskService.getPaperTaskById(id);
	}
	
	@RequestMapping("/getAppPath")
	@ResponseBody
	public Map<String,Object> getAppPath(HttpServletRequest request) {
		Map<String,Object> result = new HashMap<String,Object>();
		String path = General.getBasePath(request);
		result.put("appPath", path);
		return result;
	}
	
	@RequestMapping("/getReivewTask/{id}")
	@ResponseBody
	public Map<String,Object> getReivewTask(HttpServletRequest request, @PathVariable Integer id) {
		Map<String,Object> result = new HashMap<String,Object>();
		result.put("row", paperTaskService.getReviewTaskById(id));
		String path = General.getBasePath(request);
		result.put("appPath", path);
		return result;
	}
	
	@RequestMapping("/normalSubmit")
	@ResponseBody
    public Map<String,Object> normalSubmit(HttpSession session,int taskId,int nextDealer,String remark) {
		try{
			paperTaskService.normalSubmit(taskId,nextDealer,remark,this.getCurUser(session));
			messageService.saveMessage(taskId, nextDealer, getCurUser(session));
			Map<String,Object> result = successResult("提交数据成功");
			return result;
		}catch(Exception e){
			log.error("提交任务[id=" + taskId + "]的数据失败，原因:" + e.getMessage(), e);
			return failedResult(e);
		}
    }
	
	@RequestMapping("/reviewSubmit")
	@ResponseBody
    public Map<String,Object> reviewSubmit(HttpSession session,int taskId,int nextDealer,String remark) {
		try{
			paperTaskService.reviewSubmit(taskId,nextDealer,remark,this.getCurUser(session));
			messageService.saveMessage(taskId, nextDealer, getCurUser(session));
			Map<String,Object> result = successResult("提交数据成功");
			return result;
		}catch(Exception e){
			log.error("提交任务[id=" + taskId + "]的数据失败，原因:" + e.getMessage(), e);
			return failedResult(e);
		}
    }
	
	@RequestMapping("/saveAuditResult")
	@ResponseBody
	public Map<String,Object> saveAuditResult(int taskId,int nextDealer,int auditResult,String remark, HttpSession session){
		try{
			paperTaskService.saveAuditResult(taskId, nextDealer, auditResult, remark, getCurUser(session));
			messageService.saveMessage(taskId, nextDealer, getCurUser(session));
			Map<String,Object> resultMap = successResult("保存审核结果成功");
			return resultMap;
		}catch(Exception e){
			log.error("保存任务[id=" + taskId + "]的审核结果失败，原因：" + e.getMessage(), e);
			return failedResult(e);
		}
	}
	
	@RequestMapping("/saveArchiveResult")
	@ResponseBody
	public Map<String,Object> saveArchiveResult(int taskId,String remark, HttpSession session){
		try{
			paperTaskService.saveArchiveResult(taskId, remark, getCurUser(session));
			Map<String,Object> resultMap = successResult("归档成功");
			return resultMap;
		}catch(Exception e){
			log.error("归档任务[id=" + taskId + "]失败，原因：" + e.getMessage(), e);
			return failedResult(e);
		}
	}
	
	@RequestMapping(value="/checkWordVersion")
	@ResponseBody
	public Map<String,Object> checkWordVersion(int paperId, int attId, String wordType, HttpSession session) throws UnsupportedEncodingException, BizException{
		try{
			boolean checkResult = paperTaskService.checkWordVersion(paperId,attId,wordType);
			Map<String,Object> resultMap = successResult("校验版本完成，版本" + (checkResult?"一致":"不一致"));
			resultMap.put("checkResult", checkResult);
			return resultMap;
		}catch(Exception e){
			log.error("校验最新Word试卷paperId=" + paperId + "]与最新上传的的附件[attId=" + attId + "]失败，原因：" + e.getMessage(), e);
			return failedResult("校验版本完成失败");
		}
	}
	
	@RequestMapping(value="/submitCurWord")
	@ResponseBody
	public Map<String,Object> submitCurWord(int taskId, int paperId, int attId, String wordType, HttpSession session) throws UnsupportedEncodingException, BizException{
		try{
			paperTaskService.submitCurWord(taskId, paperId, attId, wordType, this.getCurUser(session));
			Map<String,Object> resultMap = successResult("上传最新Word文件成功");
			return resultMap;
		}catch(Exception e){
			log.error("上传最新Word文件[taskId=" + taskId + ",paperId=" + paperId + ",attId=" + attId + ",wordType=" + wordType + "]失败，原因：" + e.getMessage(), e);
			return failedResult("上传最新Word文件失败");
		}
	}
	
	/**
	 * 上传专卡
	 * @param taskId
	 * @param paperId
	 * @param attId
	 * @param wordType
	 * @param session
	 * @return
	 * @throws UnsupportedEncodingException
	 * @throws BizException
	 */
	@RequestMapping(value="/submitZkWord")
	@ResponseBody
	public Map<String,Object> submitZkWord(int taskId, int paperId, int attId, String wordType, HttpSession session) throws UnsupportedEncodingException, BizException{
		try{
			paperTaskService.submitReviewAtt(taskId, paperId, attId, wordType, this.getCurUser(session));
			Map<String,Object> resultMap = successResult("上传最新cdr文件成功");
			return resultMap;
		}catch(Exception e){
			log.error("上传最新cdr文件[taskId=" + taskId + ",paperId=" + paperId + ",attId=" + attId + ",wordType=" + wordType + "]失败，原因：" + e.getMessage(), e);
			return failedResult("上传最新cdr文件失败");
		}
	}
	
	/**
	 * 提交复审附件
	 * @param taskId
	 * @param paperId
	 * @param attId
	 * @param wordType
	 * @param session
	 * @return
	 * @throws UnsupportedEncodingException
	 * @throws BizException
	 */
	@RequestMapping(value="/submitReviewAtt")
	@ResponseBody
	public Map<String,Object> submitReviewAtt(@RequestBody List<Map<String, Object>> list, HttpSession session) throws UnsupportedEncodingException, BizException{
		try{
			for(int i = 0;i < list.size(); i ++){
				Map<String, Object> map = list.get(i);
				Integer taskId = (Integer) map.get("taskId");
				Integer attId = (Integer) map.get("attId");
				Integer paperId = (Integer) map.get("paperId");
				String wordType = (String) map.get("wordType");
				paperTaskService.submitReviewAtt(taskId, paperId, attId, wordType, this.getCurUser(session));
			}
			Map<String,Object> resultMap = successResult("上传最新Word文件成功");
			return resultMap;
		}catch(Exception e){
			log.error("附件上传失败，原因：" + e.getMessage(), e);
			return failedResult("上传最新Word文件失败");
		}
	}
	
	@RequestMapping("/worked")
	public String worked(){
		return "/task/worked";
	}
	@RequestMapping("/relevance")
	public ModelAndView relevance(HttpSession session){
		ModelAndView mov = new ModelAndView(BASE_JSP_PATH + "relevance");
		mov.addObject("status", paperTaskService.queryRelatedPaperTaskStatus(this.getCurUser(session).getId()));
		
		return mov;
	}
	@RequestMapping("/archive")
	public String archive(){
		return "/task/archive";
	}
	
	@RequestMapping(value="/queryRelatedPaperTasks")
	@ResponseBody
	public Map<String, Object> queryRelatedPaperTasks(HttpSession session, TaskQueryParams params){
		if(params == null){
			params = new TaskQueryParams();
		}
		params.setRows(999);
		Map<String,Object> result = new HashMap<String, Object>();
		params.setCurDealer(this.getCurUser(session).getId());
		List<PaperTask> rows = paperTaskService.queryRelatedPaperTasks(params);
		List<PaperTask> resultList = new ArrayList<PaperTask>();
		if(rows != null && rows.size() > 0){
			for(int i = 0;i < rows.size();i ++){
				PaperTask task = rows.get(i);
				if(Consts.TaskBatchType.SHI_JUAN_FU_SHEN.equals(task.getBatchType())){
					PaperTask paperTask = new PaperTask();
					paperTask.setBatchType(Consts.TaskBatchType.RU_WEI_MING_TI);
					paperTask.setTaskNo(task.getTaskNo());
					List<PaperTask> list = paperTaskService.queryPaperTaskByParam(paperTask);
					if(list != null && list.size() > 0){
						PaperTask pt = list.get(0);
						task.setCourseId(pt.getCourseId());
						task.setCourse(pt.getCourse());
					}
				}
				resultList.add(task);
			}
		}
		result.put("rows", resultList);
		result.put("total", params.getTotalNum());
		return result;
	}
	
	/**
	 * 保存题卡配置
	 * @param taskId
	 * @param paperId
	 * @param tikaType
	 * @param session
	 * @return
	 */
	@RequestMapping(value="/saveTikaCfg")
	@ResponseBody
	public Map<String,Object> saveTikaCfg(int taskId, int paperId, String tikaType, HttpSession session){
		try{
			paperTaskService.saveTikaCfg(taskId, paperId, tikaType, this.getCurUser(session));
			Map<String,Object> resultMap = successResult("保存题卡配置成功");
			return resultMap;
		}catch(Exception e){
			log.error("保存题卡配置失败，原因：" + e.getMessage(), e);
			return failedResult("保存题卡配置失败");
		}
	}
	
	/**
	 * 获取试卷中的转印说明AttId，如果没有，就使用转印说明模板，并保存到试卷信息里面
	 * @param index 附件一、附件二下标
	 * @param taskId
	 * @param session
	 * @return
	 */
	@RequestMapping(value="/getZhuanyinAtt")
	@ResponseBody
	public Map<String,Object> getZhuanyinAtt(int index, int taskId , HttpSession session){
		try{
			Integer lastZhuanyinWord = paperTaskService.getZhuanyinAtt(index, taskId, this.getCurUser(session));
			Map<String,Object> resultMap = successResult("获取转印说明成功");
			resultMap.put("lastZhuanyinWord", lastZhuanyinWord);
			return resultMap;
		}catch(Exception e){
			log.error("获取转印说明失败，原因：" + e.getMessage(), e);
			return failedResult("获取转印说明失败");
		}
	}
}
