/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.act.web;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.SpringContextHolder;
import com.jeeplus.common.websocket.service.system.SystemInfoSocketHandler;
import com.jeeplus.modules.act.service.ActModelService;
import com.jeeplus.modules.oa.entity.OaNotify;
import com.jeeplus.modules.oa.entity.OaNotifyRecord;
import com.jeeplus.modules.oa.service.OaNotifyService;
import com.jeeplus.modules.sg.managementcenter.activiti.entity.*;
import com.jeeplus.modules.sg.managementcenter.activiti.service.ConstructionService;
import com.jeeplus.modules.sg.managementcenter.activiti.service.DiscloseService;
import com.jeeplus.modules.sg.managementcenter.activiti.service.ProcessPersonnelService;
import com.jeeplus.modules.sg.managementcenter.activiti.service.UploadImagesService;
import com.jeeplus.modules.sg.managementcenter.activiti.utils.MyActiviUtils;
import com.jeeplus.modules.sg.managementcenter.project.entity.Project;
import com.jeeplus.modules.sg.managementcenter.project.service.ProjectService;
import com.jeeplus.modules.sg.picking.activiti.entity.PickList;
import com.jeeplus.modules.sg.picking.activiti.entity.ShowList;
import com.jeeplus.modules.sg.picking.activiti.service.PickIngService;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.service.SystemService;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.impl.RepositoryServiceImpl;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.pvm.PvmActivity;
import org.activiti.engine.impl.pvm.PvmTransition;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.impl.pvm.process.ProcessDefinitionImpl;
import org.activiti.engine.impl.pvm.process.TransitionImpl;
import org.activiti.engine.impl.task.TaskDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.act.entity.Act;
import com.jeeplus.modules.act.service.ActTaskService;
import com.jeeplus.modules.act.utils.ActUtils;
import com.jeeplus.modules.sys.utils.UserUtils;

/**
 * 流程个人任务相关Controller
 * @author jeeplus
 * @version 2016-11-03
 */
@Controller
@RequestMapping(value = "${adminPath}/act/task")
public class ActTaskController extends BaseController {

	@Autowired
	private ActTaskService actTaskService;

	@Autowired
	private HistoryService historyService;

	@Autowired
	private RuntimeService runtimeService;

	@Autowired
	private RepositoryService repositoryService;

	@Autowired
	private TaskService taskService;

	@Autowired
	private ConstructionService constructionService;

	@Autowired
	private DiscloseService discloseService;

	@Autowired
	private UploadImagesService uploadImagesService;

	@Autowired
	private OaNotifyService oaNotifyService;
	@Autowired
	private ProcessPersonnelService processPersonnelService;

	@Autowired
	private ProjectService projectService;

	@Autowired
	private ActModelService actModelService;

	@Autowired
	private PickIngService pickIngService;

	@Autowired
	private SystemService systemService;

	/**
	 * 获取待办列表
	 * @return
	 */
	@RequestMapping(value = {"todo", ""})
	public String todoList(Act act, HttpServletRequest request,HttpServletResponse response, Model model) throws Exception {
		Page<org.activiti.engine.repository.Model> page2 = actModelService.modelList(
				new Page<org.activiti.engine.repository.Model>(request, response), "");
		List<org.activiti.engine.repository.Model> list2 = page2.getList();
		model.addAttribute("act", list2);
		return "modules/bpm/task/todo/taskTodoList";
	}

	@ResponseBody
	@RequestMapping(value = "todo/data")
	public  Map<String, Object> todoListData(Act act, HttpServletRequest request,HttpServletResponse response, Model model,String nameSelect) throws Exception {
		Page<HashMap<String,String>> page = actTaskService.todoList(new  Page<HashMap<String,String>>(request, response),act);
		return getBootstrapData(page);
	}
	
	/**
	 * 获取已办任务
	 * @return
	 */
	@RequestMapping(value = "historic")
	public String historicList(Act act, HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
		return "modules/bpm/task/history/taskHistoricList";
	}

	@ResponseBody
	@RequestMapping(value = "historic/data")
	public Map<String, Object>  historicListData(Act act, HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
		Page<HashMap<String,String>> page = actTaskService.historicList(new  Page<HashMap<String,String>>(request, response), act);
		return getBootstrapData(page);
	}

	/**
	 * 获取我的申请列表
	 * @return
	 */
	@RequestMapping(value = "myApplyed")
	public String myApplyedList(Act act, HttpServletResponse response, Model model) throws Exception {
		return "modules/bpm/task/apply/taskMyAppledList";
	}

	@ResponseBody
	@RequestMapping(value = "myApplyed/data")
	public  Map<String, Object> myApplyedListData(Act act, HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
		Page<HashMap> page = actTaskService.getMyStartedProcIns(UserUtils.getUser(),new Page<HashMap>(request, response));
		return getBootstrapData(page);
	}

	/**
	 * 获取流转历史列表
	 * @param startAct 开始活动节点名称
	 * @param endAct 结束活动节点名称
	 */
	@RequestMapping(value = "histoicFlow")
	public String histoicFlow(Act act, String startAct, String endAct, Model model){
		if (StringUtils.isNotBlank(act.getProcInsId())){
			List<Act> histoicFlowList = actTaskService.histoicFlowList(act.getProcInsId(), startAct, endAct);
			model.addAttribute("histoicFlowList", histoicFlowList);
		}
		return "modules/bpm/task/history/taskHistoricFlow";
	}
	
