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

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

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jeeplus.common.utils.MenuStatusEnum;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.modules.act.entity.Act;
import com.jeeplus.modules.act.service.ActTaskService;
import com.jeeplus.modules.act.utils.ActUtils;
import com.jeeplus.modules.exampleeconomics.dao.ExampleEconomicsDao;
import com.jeeplus.modules.exampleeconomics.entity.ExampleEconomics;
import com.jeeplus.modules.exampleeconomics.service.ExampleEconomicsService;
import com.jeeplus.modules.exampleexpend.dao.ExampleExpendDao;
import com.jeeplus.modules.exampleexpend.entity.ExampleExpend;
import com.jeeplus.modules.exampleexpend.service.ExampleExpendService;
import com.jeeplus.modules.exampleproject.dao.ExampleProjectDao;
import com.jeeplus.modules.exampleproject.entity.ExampleProject;
import com.jeeplus.modules.exampleproject.service.ExampleProjectService;
import com.jeeplus.modules.examplesingle.dao.ExampleSingleDao;
import com.jeeplus.modules.examplesingle.entity.ExampleSingle;
import com.jeeplus.modules.examplesingle.service.ExampleSingleService;
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.workprojectnotify.entity.WorkProjectNotify;
import com.jeeplus.modules.workprojectnotify.service.WorkProjectNotifyService;
import com.jeeplus.modules.workprojectnotify.util.UtilNotify;
import org.activiti.engine.ActivitiObjectNotFoundException;
import org.activiti.engine.HistoryService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
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.workexample.entity.WorkExample;
import com.jeeplus.modules.workexample.dao.WorkExampleDao;

/**
 * 案例Service
 * @author ssrh
 * @version 2018-08-27
 */
@Service
@Transactional(readOnly = true)
public class WorkExampleService extends CrudService<WorkExampleDao, WorkExample> {
	@Autowired
	private IdentityService identityService;
	@Autowired
	private HistoryService historyService;

	@Autowired
	private WorkActivityMenuService workActivityMenuService;
	@Autowired
	private WorkProjectNotifyService workProjectNotifyService;
	@Autowired
	private RuntimeService runtimeService;
	@Autowired
	private OfficeService officeService;
	@Autowired
	private WorkExampleDao workExampleDao;
	@Autowired
	private ExampleEconomicsDao exampleEconomicsDao;
	@Autowired
	private ExampleExpendDao exampleExpendDao;
	@Autowired
	private ExampleProjectDao exampleProjectDao;
	@Autowired
	private ExampleSingleDao exampleSingleDao;
	@Autowired
	private ExampleProjectService exampleProjectService;
	@Autowired
	private ExampleSingleService exampleSingleService;
	@Autowired
	private ExampleExpendService exampleExpendService;
	@Autowired
	private ExampleEconomicsService exampleEconomicsService;
	@Autowired
	private WorkActivityProcessService workActivityProcessService;
	@Autowired
	private ActTaskService actTaskService;
	@Autowired
	private ActivityService activityService;
	@Autowired
	private WorkActivityProcessDao workActivityProcessDao;
	public WorkExample get(String id) {
		WorkExample workExample = super.get(id);
		if(workExample!=null){
			ExampleProject exampleProject = new ExampleProject();
			exampleProject.setExampleId(id);
			List<ExampleProject> exampleProjectList = exampleProjectService.findList(exampleProject);
			workExample.setExampleProjectList(exampleProjectList);

			ExampleExpend exampleExpend = new ExampleExpend();
			exampleExpend.setExampleId(id);
			List<ExampleExpend> exampleExpendList = exampleExpendService.findList(exampleExpend);
			workExample.setExampleExpendList(exampleExpendList);

			ExampleEconomics exampleEconomics = new ExampleEconomics();
			exampleEconomics.setExampleId(id);
			List<ExampleEconomics> exampleEconomicsList = exampleEconomicsService.findList(exampleEconomics);
			workExample.setExampleEconomicsList(exampleEconomicsList);

			ExampleSingle exampleSingle = new ExampleSingle();
			exampleSingle.setExampleId(id);
			List<ExampleSingle> exampleSingleList = exampleSingleService.findList(exampleSingle);
			workExample.setExampleSingleList(exampleSingleList);
		}
		return workExample;
	}
	public WorkExample getByTypes(WorkExample workExample) {
		WorkExample entity = dao.getByTypes(workExample);
		return entity;
	}
	public BigDecimal getSumBuildScale(WorkExample workExample) {
		BigDecimal sum = dao.getSumBuildScale(workExample);
		return sum;
	}

