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

import java.util.*;

import com.google.common.collect.Maps;
import com.jeeplus.common.utils.IdGen;
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.projectrecord.dao.WorkProjectUserDao;
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.DictUtils;
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.workprojectnotify.entity.WorkProjectNotify;
import com.jeeplus.modules.workprojectnotify.service.WorkProjectNotifyService;
import com.jeeplus.modules.workprojectnotify.util.UtilNotify;
import com.jeeplus.modules.workreimbursement.dao.ReimbursementVATTaxDao;
import com.jeeplus.modules.workreimbursement.dao.WorkAccountDao;
import com.jeeplus.modules.workreimbursement.dao.WorkReimbursementDao;
import com.jeeplus.modules.workstaff.service.WorkStaffBasicInfoService;
import org.activiti.engine.*;
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.workstaff.entity.WorkStaffBasicInfo;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.service.CrudService;
import com.jeeplus.modules.workrelationship.entity.WorkRelationship;
import com.jeeplus.modules.workrelationship.dao.WorkRelationshipDao;

/**
 * 劳动关系Service
 * @author lw
 * @version 2018-07-31
 */
@Service
@Transactional(readOnly = true)
public class WorkRelationshipService extends CrudService<WorkRelationshipDao, WorkRelationship> {
	@Autowired
	private WorkRelationshipDao workRelationshipDao;
	@Autowired
	private RuntimeService runtimeService;
	@Autowired
	protected TaskService taskService;
	@Autowired
	protected HistoryService historyService;
	@Autowired
	protected RepositoryService repositoryService;
	@Autowired
	private IdentityService identityService;

	@Autowired
	private WorkClientAttachmentDao workClientAttachmentDao;

	@Autowired
	private ActTaskService actTaskService;

	@Autowired
	private WorkProjectNotifyService workProjectNotifyService;
	@Autowired
	private WorkActivityMenuService workActivityMenuService;
	@Autowired
	private WorkActivityProcessService workActivityProcessService;
	@Autowired
	private ActivityService activityService;
	@Autowired
	private WorkActivityProcessDao workActivityProcessDao;
	@Autowired
	private WorkProjectUserDao workProjectUserDao;
	@Autowired
	private SerialNumTplService serialNumTplService;
	@Autowired
	private OfficeService officeService;
	@Autowired
	private WorkStaffBasicInfoService workStaffBasicInfoService;
	@SuppressWarnings("unchecked")
	public WorkRelationship get(String id) {
		WorkRelationship workRelationship = super.get(id);
		if(workRelationship !=null){
			//附件
			WorkClientAttachment workClientAttachment = new WorkClientAttachment();
			workClientAttachment.setAttachmentId(id);
			workClientAttachment.setAttachmentFlag("108");
			workRelationship.setWorkAttachments(workClientAttachmentDao.findList(workClientAttachment));

			if(workRelationship!=null && workRelationship.getWorkStaffBasicInfo()!=null &&
					StringUtils.isNotBlank(workRelationship.getWorkStaffBasicInfo().getId())){
				//历史关系
				if(StringUtils.isNotBlank(id)){
					List<WorkRelationship> workRelationships = this.getWorkRelationships(id,workRelationship.getWorkStaffBasicInfo().getId());
					workRelationship.setWorkRelationships(workRelationships);
				}
				WorkStaffBasicInfo workStaffBasicInfo = workStaffBasicInfoService.getAchives(workRelationship.getWorkStaffBasicInfo().getId());
				workRelationship.setWorkStaffBasicInfo(workStaffBasicInfo);

			}
		}
		return workRelationship;
	}

	public List<WorkRelationship> getWorkRelationships(String id ,String sId){
		List<WorkRelationship> list = new ArrayList<>();
		if(StringUtils.isNotBlank(sId)){
			list = workRelationshipDao.getWorkRelationships(id,sId);
			if(list !=null && list.size()>0){
				for (WorkRelationship w:
					 list) {
					WorkClientAttachment workClientAttachment = new WorkClientAttachment();
					workClientAttachment.setAttachmentId(w.getId());
					workClientAttachment.setAttachmentFlag("108");
					w.setWorkAttachments(workClientAttachmentDao.findList(workClientAttachment));
				}
			}
		}
		return list;
	};
	public List<WorkRelationship> findList(WorkRelationship workRelationship) {
		return super.findList(workRelationship);
	}
	//定时检测合同终止数据
	public List<WorkRelationship> findLists(WorkRelationship workRelationship) {
		return workRelationshipDao.findLists(workRelationship);
	}
	
	public Page<WorkRelationship> findPage(Page<WorkRelationship> page, WorkRelationship workRelationship) {
		workRelationship.getSqlMap().put("dsf", dataScopeFilter(workRelationship.getCurrentUser(), "o", "u","s", MenuStatusEnum.WORK_RELATIONSHIP.getValue()));
		workRelationship.setPage(page);
		page.setList(findList(workRelationship));
		return page;
	}
	
