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

import java.text.SimpleDateFormat;
import java.util.*;

import com.google.common.collect.Maps;
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.workout.service.WorkOutService;
import com.jeeplus.modules.workovertime.dao.WorkOvertimeDao;
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 com.jeeplus.modules.workstaff.entity.WorkStaffBasicInfo;
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.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.service.CrudService;
import com.jeeplus.modules.workfield.entity.WorkField;
import com.jeeplus.modules.workfield.dao.WorkFieldDao;

/**
 * 外勤申请Service
 * @author ssrh
 * @version 2018-09-06
 */
@Service
@Transactional(readOnly = true)
public class WorkFieldService extends CrudService<WorkFieldDao, WorkField> {
	@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 ActivityService activityService;
	@Autowired
	private WorkActivityProcessDao workActivityProcessDao;
	@Autowired
	private WorkStaffAchivesDao workStaffAchivesDao;
	@Autowired
	private LeaveApplyService leaveApplyService;
	@Autowired
	@Lazy
	private WorkOutService workOutService;

	@Autowired
	private WorkFieldDao workFieldDao;
	@Autowired
	private WorkClientAttachmentDao workClientAttachmentDao;
	public WorkField get(String id) {
		WorkField workField = super.get(id);
		if(workField!=null){
			//附件
			WorkClientAttachment workClientAttachment = new WorkClientAttachment();
			workClientAttachment.setAttachmentId(id);
			workClientAttachment.setAttachmentFlag("75");
			workField.setWorkAttachments(workClientAttachmentDao.findList(workClientAttachment));
		}
		return workField;
	}

	public WorkField getByStaffIdAndTime(String staffId, String time) {
		WorkField workField = dao.getByStaffIdAndTime(staffId, time);
		return workField;
	}

	public List<WorkField> findList(WorkField workField) {
		return super.findList(workField);
	}
	
	public Page<WorkField> findPage(Page<WorkField> page, WorkField workField) {
		workField.getSqlMap().put("dsf", dataScopeFilter(workField.getCurrentUser(), "o", "u","s", MenuStatusEnum.WORK_FIELD.getValue()));
		workField.setPage(page);
		page.setList(findList(workField));
		return page;
	}
	
	@Transactional(readOnly = false)
	public void save(WorkField workField) {
		super.save(workField);
		updateInfo(workField);
	}

