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

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

import com.google.common.collect.Maps;
import com.jeeplus.common.utils.MenuStatusEnum;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.websocket.onchat.ChatServerPool;
import com.jeeplus.modules.act.service.ActTaskService;
import com.jeeplus.modules.act.utils.ActUtils;
import com.jeeplus.modules.serialnum.service.SerialNumTplService;
import com.jeeplus.modules.sys.entity.Office;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.service.OfficeService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workactivity.dao.WorkActivityProcessDao;
import com.jeeplus.modules.workactivity.entity.Activity;
import com.jeeplus.modules.workactivity.entity.WorkActivityProcess;
import com.jeeplus.modules.workactivity.service.ActivityService;
import com.jeeplus.modules.workactivity.service.WorkActivityProcessService;
import com.jeeplus.modules.workactivitymenu.entity.WorkActivityMenu;
import com.jeeplus.modules.workactivitymenu.service.WorkActivityMenuService;
import com.jeeplus.modules.workclientinfo.dao.WorkClientAttachmentDao;
import com.jeeplus.modules.workclientinfo.entity.WorkClientAttachment;
import com.jeeplus.modules.workcontractinfo.dao.WorkContractInfoDao;
import com.jeeplus.modules.workcontractinfo.service.WorkContractInfoService;
import com.jeeplus.modules.workprojectnotify.entity.WorkProjectNotify;
import com.jeeplus.modules.workprojectnotify.service.WorkProjectNotifyService;
import com.jeeplus.modules.workprojectnotify.util.UtilNotify;
import org.activiti.engine.ActivitiObjectNotFoundException;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.java_websocket.WebSocket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeeplus.modules.workcontractinfo.entity.WorkContractInfo;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.service.CrudService;
import com.jeeplus.modules.workcontractrecord.entity.WorkContractRecord;
import com.jeeplus.modules.workcontractrecord.dao.WorkContractRecordDao;

/**
 * 合同归档Service
 * @author lw
 * @version 2018-06-08
 */
@Service
@Transactional(readOnly = true)
public class WorkContractRecordService extends CrudService<WorkContractRecordDao, WorkContractRecord> {
	@Autowired
	private WorkClientAttachmentDao workClientAttachmentDao;
	@Autowired
	private WorkContractInfoService workConttractInfoService;
	@Autowired
	private WorkContractInfoService workContractInfoService;
	@Autowired
	private IdentityService identityService;
	@Autowired
	private WorkActivityMenuService workActivityMenuService;
	@Autowired
	private WorkProjectNotifyService workProjectNotifyService;
	@Autowired
	private RuntimeService runtimeService;
	@Autowired
	private OfficeService officeService;

	@Autowired
	private WorkActivityProcessService workActivityProcessService;
	@Autowired
	private WorkContractRecordDao workContractRecordDao;
	@Autowired
	private ActTaskService actTaskService;
	@Autowired
	private ActivityService activityService;
	@Autowired
	private WorkActivityProcessDao workActivityProcessDao;
	@Autowired
	private SerialNumTplService serialNumTplService;

	@SuppressWarnings("unchecked")
	public WorkContractRecord get(String id) {
		WorkContractRecord workContractRecord = super.get(id);
		//附件
		if(workContractRecord!=null){
			WorkClientAttachment workClientAttachment = new WorkClientAttachment();
			workClientAttachment.setAttachmentId(id);
			workClientAttachment.setAttachmentFlag("85");
			workContractRecord.setWorkAttachments(workClientAttachmentDao.findList(workClientAttachment));
			if(workContractRecord!=null&&workContractRecord.getWorkContractInfo()!=null&& StringUtils.isNotBlank(workContractRecord.getWorkContractInfo().getId())){
				WorkContractInfo w = workConttractInfoService.get(workContractRecord.getWorkContractInfo().getId());
				if(w!=null){
					workContractRecord.setWorkContractInfo(w);
				}
			}
		}
		return workContractRecord;
	}
	
	public List<WorkContractRecord> findList(WorkContractRecord workContractRecord) {
		return super.findList(workContractRecord);
	}
	
	public Page<WorkContractRecord> findPage(Page<WorkContractRecord> page, WorkContractRecord workContractRecord) {
//		workContractRecord.getSqlMap().put("dsf", dataScopeFilter(workContractRecord.getCurrentUser(), "o", "u","s", MenuStatusEnum.WORK_CONTRACTRECORD.getValue()));
		String companyId = UserUtils.getUser().getComId();
		workContractRecord.getSqlMap().put("dsf","and (a.company_id='"+companyId+"')");
		workContractRecord.setPage(page);
		page.setList(findList(workContractRecord));
		return page;
	}
	
