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

import com.google.common.collect.Maps;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.service.CrudService;
import com.jeeplus.common.utils.MenuStatusEnum;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.modules.act.service.ActTaskService;
import com.jeeplus.modules.act.utils.ActUtils;
import com.jeeplus.modules.leaveapply.service.LeaveApplyService;
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.workfield.service.WorkFieldService;
import com.jeeplus.modules.workleave.dao.WorkLeaveDao;
import com.jeeplus.modules.workleave.entity.WorkLeave;
import com.jeeplus.modules.workprojectnotify.entity.WorkProjectNotify;
import com.jeeplus.modules.workprojectnotify.service.WorkProjectNotifyService;
import com.jeeplus.modules.workprojectnotify.util.UtilNotify;
import com.jeeplus.modules.workstaff.dao.WorkStaffAchivesDao;
import org.activiti.engine.ActivitiObjectNotFoundException;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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


@Service
@Transactional(readOnly = true)
public class WorkLeaveService extends CrudService<WorkLeaveDao, WorkLeave> {
	@Autowired
	private IdentityService identityService;
	@Autowired
	private WorkActivityMenuService workActivityMenuService;
	@Autowired
	private WorkProjectNotifyService workProjectNotifyService;
	@Autowired
	private SerialNumTplService serialNumTplService;

	@Autowired
	private RuntimeService runtimeService;
	@Autowired
	private OfficeService officeService;
	@Autowired
	private WorkActivityProcessService workActivityProcessService;
	@Autowired
	private ActTaskService actTaskService;
	@Autowired
	private WorkFieldService workFieldService;
	@Autowired
	private ActivityService activityService;
	@Autowired
	private LeaveApplyService leaveApplyService;
	@Autowired
	private WorkActivityProcessDao workActivityProcessDao;
	@Autowired
	private WorkStaffAchivesDao workStaffAchivesDao;
	@Autowired
	private WorkLeaveDao workLeaveDao;
	@Autowired
	private WorkClientAttachmentDao workClientAttachmentDao;

	public WorkLeave get(String id) {
		WorkLeave workLeave = super.get(id);
		if(workLeave!=null){
			//附件
			WorkClientAttachment workClientAttachment = new WorkClientAttachment();
			workClientAttachment.setAttachmentId(id);
			workClientAttachment.setAttachmentFlag("99");
			workLeave.setWorkAttachments(workClientAttachmentDao.findList(workClientAttachment));
		}
		return workLeave;
	}
	public WorkLeave getByStaffIdAndTime(String staffId, String time) {
		WorkLeave workLeave = dao.getByStaffIdAndTime(staffId, time);
		return workLeave;
	}

	public List<WorkLeave> findList(WorkLeave workLeave) {
		return super.findList(workLeave);
	}
	
	public Page<WorkLeave> findPage(Page<WorkLeave> page, WorkLeave workLeave) {
		workLeave.getSqlMap().put("dsf", dataScopeFilter(workLeave.getCurrentUser(), "o", "u","s", MenuStatusEnum.WORK_OVERTIME.getValue()));
		workLeave.setPage(page);
		page.setList(findList(workLeave));
		return page;
	}
	