	@Transactional(readOnly = false)
	public void updateInfo(WorkField workField) {
		//附件信息
		for (WorkClientAttachment workClientAttachment : workField.getWorkAttachments()) {
			if (workClientAttachment.getId() == null) {
				continue;
			}
			if (WorkClientAttachment.DEL_FLAG_NORMAL.equals(workClientAttachment.getDelFlag())) {
				workClientAttachment.setAttachmentId(workField.getId());
				workClientAttachment.setAttachmentFlag("75");
				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 String validateTime(Date startTime, String startType, Date endTime, String endType){
		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd");
		WorkStaffBasicInfo workStaffBasicInfo=leaveApplyService.getBasicInfo();
		List<WorkField> leaveDetails=workFieldDao.findListValidateTime(workStaffBasicInfo.getId());
		double start=Integer.parseInt(sdf1.format(startTime));
		double end=Integer.parseInt(sdf1.format(endTime));
		if("2".equals(startType)){
			start=start+0.5;
		}
		if("2".equals(endType)){
			end=end+0.5;
		}
		for(int i=0;i<leaveDetails.size();i++){
			WorkField detail=leaveDetails.get(i);
			Date stateTime1 = detail.getStartDate();
			double start1=Integer.parseInt(sdf1.format(stateTime1));
			Date realEndTime1 = detail.getEndDate();
			double realEnd1=Integer.parseInt(sdf1.format(realEndTime1));
			String startType1 = detail.getStartType();
			String realEndType1 = detail.getEndType();
			if("2".equals(startType1)){
				start1=start1+0.5;
			}
			if("2".equals(realEndType1)){
				realEnd1=realEnd1+0.5;
			}
			if((start>=start1&&start<=realEnd1)||(end>=start1&&end<=realEnd1)
					||(start1>=start&&start1<=end)||(realEnd1>=start&&realEnd1<=end)){
				return  "外勤时间存在重叠情况！";
			}
		}
		return "";
	}
	/**
	 * 提交存储
	 * @param
	 * @param variables
	 */
	@Transactional(readOnly = false)
	public String save(WorkField workField, Map<String, Object> variables, String processInstanceId) {
		//时间校验
		String sign1 = leaveApplyService.validateTime(workField.getStartDate(),workField.getStartType(),workField.getEndDate(),workField.getEndType());
		if(StringUtils.isNotBlank(sign1)){
			updateInfo(workField);
			if("2".equals(workField.getStatus())){
				workField.setStatus("1");
			}
			super.save(workField);
			return sign1;
		}else{
			String sign2 = workOutService.validateTime(workField.getStartDate(),workField.getStartType(),workField.getEndDate(),workField.getEndType());
			if(StringUtils.isNotBlank(sign2)){
				updateInfo(workField);
				if("2".equals(workField.getStatus())){
					workField.setStatus("1");
				}
				super.save(workField);
				return sign2;
			}else{
				String sign3 = this.validateTime(workField.getStartDate(),workField.getStartType(),workField.getEndDate(),workField.getEndType());
				if(StringUtils.isNotBlank(sign3)){
					updateInfo(workField);
					if("2".equals(workField.getStatus())){
						workField.setStatus("1");
					}
					super.save(workField);
					return sign3;
				}
			}
		}
		User user = UserUtils.getUser();
		if (StringUtils.isBlank(workField.getNum())) {
			workField.setNum(serialNumTplService.genSerialNum(user.getCompany(), workField.SERIAL_BIZCODE));
		}
		super.save(workField);
		Office office = officeService.get(workField.getOfficeId());
		String str =  "外勤申请编号:"+workField.getNum()+",外勤事由:"+workField.getReason()+",所属部门:"+office.getName();
		String title = "外勤申请人:"+user.getName();
		updateInfo(workField);
		// 用来设置启动流程的人员ID，引擎会自动把用户ID保存到activiti:initiator中
		identityService.setAuthenticatedUserId(user.getId());
		// 启动流程
		String businessKey = workField.getId().toString();
		WorkActivityMenu workActivityMenu = workActivityMenuService.findByParentAndOffice("zzsqliuokjyhg94yuhbqasdfiiii750904", office);
		// 启动流程
		String processType = workActivityMenu.getProcessType();
		StringBuffer buffer = new StringBuffer();
		Activity activity = new Activity();
		WorkProjectNotify workProjectNotify = UtilNotify
				.saveNotify(workField.getId(),
						null,
						workField.getCompanyId(),
						title,
						str,
						"79",
						"0",
						"待审批",
						""
				);
		List<User> users = new ArrayList<>();
		List<User> bmzrs = UserUtils.getByRoleActivityEnname("bmzr",2,office.getId(),"21",workField.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(),"21",workField.getCreateBy());
					if (enusers.size()==0){
						workField.setStatus("1");
						super.save(workField);
						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(),"21",workField.getCreateBy());
				}
				//人员审批
				if (StringUtils.isNotBlank(activity.getUser().getId())) {
					users.add(activity.getUser());
				}
			}
			workProjectNotify.setId("");
		} else {
			variables.put("bmzrList", bmzrs);
			if (bmzrs.size()==0 ){
				workField.setStatus("1");
				super.save(workField);
			}
			if (bmzrs.size()==0){
				return "流程审批人不能为空,角色部门负责人下无用户,请联系管理员！";
			}
			variables.put("bmzrcount",bmzrs.size());
			processType = "workfield";
			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","79");
			UserUtils.pushInfoToApp(title,str,extras,u.getId());
			UserUtils.pushIm(u.getId(),str);
		}
		variables.put("type", processType);
		variables.put("busId", businessKey);
		variables.put("title", "审批单：" + workField.getNum());//设置标题；

		ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processType, businessKey, variables);
		workField.setProcessInstance(processInstance);
		if (StringUtils.isNotBlank(processInstanceId)) {
			workActivityProcessService.updateProcessInstanceId(processInstance.getId(),processInstanceId);
			workActivityProcessService.deleteProcessInstanceId(processInstanceId);
			workActivityProcessService.deleteProcessIdAuditUsers(processInstanceId);
		}
		// 更新流程实例ID
		workField.setProcessInstanceId(processInstance.getId());
		workFieldDao.updateProcessInstanceId(workField);
		List<Activity> list = workActivityMenu.getActivities();
		if (list != null && list.size() != 0) {
			workActivityProcessService.saveList(list, processInstance.getId());
		} else {
			WorkActivityProcess workActivityProcess = new WorkActivityProcess();
			workActivityProcess.setProcessKey("workfield");
			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 delete(WorkField workField) {
		super.delete(workField);
		WorkProjectNotify notify = new WorkProjectNotify();
		notify.setNotifyId(workField.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(WorkField workField,List<User> auditUsers) {
		String userName = UserUtils.get(workField.getCreateBy().getId()).getName();
		Office office = officeService.get(workField.getOfficeId());
		String title = "外勤申请人:"+userName;
		String str  =  "外勤申请编号:"+workField.getNum()+",外勤事由:"+workField.getReason()+",所属部门:"+office.getName();
		// 对不同环节的业务逻辑进行操作
		String taskDefKey = workField.getAct().getTaskDefKey();
		if (!"modifyApply".equals(taskDefKey)) {
			actTaskService.claim(workField.getAct().getTaskId(), UserUtils.getUser().getId());
		}else{
			//时间校验
			String sign1 = leaveApplyService.validateTime(workField.getStartDate(),workField.getStartType(),workField.getEndDate(),workField.getEndType());
			if(StringUtils.isNotBlank(sign1)){
				return sign1;
			}else{
				String sign2 = workOutService.validateTime(workField.getStartDate(),workField.getStartType(),workField.getEndDate(),workField.getEndType());
				if(StringUtils.isNotBlank(sign2)){
					return sign2;
				}else{
					String sign3 = this.validateTime(workField.getStartDate(),workField.getStartType(),workField.getEndDate(),workField.getEndType());
					if(StringUtils.isNotBlank(sign3)){
						return sign3;
					}
				}
			}
			workField.getAct().setFlag("yes");
			updateInfo(workField);
		}
		String comment = "";
		if (workField.getStatus().equals("4")){
			comment = ("yes".equals(workField.getAct().getFlag())?"[重新申请] ":"[已撤销] ");
		}else {
			comment = ("yes".equals(workField.getAct().getFlag())?"[同意] ":"[驳回] ")+workField.getAct().getComment();
		}
		//yes 的时候状态为审核通过 否则为未通过
		//1 审核中 2 未通过
		workField.setStatus(("yes".equals(workField.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(workField.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(workField.getProcessInstanceId());
		List<WorkActivityProcess> workActivityProcesses = workActivityProcessService.findList(selectProcess);
		List<Activity> activities = workActivityMenu.getActivities();
		if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("workfield")) {
			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(workField.getAct().getFlag())) {
						workField.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(workField.getAct().getFlag())) {
						workField.setStatus("3");
						workActivityProcess.setIsApproval("2");
					} else {
						workActivityProcess.setIsApproval("1");
					}
					break;
				}
			}
		} else {
			workActivityMenu.setProcessType("workfield");
			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(workField.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(workField.getAct().getFlag())) {
						workField.setStatus("3");
					}
					break;
				} else if ("apply_end".equals(taskDefKey)) {
				}

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

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

					}
				}

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

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

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

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

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

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