	@Transactional(readOnly = false)
	public void save(WorkContractRecord workContractRecord) {
		super.save(workContractRecord);
		updateWorkReimbursementInfo(workContractRecord);
	}

	/**
	 * 提交存储
	 * @param
	 * @param variables
	 */
	@Transactional(readOnly = false)
	public String save(WorkContractRecord workContractRecord, Map<String, Object> variables, String processInstanceId) {
			User user = UserUtils.getUser();
		WorkContractInfo workContractInfo = workContractInfoService.get(workContractRecord.getWorkContractInfo().getId());
			String recordNum = this.findRecordNum(workContractInfo.getContractNum());
			if(StringUtils.isBlank(recordNum)){
				workContractRecord.setRecordNum(workContractInfo.getContractNum()+"-1");
			}else{
				workContractRecord.setRecordNum(recordNum);
			}
			super.save(workContractRecord);
			String str = "";
			Office office = officeService.get(workContractRecord.getOfficeId());
			str =  "归档申请编号："+workContractRecord.getRecordNum()+",主委托方："+workContractRecord.getWorkContractInfo().getClient().getName()+",申请人:"+user.getName()+",所属部门:"+office.getName();
			String title = "合同名称:"+workContractRecord.getWorkContractInfo().getName();
			updateWorkReimbursementInfo(workContractRecord);
			// 用来设置启动流程的人员ID，引擎会自动把用户ID保存到activiti:initiator中
			identityService.setAuthenticatedUserId(user.getId());
			// 启动流程
			String businessKey = workContractRecord.getId().toString();
			WorkActivityMenu workActivityMenu = workActivityMenuService.findByParentAndOffice("zth3125f1f194c82bdea9htgdc750904", office);
			// 启动流程
			String processType = workActivityMenu.getProcessType();
			StringBuffer buffer = new StringBuffer();
			Activity activity = new Activity();
			WorkProjectNotify workProjectNotify = UtilNotify
					.saveNotify(workContractRecord.getId(),
							null,
							workContractRecord.getCompanyId(),
							title,
							str,
							"42",
							"0",
							"待审批",
							""
					);
			List<User> users = new ArrayList<>();
			List<User> bmzrs = UserUtils.getByRoleActivityEnname("htgdgly",3,office.getId(),"8",workContractRecord.getCreateBy());

			if (StringUtils.isNotBlank(workActivityMenu.getId())) {
				workProjectNotify.setNotifyRole("");
				workActivityMenu = workActivityMenuService.get(workActivityMenu.getId());
				List<Activity> activities = workActivityMenu.getActivities();
				for (Activity a : activities) {
					String encount = a.getEncount();
					String enlist = a.getEnlist();
					if (a.getRole()!=null && StringUtils.isNotBlank(a.getRole().getEnname())){
						List enusers = UserUtils.getByRoleActivityEnnames(a.getRole().getEnname(),office.getId(),"3",workContractRecord.getCreateBy());
						if (enusers.size()==0){
							return "流程审批人不能为空,角色"+a.getRole().getName()+"下无用户,请联系管理员！";
						}
						variables.put(enlist, enusers);
						variables.put(encount, enusers.size());
					}
					if (a.getDelFlag().equals("0") && a.getCount() == 1) {
						activity = a;
					}
				}
				buffer.append(activity.getRole().getEnname());
				if (activity != null && StringUtils.isNotBlank(activity.getId())) {
					//角色审批
					if (StringUtils.isNotBlank(activity.getRole().getEnname())) {
						users = UserUtils.getByRoleActivityEnnames(activity.getRole().getEnname(),office.getId(),"3",workContractRecord.getCreateBy());
					}
					//人员审批
					if (StringUtils.isNotBlank(activity.getUser().getId())) {
						users.add(activity.getUser());
					}
				}
				workProjectNotify.setId("");
			} else {
				if (bmzrs.size()==0){
					return "流程审批人不能为空,角色合同归档管理员下无用户,请联系管理员！";
				}
				variables.put("bmzrList", bmzrs);
				variables.put("bmzrCount",bmzrs.size());
				processType = "contractArchive";
				users.addAll(bmzrs);
			}
			for (User u : users){
				workProjectNotify.setUser(u);
				workProjectNotify.setId("");
				workProjectNotify.setNotifyRole("归档管理员审批");
				workProjectNotifyService
						.save(workProjectNotify);
				/*List<WebSocket> toUserConns = ChatServerPool.getWebSocketByUser(u.getId());
				for (WebSocket toUserConn:toUserConns) {
					String message = "{\"to\":\""+u.getId()+"\"," +
							"\"msg\":\"审批信息 归档申请人："+user.getName()+",归档合同："+workContractRecord.getRecordNum() + " 待审批!\"," +
							"\"useType\":\"sys\"}";
					ChatServerPool.sendMessageToUser(toUserConn, message);//同时向本人发送消息
				}*/
				Map<String,Object> extras = new HashMap<>();
				extras.put("type","7001");
				extras.put("id",workProjectNotify.getId());
				extras.put("procDefKey","42");
				UserUtils.pushInfoToApp(title,str,extras,u.getId());
				UserUtils.pushIm(u.getId(),str);
			}
			variables.put("type", processType);
			variables.put("busId", businessKey);
			variables.put("title", "审批单：" + workContractRecord.getRecordNum());//设置标题；

			ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processType, businessKey, variables);
			workContractRecord.setProcessInstance(processInstance);
			if (StringUtils.isNotBlank(processInstanceId)) {
				workActivityProcessService.updateProcessInstanceId(processInstance.getId(),processInstanceId);
				workActivityProcessService.deleteProcessInstanceId(processInstanceId);
				workActivityProcessService.deleteProcessIdAuditUsers(processInstanceId);
			}
			// 更新流程实例ID
			workContractRecord.setProcessInstanceId(processInstance.getId());
			workContractRecordDao.updateProcessInstanceId(workContractRecord);
			List<Activity> list = workActivityMenu.getActivities();
			if (list != null && list.size() != 0) {
				workActivityProcessService.saveList(list, processInstance.getId());
			} else {
				WorkActivityProcess workActivityProcess = new WorkActivityProcess();
				workActivityProcess.setProcessKey("contractArchive");
				workActivityProcess.setCount(1);
				workActivityProcess.setProcessInstanceId(processInstance.getId());
				workActivityProcess.setIsApproval("0");
				workActivityProcessService.save(workActivityProcess);
				workActivityProcessService.insertAuditsByType(bmzrs,processInstance.getId(),1,1);
			}
			logger.debug("start process of {key={}, bkey={}, pid={}, variables={}}", new Object[]{
					ActUtils.PD_REIMBURSEMENT[0], businessKey, processInstance.getId(), variables});