	/**
	 * 获取流程流向图
	 * @param startAct 开始活动节点名称
	 * @param endAct 结束活动节点名称
	 */
	@RequestMapping(value = "flowChart")
	public String flowChart(Act act, String startAct, String endAct, Model model){
		if (StringUtils.isNotBlank(act.getProcInsId())){
			List<Act> histoicFlowList = actTaskService.histoicFlowList(act.getProcInsId(), startAct, endAct);
			model.addAttribute("histoicFlowList", histoicFlowList);
		}
		return "modules/bpm/task/chart/taskFlowChart";
	}
	
	/**
	 * 获取流程列表
	 * @param category 流程分类
	 */
	@RequestMapping(value = "process")
	public String processList(String category, HttpServletRequest request, HttpServletResponse response, Model model) {
	    Page<Object[]> page = new Page<Object[]>(request, response);
		model.addAttribute("category", category);
		return "modules/bpm/task/process/taskProcessList";
	}

	/**
	 * 获取流程表单
	 */
	@RequestMapping(value = "form")
	public String form(Act act, HttpServletRequest request, Model model){
		// 获取流程XML上的表单KEY
		String formKey = actTaskService.getFormKey(act.getProcDefId(), act.getTaskDefKey());
		// 获取流程实例对象
		if (act.getProcInsId() != null){
			if(actTaskService.getProcIns(act.getProcInsId())!=null){
				try {
					act.setProcIns(actTaskService.getProcIns(act.getProcInsId()));
				} catch (Exception e) {
					e.printStackTrace();
				}
			}else{
				act.setFinishedProcIns(actTaskService.getFinishedProcIns(act.getProcInsId()));
			}

			if(actTaskService.isNextGatewaty(act.getProcInsId())){
				act.setIsNextGatewaty(true);
			}else{
				act.setIsNextGatewaty(false);
			}
		}
		return "redirect:" + ActUtils.getFormUrl(formKey, act);
	}


	/**
	 * 根据流程实例ID,获取当前节点的流程表单详情
	 */
	@RequestMapping(value = "formDetail")
	public String formDetail(Act act, HttpServletRequest request, Model model){
		// 获取流程XML上的表单KEY
		String taskDefKey = nextTaskDefinition(act.getProcInsId());
		String formKey = actTaskService.getFormKey(act.getProcDefId(), taskDefKey);
		// 获取流程实例对象
		if (act.getProcInsId() != null){
			if(actTaskService.getProcIns(act.getProcInsId())!=null){
				act.setProcIns(actTaskService.getProcIns(act.getProcInsId()));
			}else{
				act.setFinishedProcIns(actTaskService.getFinishedProcIns(act.getProcInsId()));
			}

			if(actTaskService.isNextGatewaty(act.getProcInsId())){
				act.setIsNextGatewaty(true);
			}else{
				act.setIsNextGatewaty(false);
			}

		}
		return "redirect:" + ActUtils.getFormUrl(formKey, act);
	}
	/**
	 * 启动流程
	 */
	@RequestMapping(value = "start")
	@ResponseBody
	public String start(Act act, String table, String id, Model model) throws Exception {
		actTaskService.startProcess(act.getProcDefKey(), act.getBusinessId(), act.getBusinessTable(), act.getTitle());
		return "true";//adminPath + "/act/task";
	}

	/**
	 * 签收任务
	 */
	@RequestMapping(value = "claim")
	@ResponseBody
	public String claim(Act act) {
		String userId = UserUtils.getUser().getLoginName();//ObjectUtils.toString(UserUtils.getUser().getId());
		actTaskService.claim(act.getTaskId(), userId);
		return "true";//adminPath + "/act/task";
	}
	
	/**
	 * 完成任务
	 * 		vars.keys=flag,pass
	 * 		vars.values=1,true
	 * 		vars.types=S,B  @see com.jeeplus.jeeplus.modules.act.utils.PropertyType
	 */
	@RequestMapping(value = "complete")
	@ResponseBody
	public String complete(Act act) {
		actTaskService.complete(act.getTaskId(), act.getProcInsId(), act.getComment(), act.getVars().getVariableMap());
		return "true";//adminPath + "/act/task";
	}
	
	/**
	 * 读取带跟踪的图片
	 */
	@RequestMapping(value = "trace/photo/{procDefId}/{execId}")
	public void tracePhoto(@PathVariable("procDefId") String procDefId, @PathVariable("execId") String execId, HttpServletResponse response) throws Exception {
		InputStream imageStream = actTaskService.tracePhoto(procDefId, execId);
		
		// 输出资源内容到相应对象
		byte[] b = new byte[1024];
		int len;
		while ((len = imageStream.read(b, 0, 1024)) != -1) {
			response.getOutputStream().write(b, 0, len);
		}
	}
	