	public List<WorkExample> findList(WorkExample workExample) {
		return super.findList(workExample);
	}
	
	public Page<WorkExample> findPage(Page<WorkExample> page, WorkExample workExample) {
		workExample.getSqlMap().put("dsf", dataScopeFilter(workExample.getCurrentUser(), "o", "u","s", MenuStatusEnum.WORK_EXAMPLE.getValue()));
		workExample.setPage(page);
		page.setList(findList(workExample));
		return page;
	}
	
	@Transactional(readOnly = false)
	public void save(WorkExample workExample) {
		super.save(workExample);
		updateInfo(workExample);
	}
	@Transactional(readOnly = false)
	public void updateInfo(WorkExample workExample) {
		for (ExampleSingle exampleSingle : workExample.getExampleSingleList()) {
			if (ExampleSingle.DEL_FLAG_NORMAL.equals(exampleSingle.getDelFlag())) {
				if (StringUtils.isBlank(exampleSingle.getId())) {
					exampleSingle.preInsert();
					exampleSingleDao.insert(exampleSingle);
				} else {
					exampleSingle.preUpdate();
					exampleSingleDao.update(exampleSingle);
				}
			} else {
				exampleSingleDao.delete(exampleSingle);
			}
		}
		for (ExampleProject exampleProject : workExample.getExampleProjectList()) {
			if (ExampleProject.DEL_FLAG_NORMAL.equals(exampleProject.getDelFlag())) {
				if (StringUtils.isBlank(exampleProject.getId())) {
					exampleProject.preInsert();
					exampleProjectDao.insert(exampleProject);
				} else {
					exampleProject.preUpdate();
					exampleProjectDao.update(exampleProject);
				}
			} else {
				exampleProjectDao.delete(exampleProject);
			}
		}
		for (ExampleExpend exampleExpend : workExample.getExampleExpendList()) {
			if (ExampleExpend.DEL_FLAG_NORMAL.equals(exampleExpend.getDelFlag())) {
				if (StringUtils.isBlank(exampleExpend.getId())) {
					exampleExpend.preInsert();
					exampleExpendDao.insert(exampleExpend);
				} else {
					exampleExpend.preUpdate();
					exampleExpendDao.update(exampleExpend);
				}
			} else {
				exampleExpendDao.delete(exampleExpend);
			}
		}
		for (ExampleEconomics exampleEconomics : workExample.getExampleEconomicsList()) {
			if (ExampleEconomics.DEL_FLAG_NORMAL.equals(exampleEconomics.getDelFlag())) {
				if (StringUtils.isBlank(exampleEconomics.getId())) {
					exampleEconomics.preInsert();
					exampleEconomicsDao.insert(exampleEconomics);
				} else {
					exampleEconomics.preUpdate();
					exampleEconomicsDao.update(exampleEconomics);
				}
			} else {
				exampleEconomicsDao.delete(exampleEconomics);
			}
		}
	}
	@Transactional(readOnly = false)
	public void delete(WorkExample workExample) {
		super.delete(workExample);
		//删除 单项工程造价指标
		exampleSingleDao.deleteByEId(workExample.getId());
		//删除 经济指标
		exampleEconomicsDao.deleteByEId(workExample.getId());
		//删除 主要工程量指标
		exampleProjectDao.deleteByEId(workExample.getId());
		//删除 主要工料价格及消耗量指标
		exampleExpendDao.deleteByEId(workExample.getId());
		WorkProjectNotify notify = new WorkProjectNotify();
		notify.setNotifyId(workExample.getId());
		List<User> users = workProjectNotifyService.readByNotifyId(notify);
		if (users!=null && users.size()!=0){
			for (User user:users){
				UserUtils.pushMeIm(user.getId());
			}
		}
	}