		return "";
	}
	@Transactional(readOnly = false)
	public void updateWorkReimbursementInfo(WorkContractRecord workContractRecord) {
		//附件信息
		for (WorkClientAttachment workClientAttachment : workContractRecord.getWorkAttachments()) {
			if (workClientAttachment.getId() == null) {
				continue;
			}
			if (WorkClientAttachment.DEL_FLAG_NORMAL.equals(workClientAttachment.getDelFlag())) {
				workClientAttachment.setAttachmentId(workContractRecord.getId());
				workClientAttachment.setAttachmentFlag("85");
				workClientAttachment.setAttachmentUser(UserUtils.getUser().getId());
				if (StringUtils.isBlank(workClientAttachment.getId()) || "null".equals(workClientAttachment.getId())) {
					workClientAttachment.preInsert();
					workClientAttachmentDao.insert(workClientAttachment);
				} else {
					workClientAttachment.preUpdate();
					workClientAttachmentDao.update(workClientAttachment);
				}
			} else {
				workClientAttachmentDao.delete(workClientAttachment);
			}
		}
	}
	@Transactional(readOnly = false)
	public void delete(WorkContractRecord workContractRecord) {
		//恢复为待归档状态
		if(workContractRecord.getWorkContractInfo()!=null){
			if(StringUtils.isNotBlank(workContractRecord.getWorkContractInfo().getId())){
				WorkContractInfo workContractInfo = workConttractInfoService.get(workContractRecord.getWorkContractInfo().getId());
				workContractInfo.setRecordState("1");
				workConttractInfoService.save(workContractInfo);
			}
		}
		super.delete(workContractRecord);
		WorkProjectNotify notify = new WorkProjectNotify();
		notify.setNotifyId(workContractRecord.getId());
		List<User> users = workProjectNotifyService.readByNotifyId(notify);
		if (users!=null && users.size()!=0){
			for (User user:users){
				UserUtils.pushMeIm(user.getId());
			}
		}
	}

	/**
	 * 审核流程
	 * @param
	 */
	@Transactional(readOnly = false)
	public String auditSave(WorkContractRecord workContractRecord,List<User> auditUsers) {
			String userName = UserUtils.get(workContractRecord.getCreateBy().getId()).getName();
			Office office = officeService.get(workContractRecord.getOfficeId());
			String str =  "归档申请编号："+workContractRecord.getRecordNum()+",主委托方："+workContractRecord.getWorkContractInfo().getClient().getName()+",申请人:"+userName+",所属部门:"+office.getName();
			String title = "合同名称:"+workContractRecord.getWorkContractInfo().getName();
			// 对不同环节的业务逻辑进行操作
			String taskDefKey = workContractRecord.getAct().getTaskDefKey();
			if (!"modifyApply".equals(taskDefKey)) {
				actTaskService.claim(workContractRecord.getAct().getTaskId(), UserUtils.getUser().getId());
			}else {
				workContractRecord.getAct().setFlag("yes");
				updateWorkReimbursementInfo(workContractRecord);
			}
			String comment = "";
			if (workContractRecord.getStatus().equals("4")){
				comment = ("yes".equals(workContractRecord.getAct().getFlag())?"[重新申请] ":"[已撤销] ");
			}else {
				comment = ("yes".equals(workContractRecord.getAct().getFlag())?"[同意] ":"[驳回] ")+workContractRecord.getAct().getComment();
			}
			//yes 的时候状态为审核通过 否则为未通过
			workContractRecord.setStatus(("yes".equals(workContractRecord.getAct().getFlag()) ? "2" : "4"));
			Map<String, Object> vars = Maps.newHashMap();
			//业务逻辑对应的条件表达式
			String exp = "";
			String taskCount = "";
			String notifyRole = "";
			int key = 0;
			String enname = "";
			List<Activity> activitieList = activityService.getByProcessInstanceId(workContractRecord.getProcessInstanceId());
			WorkActivityMenu workActivityMenu = new WorkActivityMenu();
			if (activitieList != null && activitieList.size() != 0) {
				workActivityMenu.setProcessType(activitieList.get(0).getProcessKey());
				workActivityMenu.setActivities(activitieList);
			}

			WorkActivityProcess workActivityProcess = new WorkActivityProcess();
			WorkActivityProcess selectProcess = new WorkActivityProcess();
			selectProcess.setProcessInstanceId(workContractRecord.getProcessInstanceId());
			List<WorkActivityProcess> workActivityProcesses = workActivityProcessService.findList(selectProcess);
			List<Activity> activities = workActivityMenu.getActivities();
			if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("contractArchive")) {
				key = 1;
				for (int i = 0; i < workActivityProcesses.size(); i++) {
					WorkActivityProcess activityProcess = workActivityProcesses.get(i);
					if (taskDefKey.equals(activityProcess.getActivityTask()) && !taskDefKey.equals("modifyApply")) {
						taskCount = activityProcess.getCount()+"";
						workActivityProcess = activityProcess;
						if (!workActivityProcess.getIsApproval().equals("0")) {
							workActivityProcess.setId("");
						}
						exp = "pass";
						if (!"yes".equals(workContractRecord.getAct().getFlag())) {
							workContractRecord.setStatus("4");
							workActivityProcess.setIsApproval("2");
							String returnBack = "-1";
							for (Activity activity : activities) {
								if (activity.getCount() == activityProcess.getCount()) {
									notifyRole = activity.getName();
									returnBack = activity.getReturnBack();
									break;
								}
							}
							if (returnBack.equals("0")) {
								workActivityProcess.setId("");
							}

						} else {
							workActivityProcess.setIsApproval("1");
						}
					}else if(taskDefKey.equals("modifyApply")){
						notifyRole = "调整申请";
						taskCount = "0";
						exp = "pass";
						workActivityProcess.setId("");
						workActivityProcess.setCount(0);
						if (!"yes".equals(workContractRecord.getAct().getFlag())) {
							workContractRecord.setStatus("3");
							workActivityProcess.setIsApproval("2");
						} else {
							workActivityProcess.setIsApproval("1");
						}
						break;
					}
				}
			} else {
				workActivityMenu.setProcessType("contractArchive");
				for (int i = 0; i < workActivityProcesses.size(); i++) {
					WorkActivityProcess activityProcess = workActivityProcesses.get(i);
					String count = activityProcess.getCount() + "";
					workActivityProcess = activityProcess;
					if (!workActivityProcess.getIsApproval().equals("0")) {
						workActivityProcess.setId("");
					}
					// 审核环节
					if ("bmzr".equals(taskDefKey) && count.contains("1")) {
						taskCount = "1";
						exp = "pass";
						if ("yes".equals(workContractRecord.getAct().getFlag())) {
							notifyRole = "归档完成";
							workActivityProcess.setIsApproval("1");
						} else {
							notifyRole = "调整申请";
							workActivityProcess.setIsApproval("2");
						}
						break;
					} else if ("modifyApply".equals(taskDefKey)&& count.contains("0")) {
						notifyRole = "合同管理员归档";
						taskCount = "0";
						exp = "pass";
						workActivityProcess.setCount(0);
						enname ="bmzr";
						if (!"yes".equals(workContractRecord.getAct().getFlag())) {
							workContractRecord.setStatus("3");
						}
						break;
					} else if ("apply_end".equals(taskDefKey)) {
					}

				}
			}
			// 设置意见
			workContractRecord.getAct().setComment(("yes".equals(workContractRecord.getAct().getFlag()) ? "[同意] " : "[驳回] ") + workContractRecord.getAct().getComment());
			workContractRecord.preUpdate();
			// 提交流程任务
			vars.put(exp, "yes".equals(workContractRecord.getAct().getFlag()) ? true : false);
		    vars.put("passs", true);
			workActivityProcessService.updateProcess(workActivityProcess,workActivityMenu,key,taskCount,workContractRecord.getProcessInstanceId(),taskDefKey,"modifyApply",workContractRecord.getAct().getFlag(),comment, activities);
			// 提交流程任务
			actTaskService.complete(workContractRecord.getAct().getTaskId(), workContractRecord.getAct().getProcInsId(), workContractRecord.getAct().getComment(), vars);
			boolean state = actTaskService.isProcessEnd(workContractRecord.getAct().getProcInsId());
			List<User> users = new ArrayList<>();
			List<User> userList = new ArrayList<>();
			if (!state) {
				str =  "归档申请编号："+workContractRecord.getRecordNum()+",主委托方："+workContractRecord.getWorkContractInfo().getClient().getName();
				title = "合同名称:"+workContractRecord.getWorkContractInfo().getName();
				users.add(workContractRecord.getCreateBy());
				if ("yes".equals(workContractRecord.getAct().getFlag())) {
					workContractRecord.setStatus("5");
					WorkProjectNotify notify = new WorkProjectNotify();
					notify.setNotifyId(workContractRecord.getId());
					userList = workProjectNotifyService.readByNotifyId(notify);
					workProjectNotifyService
							.save(UtilNotify
									.saveNotify(workContractRecord.getId(),
											workContractRecord.getCreateBy(),
											workContractRecord.getCompanyId(),
											title,
											str,
											"42",
											"0",
											"待通知",
											notifyRole));
					//归档中状态
					if(workContractRecord.getWorkContractInfo()!=null){
						if(StringUtils.isNotBlank(workContractRecord.getWorkContractInfo().getId())){
							WorkContractInfo workContractInfo = workContractInfoService.get(workContractRecord.getWorkContractInfo().getId());
							workContractInfo.setContractState("5");
							workContractInfoService.save(workContractInfo);
						}
					}

				} else {
					WorkProjectNotify notify = new WorkProjectNotify();
					notify.setNotifyId(workContractRecord.getId());
					userList = workProjectNotifyService.readByNotifyId(notify);
					if (StringUtils.isNotBlank(workContractRecord.getStatus()) && !workContractRecord.getStatus().equals("3")){
						workContractRecord.setStatus("4");
						workProjectNotifyService
								.save(UtilNotify
										.saveNotify(workContractRecord.getId(),
												workContractRecord.getCreateBy(),
												workContractRecord.getCompanyId(),
												title,
												str,
												"42",
												"0",
												"待通知",
												notifyRole));
					}
				}
				workActivityProcessService.deleteProcessIdAuditUsers(workContractRecord.getProcessInstanceId());
			} else {
				if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("contractArchive")) {
					WorkProjectNotify notify = new WorkProjectNotify();
					notify.setNotifyId(workContractRecord.getId());
					userList = workProjectNotifyService.readByNotifyId(notify);
					WorkProjectNotify workProjectNotify = UtilNotify
							.saveNotify(workContractRecord.getId(),
									new User(),
									workContractRecord.getCompanyId(),
									title,
									str,
									"42",
									"0",
									"待审批",
									notifyRole);
					List<WorkProjectNotify> workProjectNotifys = activityService.getByFlagAndTaskDefKeyList(
							activities,
							workProjectNotify,
							taskDefKey,
							workContractRecord.getAct().getFlag(),
							taskCount,
							workContractRecord.getCreateBy(),
							workContractRecord.getOfficeId(),
							"3");
					for (WorkProjectNotify workProjectNotify1:workProjectNotifys){
						users.add(workProjectNotify1.getUser());
						workProjectNotify1.setId("");
						workProjectNotify1.setIsNewRecord(false);
						workProjectNotifyService
								.save(workProjectNotify1);
						if (!"modifyApply".equals(taskDefKey)){
							Map<String,Object> extras = new HashMap<>();
								extras.put("type","7001");
							extras.put("id",workProjectNotify.getId());
							extras.put("procDefKey","42");
							UserUtils.pushInfoToApp(title,str,extras,workProjectNotify1.getUser().getId());

						}
					}

				} else {
					if (!"yes".equals(workContractRecord.getAct().getFlag())) {
						WorkProjectNotify notify = new WorkProjectNotify();
						notify.setNotifyId(workContractRecord.getId());
						userList = workProjectNotifyService.readByNotifyId(notify);
						workProjectNotifyService
								.save(UtilNotify
										.saveNotify(workContractRecord.getId(),
												workContractRecord.getCreateBy(),
												workContractRecord.getCompanyId(),
												title,
												str,
												"42",
												"0",
												"重新申请",
												notifyRole));
						users.add( workContractRecord.getCreateBy());
					} else {
						if (StringUtils.isNotBlank(enname)) {
							WorkProjectNotify notify = new WorkProjectNotify();
							notify.setNotifyId(workContractRecord.getId());
							userList = workProjectNotifyService.readByNotifyId(notify);
							WorkProjectNotify workProjectNotify = UtilNotify
									.saveNotify(workContractRecord.getId(),
											new User(),
											workContractRecord.getCompanyId(),
											title,
											str,
											"42",
											"0",
											"待审批",
											notifyRole);
							for (User user1:auditUsers){
								users.add(user1);
								workProjectNotify.setUser(user1);
								workProjectNotify.setId("");
								workProjectNotify.setIsNewRecord(false);
								workProjectNotifyService
										.save(workProjectNotify);
								if (!"modifyApply".equals(taskDefKey)){
									Map<String,Object> extras = new HashMap<>();
										extras.put("type","7001");
									extras.put("id",workProjectNotify.getId());
									extras.put("procDefKey","42");
									UserUtils.pushInfoToApp(title,str,extras,user1.getId());

								}
							}
						}else {
							WorkProjectNotify notify = new WorkProjectNotify();
							notify.setNotifyId(workContractRecord.getId());
							userList = workProjectNotifyService.readByNotifyId(notify);
							users.addAll(userList);
							users.add(workContractRecord.getCreateBy());
							workProjectNotifyService
									.save(UtilNotify
											.saveNotify(workContractRecord.getId(),
													workContractRecord.getCreateBy(),
													workContractRecord.getCompanyId(),
													title,
													str,
													"42",
													"0",
													"重新申请",
													notifyRole));
						}
					}
				}
			}
			if (users!=null && users.size()!=0) {
				for (User u : users) {
					UserUtils.pushIm(u.getId(),str);
				}
			}
			if (userList!=null && userList.size()!=0) {
				for (User u : userList) {
					UserUtils.pushMeIm(u.getId());
				}
			}
			workContractRecordDao.update(workContractRecord);
			if("5".equals(workContractRecord.getStatus())){
				if(workContractRecord.getWorkContractInfo()!=null){
					String cid = workContractRecord.getWorkContractInfo().getId();
					workContractRecordDao.updateRecordStatus(cid);
				}
			}
			return "保存审核意见成功！";
	}
	public Page<WorkContractInfo> findPageByworkContractInfo(Page<WorkContractInfo> page, WorkContractInfo workContractInfo) {
		workContractInfo.getSqlMap().put("dsf", dataScopeFilter(workContractInfo.getCurrentUser(), "o", "u","s", MenuStatusEnum.WORK_CONTRACTRECORD.getValue()));
		workContractInfo.setPage(page);
		page.setList(dao.findListByworkContractInfo(workContractInfo));
		return page;
	}
	/**
	 * 获取流程详细信息
	 * @param processInstanceId
	 */
	@SuppressWarnings("unchecked")
	public WorkContractRecord getByProcessInstanceId(String processInstanceId) {
		WorkContractRecord workContractRecord = workContractRecordDao.getByProcessInstanceId(processInstanceId);
		return workContractRecord;
	}
	/**
	 * 强制撤销
	 * @param
	 */
	@Transactional(readOnly = false)
	public void cancelInvalidate(WorkContractRecord workContractRecord) {
		String invalidateProcessInstanceId = workContractRecord.getProcessInstanceId();
		try {
			//将流程图中尚未走到的task的流程追踪信息逻辑删除，添加一条"撤销"流程追踪信息
			WorkActivityProcess process = new WorkActivityProcess();
			process.setProcessInstanceId(workContractRecord.getProcessInstanceId());
			process.setIsApproval("0");
			WorkActivityProcess workActivityProcess = new WorkActivityProcess();
			workActivityProcess.setProcessInstanceId(workContractRecord.getProcessInstanceId());
			List<WorkActivityProcess> processList = workActivityProcessService.findList(workActivityProcess);
			WorkProjectNotify notify = new WorkProjectNotify();
			notify.setNotifyId(workContractRecord.getId());
			List<User> userList = workProjectNotifyService.readByNotifyId(notify);
			if (userList!=null && userList.size()!=0) {
				for (User u : userList) {
					User user = UserUtils.get(u.getId());
					/*List<WebSocket> toUserConns = ChatServerPool.getWebSocketByUser(u.getId());
					for (WebSocket toUserConn : toUserConns) {
						String message = "{\"to\":\""+u.getId()+"\"," +
								"\"msg\":\"审批信息 归档申请人:"+ user.getName()+",归档编号:"+workContractRecord.getRecordNum()+" 强制撤销!\"," +
								"\"useType\":\"sys\"}";
						ChatServerPool.sendMessageToUser(toUserConn, message);//同时向本人发送消息
					}*/
					UserUtils.pushIm(u.getId(),"归档申请人:"+ user.getName()+",归档编号:"+workContractRecord.getRecordNum()+" 强制撤销!");

				}
			}
			if(processList!=null && processList.size()>0){
				for (int i =0;i<processList.size();i++) {
					WorkActivityProcess p = processList.get(i);
					if(StringUtils.isNotBlank(p.getIsApproval()) && "0".equals(p.getIsApproval())){
						p.setDelFlag("1");
						p.setIsApproval("-1");
						workActivityProcessDao.updateDelFlagAndIsApproval(p);
					}
				}
				WorkActivityProcess pro = new WorkActivityProcess();
				pro.setId("");
				pro.preInsert();
				pro.setDelFlag("0");
				pro.setRemarks("[强制撤销]");
				pro.setProcessKey(processList.get(0).getProcessKey());
				pro.setIsApproval("1");
				pro.setProcessInstanceId(processList.get(0).getProcessInstanceId());
				pro.setCount(0);
				workActivityProcessDao.insert(pro);
			}

			//结束该流程,设为"撤销"状态
			actTaskService.endProcessInstance(invalidateProcessInstanceId,"归档申请-强制撤销");
			workContractRecord.setStatus("3");
			workContractRecord.preUpdate();
			workContractRecordDao.update(workContractRecord);

		}catch (ActivitiObjectNotFoundException e){
			System.err.println("撤销合同作废异常，因为这个流程已不存在!");
			e.printStackTrace();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
	//获取同合同编号下 最新的归档编号
	public String findRecordNum(String num) {
		String s = dao.findRecordNum(num);
		if(StringUtils.isNotBlank(s)){
			String s2 = s.replace(num+"-","");
			try {
				int a = Integer.parseInt(s2);
				a  = a+1;
				return num+"-"+String.valueOf(a);
			} catch (NumberFormatException e) {
				e.printStackTrace();
			}
		}
		return s;
	}
}