	/**
	 * 输出跟踪流程信息
	 * 
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "trace/info/{proInsId}")
	public List<Map<String, Object>> traceInfo(@PathVariable("proInsId") String proInsId) throws Exception {
		List<Map<String, Object>> activityInfos = actTaskService.traceProcess(proInsId);
		return activityInfos;
	}

	/**
	 * 显示流程图
	 
	@RequestMapping(value = "processPic")
	public void processPic(String procDefId, HttpServletResponse response) throws Exception {
		ProcessDefinition procDef = repositoryService.createProcessDefinitionQuery().processDefinitionId(procDefId).singleResult();
		String diagramResourceName = procDef.getDiagramResourceName();
		InputStream imageStream = repositoryService.getResourceAsStream(procDef.getDeploymentId(), diagramResourceName);
		byte[] b = new byte[1024];
		int len = -1;
		while ((len = imageStream.read(b, 0, 1024)) != -1) {
			response.getOutputStream().write(b, 0, len);
		}
	}*/
	
	/**
	 * 获取跟踪信息
	 
	@RequestMapping(value = "processMap")
	public String processMap(String procDefId, String proInstId, Model model)
			throws Exception {
		List<ActivityImpl> actImpls = new ArrayList<ActivityImpl>();
		ProcessDefinition processDefinition = repositoryService
				.createProcessDefinitionQuery().processDefinitionId(procDefId)
				.singleResult();
		ProcessDefinitionImpl pdImpl = (ProcessDefinitionImpl) processDefinition;
		String processDefinitionId = pdImpl.getId();// 流程标识
		ProcessDefinitionEntity def = (ProcessDefinitionEntity) ((RepositoryServiceImpl) repositoryService)
				.getDeployedProcessDefinition(processDefinitionId);
		List<ActivityImpl> activitiList = def.getActivities();// 获得当前任务的所有节点
		List<String> activeActivityIds = runtimeService.getActiveActivityIds(proInstId);
		for (String activeId : activeActivityIds) {
			for (ActivityImpl activityImpl : activitiList) {
				String id = activityImpl.getId();
				if (activityImpl.isScope()) {
					if (activityImpl.getActivities().size() > 1) {
						List<ActivityImpl> subAcList = activityImpl
								.getActivities();
						for (ActivityImpl subActImpl : subAcList) {
							String subid = subActImpl.getId();
							System.out.println("subImpl:" + subid);
							if (activeId.equals(subid)) {// 获得执行到那个节点
								actImpls.add(subActImpl);
								break;
							}
						}
					}
				}
				if (activeId.equals(id)) {// 获得执行到那个节点
					actImpls.add(activityImpl);
					System.out.println(id);
				}
			}
		}
		model.addAttribute("procDefId", procDefId);
		model.addAttribute("proInstId", proInstId);
		model.addAttribute("actImpls", actImpls);
		return "modules/act/actTaskMap";
	}*/
	
	/**
	 * 删除任务
	 * @param taskId 流程实例ID
	 * @param reason 删除原因
	 */
	@ResponseBody
	@RequiresPermissions("act:process:edit")
	@RequestMapping(value = "deleteTask")
	public AjaxJson deleteTask(String taskId, String reason) {
		AjaxJson j = new AjaxJson();
		if (StringUtils.isBlank(reason)){
			j.setSuccess(false);
			j.setMsg("请填写删除原因");
		}else{
			actTaskService.deleteTask(taskId, reason);
			j.setSuccess(true);
			j.setMsg("删除任务成功，任务ID=" + taskId);
		}
		return j;
	}

	/**
	 * 审批
	 * @param act
	 */
	@ResponseBody
	@RequestMapping(value = "audit")
	public AjaxJson auditTask(Act act) {
		AjaxJson j = new AjaxJson();
		actTaskService.auditSave(act);
		j.setMsg("审批成功");
		return j;
	}


