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

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

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

import com.jeeplus.modules.worksupplier.entity.WorkSupplier;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.service.CrudService;
import com.jeeplus.modules.workstockcontract.entity.WorkStockContract;
import com.jeeplus.modules.workstockcontract.dao.WorkStockContractDao;

/**
 * 采购合同Service
 * @author lw
 * @version 2018-07-11
 */
@Service
@Transactional(readOnly = true)
public class WorkStockContractService extends CrudService<WorkStockContractDao, WorkStockContract> {
	@Autowired
	private WorkClientAttachmentDao workClientAttachmentDao;
	@Autowired
	private IdentityService identityService;
	@Autowired
	private WorkActivityMenuService workActivityMenuService;
	@Autowired
	private WorkProjectNotifyService workProjectNotifyService;
	@Autowired
	private RuntimeService runtimeService;
	@Autowired
	private WorkActivityProcessService workActivityProcessService;
	@Autowired
	private ActTaskService actTaskService;
	@Autowired
	private ActivityService activityService;
	@Autowired
	private WorkActivityProcessDao workActivityProcessDao;
	@Autowired
	private WorkStockContractDao workStockContractDao;
	@Autowired
	private ISignatureDocumentService signatureDocumentService;
	@Autowired
	private WorkItemStockService workItemStockService;

	public WorkStockContract get(String id) {
		WorkStockContract workStockContract = super.get(id);
		if(workStockContract!=null){
			//附件
			WorkClientAttachment workClientAttachment = new WorkClientAttachment();
			workClientAttachment.setAttachmentId(id);
			workClientAttachment.setAttachmentFlag("103");
			workStockContract.setWorkAttachments(workClientAttachmentDao.findList(workClientAttachment));
			//归档附件
			WorkClientAttachment workClientAttachment2 = new WorkClientAttachment();
			workClientAttachment2.setAttachmentId(id);
			workClientAttachment2.setAttachmentFlag("104");
			workStockContract.setWorkRecordAttachments(workClientAttachmentDao.findList(workClientAttachment2));
			//商品列表
			if(StringUtils.isNotBlank(id)){
				WorkItemStock workItemStock = new WorkItemStock();
				workItemStock.setContractId(id);
				workStockContract.setWorkCatalogueItemList(workItemStockService.findListByContract(workItemStock));
			}
		}
		return workStockContract;
	}
	
	public List<WorkStockContract> findList(WorkStockContract workStockContract) {
		return super.findList(workStockContract);
	}
	
	public Page<WorkStockContract> findPage(Page<WorkStockContract> page, WorkStockContract workStockContract) {
		workStockContract.getSqlMap().put("dsf", dataScopeFilter(workStockContract.getCurrentUser(), "o", "u","s", MenuStatusEnum.WORK_STOCKCONTRACT.getValue()));
		workStockContract.setPage(page);
		page.setList(findList(workStockContract));
		return page;
	}
	
	@Transactional(readOnly = false)
	public void save(WorkStockContract workStockContract) {
		super.save(workStockContract);
		updateWorkReimbursementInfo(workStockContract);
	}
	@Transactional(readOnly = false)
	public void updateWorkReimbursementInfo(WorkStockContract workStockContract) {
		//附件信息
		for (WorkClientAttachment workClientAttachment : workStockContract.getWorkAttachments()) {
			if (workClientAttachment.getId() == null) {
				continue;
			}
			if (WorkClientAttachment.DEL_FLAG_NORMAL.equals(workClientAttachment.getDelFlag())) {
				if("103".equals(workClientAttachment.getAttachmentFlag())){
					workClientAttachment.setAttachmentId(workStockContract.getId());
					workClientAttachment.setAttachmentFlag("103");
					workClientAttachment.setAttachmentUser(UserUtils.getUser().getId());
					if (StringUtils.isBlank(workClientAttachment.getId()) || "null".equals(workClientAttachment.getId())) {
						workClientAttachment.preInsert();
						workClientAttachmentDao.insert(workClientAttachment);
						signatureDocumentService.createIsignature(workClientAttachment.getUrl(),workClientAttachment.getAttachmentName(),workClientAttachment.getId(),workStockContract.getName());
					} else {
						workClientAttachment.preUpdate();
						workClientAttachmentDao.update(workClientAttachment);
					}
				}else if("104".equals(workClientAttachment.getAttachmentFlag())){
					workClientAttachment.setAttachmentId(workStockContract.getId());
					workClientAttachment.setAttachmentFlag("104");
					workClientAttachment.setAttachmentUser(UserUtils.getUser().getId());
					if (StringUtils.isBlank(workClientAttachment.getId()) || "null".equals(workClientAttachment.getId())) {
						workClientAttachment.preInsert();
						workClientAttachmentDao.insert(workClientAttachment);
						signatureDocumentService.createIsignature(workClientAttachment.getUrl(),workClientAttachment.getAttachmentName(),workClientAttachment.getId(),workStockContract.getName());
					} else {
						workClientAttachment.preUpdate();
						workClientAttachmentDao.update(workClientAttachment);
					}
				}
			} else {
				workClientAttachmentDao.delete(workClientAttachment);
			}
		}
	}
	@Transactional(readOnly = false)
	public void delete(WorkStockContract workStockContract) {
		super.delete(workStockContract);
		WorkProjectNotify notify = new WorkProjectNotify();
		notify.setNotifyId(workStockContract.getId());
		workProjectNotifyService.readByNotifyId(notify);
	}
	