	@Transactional(readOnly = false)
	public String save(WorkExample workExample, Map<String, Object> variables, String processInstanceId) {
		User user = UserUtils.getUser();
		super.save(workExample);
		Office office = officeService.get(workExample.getOfficeId());
		String str = "案例申请人："+UserUtils.get(workExample.getCreateBy().getId()).getName()+",工程名称："+workExample.getName();
		String title = "工程名称:"+workExample.getName();
		updateInfo(workExample);
		// 用来设置启动流程的人员ID，引擎会自动把用户ID保存到activiti:initiator中
		identityService.setAuthenticatedUserId(user.getId());
		// 启动流程
		String businessKey = workExample.getId().toString();
		WorkActivityMenu workActivityMenu = workActivityMenuService.findByParentAndOffice("ggh3125f1f194c82b0000uuyic750904", office);
		// 启动流程
		String processType = workActivityMenu.getProcessType();
		StringBuffer buffer = new StringBuffer();
		Activity activity = new Activity();
		WorkProjectNotify workProjectNotify = UtilNotify
				.saveNotify(workExample.getId(),
						null,
						workExample.getCompanyId(),
						title,
						str,
						"76",
						"0",
						"待审批",
						""
				);
		List<User> users = new ArrayList<>();
		List<User> alshrs = UserUtils.getByRoleActivityEnname("alshr",3,office.getId(),"10",workExample.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(),"10",workExample.getCreateBy());
					if (enusers.size()==0){
						workExample.setStatus("1");
						super.save(workExample);
						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(),"10",workExample.getCreateBy());
				}
				//人员审批
				if (StringUtils.isNotBlank(activity.getUser().getId())) {
					users.add(activity.getUser());
				}
			}
			workProjectNotify.setId("");
		} else {
			variables.put("alshrList", alshrs);
			if (alshrs.size()==0 ){
				workExample.setStatus("1");
				super.save(workExample);
			}
			if (alshrs.size()==0){
				return "流程审批人不能为空,案例审核人下无用户,请联系管理员！";
			}
			variables.put("alshrcount",alshrs.size());
			processType = "workexample";
			users.addAll(alshrs);
		}
		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","13");
			UserUtils.pushInfoToApp(title,str,extras,u.getId());
			UserUtils.pushIm(u.getId(),str);
		}
		variables.put("type", processType);
		variables.put("busId", businessKey);
		variables.put("title", "审批单：" + workExample.getName());//设置标题；

		ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processType, businessKey, variables);
		workExample.setProcessInstance(processInstance);
		if (StringUtils.isNotBlank(processInstanceId)) {
			workActivityProcessService.updateProcessInstanceId(processInstance.getId(),processInstanceId);
			workActivityProcessService.deleteProcessInstanceId(processInstanceId);
			workActivityProcessService.deleteProcessIdAuditUsers(processInstanceId);
		}
		// 更新流程实例ID
		workExample.setProcessInstanceId(processInstance.getId());
		workExampleDao.updateProcessInstanceId(workExample);
		List<Activity> list = workActivityMenu.getActivities();
		if (list != null && list.size() != 0) {
			workActivityProcessService.saveList(list, processInstance.getId());
		} else {
			WorkActivityProcess workActivityProcess = new WorkActivityProcess();
			workActivityProcess.setProcessKey("workexample");
			workActivityProcess.setCount(1);
			workActivityProcess.setProcessInstanceId(processInstance.getId());
			workActivityProcess.setIsApproval("0");
			workActivityProcessService.save(workActivityProcess);
			workActivityProcessService.insertAuditsByType(alshrs,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(WorkExample workExample,List<User> auditUsers) {
		String content = workExample.getAct().getComment();
		Office office = officeService.get(workExample.getOfficeId());
		String str = "案例申请人："+UserUtils.get(workExample.getCreateBy().getId()).getName()+",工程名称："+workExample.getName();
		String title = "工程名称:"+workExample.getName();
		workExample.setAct(getByAct(workExample.getProcessInstanceId()));
		// 对不同环节的业务逻辑进行操作
		String taskDefKey = workExample.getAct().getTaskDefKey();
		if (!"modifyApply".equals(taskDefKey)) {
			actTaskService.claim(workExample.getAct().getTaskId(), UserUtils.getUser().getId());
		}else{
			workExample.getAct().setFlag("no");
			updateInfo(workExample);
		}
		String comment = "";
		workExample.getAct().setFlag("no");
		if (workExample.getStatus().equals("4")){
			comment = ("yes".equals(workExample.getAct().getFlag())?"[重新申请] ":"[已撤销] ");
		}else {
			comment = ("yes".equals(workExample.getAct().getFlag())?"[同意] ":"[驳回] ")+content;
		}
		//yes 的时候状态为审核通过 否则为未通过
		//1 审核中 2 未通过
		workExample.setStatus(("yes".equals(workExample.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(workExample.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(workExample.getProcessInstanceId());
		List<WorkActivityProcess> workActivityProcesses = workActivityProcessService.findList(selectProcess);
		List<Activity> activities = workActivityMenu.getActivities();
		if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("workexample")) {
			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(workExample.getAct().getFlag())) {
						workExample.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(workExample.getAct().getFlag())) {
						workExample.setStatus("3");
						workActivityProcess.setIsApproval("2");
					} else {
						workActivityProcess.setIsApproval("1");
					}
					break;
				}
			}
		} else {
			workActivityMenu.setProcessType("workexample");
			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 ("alshr".equals(taskDefKey) && count.contains("1")) {
					taskCount = "1";
					exp = "pass";
					if ("yes".equals(workExample.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 = "alshr";
					if (!"yes".equals(workExample.getAct().getFlag())) {
						workExample.setStatus("3");
					}
					break;
				} else if ("apply_end".equals(taskDefKey)) {
				}

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

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

					}
				}

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

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

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

	@Transactional(readOnly = false)
	public String auditSave(WorkExample workExample,List<User> auditUsers) {
		String content = workExample.getAct().getComment();
		Office office = officeService.get(workExample.getOfficeId());
		String str = "案例申请人："+UserUtils.get(workExample.getCreateBy().getId()).getName()+",工程名称："+workExample.getName();
		String title = "工程名称:"+workExample.getName();
		workExample.setAct(getByAct(workExample.getProcessInstanceId()));
		// 对不同环节的业务逻辑进行操作
		String taskDefKey = workExample.getAct().getTaskDefKey();
		if (!"modifyApply".equals(taskDefKey)) {
			actTaskService.claim(workExample.getAct().getTaskId(), UserUtils.getUser().getId());
		}else{
			workExample.getAct().setFlag("yes");
			updateInfo(workExample);
		}
		String comment = "";
		workExample.getAct().setFlag("yes");
		if (workExample.getStatus().equals("4")){
			comment = ("yes".equals(workExample.getAct().getFlag())?"[重新申请] ":"[已撤销] ");
		}else {
			comment = ("yes".equals(workExample.getAct().getFlag())?"[同意] ":"[驳回] ")+content;
		}
		//yes 的时候状态为审核通过 否则为未通过
		//1 审核中 2 未通过
		workExample.setStatus(("yes".equals(workExample.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(workExample.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(workExample.getProcessInstanceId());
		List<WorkActivityProcess> workActivityProcesses = workActivityProcessService.findList(selectProcess);
		List<Activity> activities = workActivityMenu.getActivities();
		if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("workexample")) {
			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(workExample.getAct().getFlag())) {
						workExample.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(workExample.getAct().getFlag())) {
						workExample.setStatus("3");
						workActivityProcess.setIsApproval("2");
					} else {
						workActivityProcess.setIsApproval("1");
					}
					break;
				}
			}
		} else {
			workActivityMenu.setProcessType("workexample");
			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 ("alshr".equals(taskDefKey) && count.contains("1")) {
					taskCount = "1";
					exp = "pass";
					if ("yes".equals(workExample.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 = "alshr";
					if (!"yes".equals(workExample.getAct().getFlag())) {
						workExample.setStatus("3");
					}
					break;
				} else if ("apply_end".equals(taskDefKey)) {
				}

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

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

					}
				}

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

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

		workExampleDao.update(workExample);
		return "保存审核意见成功！";
	}
	/**
	 * 获取流程详细信息
	 * @param processInstanceId
	 */
	@SuppressWarnings("unchecked")
	public WorkExample getByProcessInstanceId(String processInstanceId) {
		WorkExample workExample = workExampleDao.getByProcessInstanceId(processInstanceId);
		return workExample;
	}


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

	}

	public Act getByAct(String processInstanceId){
		Act act = new Act();
		HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
		ProcessInstance processInstance = actTaskService.getProcIns(processInstanceId);
		if (processInstance!=null) {
			List<Task> taskList = actTaskService.getCurrentTaskList(processInstance);
			if(taskList!=null && taskList.size()>1){
				for (Task taskInfok:taskList) {
					if (taskInfok.getAssignee().equals(UserUtils.getUser().getId())) {
						act.setTaskId(taskInfok.getId());
						act.setTaskName(taskInfok.getName());
						act.setTaskDefKey(taskInfok.getTaskDefinitionKey());
						act.setProcDefId(taskInfok.getProcessDefinitionId());
						act.setProcInsId(taskInfok.getProcessInstanceId());
						act.setTask(taskInfok);
					}
				}
			}else {
				Task task = actTaskService.getCurrentTaskInfo(processInstance);
				act.setTaskId(task.getId());
				act.setTaskName(task.getName());
				act.setTaskDefKey(task.getTaskDefinitionKey());
				act.setProcDefId(task.getProcessDefinitionId());
				act.setProcInsId(task.getProcessInstanceId());
				act.setTask(task);
			}
		}
		return  act;
	}
}