	/**
	 * 经研所审批
	 * @param act
	 */
	@ResponseBody
	@RequestMapping(value = "economics")
	public AjaxJson economics(Act act,String pic,UploadImages uploadImages) {
		AjaxJson j = new AjaxJson();
		try {
			if (pic!=null&&pic!="") {
				uploadImages.setPath(pic);
				uploadImages.setProcInsId(act.getProcInsId());
				uploadImages.setImgName("上传新图纸");
				uploadImages.setuId(UserUtils.getUser().getLoginName());
				uploadImagesService.save(uploadImages);
			}
			String comment = URLDecoder.decode(act.getComment(), "UTF-8");
			act.setComment(comment);
			actTaskService.economics(act);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		j.setMsg("审批成功");
		return j;
	}

	/**
	 * 人工选择问题类型审批
	 * @param act
	 */
	@ResponseBody
	@RequestMapping(value = "artificialTask")
	public AjaxJson artificialTask(Act act) {
		AjaxJson j = new AjaxJson();
		try {
			String comment = URLDecoder.decode(act.getComment(), "UTF-8");
			act.setComment(comment);
			actTaskService.artificialTask(act);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		j.setMsg("审批成功");
		return j;
	}
	/**
	 * 项目经理人工任何问题
	 * @param act
	 */
	@ResponseBody
	@RequestMapping(value = "humanReviewTask")
	public AjaxJson humanReviewTask(Act act) {
		AjaxJson j = new AjaxJson();
		try {
			String comment = URLDecoder.decode(act.getComment(), "UTF-8");
			act.setComment(comment);
			actTaskService.humanReviewTask(act);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		j.setMsg("审批成功");
		return j;
	}


	/**
	 * 是否可以政策处理（农场/民事）
	 * @param act
	 */
	@ResponseBody
	@RequestMapping(value = "policiesChange")
	public AjaxJson policiesChange(Act act) {
		AjaxJson j = new AjaxJson();
		try {
			String comment = URLDecoder.decode(act.getComment(), "UTF-8");
			act.setComment(comment);
			actTaskService.policiesChange(act);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		j.setMsg("审批成功");
		return j;
	}

	/**
	 * 上传借款单据
	 * @param act
	 */
	@ResponseBody
	@RequestMapping(value = "loanUploadList")
	public AjaxJson loanUploadList(Act act, String pic, UploadImages uploadImages) {
		AjaxJson j = new AjaxJson();
		try {
			if (pic!=null&&pic!="") {
				uploadImages.setPath(pic);
				uploadImages.setProcInsId(act.getProcInsId());
				uploadImages.setImgName("上传借款单据");
				uploadImages.setuId(UserUtils.getUser().getLoginName());
				uploadImagesService.save(uploadImages);
			}
			String comment = URLDecoder.decode(act.getComment(), "UTF-8");
			act.setComment(comment);
			actTaskService.loanUploadList(act);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		j.setMsg("审批成功");
		return j;
	}

	/**
	 * 项目经理重新审核是否可以政策处理（农场/民事）
	 * @param act
	 */
	@ResponseBody
	@RequestMapping(value = "managerPolicesChange")
	public AjaxJson managerPolicesChange(Act act) {
		AjaxJson j = new AjaxJson();
		try {
			String comment = URLDecoder.decode(act.getComment(), "UTF-8");
			act.setComment(comment);
			actTaskService.managerPolicesChange(act);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		j.setMsg("审批成功");
		return j;
	}

	/**
	 * 上传未签字版政策处理清单
	 * @param act
	 */
	@ResponseBody
	@RequestMapping(value = "notSignUpload")
	public AjaxJson notSignUpload(Act act, String pic, UploadImages uploadImages) {
		AjaxJson j = new AjaxJson();
		try {
			if (pic!=null&&pic!="") {
				uploadImages.setPath(pic);
				uploadImages.setProcInsId(act.getProcInsId());
				uploadImages.setImgName("上传未签字版政策处理清单");
				uploadImages.setuId(UserUtils.getUser().getLoginName());
				uploadImagesService.save(uploadImages);
			}
			String comment = URLDecoder.decode(act.getComment(), "UTF-8");
			act.setComment(comment);
			actTaskService.notSignUpload(act);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		j.setMsg("审批成功");
		return j;
	}


	/**
	 * 上传签字版政策处理清单
	 * @param act
	 */
	@ResponseBody
	@RequestMapping(value = "signUploadList")
	public AjaxJson signUploadList(Act act, String pic, UploadImages uploadImages) {
		AjaxJson j = new AjaxJson();
		try {
			if (pic!=null&&pic!="") {
				uploadImages.setPath(pic);
				uploadImages.setProcInsId(act.getProcInsId());
				uploadImages.setImgName("上传签字版政策处理清单");
				uploadImages.setuId(UserUtils.getUser().getLoginName());
				uploadImagesService.save(uploadImages);
			}
			String comment = URLDecoder.decode(act.getComment(), "UTF-8");
			act.setComment(comment);
			actTaskService.signUploadList(act);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		j.setMsg("审批成功");
		return j;
	}

	/**
	 * 上传签字版合同
	 * @param act
	 */
	@ResponseBody
	@RequestMapping(value = "contractUploadList")
	public AjaxJson contractUploadList(Act act, String pic, UploadImages uploadImages) {
		AjaxJson j = new AjaxJson();
		try {
			if (pic!=null&&pic!="") {
				uploadImages.setPath(pic);
				uploadImages.setProcInsId(act.getProcInsId());
				uploadImages.setImgName("上传签字版合同");
				uploadImages.setuId(UserUtils.getUser().getLoginName());
				uploadImagesService.save(uploadImages);
			}
			String comment = URLDecoder.decode(act.getComment(), "UTF-8");
			act.setComment(comment);
			actTaskService.contractUploadList(act);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		j.setMsg("审批成功");
		return j;
	}

	/**
	 * 配网运行人员判定设计变更
	 * @param act
	 */
	@ResponseBody
	@RequestMapping(value = "operator")
	public AjaxJson operator(Act act, String pic, UploadImages uploadImages) {
		AjaxJson j = new AjaxJson();
		try {
			if (pic!=null&&!"".equals(pic)) {
				uploadImages.setPath(pic);
				uploadImages.setProcInsId(act.getProcInsId());
				uploadImages.setuId(UserUtils.getUser().getLoginName());
				uploadImages.setImgName("新方案图纸");
				uploadImagesService.save(uploadImages);
			}
			String comment = URLDecoder.decode(act.getComment(), "UTF-8");
			act.setComment(comment);
			actTaskService.operator(act);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		j.setMsg("审批成功");
		return j;
	}

	/**
	 * 项目经理判断是否需要设计变更
	 * @param act
	 */
	@ResponseBody
	@RequestMapping(value = "managerDesign")
	public AjaxJson managerDesign(Act act) {
		AjaxJson j = new AjaxJson();
		try {
			String comment = URLDecoder.decode(act.getComment(), "UTF-8");
			act.setComment(comment);
			actTaskService.managerDesign(act);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		j.setMsg("审批成功");
		return j;
	}

	/**
	 * 设计单位人员提交文件
	 * @param act
	 */
	@ResponseBody
	@RequestMapping(value = "designUpload")
	public AjaxJson designUpload(Act act, String pic, String pic1,String pic2,UploadImages uploadImages) {
		AjaxJson j = new AjaxJson();
		try {
			if (pic!=null&&pic!="") {
				uploadImages.setPath(pic);
				uploadImages.setProcInsId(act.getProcInsId());
				uploadImages.setImgName("变更后图纸");
				uploadImages.setuId(UserUtils.getUser().getLoginName());
				uploadImagesService.insert(uploadImages);
			}
			if (pic1!=null&&pic1!="") {
				uploadImages.setPath(pic1);
				uploadImages.setProcInsId(act.getProcInsId());
				uploadImages.setImgName("预算书");
				uploadImages.setuId(UserUtils.getUser().getLoginName());
				uploadImagesService.insert(uploadImages);
			}
			if (pic2!=null&&pic2!="") {
				uploadImages.setPath(pic2);
				uploadImages.setProcInsId(act.getProcInsId());
				uploadImages.setImgName("物资清册");
				uploadImages.setuId(UserUtils.getUser().getLoginName());
				uploadImagesService.insert(uploadImages);
			}
			String comment = URLDecoder.decode(act.getComment(), "UTF-8");
			act.setComment(comment);
			actTaskService.designUpload(act);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		j.setMsg("审批成功");
		return j;
	}

	/**
	 * 配网运行人员判断变更后材料
	 * @param act
	 */
	@ResponseBody
	@RequestMapping(value = "operatorUpload")
	public AjaxJson operatorUpload(Act act) {
		AjaxJson j = new AjaxJson();
		try {
			String comment = URLDecoder.decode(act.getComment(), "UTF-8");
			act.setComment(comment);
			actTaskService.operatorUpload(act);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		j.setMsg("审批成功");
		return j;
	}

	/**
	 * 配网项目经理判断变更后材料
	 * @param act
	 */
	@ResponseBody
	@RequestMapping(value = "managerUpload")
	public AjaxJson managerUpload(Act act) {
		AjaxJson j = new AjaxJson();
		try {
			String comment = URLDecoder.decode(act.getComment(), "UTF-8");
			act.setComment(comment);
			actTaskService.managerUpload(act);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		j.setMsg("审批成功");
		return j;
	}

	/**
	 * 施工审批
	 * @param act
	 */
	@ResponseBody
	@RequestMapping(value = "audit2")
	public AjaxJson auditTask2(Act act) {
		AjaxJson j = new AjaxJson();
		try {
			String comment = URLDecoder.decode(act.getComment(), "UTF-8");
			act.setComment(comment);
			actTaskService.auditSave2(act);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		j.setMsg("审批成功");
		return j;
	}

	/**
	 * 项目经理组织交底
	 * @param
	 */
	@ResponseBody
	@RequestMapping(value = "audit3")
	public AjaxJson auditTask3(Act act) {
		AjaxJson j = new AjaxJson();
		String s = "";
//		MyNeedList 项目经理组织交底 = MyActiviUtils.findActivity("项目经理组织交底");
		boolean flag = false;
		Disclose dc = new Disclose();
		dc.setProcInsId(act.getProcInsId());
		Disclose disclose = discloseService.get(dc);
		if (null==disclose){
			j.setSuccess(false);
			j.setMsg("请导入数据");
			return j;
		}
		Boolean flagDesign = actTaskService.isJudgeDesign(disclose);//设计变更
		Boolean flagItemCLose =actTaskService.isJudgeItemClose(disclose);//项目关闭
		String flagDeal =actTaskService.newJudgeDeal(disclose);
		if (null==disclose.getPrecondition()||"".equals(disclose.getPrecondition())){
			if (flagItemCLose){
				if (null==disclose.getExplanationOfNecessity()||disclose.getExplanationOfNecessity().equals("")){
					s="必要性问题说明不能为空!";
					flag = true;
				}
			}
			if (flagDesign){
				if (null==disclose.getInconsistentDescription()||disclose.getInconsistentDescription().equals("")){
					s+="图纸现场不一致说明不能为空!";
					flag = true;
				}
			}
			if ("民事农村".equals(flagDeal)||"行政".equals(flagDeal)) {
				String policyHandlingInstructions = disclose.getPolicyHandlingInstructions();
				if (policyHandlingInstructions == null || "".equals(policyHandlingInstructions)) {
					s += "政策处理说明不能为空";
					flag = true;
				}
			}
			if (null==disclose.getPolicyHandlingInstructions()||disclose.getPolicyHandlingInstructions().equals("")){
				s+=" 政策处理说明不能为空!";
				flag=true;
			}

			if (flag){
				j.setSuccess(false);
				j.setMsg(s);
				return j;
			}
		}
		try {
			String comment = URLDecoder.decode(act.getComment(), "UTF-8");
			act.setComment(comment);
			actTaskService.auditSave3(act,disclose,flagDesign,flagItemCLose,flagDeal);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		j.setMsg("审批成功");
		return j;
	}
	/*
		交底:判断项目是否需要关闭
	 */
	@ResponseBody
	@RequestMapping(value = "speciallyTask")
	public AjaxJson speciallyTask(Act act,String tuser,Construction construction) {
		AjaxJson j = new AjaxJson();

		try {
			String comment = URLDecoder.decode(act.getComment(), "UTF-8");
			act.setComment(comment);
			actTaskService.specially(act);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		if ("yes".equals(act.getFlag())){
			j.setMsg("审批成功");
		}else {
			j.setMsg("驳回成功");
		}
		return j;
	}
	/*
		项目关闭：项目经理
	 */
	@ResponseBody
	@RequestMapping(value = "managerFormTask")
	public AjaxJson managerFormTask(Act act,String fullName,String tuser,Construction construction) {
		AjaxJson j = new AjaxJson();
		try {
			String comment = URLDecoder.decode(act.getComment(), "UTF-8");
			act.setComment(comment);
			actTaskService.managerFormTask(act,fullName);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		if ("yes".equals(act.getFlag())){
			j.setMsg("审批成功");
		}else {
			j.setMsg("驳回成功");
		}

		return j;
	}
	/*
		项目关闭：运行人员
	 */
	@ResponseBody
	@RequestMapping(value = "memberTask")
	public AjaxJson memberTask(Act act,String fullTime,String tuser,Construction construction) {
		AjaxJson j = new AjaxJson();
		try {
			String comment = URLDecoder.decode(act.getComment(), "UTF-8");
			act.setComment(comment);
			actTaskService.addMember(act,fullTime);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		if ("yes".equals(act.getFlag())){
			j.setMsg("审批成功");
		}else {
			j.setMsg("驳回成功");
		}

		return j;
	}
	/*
		项目关闭：系统专职
	 */
	@ResponseBody
	@RequestMapping(value = "departmentTask")
	public AjaxJson departmentTask(Act act,String tuser,Construction construction) {
		AjaxJson j = new AjaxJson();
		try {
			String comment = URLDecoder.decode(act.getComment(), "UTF-8");
			act.setComment(comment);
			actTaskService.addDepartment(act);
			projectService.updateStatusBy("0",act.getProcInsId());
			projectService.updateStatusByClose("1",act.getProcInsId());
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		Project user = MyActiviUtils.findUser(act.getProcInsId());
		User user1 = systemService.getUserByLoginName(user.getProjectManageRole());
		OaNotify  oaNotify = new OaNotify();
		oaNotify.setType("4");
		oaNotify.setTitle("施工交底结束");
		oaNotify.setContent("施工交底结束");
		oaNotify.setStatus("1");
		oaNotify.setOaNotifyRecordIds(user1.getId());
		oaNotifyService.save(oaNotify);
		List<OaNotifyRecord> list = oaNotify.getOaNotifyRecordList();
		for(OaNotifyRecord o : list){
			//发送通知到客户端
			ServletContext context = SpringContextHolder
					.getBean(ServletContext.class);
			new SystemInfoSocketHandler().sendMessageToUser(UserUtils.get(o.getUser().getId()).getLoginName(), "收到一条新通知，请到我的通知查看！");
		}
		j.setMsg("审批成功;已经通知"+user.getProjectManageRole());
		return j;
	}

	@ResponseBody
	@RequestMapping(value = "policiesDealTask")
	public AjaxJson policiesDealTask(Act act,String fullName,String tuser,Construction construction) {
		AjaxJson j = new AjaxJson();
		try {
			String comment = URLDecoder.decode(act.getComment(), "UTF-8");
			act.setComment(comment);
			actTaskService.policiesDeal(act,fullName);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		if ("yes".equals(act.getFlag())){
			j.setMsg("审批成功");
		}else {
			j.setMsg("驳回成功");
		}

		return j;
	}
	/*
		政策处理：施工单位人员上传未覆盖盖章
	 */
	@ResponseBody
	@RequestMapping(value = "coveredTask")
	public AjaxJson coveredTask(Act act,String fullName,String pic, UploadImages uploadImages) {
		AjaxJson j = new AjaxJson();
		try {
			if (pic!=null&&pic!="") {
				uploadImages.setPath(pic);
				uploadImages.setProcInsId(act.getProcInsId());
				uploadImages.setImgName("上传未盖章施工方案");
				uploadImages.setuId(UserUtils.getUser().getLoginName());
				uploadImagesService.save(uploadImages);
			}
			String comment = URLDecoder.decode(act.getComment(), "UTF-8");
			act.setComment(comment);
			actTaskService.covered(act,fullName);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		if ("yes".equals(act.getFlag())){
			j.setMsg("审批成功");
		}else {
			j.setMsg("驳回成功");
		}
		return j;
	}
	/*
		政策处理：施工单位人员上传盖章施工方案
	 */
	@ResponseBody
	@RequestMapping(value = "sealTask")
	public AjaxJson sealTask(Act act,String pic, UploadImages uploadImages) {
		AjaxJson j = new AjaxJson();
		try {
			if (pic!=null&&pic!="") {
				uploadImages.setPath(pic);
				uploadImages.setProcInsId(act.getProcInsId());
				uploadImages.setImgName("上传盖章施工方案");
				uploadImages.setuId(UserUtils.getUser().getLoginName());
				uploadImagesService.save(uploadImages);
			}
			String comment = URLDecoder.decode(act.getComment(), "UTF-8");
			act.setComment(comment);
			actTaskService.seal(act);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		if ("yes".equals(act.getFlag())){
			j.setMsg("审批成功");
		}else {
			j.setMsg("驳回成功");
		}
		return j;
	}
	@ResponseBody
	@RequestMapping(value = "phaseManagerTask")
	public AjaxJson phaseManagerTask(Act act,String fullName) {
		AjaxJson j = new AjaxJson();
		try {
			String comment = URLDecoder.decode(act.getComment(), "UTF-8");
			act.setComment(comment);
			actTaskService.phaseManager(act,fullName);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		if ("yes".equals(act.getFlag())){
			j.setMsg("审批成功");
		}else {
			j.setMsg("驳回成功");
		}
		return j;
	}
	/*
		政策处理：配网政策处理专职 : 上传收据
	 */
	@ResponseBody
	@RequestMapping(value = "receiptTask")
	public AjaxJson receiptTask(Act act,String pic, UploadImages uploadImages) {
		AjaxJson j = new AjaxJson();
		try {
			if (pic!=null&&pic!="") {
				uploadImages.setPath(pic);
				uploadImages.setProcInsId(act.getProcInsId());
				uploadImages.setImgName("上传收据");
				uploadImages.setuId(UserUtils.getUser().getLoginName());
				uploadImagesService.save(uploadImages);
			}
			String comment = URLDecoder.decode(act.getComment(), "UTF-8");
			act.setComment(comment);
			actTaskService.receiptTask(act);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		if ("yes".equals(act.getFlag())){
			j.setMsg("审批成功");
		}else {
			j.setMsg("驳回成功");
		}
		return j;
	}
	/*
		政策处理：配网政策处理专职 :上传缴费单
	 */
	@ResponseBody
	@RequestMapping(value = "singleTask")
	public AjaxJson singleTask(Act act,String pic, UploadImages uploadImages) {
		AjaxJson j = new AjaxJson();
		try {
			if (pic!=null&&pic!="") {
				uploadImages.setPath(pic);
				uploadImages.setProcInsId(act.getProcInsId());
				uploadImages.setImgName("上传缴费单");
				uploadImages.setuId(UserUtils.getUser().getLoginName());
				uploadImagesService.save(uploadImages);
			}
			String comment = URLDecoder.decode(act.getComment(), "UTF-8");
			act.setComment(comment);
			actTaskService.singleTask(act);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		j.setMsg("审批成功");
		return j;
	}
	/*
		政策处理：配网政策处理专职 :上传借款单据
	 */
	@ResponseBody
	@RequestMapping(value = "policyPay1Task")
	public AjaxJson policyPay1Task(Act act,String pic, UploadImages uploadImages) {
		AjaxJson j = new AjaxJson();
		try {
			if (pic!=null&& !pic.equals("")) {
				uploadImages.setPath(pic);
				uploadImages.setProcInsId(act.getProcInsId());
				uploadImages.setImgName("上传借款单据");
				uploadImages.setuId(UserUtils.getUser().getLoginName());
				uploadImagesService.save(uploadImages);
			}
			String comment = URLDecoder.decode(act.getComment(), "UTF-8");
			act.setComment(comment);
			actTaskService.policy1Pay(act);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		j.setMsg("审批成功");
		return j;
	}
	/**
	 * 施工交底审批
	 * @param act*/
	@ResponseBody
	@RequestMapping(value = "newAudit")
	public AjaxJson newAuditTask(Act act,String tuser,Construction construction) {
		AjaxJson j = new AjaxJson();
		try {
			String comment = URLDecoder.decode(act.getComment(), "UTF-8");
			act.setComment(comment);
			actTaskService.newAuditSave(act,tuser,construction);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		j.setMsg("审批成功");
		return j;
	}

	/**
	 * 取回流程
	 * @param taskId
	 */
	@ResponseBody
	@RequestMapping(value = "callback")
	public AjaxJson callback(@Param("taskId") String taskId) {
		AjaxJson j = new AjaxJson();
		try {
			Map<String, Object> variables;
			// 取得当前任务
			HistoricTaskInstance currTask = historyService
					.createHistoricTaskInstanceQuery().taskId(taskId)
					.singleResult();
			// 取得流程实例
			ProcessInstance instance = runtimeService
					.createProcessInstanceQuery()
					.processInstanceId(currTask.getProcessInstanceId())
					.singleResult();
			if (instance == null) {
				j.setSuccess(false);
				j.setMsg("流程已经结束");
				return j;
			}
			variables=instance.getProcessVariables();
			// 取得流程定义
			ProcessDefinitionEntity definition = (ProcessDefinitionEntity) ((RepositoryServiceImpl) repositoryService)
					.getDeployedProcessDefinition(currTask
							.getProcessDefinitionId());
			if (definition == null) {
				j.setSuccess(false);
				j.setMsg("流程定义未找到");
				return j;
			}
			// 取得下一步活动
			ActivityImpl currActivity = ((ProcessDefinitionImpl) definition)
					.findActivity(currTask.getTaskDefinitionKey());
			List<PvmTransition> nextTransitionList = currActivity
					.getOutgoingTransitions();
			for (PvmTransition nextTransition : nextTransitionList) {
				PvmActivity nextActivity = nextTransition.getDestination();
				List<HistoricTaskInstance> completeTasks = historyService
						.createHistoricTaskInstanceQuery()
						.processInstanceId(instance.getId())
						.taskDefinitionKey(nextActivity.getId()).finished()
						.list();
				int finished = completeTasks.size();
				if (finished > 0) {
					j.setSuccess(false);
					j.setMsg("存在已经完成的下一步，流程不能取回");
					return j;
				}
				List<Task> nextTasks = taskService.createTaskQuery().processInstanceId(instance.getId())
						.taskDefinitionKey(nextActivity.getId()).list();
				for (Task nextTask : nextTasks) {
					//取活动，清除活动方向
					List<PvmTransition> oriPvmTransitionList = new ArrayList<PvmTransition>();
					List<PvmTransition> pvmTransitionList = nextActivity
							.getOutgoingTransitions();
					for (PvmTransition pvmTransition : pvmTransitionList) {
						oriPvmTransitionList.add(pvmTransition);
					}
					pvmTransitionList.clear();
					//建立新方向
					ActivityImpl nextActivityImpl = ((ProcessDefinitionImpl) definition)
							.findActivity(nextTask.getTaskDefinitionKey());
					TransitionImpl newTransition = nextActivityImpl
							.createOutgoingTransition();
					newTransition.setDestination(currActivity);
					//完成任务
					taskService.complete(nextTask.getId(), variables);
					historyService.deleteHistoricTaskInstance(nextTask.getId());
					//恢复方向
					currActivity.getIncomingTransitions().remove(newTransition);
					List<PvmTransition> pvmTList = nextActivity
							.getOutgoingTransitions();
					pvmTList.clear();
					for (PvmTransition pvmTransition : oriPvmTransitionList) {
						pvmTransitionList.add(pvmTransition);
					}
				}
			}
			historyService.deleteHistoricTaskInstance(currTask.getId());
			j.setSuccess(true);
			j.setMsg("取回成功");
			return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("流程取回失败，未知错误.");
			return j;
		}
	}


	/**
	 * 根据实例编号查找下一个任务节点
	 * @param  procInstId ：实例编号
	 * @return
	 */
	public String nextTaskDefinition(String procInstId){
		//流程标示
		String processDefinitionId = historyService.createHistoricProcessInstanceQuery().processInstanceId(procInstId).singleResult().getProcessDefinitionId();

		ProcessDefinitionEntity def = (ProcessDefinitionEntity) ((RepositoryServiceImpl)repositoryService).getDeployedProcessDefinition(processDefinitionId);
		//执行实例
		ExecutionEntity execution = (ExecutionEntity) runtimeService.createProcessInstanceQuery().processInstanceId(procInstId).singleResult();
		//当前实例的执行到哪个节点
		if(execution == null){
			TaskDefinition[] taskDefinitions = {};
			taskDefinitions = def.getTaskDefinitions().values().toArray(taskDefinitions);
			return taskDefinitions[taskDefinitions.length -1].getKey();
		}else{
			return  execution.getActivityId();
		}
	}

	@ResponseBody
	@RequestMapping(value = "pickIng")
	public AjaxJson pickIng(Act act,String selectNumber) {
		AjaxJson j = new AjaxJson();
		try {
			pickIngService.updateSelectNumber(selectNumber, act.getProcInsId());
			String comment = URLDecoder.decode(act.getComment(), "UTF-8");
			act.setComment(comment);
			actTaskService.pickIng(act);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		j.setMsg("审批成功");
		return j;
	}

	/**
	 * 审批
	 * @param act
	 */
	@ResponseBody
	@RequestMapping(value = "constructionLeader")
	public AjaxJson constructionLeader(Act act) {
		AjaxJson j = new AjaxJson();
		actTaskService.constructionLeader(act);
		j.setMsg("审批成功");
		return j;
	}


	/**
	 * 运行人员审核图纸
	 * */
	@ResponseBody
	@RequestMapping(value = "auditDrawings")
	public AjaxJson auditDrawings(Act act) {
		AjaxJson j = new AjaxJson();
		try {
			String comment = URLDecoder.decode(act.getComment(), "UTF-8");
			act.setComment(comment);
			actTaskService.auditDrawings(act);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		j.setMsg("审批成功");
		return j;
	}

	/**
	 * 项目经理审核流程提前领料是否通过
	 * */
	@ResponseBody
	@RequestMapping(value = "applicationAudit")
	public AjaxJson applicationAudit(Act act) {
		AjaxJson j = new AjaxJson();
		try {
			String comment = URLDecoder.decode(act.getComment(), "UTF-8");
			act.setComment(comment);
			actTaskService.applicationAudit(act);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		j.setMsg("审批成功");
		return j;
	}

}