	public Page<WorkSupplier> findPageBysupplier(Page<WorkSupplier> page, WorkSupplier supplier) {
		supplier.setPage(page);
		page.setList(dao.findListBysupplier(supplier));
		return page;
	}

	/**
	 * 审核流程
	 * @param
	 */
	@Transactional(readOnly = false)
	public String auditSave(WorkStockContract workStockContract,List<User> auditUsers) {
			String str = "";
			if(workStockContract.getSupplier()!=null){
				str =  "合同编号："+workStockContract.getNumber()+",供应商名称："+workStockContract.getSupplier().getName()+",合同金额(元):"+workStockContract.getMoney();
			}else{
				str =  "合同编号："+workStockContract.getNumber()+",合同金额(元):"+workStockContract.getMoney();
			}
			String title = "合同名称:"+workStockContract.getName();
			// 对不同环节的业务逻辑进行操作
			String taskDefKey = workStockContract.getAct().getTaskDefKey();
			if (!"modifyApply".equals(taskDefKey) && !"sqr".equals(taskDefKey)) {
				actTaskService.claim(workStockContract.getAct().getTaskId(), UserUtils.getUser().getId());
			}else {
				workStockContract.getAct().setFlag("yes");
				updateWorkReimbursementInfo(workStockContract);
			}
			String comment = "";
			if (workStockContract.getStatus().equals("4")){
				comment = ("yes".equals(workStockContract.getAct().getFlag())?"[重新申请] ":"[已撤销] ");
			}else {
				comment = ("yes".equals(workStockContract.getAct().getFlag())?"[同意] ":"[驳回] ")+workStockContract.getAct().getComment();
			}
			//yes 的时候状态为审核通过 否则为未通过
			workStockContract.setStatus(("yes".equals(workStockContract.getAct().getFlag()) ? "2" : "4"));
			//String buffer = UserUtils.getRoleActivityEnname(UserUtils.getSelectCompany().getId(),workStockContract.getCreateBy());
			Map<String, Object> vars = Maps.newHashMap();
			//业务逻辑对应的条件表达式
			String exp = "";
			String taskCount = "";
			String notifyRole = "";
			List<User> users = new ArrayList<>();
			List<User> userList = new ArrayList<>();
			int key = 0;
			String enname = "";
			List<Activity> activitieList = activityService.getByProcessInstanceId(workStockContract.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(workStockContract.getProcessInstanceId());
			List<WorkActivityProcess> workActivityProcesses = workActivityProcessService.findList(selectProcess);
			List<Activity> activities = workActivityMenu.getActivities();
			if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("workstockcontract")) {
				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(workStockContract.getAct().getFlag())) {
							workStockContract.setStatus("4");
							workActivityProcess.setIsApproval("2");
							String returnBack = "-1";
							for (Activity activity : activities) {
								if (activity.getCount() == activityProcess.getCount()) {
									notifyRole = activity.getName();
									returnBack = activity.getReturnBack();
									break;
								}
							}
							if (returnBack.equals("0")) {
								workActivityProcess.setId("");
							}
						} else {
							workActivityProcess.setIsApproval("1");
						}
					}else if(taskDefKey.equals("modifyApply")){
						notifyRole = "调整申请";
						taskCount = "0";
						exp = "pass";
						workActivityProcess.setId("");
						workActivityProcess.setCount(0);
						if (!"yes".equals(workStockContract.getAct().getFlag())) {
							workStockContract.setStatus("3");
							workActivityProcess.setIsApproval("2");
						} else {
							workActivityProcess.setIsApproval("1");
						}
						break;
					}
				}
			} else {
				workActivityMenu.setProcessType("workstockcontract");
				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 ("hzbzr".equals(taskDefKey) && count.contains("1")) {
						taskCount = "1";
						exp = "pass";
						if ("yes".equals(workStockContract.getAct().getFlag())) {
							vars.put("gzrList", auditUsers);
							vars.put("gzrcount",auditUsers.size());
							workActivityProcessService.insertAuditsByType(auditUsers,workStockContract.getProcessInstanceId(),2,1);
							notifyRole = "盖章人盖章";
							workActivityProcess.setIsApproval("1");
							enname = "gzr";
						} else {
							notifyRole = "调整申请";
							workActivityProcess.setIsApproval("2");
						}
						break;
					} else if ("gzr".equals(taskDefKey) && count.contains("2")) {
						taskCount = "2";
						exp = "pass";
						if ("yes".equals(workStockContract.getAct().getFlag())) {
							notifyRole = "申请人归档";
							workActivityProcess.setIsApproval("1");
							enname = "不为空";
							WorkProjectNotify notify = new WorkProjectNotify();
							notify.setNotifyId(workStockContract.getId());
							userList = workProjectNotifyService.readByNotifyId(notify);
							WorkProjectNotify workProjectNotify = UtilNotify
									.saveNotify(workStockContract.getId(),
											workStockContract.getCreateBy(),
											workStockContract.getCompanyId(),
											title,
											str,
											"57",
											"0",
											"待审批",
											notifyRole);
							workProjectNotify.setId("");
							workProjectNotify.setIsNewRecord(false);
							workProjectNotifyService
									.save(workProjectNotify);
							users.add(workStockContract.getCreateBy());
						} else {
							notifyRole = "调整申请";
							workActivityProcess.setIsApproval("2");
						}
						break;
					} else if ("sqr".equals(taskDefKey) && count.contains("3")) {
						taskCount = "3";
						exp = "pass";
						if ("yes".equals(workStockContract.getAct().getFlag())) {
							notifyRole = "审批通过";
							workActivityProcess.setIsApproval("1");
						} else {
							notifyRole = "调整申请";
							workActivityProcess.setIsApproval("2");
						}
						break;
					}  else if ("modifyApply".equals(taskDefKey)&& count.contains("0")) {
						notifyRole = "行政部负责人审批";
						taskCount = "0";
						exp = "pass";
						workActivityProcess.setCount(0);
						enname = "xzbzr";
						if (!"yes".equals(workStockContract.getAct().getFlag())) {
							workStockContract.setStatus("3");
						}
						break;
					} else if ("apply_end".equals(taskDefKey)) {
					}

				}
			}
			// 设置意见
			workStockContract.getAct().setComment(("yes".equals(workStockContract.getAct().getFlag()) ? "[同意] " : "[驳回] ") + workStockContract.getAct().getComment());
			workStockContract.preUpdate();
			// 提交流程任务
			vars.put(exp, "yes".equals(workStockContract.getAct().getFlag()) ? true : false);
			vars.put("passs", true);
			workActivityProcessService.updateProcess(workActivityProcess,workActivityMenu,key,taskCount,workStockContract.getProcessInstanceId(),taskDefKey,"modifyApply",workStockContract.getAct().getFlag(),comment, activities);
			// 提交流程任务
			actTaskService.complete(workStockContract.getAct().getTaskId(), workStockContract.getAct().getProcInsId(), workStockContract.getAct().getComment(), vars);
			boolean state = actTaskService.isProcessEnd(workStockContract.getAct().getProcInsId());
			if (!state) {
				if(workStockContract.getSupplier()!=null){
					str =  "合同编号："+workStockContract.getNumber()+",供应商名称："+workStockContract.getSupplier().getName()+",合同金额(元):"+workStockContract.getMoney();
				}else{
					str =  "合同编号："+workStockContract.getNumber()+",合同金额(元):"+workStockContract.getMoney();
				}
				title = "合同名称:"+workStockContract.getName();
				users.add(workStockContract.getCreateBy());
				if ("yes".equals(workStockContract.getAct().getFlag())) {
					workStockContract.setStatus("5");
					WorkProjectNotify notify = new WorkProjectNotify();
					notify.setNotifyId(workStockContract.getId());
					userList = workProjectNotifyService.readByNotifyId(notify);
					workProjectNotifyService
							.save(UtilNotify
									.saveNotify(workStockContract.getId(),
											workStockContract.getCreateBy(),
											workStockContract.getCompanyId(),
											title,
											str,
											"57",
											"0",
											"待通知",
											notifyRole));

				} else {
					WorkProjectNotify notify = new WorkProjectNotify();
					notify.setNotifyId(workStockContract.getId());
					userList = workProjectNotifyService.readByNotifyId(notify);
					if (StringUtils.isNotBlank(workStockContract.getStatus()) && !workStockContract.getStatus().equals("3")){
						title = "您的采购合同申请:"+workStockContract.getName()+"：被驳回!";
						workStockContract.setStatus("4");
						workProjectNotifyService
								.save(UtilNotify
										.saveNotify(workStockContract.getId(),
												workStockContract.getCreateBy(),
												workStockContract.getCompanyId(),
												title,
												str,
												"57",
												"0",
												"待通知",
												notifyRole));
					}
				}
				workActivityProcessService.deleteProcessIdAuditUsers(workStockContract.getProcessInstanceId());
			} else {
				if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("workstockcontract")) {
					WorkProjectNotify notify = new WorkProjectNotify();
					notify.setNotifyId(workStockContract.getId());
					userList = workProjectNotifyService.readByNotifyId(notify);
					WorkProjectNotify workProjectNotify = UtilNotify
							.saveNotify(workStockContract.getId(),
									new User(),
									workStockContract.getCompanyId(),
									title,
									str,
									"57",
									"0",
									"待审批",
									notifyRole);
					List<WorkProjectNotify> workProjectNotifys = activityService.getByFlagAndTaskDefKeyList(
							activities,
							workProjectNotify,
							taskDefKey,
							workStockContract.getAct().getFlag(),
							taskCount,
							workStockContract.getCreateBy(),
							workStockContract.getOfficeId(),
							"13");
					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","57");
							UserUtils.pushInfoToApp(title,str,extras,workProjectNotify1.getUser().getId());

						}
					}

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

								}
							}
						}else if(StringUtils.isBlank(enname)) {
							WorkProjectNotify notify = new WorkProjectNotify();
							notify.setNotifyId(workStockContract.getId());
							userList = workProjectNotifyService.readByNotifyId(notify);
							users.addAll(userList);
							users.add(workStockContract.getCreateBy());
							workProjectNotifyService
									.save(UtilNotify
											.saveNotify(workStockContract.getId(),
													workStockContract.getCreateBy(),
													workStockContract.getCompanyId(),
													title,
													str,
													"57",
													"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());
				}
			}
			workStockContractDao.update(workStockContract);
		return "保存审核意见成功！";
	}
	/**
	 * 获取流程详细信息
	 * @param processInstanceId
	 */
	@SuppressWarnings("unchecked")
	public WorkStockContract getByProcessInstanceId(String processInstanceId) {
		WorkStockContract workStockContract = workStockContractDao.getByProcessInstanceId(processInstanceId);
		return workStockContract;
	}
	/**
	 * 提交存储
	 * @param
	 * @param variables
	 */
	@Transactional(readOnly = false)
	public String save(WorkStockContract workStockContract, Map<String, Object> variables, String processInstanceId) {
		try {
			User user = UserUtils.getUser();
			super.save(workStockContract);
			String str = "";
			if(workStockContract.getSupplier()!=null){
				str =  "合同编号："+workStockContract.getNumber()+",供应商名称："+workStockContract.getSupplier().getName()+",合同金额(元):"+workStockContract.getMoney();
			}else{
				str =  "合同编号："+workStockContract.getNumber()+",合同金额(元):"+workStockContract.getMoney();
			}
			String title = "合同名称:"+workStockContract.getName();
			updateWorkReimbursementInfo(workStockContract);
			// 用来设置启动流程的人员ID，引擎会自动把用户ID保存到activiti:initiator中
			identityService.setAuthenticatedUserId(user.getId());
			// 启动流程
			String businessKey = workStockContract.getId().toString();
			Office office = UserUtils.getSelectOffice();
			WorkActivityMenu workActivityMenu = workActivityMenuService.findByParentAndOffice("ggh3125f1f194c82bdeoooocdc750904", office);
			// 启动流程
			String processType = workActivityMenu.getProcessType();
			StringBuffer buffer = new StringBuffer();
			Activity activity = new Activity();
			WorkProjectNotify workProjectNotify = UtilNotify
					.saveNotify(workStockContract.getId(),
							null,
							workStockContract.getCompanyId(),
							title,
							str,
							"57",
							"0",
							"待审批",
							""
					);
			List<User> users = new ArrayList<>();
			List<User> hzbzrs = UserUtils.getByRoleActivityEnname("xzbzr",3,office.getId(),"13",workStockContract.getCreateBy());
			List<User> gzrs = UserUtils.getByRoleActivityEnname("gzr",3,office.getId(),"13",workStockContract.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(),"13",workStockContract.getCreateBy());
						if (enusers.size()==0){
							workStockContract.setStatus("1");
							this.save(workStockContract);
							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(),"13",workStockContract.getCreateBy());
					}
					//人员审批
					if (StringUtils.isNotBlank(activity.getUser().getId())) {
						users.add(activity.getUser());
					}
				}
				workProjectNotify.setId("");
			} else {
				variables.put("hzbzrList", hzbzrs);
				//variables.put("gzrList", gzrs);
				if (hzbzrs.size()==0 || gzrs.size()==0){
					workStockContract.setStatus("1");
					this.save(workStockContract);
				}
				if (hzbzrs.size()==0){
					return "流程审批人不能为空,角色行政部负责人下无用户,请联系管理员！";
				}
				/*if (gzrs.size()==0){
					return "流程审批人不能为空,角色盖章人下无用户,请联系管理员！";
				}*/
				variables.put("hzbzrcount",hzbzrs.size());
				//variables.put("gzrcount",gzrs.size());
				processType = "workstockcontract";
				users.addAll(hzbzrs);
			}
			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()+",采购合同："+workStockContract.getName() + " 待审批!\"," +
							"\"useType\":\"sys\"}";*/
				Map<String,Object> extras = new HashMap<>();
				extras.put("type","7001");
				extras.put("id",workProjectNotify.getId());
				extras.put("procDefKey","57");
				UserUtils.pushInfoToApp(title,str,extras,u.getId());
				UserUtils.pushIm(u.getId(),str);
			}
			variables.put("type", processType);
			variables.put("busId", businessKey);
			variables.put("title", "审批单：" + workStockContract.getName());//设置标题；

			ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processType, businessKey, variables);
			workStockContract.setProcessInstance(processInstance);
			if (StringUtils.isNotBlank(processInstanceId)) {
				workActivityProcessService.updateProcessInstanceId(processInstance.getId(),processInstanceId);
				workActivityProcessService.deleteProcessInstanceId(processInstanceId);
				workActivityProcessService.deleteProcessIdAuditUsers(processInstanceId);
			}
			// 更新流程实例ID
			workStockContract.setProcessInstanceId(processInstance.getId());
			workStockContractDao.updateProcessInstanceId(workStockContract);
			List<Activity> list = workActivityMenu.getActivities();
			if (list != null && list.size() != 0) {
				workActivityProcessService.saveList(list, processInstance.getId());
			} else {
				WorkActivityProcess workActivityProcess = new WorkActivityProcess();
				workActivityProcess.setProcessKey("workstockcontract");
				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(hzbzrs,processInstance.getId(),1,1);
				workActivityProcessService.insertAuditsByType(gzrs,processInstance.getId(),2,0);
			}
			logger.debug("start process of {key={}, bkey={}, pid={}, variables={}}", new Object[]{
					ActUtils.PD_REIMBURSEMENT[0], businessKey, processInstance.getId(), variables});
		}catch (Exception e){
			logger.info("Exception e:"+e);
			return "Exception e:"+e;
		}
		return "";
	}
	/**
	 * 强制撤销
	 * @param
	 */
	@Transactional(readOnly = false)
	public void cancelInvalidate(WorkStockContract workStockContract) {
		String invalidateProcessInstanceId = workStockContract.getProcessInstanceId();
		try {
			//将流程图中尚未走到的task的流程追踪信息逻辑删除，添加一条"撤销"流程追踪信息
			WorkActivityProcess process = new WorkActivityProcess();
			process.setProcessInstanceId(workStockContract.getProcessInstanceId());
			process.setIsApproval("0");
			WorkActivityProcess workActivityProcess = new WorkActivityProcess();
			workActivityProcess.setProcessInstanceId(workStockContract.getProcessInstanceId());
			List<WorkActivityProcess> processList = workActivityProcessService.findList(workActivityProcess);
			WorkProjectNotify notify = new WorkProjectNotify();
			notify.setNotifyId(workStockContract.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()+",采购合同:"+workStockContract.getName()+" 强制撤销!\"," +
								"\"useType\":\"sys\"}";
						ChatServerPool.sendMessageToUser(toUserConn, message);//同时向本人发送消息
					}*/
					UserUtils.pushIm(u.getId(),"采购合同申请人:"+ user.getName()+",采购合同:"+workStockContract.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.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,"采购合同申请-强制撤销");
			workStockContract.setStatus("3");
			workStockContract.preUpdate();
			workStockContractDao.update(workStockContract);

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

	@Transactional(readOnly = false)
	public void updateCompleteStatus(WorkStockContract workStockContract) {
		workStockContractDao.updateCompleteStatus(workStockContract);
	}
}