	@Transactional(readOnly = false)
	public void save(WorkRelationship workRelationship) {
		super.save(workRelationship);
		updateWorkReimbursementInfo(workRelationship);
	}
	@Transactional(readOnly = false)
	public void updateWorkReimbursementInfo(WorkRelationship workRelationship) {
		//附件信息
		for (WorkClientAttachment workClientAttachment : workRelationship.getWorkAttachments()) {
			if (workClientAttachment.getId() == null) {
				continue;
			}
			if (WorkClientAttachment.DEL_FLAG_NORMAL.equals(workClientAttachment.getDelFlag())) {
				workClientAttachment.setAttachmentId(workRelationship.getId());
				workClientAttachment.setAttachmentFlag("108");
				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(WorkRelationship workRelationship) {
		super.delete(workRelationship);
		WorkProjectNotify notify = new WorkProjectNotify();
		notify.setNotifyId(workRelationship.getId());
		workProjectNotifyService.readByNotifyId(notify);
	}
	
	public Page<WorkStaffBasicInfo> findPageByworkStaffBasicInfo(Page<WorkStaffBasicInfo> page, WorkStaffBasicInfo workStaffBasicInfo) {
		workStaffBasicInfo.setPage(page);
		page.setList(dao.findListByworkStaffBasicInfo(workStaffBasicInfo));
		return page;
	}

	@Transactional(readOnly = false)
	public String save(WorkRelationship workRelationship, Map<String, Object> variables, String processInstanceId) {
		User user = UserUtils.getUser();
		if(workRelationship!=null && StringUtils.isNotBlank(workRelationship.getContractType()) && workRelationship.getContractType().contains(",")){
			workRelationship.setContractType(workRelationship.getContractType().replace(",",""));
		}
		super.save(workRelationship);
		String str = "";
		//获取人员
		User sU = null;
		Office office = null;
		if(workRelationship.getWorkStaffBasicInfo()!=null){
			String sid = workRelationship.getWorkStaffBasicInfo().getId();
			if(StringUtils.isNotBlank(sid)){
				WorkStaffBasicInfo w = workStaffBasicInfoService.getAchives(sid);
				String uid = w.getUserId();
				if(StringUtils.isNotBlank(uid)){
					sU = UserUtils.get(uid);
				}
				office = w.getOffice();
			}
		}
		if(sU == null){
			workRelationship.setStatus("1");
			if(workRelationship!=null && StringUtils.isNotBlank(workRelationship.getContractType()) && workRelationship.getContractType().contains(",")){
				workRelationship.setContractType(workRelationship.getContractType().replace(",",""));
			}
			super.save(workRelationship);
			return "流程审批人不能为空,所选人员未注册,请联系管理员！";
		}
		if(office == null){
			workRelationship.setStatus("1");
			if(workRelationship!=null && StringUtils.isNotBlank(workRelationship.getContractType()) && workRelationship.getContractType().contains(",")){
				workRelationship.setContractType(workRelationship.getContractType().replace(",",""));
			}
			super.save(workRelationship);
			return "流程审批人不能为空,所选人员所在部门异常,请联系管理员！";
		}
		if(StringUtils.isNotBlank(workRelationship.getContractNum())){
			str =  "合同编号:"+workRelationship.getContractNum()+",合同类型:"+ DictUtils.getDictLabel(workRelationship.getContractType(),"relsp_cType","")
					+",员工状态:"+workRelationship.getWorkStaffBasicInfo().getStatus();
		}else{
			str =  "合同类型:"+ DictUtils.getDictLabel(workRelationship.getContractType(),"relsp_cType","")
					+",员工状态:"+workRelationship.getWorkStaffBasicInfo().getStatus();
		}
		String title = "人员名称:"+workRelationship.getWorkStaffBasicInfo().getName();
		updateWorkReimbursementInfo(workRelationship);
		// 用来设置启动流程的人员ID，引擎会自动把用户ID保存到activiti:initiator中
		identityService.setAuthenticatedUserId(user.getId());
		// 启动流程
		String businessKey = workRelationship.getId().toString();
		WorkActivityMenu workActivityMenu = workActivityMenuService.findByParentAndOffice("zzsql3125f1f194c82bdea9miiii750904", office);
		// 启动流程
		String processType = workActivityMenu.getProcessType();
		StringBuffer buffer = new StringBuffer();
		Activity activity = new Activity();
		WorkProjectNotify workProjectNotify = UtilNotify
				.saveNotify(workRelationship.getId(),
						null,
						workRelationship.getCompanyId(),
						title,
						str,
						"67",
						"0",
						"待审批",
						""
				);
		List<User> users = new ArrayList<>();
		List<User> rlzybzrs = UserUtils.getByRoleActivityEnname("bmzr",2,office.getId(),"18",workRelationship.getCreateBy());
		List<User> rlzys = UserUtils.getByRoleActivityEnname("rlzy",3,office.getId(),"18",workRelationship.getCreateBy());
		List<User> qyrs = new ArrayList();
		if(workRelationship.getWorkStaffBasicInfo()!=null && StringUtils.isNotBlank(workRelationship.getWorkStaffBasicInfo().getUserId())){
			qyrs.add(sU);
		}
		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(),"18",workRelationship.getCreateBy());
					if (enusers.size()==0){
						workRelationship.setStatus("1");
						if(workRelationship!=null && StringUtils.isNotBlank(workRelationship.getContractType()) && workRelationship.getContractType().contains(",")){
							workRelationship.setContractType(workRelationship.getContractType().replace(",",""));
						}
						super.save(workRelationship);
						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(),"18",workRelationship.getCreateBy());
				}
				//人员审批
				if (StringUtils.isNotBlank(activity.getUser().getId())) {
					users.add(activity.getUser());
				}
			}
			workProjectNotify.setId("");
		} else {
			variables.put("rlzybzrList", rlzybzrs);
			if (rlzybzrs.size()==0 ){
				workRelationship.setStatus("1");
				if(workRelationship!=null && StringUtils.isNotBlank(workRelationship.getContractType()) && workRelationship.getContractType().contains(",")){
					workRelationship.setContractType(workRelationship.getContractType().replace(",",""));
				}
				super.save(workRelationship);
			}
			if (rlzybzrs.size()==0){
				return "流程审批人不能为空,角色部门主任下无用户,请联系管理员！";
			}
			variables.put("rlzybzrcount",rlzybzrs.size());
			processType = "workrelationship";
			users.addAll(rlzybzrs);
		}
		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() + ",报销编号:"+ workReimbursement.getNumber() + " 待审批!\"," +
                            "\"useType\":\"sys\"}";
                    ChatServerPool.sendMessageToUser(toUserConn, message);//同时向本人发送消息
                }*/
			Map<String,Object> extras = new HashMap<>();
			extras.put("type","7001");
			extras.put("id",workProjectNotify.getId());
			extras.put("procDefKey","67");
			UserUtils.pushInfoToApp(title,str,extras,u.getId());
			UserUtils.pushIm(u.getId(),str);
		}
		variables.put("type", processType);
		variables.put("busId", businessKey);
		variables.put("title", "劳动关系审批单：" + sU.getName());//设置标题；

		ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processType, businessKey, variables);
		workRelationship.setProcessInstance(processInstance);
		if (StringUtils.isNotBlank(processInstanceId)) {
			workActivityProcessService.updateProcessInstanceId(processInstance.getId(),processInstanceId);
			workActivityProcessService.deleteProcessInstanceId(processInstanceId);
			workActivityProcessService.deleteProcessIdAuditUsers(processInstanceId);
		}
		// 更新流程实例ID
		workRelationship.setProcessInstanceId(processInstance.getId());
		workRelationshipDao.updateProcessInstanceId(workRelationship);
		List<Activity> list = workActivityMenu.getActivities();
		if (list != null && list.size() != 0) {
			workActivityProcessService.saveList(list, processInstance.getId());
		} else {
			WorkActivityProcess workActivityProcess = new WorkActivityProcess();
			workActivityProcess.setProcessKey("workrelationship");
			workActivityProcess.setCount(1);
			workActivityProcess.setProcessInstanceId(processInstance.getId());
			workActivityProcess.setIsApproval("0");
			workActivityProcessService.save(workActivityProcess);
			workActivityProcess.setCount(2);
			workActivityProcess.setId("");
			workActivityProcessService.save(workActivityProcess);
			workActivityProcess.setCount(3);
			workActivityProcess.setId("");
			workActivityProcessService.save(workActivityProcess);
			workActivityProcessService.insertAuditsByType(rlzybzrs,processInstance.getId(),1,1);
			workActivityProcessService.insertAuditsByType(rlzys,processInstance.getId(),2,0);
			workActivityProcessService.insertAuditsByType(qyrs,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 String saveRelation(WorkRelationship workRelationship, Map<String, Object> variables, String processInstanceId) {
		try{
			super.save(workRelationship);
			User user = UserUtils.get(workRelationship.getWorkStaffBasicInfo().getUserId());
			if(workRelationship!=null && StringUtils.isNotBlank(workRelationship.getContractType()) && workRelationship.getContractType().contains(",")){
				workRelationship.setContractType(workRelationship.getContractType().replace(",",""));
			}
			String str = "";
			//获取人员
			User sU = null;
			Office office = null;
			if(workRelationship.getWorkStaffBasicInfo()!=null){
				String sid = workRelationship.getWorkStaffBasicInfo().getId();
				if(StringUtils.isNotBlank(sid)){
					WorkStaffBasicInfo w = workStaffBasicInfoService.getAchives(sid);
					String uid = w.getUserId();
					if(StringUtils.isNotBlank(uid)){
						sU = UserUtils.get(uid);
					}
					office = w.getOffice();
				}
			}
			if(sU == null){
				if(workRelationship!=null && StringUtils.isNotBlank(workRelationship.getContractType()) && workRelationship.getContractType().contains(",")){
					workRelationship.setContractType(workRelationship.getContractType().replace(",",""));
				}
				return "流程审批人不能为空,所选人员未注册,请联系管理员！";
			}
			if(office == null){
				if(workRelationship!=null && StringUtils.isNotBlank(workRelationship.getContractType()) && workRelationship.getContractType().contains(",")){
					workRelationship.setContractType(workRelationship.getContractType().replace(",",""));
				}
				return "流程审批人不能为空,所选人员所在部门异常,请联系管理员！";
			}
			if(StringUtils.isNotBlank(workRelationship.getContractNum())){
				str =  "合同编号:"+workRelationship.getContractNum()+",合同类型:"+ DictUtils.getDictLabel(workRelationship.getContractType(),"relsp_cType","")
						+",员工状态:"+workRelationship.getWorkStaffBasicInfo().getStatus();
			}else{
				str =  "合同类型:"+ DictUtils.getDictLabel(workRelationship.getContractType(),"relsp_cType","")
						+",员工状态:"+workRelationship.getWorkStaffBasicInfo().getStatus();
			}
			String title = "人员名称:"+workRelationship.getWorkStaffBasicInfo().getName();
			updateWorkReimbursementInfo(workRelationship);
			// 用来设置启动流程的人员ID，引擎会自动把用户ID保存到activiti:initiator中
			identityService.setAuthenticatedUserId(user.getId());
			// 启动流程
			String businessKey = workRelationship.getId().toString();
			WorkActivityMenu workActivityMenu = workActivityMenuService.findByParentAndOffice("zzsql3125f1f194c82bdea9miiii750904", office);
			// 启动流程
			String processType = workActivityMenu.getProcessType();
			StringBuffer buffer = new StringBuffer();
			Activity activity = new Activity();
			WorkProjectNotify workProjectNotify = UtilNotify
					.saveNotify(workRelationship.getId(),
							null,
							workRelationship.getCompanyId(),
							title,
							str,
							"67",
							"0",
							"待审批",
							""
					);
			List<User> users = new ArrayList<>();
			List<User> rlzybzrs = UserUtils.getByRoleActivityEnnameTask("bmzr",2,office.getId(),"18",workRelationship.getCreateBy());
			List<User> rlzys = UserUtils.getByRoleActivityEnnameTask("rlzy",3,office.getId(),"18",workRelationship.getCreateBy());
			List<User> qyrs = new ArrayList();
			if(workRelationship.getWorkStaffBasicInfo()!=null && StringUtils.isNotBlank(workRelationship.getWorkStaffBasicInfo().getUserId())){
				qyrs.add(sU);
			}
			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(),"18",workRelationship.getCreateBy());
						if (enusers.size()==0){
							workRelationship.setStatus("1");
							if(workRelationship!=null && StringUtils.isNotBlank(workRelationship.getContractType()) && workRelationship.getContractType().contains(",")){
								workRelationship.setContractType(workRelationship.getContractType().replace(",",""));
							}
							super.save(workRelationship);
							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(),"18",workRelationship.getCreateBy());
					}
					//人员审批
					if (StringUtils.isNotBlank(activity.getUser().getId())) {
						users.add(activity.getUser());
					}
				}
				workProjectNotify.setId("");
			} else {
				variables.put("rlzybzrList", rlzybzrs);
				if (rlzybzrs.size()==0){
					return "流程审批人不能为空,角色部门主任下无用户,请联系管理员！";
				}
				variables.put("rlzybzrcount",rlzybzrs.size());
				processType = "workrelationship";
				users.addAll(rlzybzrs);
			}
			for (User u : users){
				workProjectNotify.setCreateBy(user);
				workProjectNotify.setUpdateBy(user);
				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() + ",报销编号:"+ workReimbursement.getNumber() + " 待审批!\"," +
								"\"useType\":\"sys\"}";
						ChatServerPool.sendMessageToUser(toUserConn, message);//同时向本人发送消息
					}*/
				Map<String,Object> extras = new HashMap<>();
				extras.put("type","7001");
				extras.put("id",workProjectNotify.getId());
				extras.put("procDefKey","67");
				UserUtils.pushInfoToApp(title,str,extras,u.getId());
				UserUtils.pushIm(u.getId(),str);
			}
			variables.put("type", processType);
			variables.put("busId", businessKey);
			variables.put("title", "劳动关系审批单：" + sU.getName());//设置标题；

			ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processType, businessKey, variables);
			workRelationship.setProcessInstance(processInstance);
			if (StringUtils.isNotBlank(processInstanceId)) {
				workActivityProcessService.updateProcessInstanceId(processInstance.getId(),processInstanceId);
				workActivityProcessService.deleteProcessInstanceId(processInstanceId);
				workActivityProcessService.deleteProcessIdAuditUsers(processInstanceId);
			}
			// 更新流程实例ID
			workRelationship.setProcessInstanceId(processInstance.getId());
			workRelationshipDao.updateProcessInstanceId(workRelationship);
			List<Activity> list = workActivityMenu.getActivities();
			if (list != null && list.size() != 0) {
				workActivityProcessService.saveList(list, processInstance.getId());
			} else {
				WorkActivityProcess workActivityProcess = new WorkActivityProcess();
				workActivityProcess.setCreateBy(user);
				workActivityProcess.setUpdateBy(user);
				workActivityProcess.setProcessKey("workrelationship");
				workActivityProcess.setCount(1);
				workActivityProcess.setProcessInstanceId(processInstance.getId());
				workActivityProcess.setIsApproval("0");
				workActivityProcessService.save(workActivityProcess);
				workActivityProcess.setCount(2);
				workActivityProcess.setId("");
				workActivityProcessService.save(workActivityProcess);
				workActivityProcess.setCount(3);
				workActivityProcess.setId("");
				workActivityProcessService.save(workActivityProcess);
				workActivityProcessService.insertAuditsByType(rlzybzrs,processInstance.getId(),1,1);
				workActivityProcessService.insertAuditsByType(rlzys,processInstance.getId(),2,0);
				workActivityProcessService.insertAuditsByType(qyrs,processInstance.getId(),3,0);
			}
		}catch (Exception e){
			logger.error("启动审批流程异常：",e);
			this.delete(workRelationship);
			return "启动审批流程异常:"+e.getMessage();
		}
		return "";
	}
	//首次签约
	@Transactional(readOnly = false)
	public String saves(WorkRelationship workRelationship, Map<String, Object> variables, String processInstanceId) {
		User user = UserUtils.getUser();
		if(workRelationship!=null && StringUtils.isNotBlank(workRelationship.getContractType()) && workRelationship.getContractType().contains(",")){
			workRelationship.setContractType(workRelationship.getContractType().replace(",",""));
		}
		super.save(workRelationship);
		String str = "";
		//获取人员
		User sU = null;
		Office office = null;
		if(workRelationship.getWorkStaffBasicInfo()!=null){
			String sid = workRelationship.getWorkStaffBasicInfo().getId();
			if(StringUtils.isNotBlank(sid)){
				WorkStaffBasicInfo w = workStaffBasicInfoService.getAchives(sid);
				String uid = w.getUserId();
				if(StringUtils.isNotBlank(uid)){
					sU = UserUtils.get(uid);
				}
				office = w.getOffice();
			}
		}
		if(sU == null){
			workRelationship.setStatus("1");
			if(workRelationship!=null && StringUtils.isNotBlank(workRelationship.getContractType()) && workRelationship.getContractType().contains(",")){
				workRelationship.setContractType(workRelationship.getContractType().replace(",",""));
			}
			super.save(workRelationship);
			return "流程审批人不能为空,所选人员未注册,请联系管理员！";
		}
		if(office == null){
			workRelationship.setStatus("1");
			if(workRelationship!=null && StringUtils.isNotBlank(workRelationship.getContractType()) && workRelationship.getContractType().contains(",")){
				workRelationship.setContractType(workRelationship.getContractType().replace(",",""));
			}
			super.save(workRelationship);
			return "流程审批人不能为空,所选人员所在部门异常,请联系管理员！";
		}
		if(StringUtils.isNotBlank(workRelationship.getContractNum())){
			str =  "合同编号:"+workRelationship.getContractNum()+",合同类型:"+ DictUtils.getDictLabel(workRelationship.getContractType(),"relsp_cType","")
					+",员工状态:"+workRelationship.getWorkStaffBasicInfo().getStatus();
		}else{
			str =  "合同类型:"+ DictUtils.getDictLabel(workRelationship.getContractType(),"relsp_cType","")
					+",员工状态:"+workRelationship.getWorkStaffBasicInfo().getStatus();
		}
		String title = "人员名称:"+workRelationship.getWorkStaffBasicInfo().getName();
		updateWorkReimbursementInfo(workRelationship);
		// 用来设置启动流程的人员ID，引擎会自动把用户ID保存到activiti:initiator中
		identityService.setAuthenticatedUserId(user.getId());
		// 启动流程
		String businessKey = workRelationship.getId().toString();
		WorkActivityMenu workActivityMenu = workActivityMenuService.findByParentAndOffice("zzsql3125f1f194c1234ea9miiii750904", office);
		// 启动流程
		String processType = workActivityMenu.getProcessType();
		StringBuffer buffer = new StringBuffer();
		Activity activity = new Activity();
		WorkProjectNotify workProjectNotify = UtilNotify
				.saveNotify(workRelationship.getId(),
						null,
						workRelationship.getCompanyId(),
						title,
						str,
						"90",
						"0",
						"待审批",
						""
				);
		List<User> users = new ArrayList<>();
		List<User> qyrs = new ArrayList();
		qyrs.add(sU);
		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(),"18",workRelationship.getCreateBy());
					if (enusers.size()==0){
						workRelationship.setStatus("1");
						if(workRelationship!=null && StringUtils.isNotBlank(workRelationship.getContractType()) && workRelationship.getContractType().contains(",")){
							workRelationship.setContractType(workRelationship.getContractType().replace(",",""));
						}
						super.save(workRelationship);
						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(),"18",workRelationship.getCreateBy());
				}
				//人员审批
				if (StringUtils.isNotBlank(activity.getUser().getId())) {
					users.add(activity.getUser());
				}
			}
			workProjectNotify.setId("");
		} else {
			variables.put("qyr",sU);
			processType = "workrelationshipfirst";
			users.addAll(qyrs);
		}
		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() + ",报销编号:"+ workReimbursement.getNumber() + " 待审批!\"," +
                            "\"useType\":\"sys\"}";
                    ChatServerPool.sendMessageToUser(toUserConn, message);//同时向本人发送消息
                }*/
			Map<String,Object> extras = new HashMap<>();
			extras.put("type","7001");
			extras.put("id",workProjectNotify.getId());
			extras.put("procDefKey","90");
			UserUtils.pushInfoToApp(title,str,extras,u.getId());
			UserUtils.pushIm(u.getId(),str);
		}
		variables.put("type", processType);
		variables.put("busId", businessKey);
		variables.put("title", "劳动关系审批单：" + sU.getName());//设置标题；

		ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processType, businessKey, variables);
		workRelationship.setProcessInstance(processInstance);
		if (StringUtils.isNotBlank(processInstanceId)) {
			workActivityProcessService.updateProcessInstanceId(processInstance.getId(),processInstanceId);
			workActivityProcessService.deleteProcessInstanceId(processInstanceId);
			workActivityProcessService.deleteProcessIdAuditUsers(processInstanceId);
		}
		// 更新流程实例ID
		workRelationship.setProcessInstanceId(processInstance.getId());
		workRelationshipDao.updateProcessInstanceId(workRelationship);
		List<Activity> list = workActivityMenu.getActivities();
		if (list != null && list.size() != 0) {
			workActivityProcessService.saveList(list, processInstance.getId());
		} else {
			WorkActivityProcess workActivityProcess = new WorkActivityProcess();
			workActivityProcess.setProcessKey("workrelationshipfirst");
			workActivityProcess.setCount(1);
			workActivityProcess.setProcessInstanceId(processInstance.getId());
			workActivityProcess.setIsApproval("0");
			workActivityProcessService.save(workActivityProcess);

			workActivityProcessService.insertAuditsByType(qyrs,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 String auditSaves(WorkRelationship workRelationship,List<User> auditUsers) {
		String str = "";
		Office office = null;
		if(workRelationship.getWorkStaffBasicInfo()!=null){
			String sid = workRelationship.getWorkStaffBasicInfo().getId();
			if(StringUtils.isNotBlank(sid)){
				WorkStaffBasicInfo w = workStaffBasicInfoService.getAchives(sid);
				if(w!=null){
					office = w.getOffice();
				}
			}
		}
		if(StringUtils.isNotBlank(workRelationship.getContractNum())){
			str =  "合同编号:"+workRelationship.getContractNum()+",合同类型:"+ DictUtils.getDictLabel(workRelationship.getContractType(),"relsp_cType","")
					+",员工状态:"+workRelationship.getWorkStaffBasicInfo().getStatus();
		}else{
			str =  "合同类型:"+ DictUtils.getDictLabel(workRelationship.getContractType(),"relsp_cType","")
					+",员工状态:"+workRelationship.getWorkStaffBasicInfo().getStatus();
		}
		String title = "人员名称:"+workRelationship.getWorkStaffBasicInfo().getName();
		// 对不同环节的业务逻辑进行操作
		String taskDefKey = workRelationship.getAct().getTaskDefKey();
		if (!"modifyApply".equals(taskDefKey)) {
			actTaskService.claim(workRelationship.getAct().getTaskId(), UserUtils.getUser().getId());
		}else {
			workRelationship.getAct().setFlag("yes");
			updateWorkReimbursementInfo(workRelationship);
		}
		String comment = "";
		if (workRelationship.getStatus().equals("4")){
			comment = ("yes".equals(workRelationship.getAct().getFlag())?"[重新申请] ":"[已撤销] ");
		}else {
			comment = ("yes".equals(workRelationship.getAct().getFlag())?"[同意] ":"[驳回] ")+workRelationship.getAct().getComment();
		}
		//yes 的时候状态为审核通过 否则为未通过
		//1 审核中 2 未通过
		workRelationship.setStatus(("yes".equals(workRelationship.getAct().getFlag()) ? "2" : "4"));
		Map<String, Object> vars = Maps.newHashMap();
		//业务逻辑对应的条件表达式
		String exp = "";
		String taskCount = "";
		String notifyRole = "";
		int key = 0;
		String enname = "";
		List<User> users = new ArrayList<>();
		List<User> userList = new ArrayList<>();
		List<Activity> activitieList = activityService.getByProcessInstanceId(workRelationship.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(workRelationship.getProcessInstanceId());
		List<WorkActivityProcess> workActivityProcesses = workActivityProcessService.findList(selectProcess);
		List<Activity> activities = workActivityMenu.getActivities();
		if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("workrelationshipfirst")) {
			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 (!"1".equals(workRelationship.getAct().getFlag())) {
						workRelationship.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 (!"1".equals(workRelationship.getAct().getFlag())) {
						workRelationship.setStatus("3");
						workActivityProcess.setIsApproval("2");
					} else {
						workActivityProcess.setIsApproval("1");
					}
					break;
				}
			}
		} else {
			workActivityMenu.setProcessType("workrelationshipfirst");
			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 ("qyr".equals(taskDefKey) && count.contains("1")) {
					taskCount = "1";
					exp = "pass";
					if ("yes".equals(workRelationship.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);
					vars.put("qyr", UserUtils.get(workRelationship.getWorkStaffBasicInfo().getId()));
					enname = "qyr";
					if (!"yes".equals(workRelationship.getAct().getFlag())) {
						workRelationship.setStatus("3");
					}
					break;
				} else if ("apply_end".equals(taskDefKey)) {
				}

			}
		}
		// 设置意见
		workRelationship.getAct().setComment(("yes".equals(workRelationship.getAct().getFlag()) ? "[驳回] " : "[同意] ") + workRelationship.getAct().getComment());
		workRelationship.preUpdate();
		// 提交流程任务
		vars.put(exp, "yes".equals(workRelationship.getAct().getFlag()) ? true : false);
		workActivityProcessService.updateProcess(workActivityProcess,workActivityMenu,key,taskCount,workRelationship.getProcessInstanceId(),taskDefKey,"modifyApply",workRelationship.getAct().getFlag(),comment, activities);
		// 提交流程任务
		actTaskService.complete(workRelationship.getAct().getTaskId(), workRelationship.getAct().getProcInsId(), workRelationship.getAct().getComment(), vars);
		boolean state = actTaskService.isProcessEnd(workRelationship.getAct().getProcInsId());
		if (!state) {
			if(StringUtils.isNotBlank(workRelationship.getContractNum())){
				str =  "合同编号:"+workRelationship.getContractNum()+",合同类型:"+ DictUtils.getDictLabel(workRelationship.getContractType(),"relsp_cType","")
						+",员工状态:"+workRelationship.getWorkStaffBasicInfo().getStatus();
			}else{
				str =  "合同类型:"+ DictUtils.getDictLabel(workRelationship.getContractType(),"relsp_cType","")
						+",员工状态:"+workRelationship.getWorkStaffBasicInfo().getStatus();
			}
			title = "人员名称:"+workRelationship.getWorkStaffBasicInfo().getName();
			users.add(workRelationship.getCreateBy());
			if ("yes".equals(workRelationship.getAct().getFlag())) {
				workRelationship.setStatus("5");
				WorkProjectNotify notify = new WorkProjectNotify();
				notify.setNotifyId(workRelationship.getId());
				userList = workProjectNotifyService.readByNotifyId(notify);
				workProjectNotifyService
						.save(UtilNotify
								.saveNotify(workRelationship.getId(),
										workRelationship.getCreateBy(),
										workRelationship.getCompanyId(),
										title,
										str,
										"90",
										"0",
										"待通知",
										notifyRole));

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

					}
				}

			} else {
				if (!"yes".equals(workRelationship.getAct().getFlag())) {
					WorkProjectNotify notify = new WorkProjectNotify();
					notify.setNotifyId(workRelationship.getId());
					userList = workProjectNotifyService.readByNotifyId(notify);
					workProjectNotifyService
							.save(UtilNotify
									.saveNotify(workRelationship.getId(),
											workRelationship.getCreateBy(),
											workRelationship.getCompanyId(),
											title,
											str,
											"90",
											"0",
											"重新申请",
											notifyRole));
					users.add( workRelationship.getCreateBy());
				}else {
					if (StringUtils.isNotBlank(enname)) {
						WorkProjectNotify notify = new WorkProjectNotify();
						notify.setNotifyId(workRelationship.getId());
						userList = workProjectNotifyService.readByNotifyId(notify);
						WorkProjectNotify workProjectNotify = UtilNotify
								.saveNotify(workRelationship.getId(),
										new User(),
										workRelationship.getCompanyId(),
										title,
										str,
										"90",
										"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","90");
								UserUtils.pushInfoToApp(title,str,extras,user1.getId());

							}
						}
					}else {
						WorkProjectNotify notify = new WorkProjectNotify();
						notify.setNotifyId(workRelationship.getId());
						userList = workProjectNotifyService.readByNotifyId(notify);
						users.addAll(userList);
						users.add(workRelationship.getCreateBy());
						workProjectNotifyService
								.save(UtilNotify
										.saveNotify(workRelationship.getId(),
												workRelationship.getCreateBy(),
												workRelationship.getCompanyId(),
												title,
												str,
												"90",
												"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());
			}
		}
		if(workRelationship!=null && StringUtils.isNotBlank(workRelationship.getContractType()) && workRelationship.getContractType().contains(",")){
			workRelationship.setContractType(workRelationship.getContractType().replace(",",""));
		}
		workRelationshipDao.update(workRelationship);
		return "保存审核意见成功！";
	}
	@Transactional(readOnly = false)
	public String auditSave(WorkRelationship workRelationship,List<User> auditUsers) {
		String str = "";
		Office office = null;
		if(workRelationship.getWorkStaffBasicInfo()!=null){
			String sid = workRelationship.getWorkStaffBasicInfo().getId();
			if(StringUtils.isNotBlank(sid)){
				WorkStaffBasicInfo w = workStaffBasicInfoService.getAchives(sid);
				if(w!=null){
					office = w.getOffice();
				}
			}
		}
		if(StringUtils.isNotBlank(workRelationship.getContractNum())){
			str =  "合同编号:"+workRelationship.getContractNum()+",合同类型:"+ DictUtils.getDictLabel(workRelationship.getContractType(),"relsp_cType","")
					+",员工状态:"+workRelationship.getWorkStaffBasicInfo().getStatus();
		}else{
			str =  "合同类型:"+ DictUtils.getDictLabel(workRelationship.getContractType(),"relsp_cType","")
					+",员工状态:"+workRelationship.getWorkStaffBasicInfo().getStatus();
		}
		String title = "人员名称:"+workRelationship.getWorkStaffBasicInfo().getName();
		// 对不同环节的业务逻辑进行操作
		String taskDefKey = workRelationship.getAct().getTaskDefKey();
		if ("rlzy".equals(taskDefKey)) {
			actTaskService.claim(workRelationship.getAct().getTaskId(), UserUtils.getUser().getId());
		}else {
			workRelationship.getAct().setFlag("1");
			updateWorkReimbursementInfo(workRelationship);
		}
		String comment = "";
		if (workRelationship.getStatus().equals("4")){
			comment = ("1".equals(workRelationship.getAct().getFlag())?"[重新申请] ":"[已撤销] ");
		}else {
			comment = ("1".equals(workRelationship.getAct().getFlag())?"[同意] ":"[驳回] ")+workRelationship.getAct().getComment();
		}
		//yes 的时候状态为审核通过 否则为未通过
		//1 审核中 2 未通过
		workRelationship.setStatus(("1".equals(workRelationship.getAct().getFlag()) ? "2" : "4"));
		Map<String, Object> vars = Maps.newHashMap();
		//业务逻辑对应的条件表达式
		String exp = "";
		String taskCount = "";
		String notifyRole = "";
		int key = 0;
		String enname = "";
		List<User> users = new ArrayList<>();
		List<User> userList = new ArrayList<>();
		List<Activity> activitieList = activityService.getByProcessInstanceId(workRelationship.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(workRelationship.getProcessInstanceId());
		List<WorkActivityProcess> workActivityProcesses = workActivityProcessService.findList(selectProcess);
		List<Activity> activities = workActivityMenu.getActivities();
		if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("workrelationship")) {
			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 (!"1".equals(workRelationship.getAct().getFlag())) {
						workRelationship.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 (!"1".equals(workRelationship.getAct().getFlag())) {
						workRelationship.setStatus("3");
						workActivityProcess.setIsApproval("2");
					} else {
						workActivityProcess.setIsApproval("1");
					}
					break;
				}
			}
		} else {
			workActivityMenu.setProcessType("workrelationship");
			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 ("rlzybzr".equals(taskDefKey) && count.contains("1")) {
					taskCount = "1";
					exp = "pass";
						vars.put("rlzyList", auditUsers);
						vars.put("rlzycount",auditUsers.size());
						workActivityProcessService.insertAuditsByType(auditUsers,workRelationship.getProcessInstanceId(),2,1);
						workActivityProcess.setIsApproval("1");
						notifyRole = "人力专员审核";
						enname = "rlzy";
					break;
				}else if ("rlzy".equals(taskDefKey) && count.contains("2")){
					taskCount = "2";
					exp = "pass";
					if("2".equals(workRelationship.getAct().getFlag())){
						//驳回给部门主任
						enname = "不为空";
						workActivityProcess.setIsApproval("2");
						notifyRole = "部门主任";
						WorkProjectNotify notify = new WorkProjectNotify();
						notify.setNotifyId(workRelationship.getId());
						userList = workProjectNotifyService.readByNotifyId(notify);
						WorkProjectNotify workProjectNotify = UtilNotify
								.saveNotify(workRelationship.getId(),
										new User(),
										workRelationship.getCompanyId(),
										title,
										str,
										"67",
										"0",
										"待审批",
										notifyRole);
						List<User> rlzybzrs = UserUtils.getByRoleActivityEnname("bmzr",2,office.getId(),"18",workRelationship.getCreateBy());
						users.addAll(rlzybzrs);
						for (User user1:rlzybzrs){
							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","67");
								UserUtils.pushInfoToApp(title,str,extras,user1.getId());
							}
						}
					}else{
						//同意状态下0续签  1不续签
						if("1".equals(workRelationship.getRenew())){
							workRelationship.getAct().setFlag("3");
							notifyRole = "审批通过";
							workActivityProcess.setIsApproval("1");
						}else{
							if(workRelationship.getWorkStaffBasicInfo()== null ){
								workRelationship = this.get(workRelationship.getId());
							}
							workRelationship.getAct().setFlag("1");
							vars.put("qyr", UserUtils.get(workRelationship.getWorkStaffBasicInfo().getId()));
							workActivityProcessService.insertAuditsByType(auditUsers,workRelationship.getProcessInstanceId(),3,1);
							notifyRole = "签约人";
							workActivityProcess.setIsApproval("1");
							enname = "qyr";
						}
					}

					break;
				} else if ("qyr".equals(taskDefKey) && count.contains("3")) {
					taskCount = "3";
					workRelationship.getAct().setFlag("1");
					exp = "pass";
					notifyRole = "审批通过";
					workActivityProcess.setIsApproval("1");
					break;
				} else if ("modifyApply".equals(taskDefKey)&& count.contains("0")) {
					taskCount = "0";
					notifyRole = "人力资源部负责人审批";
					exp = "pass";
					workActivityProcess.setCount(0);
					enname = "rlzybzr";
					if (!"1".equals(workRelationship.getAct().getFlag())) {
						workRelationship.setStatus("3");
					}
					break;
				} else if ("apply_end".equals(taskDefKey)) {
				}

			}
		}
		// 设置意见
		workRelationship.getAct().setComment(("2".equals(workRelationship.getAct().getFlag()) ? "[驳回] " : "[同意] ") + workRelationship.getAct().getComment());
		workRelationship.preUpdate();
		// 提交流程任务
		vars.put(exp, workRelationship.getAct().getFlag());
		vars.put("passs", true);
		if("3".equals(workRelationship.getAct().getFlag())){
			workActivityProcessService.updateProcessSpecial(workActivityProcess,workActivityMenu,key,taskCount,workRelationship.getProcessInstanceId(),taskDefKey,"modifyApply",workRelationship.getAct().getFlag(),comment, activities);
			WorkActivityProcess workActivityP = new WorkActivityProcess();
			workActivityP.setProcessInstanceId(workRelationship.getProcessInstanceId());
			List<WorkActivityProcess> processList = workActivityProcessService.findList(workActivityP);
			if(processList!=null && processList.size()>0){
				for (int i =0;i<processList.size();i++) {
					WorkActivityProcess p = processList.get(i);
					if(3 == p.getCount()){
						p.setDelFlag("1");
						p.setIsApproval("-1");
						workActivityProcessDao.updateDelFlagAndIsApproval(p);
					}
				}
			}
		}else{
			workActivityProcessService.updateProcessSpecial(workActivityProcess,workActivityMenu,key,taskCount,workRelationship.getProcessInstanceId(),taskDefKey,"modifyApply",workRelationship.getAct().getFlag(),comment, activities);
		}
		// 提交流程任务
		actTaskService.complete(workRelationship.getAct().getTaskId(), workRelationship.getAct().getProcInsId(), workRelationship.getAct().getComment(), vars);
		boolean state = actTaskService.isProcessEnd(workRelationship.getAct().getProcInsId());
		if (!state) {
			if(StringUtils.isNotBlank(workRelationship.getContractNum())){
				str =  "合同编号:"+workRelationship.getContractNum()+",合同类型:"+ DictUtils.getDictLabel(workRelationship.getContractType(),"relsp_cType","")
						+",员工状态:"+workRelationship.getWorkStaffBasicInfo().getStatus();
			}else{
				str =  "合同类型:"+ DictUtils.getDictLabel(workRelationship.getContractType(),"relsp_cType","")
						+",员工状态:"+workRelationship.getWorkStaffBasicInfo().getStatus();
			}
			title = "人员名称:"+workRelationship.getWorkStaffBasicInfo().getName();
			users.add(workRelationship.getCreateBy());
			if ("1".equals(workRelationship.getAct().getFlag()) || "3".equals(workRelationship.getAct().getFlag())) {
				workRelationship.setStatus("5");
				WorkProjectNotify notify = new WorkProjectNotify();
				notify.setNotifyId(workRelationship.getId());
				userList = workProjectNotifyService.readByNotifyId(notify);
				workProjectNotifyService
						.save(UtilNotify
								.saveNotify(workRelationship.getId(),
										workRelationship.getCreateBy(),
										workRelationship.getCompanyId(),
										title,
										str,
										"67",
										"0",
										"待通知",
										notifyRole));

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

					}
				}

			} else {
				//如果属于驳回到申请人环节
				if ("2".equals(workRelationship.getAct().getFlag())&&!enname.contains("不为空")) {
					WorkProjectNotify notify = new WorkProjectNotify();
					notify.setNotifyId(workRelationship.getId());
					userList = workProjectNotifyService.readByNotifyId(notify);
					//users.addAll(userList);
					workProjectNotifyService
							.save(UtilNotify
									.saveNotify(workRelationship.getId(),
											workRelationship.getCreateBy(),
											workRelationship.getCompanyId(),
											title,
											str,
											"67",
											"0",
											"重新申请",
											notifyRole));
					users.add( workRelationship.getCreateBy());
				} else if("1".equals(workRelationship.getAct().getFlag())){
						WorkProjectNotify notify = new WorkProjectNotify();
						notify.setNotifyId(workRelationship.getId());
						userList = workProjectNotifyService.readByNotifyId(notify);
						//users.addAll(userList1);
						WorkProjectNotify workProjectNotify = UtilNotify
								.saveNotify(workRelationship.getId(),
										new User(),
										workRelationship.getCompanyId(),
										title,
										str,
										"67",
										"0",
										"待审批",
										notifyRole);
						users.addAll(auditUsers);
						for (User user1:auditUsers){
							workProjectNotify.setId("");
							workProjectNotify.setUser(user1);
							workProjectNotify.setIsNewRecord(false);
							workProjectNotifyService
									.saveRelation(workProjectNotify);
							if (!"modifyApply".equals(taskDefKey)){
								Map<String,Object> extras = new HashMap<>();
									extras.put("type","7001");
								extras.put("id",workProjectNotify.getId());
								extras.put("procDefKey","67");
								UserUtils.pushInfoToApp(title,str,extras,user1.getId());

							}
						}
				}
			}
		}
		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());
			}
		}
		if(workRelationship!=null && StringUtils.isNotBlank(workRelationship.getContractType()) && workRelationship.getContractType().contains(",")){
			workRelationship.setContractType(workRelationship.getContractType().replace(",",""));
		}
		workRelationshipDao.update(workRelationship);
		return "保存审核意见成功！";
	}

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

	@Transactional(readOnly = false)
	public void cancelInvalidate(WorkRelationship workRelationship) {
		String invalidateProcessInstanceId = workRelationship.getProcessInstanceId();
		try {
			//将流程图中尚未走到的task的流程追踪信息逻辑删除，添加一条"撤销"流程追踪信息
			WorkActivityProcess process = new WorkActivityProcess();
			process.setProcessInstanceId(workRelationship.getProcessInstanceId());
			process.setIsApproval("0");
			//List<WorkActivityProcess> processList1 = workActivityProcessService.findByProcInsId(process);
			WorkActivityProcess workActivityProcess = new WorkActivityProcess();
			workActivityProcess.setProcessInstanceId(workRelationship.getProcessInstanceId());
			List<WorkActivityProcess> processList = workActivityProcessService.findList(workActivityProcess);
			WorkProjectNotify notify = new WorkProjectNotify();
			notify.setNotifyId(workRelationship.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()+",劳动关系合同编号:"+workRelationship.getContractNum() +" 强制撤销!\"," +
								"\"useType\":\"sys\"}";
						ChatServerPool.sendMessageToUser(toUserConn, message);//同时向本人发送消息
						//ChatServerPool.sendMessageToUser(toUserConn, u.getId() + "_sys_审批信息 " + "报销人:" + user.getName() + ",报销编号:" + workReimbursement.getNumber() + " 强制撤销!");//同时向本人发送消息
					}*/
					UserUtils.pushIm(u.getId(),"申请人:"+ user.getName()+"的劳动关系合同强制撤销!");
				}
			}
			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.setDelFlag("0");
				pro.preInsert();
				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,"强制撤销");
			workRelationship.setStatus("3");
			workRelationship.preUpdate();
			if(workRelationship!=null && StringUtils.isNotBlank(workRelationship.getContractType()) && workRelationship.getContractType().contains(",")){
				workRelationship.setContractType(workRelationship.getContractType().replace(",",""));
			}
			workRelationshipDao.update(workRelationship);
		}catch (ActivitiObjectNotFoundException e){
			System.err.println("撤销异常，因为这个流程已不存在!");
			e.printStackTrace();
		}
		catch (Exception e) {
			e.printStackTrace();
		}

	}
	//更新提醒标记
	@Transactional(readOnly = false)
	public int updateSign(WorkRelationship workRelationship){
		return workRelationshipDao.updateSign(workRelationship);
	}
}