	@Transactional(readOnly = false)
	public void save(WorkLeave workLeave) {
		super.save(workLeave);
		updateInfo(workLeave);
	}
	@Transactional(readOnly = false)
	public void updateInfo(WorkLeave workLeave) {
		//附件信息
		for (WorkClientAttachment workClientAttachment : workLeave.getWorkAttachments()) {
			if (workClientAttachment.getId() == null) {
				continue;
			}
			if (WorkClientAttachment.DEL_FLAG_NORMAL.equals(workClientAttachment.getDelFlag())) {
				workClientAttachment.setAttachmentId(workLeave.getId());
				workClientAttachment.setAttachmentFlag("99");
				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);
			}
		}
	}
	/**
	 * 提交存储
	 * @param
	 * @param variables
	 */
	@Transactional(readOnly = false)
	public String save(WorkLeave workLeave, Map<String, Object> variables, String processInstanceId) {
		User user = UserUtils.getUser();
		if (StringUtils.isBlank(workLeave.getNum())) {
			workLeave.setNum(serialNumTplService.genSerialNum(user.getCompany(), "20"));

		}
		workLeave.setName(user.getName());
		super.save(workLeave);
		Office office = officeService.get(workLeave.getOfficeId());
		String str =  "申请编号:"+workLeave.getNum()+",所属部门:"+office.getName();
		String title = "申请人:"+user.getName();
		updateInfo(workLeave);
		// 用来设置启动流程的人员ID，引擎会自动把用户ID保存到activiti:initiator中
		identityService.setAuthenticatedUserId(user.getId());
		// 启动流程
		String businessKey = workLeave.getId().toString();
		WorkActivityMenu workActivityMenu = workActivityMenuService.findByParentAndOffice("zzsql3125f1f194clzsqasdfiiii75904", office);
		// 启动流程
		String processType = workActivityMenu.getProcessType();
		StringBuffer buffer = new StringBuffer();
		Activity activity = new Activity();
		WorkProjectNotify workProjectNotify = UtilNotify
				.saveNotify(workLeave.getId(),
						null,
						workLeave.getCompanyId(),
						title,
						str,
						"102",
						"0",
						"待审批",
						""
				);
		List<User> users = new ArrayList<>();
		List<User> bmzrs = UserUtils.getByRoleActivityEnname("bmzr",2,office.getId(),"25",workLeave.getCreateBy());
        List<User> fgldList = UserUtils.getByRoleActivityEnname("fzjl",3,office.getId(),"25",workLeave.getCreateBy());
        List<User> zjlList = UserUtils.getByRoleActivityEnname("zjl",3,office.getId(),"25",workLeave.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(),"19",workLeave.getCreateBy());
					if (enusers.size()==0){
						workLeave.setStatus("1");
						super.save(workLeave);
						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(),"25",workLeave.getCreateBy());
				}
				//人员审批
				if (StringUtils.isNotBlank(activity.getUser().getId())) {
					users.add(activity.getUser());
				}
			}
			workProjectNotify.setId("");
		} else {
			variables.put("bmzrList", bmzrs);
			if (bmzrs.size()==0 ){
				workLeave.setStatus("1");
				super.save(workLeave);
			}
			if (bmzrs.size()==0){
				return "流程审批人不能为空,角色部门负责人下无用户,请联系管理员！";
			}
			variables.put("bmzrCount",bmzrs.size());
			processType = "workLeave";
			users.addAll(bmzrs);
		}
		for (User u : users){
			workProjectNotify.setUser(u);
			workProjectNotify.setId("");
			workProjectNotify.setNotifyRole("部门负责人审批");
			workProjectNotifyService
					.save(workProjectNotify);
			Map<String,Object> extras = new HashMap<>();
			extras.put("type","7002");
			extras.put("id",workProjectNotify.getId());
			extras.put("procDefKey","102");
			UserUtils.pushInfoToApp(title,str,extras,u.getId());
			UserUtils.pushIm(u.getId(),str);
		}
		variables.put("type", processType);
		variables.put("busId", businessKey);
		variables.put("title", "审批单：" + workLeave.getNum());//设置标题；

		ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processType, businessKey, variables);
		workLeave.setProcessInstance(processInstance);
		if (StringUtils.isNotBlank(processInstanceId)) {
			workActivityProcessService.updateProcessInstanceId(processInstance.getId(),processInstanceId);
			workActivityProcessService.deleteProcessInstanceId(processInstanceId);
			workActivityProcessService.deleteProcessIdAuditUsers(processInstanceId);
		}
		// 更新流程实例ID
		workLeave.setProcessInstanceId(processInstance.getId());
		workLeaveDao.updateProcessInstanceId(workLeave);
		List<Activity> list = workActivityMenu.getActivities();
		if (list != null && list.size() != 0) {
			workActivityProcessService.saveList(list, processInstance.getId());
		} else {
			WorkActivityProcess workActivityProcess = new WorkActivityProcess();
			workActivityProcess.setProcessKey("workLeave");
			workActivityProcess.setCount(1);
			workActivityProcess.setProcessInstanceId(processInstance.getId());
			workActivityProcess.setIsApproval("0");
			workActivityProcessService.save(workActivityProcess);
            workActivityProcess.setCount(2);
            workActivityProcessService.insert(workActivityProcess);
            workActivityProcess.setCount(3);
            workActivityProcessService.insert(workActivityProcess);
			workActivityProcessService.insertAuditsByType(bmzrs,processInstance.getId(),1,1);
            workActivityProcessService.insertAuditsByType(fgldList,processInstance.getId(),2,0);
            workActivityProcessService.insertAuditsByType(zjlList,processInstance.getId(),3,0);
		}
		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 delete(WorkLeave workLeave) {
		super.delete(workLeave);
		WorkProjectNotify notify = new WorkProjectNotify();
		notify.setNotifyId(workLeave.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(WorkLeave workLeave, List<User> auditUsers) {
        WorkLeave workLeaveinfo = workLeaveDao.get(workLeave.getId());
        if (null == workLeave.getStartDate()){
            workLeave.setStartDate(workLeaveinfo.getStartDate());
            workLeave.setEndDate(workLeaveinfo.getEndDate());
        }
        String userName = UserUtils.get(workLeave.getCreateBy().getId()).getName();
		Office office = officeService.get(workLeave.getOfficeId());
		String title = "申请人:"+userName;
		String str  =  "出差申请编号:"+workLeave.getNum()+",所属部门:"+office.getName();
		// 对不同环节的业务逻辑进行操作
		String taskDefKey = workLeave.getAct().getTaskDefKey();
		if (!"modifyApply".equals(taskDefKey)) {
			actTaskService.claim(workLeave.getAct().getTaskId(), UserUtils.getUser().getId());
		}else{
			workLeave.getAct().setFlag("yes");
			updateInfo(workLeave);
		}
		String comment = "";
		if (workLeave.getStatus().equals("4")){
			comment = ("yes".equals(workLeave.getAct().getFlag())?"[重新申请] ":"[已撤销] ");
		}else {
			comment = ("yes".equals(workLeave.getAct().getFlag())?"[同意] ":"[驳回] ")+workLeave.getAct().getComment();
		}
		//yes 的时候状态为审核通过 否则为未通过
		//1 审核中 2 未通过
		workLeave.setStatus(("yes".equals(workLeave.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(workLeave.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(workLeave.getProcessInstanceId());
		List<WorkActivityProcess> workActivityProcesses = workActivityProcessService.findList(selectProcess);
		List<Activity> activities = workActivityMenu.getActivities();
		if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("workLeave")) {
			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(workLeave.getAct().getFlag())) {
						workLeave.setStatus("4");
						workActivityProcess.setIsApproval("2");
						String returnBack = "-1";
						for (Activity activity : activities) {
							if (activity.getCount() == activityProcess.getCount()) {
								returnBack = activity.getReturnBack();
								notifyRole = activity.getName();
								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(workLeave.getAct().getFlag())) {
						workLeave.setStatus("3");
						workActivityProcess.setIsApproval("2");
					} else {
						workActivityProcess.setIsApproval("1");
					}
					break;
				}
			}
		} else {
			workActivityMenu.setProcessType("workLeave");
			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(workLeave.getAct().getFlag())) {
                        vars.put("fgldList", auditUsers);
                        vars.put("fgldCount",auditUsers.size());
                        workActivityProcessService.insertAuditsByType(auditUsers,workLeave.getProcessInstanceId(),2,1);

                        notifyRole = "副经理审核";
                        workActivityProcess.setIsApproval("1");
                        enname = "fgld";
                    } else {
                        notifyRole = "调整申请";
                        workActivityProcess.setIsApproval("2");
                    }
                    break;
				}else if ("fgld".equals(taskDefKey) && count.contains("2")) {
                    taskCount = "2";
                    exp = "pass";
                    if ("yes".equals(workLeave.getAct().getFlag())) {
                        vars.put("zjlList", auditUsers);
                        vars.put("zjlCount",auditUsers.size());
                        workActivityProcessService.insertAuditsByType(auditUsers,workLeave.getProcessInstanceId(),3,1);
                        notifyRole = "总经理审核";
                        workActivityProcess.setIsApproval("1");
                        enname = "zjl";
                    } else {
                        notifyRole = "调整申请";
                        workActivityProcess.setIsApproval("2");
                    }
                    break;
                }
             else if ("zjl".equals(taskDefKey) && count.contains("3")) {
                taskCount = "3";
                exp = "pass";
                if ("yes".equals(workLeave.getAct().getFlag())) {
                    notifyRole = "审批通过";
                    workActivityProcess.setIsApproval("1");
                } else {
                    notifyRole = "调整申请";
                    workActivityProcess.setIsApproval("2");
                }
                break;
              } else if ("modifyApply".equals(taskDefKey)&& count.contains("0")) {
					taskCount = "0";
					notifyRole = "部门负责人审批";
					exp = "pass";
					workActivityProcess.setCount(0);
					enname = "bmzr";
					if (!"yes".equals(workLeave.getAct().getFlag())) {
						workLeave.setStatus("3");
					}
					break;
				}

			}
		}
		// 设置意见
		workLeave.getAct().setComment(("yes".equals(workLeave.getAct().getFlag()) ? "[同意] " : "[驳回] ") + workLeave.getAct().getComment());
		workLeave.preUpdate();
		// 提交流程任务
		vars.put(exp, "yes".equals(workLeave.getAct().getFlag()) ? true : false);
		vars.put("passs", true);
		workActivityProcessService.updateProcess(workActivityProcess,workActivityMenu,key,taskCount,workLeave.getProcessInstanceId(),taskDefKey,"modifyApply",workLeave.getAct().getFlag(),comment, activities);
		// 提交流程任务
		actTaskService.complete(workLeave.getAct().getTaskId(), workLeave.getAct().getProcInsId(), workLeave.getAct().getComment(), vars);
		boolean state = actTaskService.isProcessEnd(workLeave.getAct().getProcInsId());
		List<User> users = new ArrayList<>();
		List<User> userList = new ArrayList<>();
		if (!state) {
			users.add(workLeave.getCreateBy());
			if ("yes".equals(workLeave.getAct().getFlag())) {
				workLeave.setStatus("5");
				WorkProjectNotify notify = new WorkProjectNotify();
				notify.setNotifyId(workLeave.getId());
				userList = workProjectNotifyService.readByNotifyId(notify);
				workProjectNotifyService
						.save(UtilNotify
								.saveNotify(workLeave.getId(),
										workLeave.getCreateBy(),
										workLeave.getCompanyId(),
										title,
										str,
										"102",
										"0",
										"待通知",
										notifyRole));

			} else {
				WorkProjectNotify notify = new WorkProjectNotify();
				notify.setNotifyId(workLeave.getId());
				userList = workProjectNotifyService.readByNotifyId(notify);
				if (StringUtils.isNotBlank(workLeave.getStatus()) && !workLeave.getStatus().equals("3")){
					workLeave.setStatus("4");
					workProjectNotifyService
							.save(UtilNotify
									.saveNotify(workLeave.getId(),
											workLeave.getCreateBy(),
											workLeave.getCompanyId(),
											title,
											str,
											"102",
											"0",
											"待通知",
											notifyRole));
				}
			}
			workActivityProcessService.deleteProcessIdAuditUsers(workLeave.getProcessInstanceId());
		} else {
			if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("workLeave")) {
				WorkProjectNotify notify = new WorkProjectNotify();
				notify.setNotifyId(workLeave.getId());
				userList = workProjectNotifyService.readByNotifyId(notify);
				//users.addAll(userList);
				WorkProjectNotify workProjectNotify = UtilNotify
						.saveNotify(workLeave.getId(),
								new User(),
								workLeave.getCompanyId(),
								title,
								str,
								"102",
								"0",
								"待审批",
								notifyRole);
				List<WorkProjectNotify> workProjectNotifys = activityService.getByFlagAndTaskDefKeyList(
						activities,
						workProjectNotify,
						taskDefKey,
						workLeave.getAct().getFlag(),
						taskCount,
						workLeave.getCreateBy(),
						workLeave.getOfficeId(),
						"19");
				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","7002");
						extras.put("id",workProjectNotify.getId());
						extras.put("procDefKey","102");
						UserUtils.pushInfoToApp(title,str,extras,workProjectNotify1.getUser().getId());

					}
				}

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

							}
						}
					}else {
						WorkProjectNotify notify = new WorkProjectNotify();
						notify.setNotifyId(workLeave.getId());
						userList = workProjectNotifyService.readByNotifyId(notify);
						users.addAll(userList);
						users.add(workLeave.getCreateBy());
						workProjectNotifyService
								.save(UtilNotify
										.saveNotify(workLeave.getId(),
												workLeave.getCreateBy(),
												workLeave.getCompanyId(),
												title,
												str,
												"102",
												"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());
			}
		}

		workLeaveDao.update(workLeave);
		return "保存审核意见成功！";
	}

	/**
	 * 获取流程详细信息
	 * @param processInstanceId
	 */
	@SuppressWarnings("unchecked")
	public WorkLeave getByProcessInstanceId(String processInstanceId) {
		WorkLeave workLeave = workLeaveDao.getByProcessInstanceId(processInstanceId);
		return workLeave;
	}

	/**
	 * 强制撤销
	 * @param
	 */
	@Transactional(readOnly = false)
	public void cancelInvalidate(WorkLeave workLeave) {
		String invalidateProcessInstanceId = workLeave.getProcessInstanceId();
		try {
			//将流程图中尚未走到的task的流程追踪信息逻辑删除，添加一条"撤销"流程追踪信息
			WorkActivityProcess process = new WorkActivityProcess();
			process.setProcessInstanceId(workLeave.getProcessInstanceId());
			process.setIsApproval("0");
			WorkActivityProcess workActivityProcess = new WorkActivityProcess();
			workActivityProcess.setProcessInstanceId(workLeave.getProcessInstanceId());
			List<WorkActivityProcess> processList = workActivityProcessService.findList(workActivityProcess);
			WorkProjectNotify notify = new WorkProjectNotify();
			notify.setNotifyId(workLeave.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()+",申请编号:"+workLeave.getNum()+" 强制撤销!");

				}
			}
			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,"申请-强制撤销");
			workLeave.setStatus("3");
			workLeave.preUpdate();
			workLeaveDao.update(workLeave);

		}catch (ActivitiObjectNotFoundException e){
			System.err.println("撤销异常，因为这个流程已不存在!");
			e.printStackTrace();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
}