/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.workborrowmangement.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.Collections3;
import com.jeeplus.common.utils.DateUtils;
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.projectrecord.enums.ProjectStatusEnum;
import com.jeeplus.modules.serialnum.service.SerialNumTplService;
import com.jeeplus.modules.sys.dao.UserDao;
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.workincomingmessage.entity.WorkIncomingMessage;
import com.jeeplus.modules.workitem.dao.WorkItemDao;
import com.jeeplus.modules.workitem.entity.WorkItem;
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.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.common.persistence.Page;
import com.jeeplus.common.service.CrudService;
import com.jeeplus.modules.workborrowmangement.entity.WorkBorrowMangement;
import com.jeeplus.modules.workborrowmangement.dao.WorkBorrowMangementDao;

/**
 * 借用管理Service
 * @author chenyuping
 * @version 2018-07-11
 */
@Service
@Transactional(readOnly = true)
public class WorkBorrowMangementService extends CrudService<WorkBorrowMangementDao, WorkBorrowMangement> {
	@Autowired
	private WorkClientAttachmentDao workClientAttachmentDao;
	@Autowired
	private UserDao userDao;
	@Autowired
	private WorkProjectNotifyService workProjectNotifyService;
	@Autowired
	private IdentityService identityService;
	@Autowired
	private ActTaskService actTaskService;
	@Autowired
	private WorkActivityMenuService workActivityMenuService;
	@Autowired
	private RuntimeService runtimeService;
	@Autowired
	private WorkActivityProcessService workActivityProcessService;
	@Autowired
	private ActivityService activityService;
	@Autowired
	protected HistoryService historyService;
	@Autowired
	private WorkActivityProcessDao workActivityProcessDao;
	@Autowired
	private SerialNumTplService serialNumTplService;
	@Autowired
	private WorkItemDao workItemDao;
	public WorkBorrowMangement get(String id) {
		return super.get(id);
	}

	/**
	 * 查询权限范围内的数据列表
	 * @param workBorrowMangement
	 * @return
	 */
	public List<WorkBorrowMangement> findList(WorkBorrowMangement workBorrowMangement) {
		if(!UserUtils.getUser().isAdmin()) {
			String dataScopeSql = dataScopeFilter(workBorrowMangement.getCurrentUser(), "o", "u", "s", MenuStatusEnum.WORK_BORROWMANGEMENT.getValue());
			workBorrowMangement.getSqlMap().put("dsf", dataScopeSql);
		}
		return super.findList(workBorrowMangement);
	}


	public Page<WorkBorrowMangement> findPage(Page<WorkBorrowMangement> page, WorkBorrowMangement workBorrowMangement) {
		if(!UserUtils.getUser().isAdmin()) {
			String dataScopeSql = dataScopeFilter(workBorrowMangement.getCurrentUser(), "o", "u", "s", MenuStatusEnum.WORK_BORROWMANGEMENT.getValue());
			workBorrowMangement.getSqlMap().put("dsf", dataScopeSql);
		}
		int count = dao.queryCount(workBorrowMangement);
		page.setCount(count);
		page.setCountFlag(false);
		workBorrowMangement.setPage(page);
		List<WorkBorrowMangement> list = dao.findList(workBorrowMangement);
		page.setList(list);
		return page;
	}

	/**
	 * 保存
	 * @param workBorrowMangement
	 * @return
	 */
	@Transactional(readOnly = false)
	public void save(WorkBorrowMangement workBorrowMangement) {
		if(StringUtils.isBlank(workBorrowMangement.getBorrower())){
			workBorrowMangement.setBorrower(UserUtils.getUser().getId());
		}
		super.save(workBorrowMangement);

	}
	/**
	 * 保存并启动流程
	 * @param workBorrowMangement
	 * @return
	 */
	@Transactional(readOnly = false)
	public String saveBorrow(WorkBorrowMangement workBorrowMangement) {
		User createBy = workBorrowMangement.getCreateBy();
		if(createBy != null){
			createBy = UserUtils.get(createBy.getId());
		}else {
			createBy = UserUtils.getUser();
			workBorrowMangement.setCreateBy(createBy);
		}
		if(StringUtils.isBlank(workBorrowMangement.getBorrower())){
			workBorrowMangement.setBorrower(UserUtils.getUser().getId());
		}
		if(StringUtils.isBlank(workBorrowMangement.getNumber())){
			workBorrowMangement.setNumber(serialNumTplService.genSerialNum(createBy.getCompany(),"14"));
		}
		if(StringUtils.isBlank(workBorrowMangement.getOfficeId())){
			workBorrowMangement.setOfficeId(UserUtils.getSelectOffice().getId());
		}
		if(workBorrowMangement.getCompanyId()==null||StringUtils.isBlank(workBorrowMangement.getCompanyId())){
			workBorrowMangement.setCompanyId(UserUtils.getSelectCompany().getId());
		}
		super.save(workBorrowMangement);

		return this.startAudit(workBorrowMangement,workBorrowMangement.getProcessInstanceId());
	}
	/**
	 * 删除数据
	 * @param workBorrowMangement
	 * @return
	 */
	@Transactional(readOnly = false)
	public void delete(WorkBorrowMangement workBorrowMangement) {
		super.delete(workBorrowMangement);
		WorkProjectNotify notify = new WorkProjectNotify();
		notify.setNotifyId(workBorrowMangement.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 startAudit(WorkBorrowMangement workBorrowMangement, String processInstanceId){
		try{
			Map<String, Object> variables = new HashMap<String, Object>();
			identityService.setAuthenticatedUserId(workBorrowMangement.getCurrentUser().getId());
			User createUser = UserUtils.getUser();
			String contentStr = "借用编号："+ workBorrowMangement.getNumber()+"，借用日期："+ DateUtils.formatDate(workBorrowMangement.getBorrowDate());
			String titleStr = "借用人："+createUser.getName();

			String businessKey = workBorrowMangement.getId();
			Office office = UserUtils.getSelectOffice();
			WorkActivityMenu workActivityMenu = workActivityMenuService.findByParentAndOffice("jygl3125f1f194c82bdegnnncdc750904", office);
			// 启动流程
			String processType = workActivityMenu.getProcessType();
			StringBuffer buffer = new StringBuffer();
			Activity activity = new Activity();
			WorkProjectNotify workProjectNotify = UtilNotify
					.saveNotify(workBorrowMangement.getId(), null, workBorrowMangement.getCompanyId(), titleStr, contentStr, "59", "0", "待审批", ""
					);

			List<User> users = new ArrayList<>();
			List<User> ywbzrList = UserUtils.getByRoleActivityEnname("bmzr",2,office.getId(),"16",workBorrowMangement.getCreateBy());
			List<User> xzzgList = UserUtils.getByRoleActivityEnname("xzzg",3,office.getId(),"16",workBorrowMangement.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(),"16",workBorrowMangement.getCreateBy());
						if (enusers.size()==0){
							workBorrowMangement.setState("1");
							this.save(workBorrowMangement);
							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(),"16",workBorrowMangement.getCreateBy());
					}
					//人员审批
					if (StringUtils.isNotBlank(activity.getUser().getId())) {
						users.add(activity.getUser());
					}
				}
				workProjectNotify.setId("");
			} else {
				if (ywbzrList.size()==0 || xzzgList.size()==0){
					workBorrowMangement.setState("1");
					this.save(workBorrowMangement);
				}
				if (ywbzrList.size()==0){
					return "流程审批人不能为空,角色业务部负责人下无用户,请联系管理员！";
				}
				processType = "workBorrowManagement";
				users.addAll(ywbzrList);
			}
			List<String> userIds = new ArrayList<>(users.size());
			for (User u : users){
				userIds.add(u.getId());
				workProjectNotify.setUser(u);
				workProjectNotify.setId("");
				workProjectNotify.setNotifyRole("业务部负责人审批");
				workProjectNotifyService.save(workProjectNotify);
				Map<String,Object> extras = new HashMap<>();
				extras.put("type","7001");
				extras.put("procDefKey","59");
				extras.put("id",workProjectNotify.getId());
				UserUtils.pushInfoToApp(titleStr, contentStr,extras,u.getId());
			}
			UserUtils.pushIm(userIds,contentStr);

			variables.put("busId", businessKey);
			variables.put("type", processType);
			variables.put("title", "审批单：" + workBorrowMangement.getNumber());//设置标题；

			ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processType, businessKey, variables);
			//        workReceiptsSettle.setProcessInstance(processInstance);
			if (org.apache.commons.lang3.StringUtils.isNotBlank(processInstanceId)) {
				workActivityProcessService.updateProcessInstanceId(processInstance.getId(),processInstanceId);
				workActivityProcessService.deleteProcessInstanceId(processInstanceId);
				workActivityProcessService.deleteProcessIdAuditUsers(processInstanceId);
			}
			List<Activity> list = workActivityMenu.getActivities();
			if (list != null && list.size() != 0) {
				workActivityProcessService.saveList(list, processInstance.getId());
			} else {
				WorkActivityProcess workActivityProcess = new WorkActivityProcess();
				workActivityProcess.setProcessKey(processType);
				workActivityProcess.setProcessInstanceId(processInstance.getId());
				workActivityProcess.setCount(1);
				workActivityProcess.setIsApproval("0");
				workActivityProcessService.insert(workActivityProcess);
				workActivityProcess.setCount(2);
				workActivityProcessService.insert(workActivityProcess);
				workActivityProcessService.insertAuditsByType(ywbzrList,processInstance.getId(),1,1);
				workActivityProcessService.insertAuditsByType(xzzgList,processInstance.getId(),2,0);
			}
			workBorrowMangement.setProcessInstanceId(processInstance.getId());
			workBorrowMangement.setState("2");
			dao.updateProcessIdAndStatus(workBorrowMangement);
		}catch (Exception e){
			logger.error("启动审批流程异常：",e);
			return "启动审批流程异常:"+e.getMessage();
		}
		return "";
	}

	/**
	 * 审核流程
	 */
	@Transactional(readOnly = false)
	public String auditSave(WorkBorrowMangement workBorrowMangement,List<User> auditUsers) {
		WorkItem workItem=workItemDao.get(workBorrowMangement.getFixedAssetsNumber());

		// 对不同环节的业务逻辑进行操作
		String taskDefKey = workBorrowMangement.getAct().getTaskDefKey();
		if (!"modifyApply".equals(taskDefKey) && !taskDefKey.contains("audit")) {
			actTaskService.claim(workBorrowMangement.getAct().getTaskId(), UserUtils.getUser().getId());
		}else {
			workBorrowMangement.getAct().setFlag("yes");
		}
		String comment = "";
		if ("4".equals(workBorrowMangement.getState()) ){
			comment = ("yes".equals(workBorrowMangement.getAct().getFlag())?"[重新申请] ":"[已撤销] ");
		}else {
			comment = ("yes".equals(workBorrowMangement.getAct().getFlag())?"[同意] ":"[驳回] ")+ workBorrowMangement.getAct().getComment();
		}
		//yes 的时候状态为审核通过 否则为未通过
		//1 审核中 2 未通过
		workBorrowMangement.setState(("yes".equals(workBorrowMangement.getAct().getFlag()) ? "2" : "4"));
		Map<String, Object> vars = Maps.newHashMap();
		//业务逻辑对应的条件表达式
		String exp = "";
		String taskCount = "";
		String notifyRole = "";
		int key = 0;
		String enname = "";
		String str="借用编号："+ workBorrowMangement.getNumber()+"，借用日期："+ DateUtils.formatDate(workBorrowMangement.getBorrowDate());
		String notifyStr = "固定资产编号："+workItem.getNumber()+"，物品名称："+ workBorrowMangement.getItemName();
		User createUser = userDao.get(workBorrowMangement.getBorrower());
		String title ="借用人："+createUser.getName();
		String notifyTitle ="物品名称："+ workBorrowMangement.getItemName();
		List<Activity> activitieList = activityService.getByProcessInstanceId(workBorrowMangement.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(workBorrowMangement.getProcessInstanceId());
		List<WorkActivityProcess> workActivityProcesses = workActivityProcessService.findList(selectProcess);
		List<Activity> activities = workActivityMenu.getActivities();
		if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("workBorrowManagement")) {
			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(workBorrowMangement.getAct().getFlag())) {
						workBorrowMangement.setState("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(workBorrowMangement.getAct().getFlag())) {
						workBorrowMangement.setState("3");
						workActivityProcess.setIsApproval("2");
					} else {
						workActivityProcess.setIsApproval("1");
					}
					break;
				}
			}
		} else {
			workActivityMenu.setProcessType("workBorrowManagement");
			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 ("ywbzr".equals(taskDefKey) && count.contains("1")) {
					taskCount = "1";
					exp = "pass";
					if ("yes".equals(workBorrowMangement.getAct().getFlag())) {
						workActivityProcessService.insertAuditsByType(auditUsers,workBorrowMangement.getProcessInstanceId(),2,1);
						notifyRole = "行政主管审核";
						workActivityProcess.setIsApproval("1");
						enname = "xzzg";
						//TODO 创建日常事务
					} else {
						notifyRole = "调整申请";
						workActivityProcess.setIsApproval("2");
					}
					break;
				} else if ("xzzg".equals(taskDefKey) && count.contains("2")) {
					taskCount = "2";
					exp = "pass";
					if ("yes".equals(workBorrowMangement.getAct().getFlag())) {
						notifyRole = "审批通过";
						workActivityProcess.setIsApproval("1");
						//修改物品一览表
						workItem.setUserOfficeId(workBorrowMangement.getOfficeId());
						workItem.setUserDate(workBorrowMangement.getBorrowDate());
						workItem.setEndUser(workBorrowMangement.getBorrower());
						workItem.setState("2");//被借用
					} else {
						notifyRole = "调整借用信息";
						workActivityProcess.setIsApproval("2");
					}
					break;
				} else if ("modifyApply".equals(taskDefKey)&& count.contains("0")) {
					notifyRole = "业务部负责人审批";
					taskCount = "0";
					exp = "pass";
					workActivityProcess.setCount(0);
					enname = "bmzr";
					if (!"yes".equals(workBorrowMangement.getAct().getFlag())) {
						workBorrowMangement.setState("3");
					}
					break;
				} else if ("apply_end".equals(taskDefKey)) {
				}

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

			} else {
				WorkProjectNotify notify = new WorkProjectNotify();
				notify.setNotifyId(workBorrowMangement.getId());
				userList = workProjectNotifyService.readByNotifyId(notify);
				if (!"3".equals( workBorrowMangement.getState())){
					workBorrowMangement.setState("4");
					workProjectNotifyService
							.save(UtilNotify
									.saveNotify(workBorrowMangement.getId(),
											workBorrowMangement.getCreateBy(),
											workBorrowMangement.getCompanyId(),
											notifyTitle,
											notifyStr,
											"59",
											"0",
											"待通知",
											notifyRole));
				}
			}
			workActivityProcessService.deleteProcessIdAuditUsers(workBorrowMangement.getProcessInstanceId());
		} else {
			if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("workBorrowManagement")) {
				WorkProjectNotify notify = new WorkProjectNotify();
				notify.setNotifyId(workBorrowMangement.getId());
				userList = workProjectNotifyService.readByNotifyId(notify);
				//users.addAll(userList);
				WorkProjectNotify workProjectNotify = UtilNotify
						.saveNotify(workBorrowMangement.getId(),
								new User(),
								workBorrowMangement.getCompanyId(),
								title,
								str,
								"59",
								"0",
								"待审批",
								notifyRole);
				List<WorkProjectNotify> workProjectNotifys = activityService.getByFlagAndTaskDefKeyList(
						activities,
						workProjectNotify,
						taskDefKey,
						workBorrowMangement.getAct().getFlag(),
						taskCount,
						workBorrowMangement.getCreateBy(),
						workBorrowMangement.getOfficeId(),
						"59");
				for (WorkProjectNotify workProjectNotify1:workProjectNotifys){
					users.add(workProjectNotify1.getUser());
					workProjectNotify1.setId("");
					workProjectNotify1.setIsNewRecord(false);
					workProjectNotifyService
							.save(workProjectNotify1);
				}

			} else {
				if (!"yes".equals(workBorrowMangement.getAct().getFlag())) {
					WorkProjectNotify notify = new WorkProjectNotify();
					notify.setNotifyId(workBorrowMangement.getId());
					userList = workProjectNotifyService.readByNotifyId(notify);
					//users.addAll(userList);
					workProjectNotifyService
							.save(UtilNotify
									.saveNotify(workBorrowMangement.getId(),
											workBorrowMangement.getCreateBy(),
											workBorrowMangement.getCompanyId(),
											title,
											str,
											"59",
											"0",
											"重新申请",
											notifyRole));
					users.add( workBorrowMangement.getCreateBy());
				} else {
					if (StringUtils.isNotBlank(enname)) {
						WorkProjectNotify notify = new WorkProjectNotify();
						notify.setNotifyId(workBorrowMangement.getId());
						userList = workProjectNotifyService.readByNotifyId(notify);
						//users.addAll(userList1);
						WorkProjectNotify workProjectNotify = UtilNotify
								.saveNotify(workBorrowMangement.getId(),
										new User(),
										workBorrowMangement.getCompanyId(),
										title,
										str,
										"59",
										"0",
										"待审批",
										notifyRole);
						users.addAll(auditUsers);
						for (User user1:auditUsers){
							workProjectNotify.setUser(user1);
							workProjectNotify.setId("");
							workProjectNotify.setIsNewRecord(false);
							workProjectNotifyService.save(workProjectNotify);
							Map<String,Object> extras = new HashMap<>();
							extras.put("type","7001");
							extras.put("procDefKey","59");
							extras.put("id",workProjectNotify.getId());
							UserUtils.pushInfoToApp(title,str,extras,user1.getId());
						}
					}else {
						WorkProjectNotify notify = new WorkProjectNotify();
						notify.setNotifyId(workBorrowMangement.getId());
						userList = workProjectNotifyService.readByNotifyId(notify);
						users.addAll(userList);
						users.add(workBorrowMangement.getCreateBy());
						workProjectNotifyService
								.save(UtilNotify
										.saveNotify(workBorrowMangement.getId(),
												workBorrowMangement.getCreateBy(),
												workBorrowMangement.getCompanyId(),
												title,
												str,
												"59",
												"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());
			}
		}
		dao.update(workBorrowMangement);
		workItemDao.update(workItem);
		return "保存审核意见成功！";
	}

	@Transactional(readOnly = false)
	public void cancelProcess(String id) throws Exception {
		WorkBorrowMangement workBorrowMangement = this.get(id);
		WorkActivityProcess process = new WorkActivityProcess();
		process.setProcessInstanceId(workBorrowMangement.getProcessInstanceId());
		process.setIsApproval("0");
		//List<WorkActivityProcess> processList1 = workActivityProcessService.findByProcInsId(process);
		WorkActivityProcess workActivityProcess = new WorkActivityProcess();
		workActivityProcess.setProcessInstanceId(workBorrowMangement.getProcessInstanceId());
		List<WorkActivityProcess> processList = workActivityProcessService.findList(workActivityProcess);
		WorkProjectNotify notify = new WorkProjectNotify();
		notify.setNotifyId(workBorrowMangement.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()+",借用审批编号:"+workBorrowMangement.getNumber() +" 强制撤销!\"," +
							"\"useType\":\"sys\"}";
					ChatServerPool.sendMessageToUser(toUserConn, message);//同时向本人发送消息
					//ChatServerPool.sendMessageToUser(toUserConn, u.getId() + "_sys_审批信息 " + "报销人:" + user.getName() + ",报销编号:" + workReimbursement.getNumber() + " 强制撤销!");//同时向本人发送消息
				}*/
				UserUtils.pushIm(u.getId(),"申请人:"+ user.getName()+",借用审批编号:"+workBorrowMangement.getNumber() +" 强制撤销!");
			}
		}
		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.setIsApproval("-1");
					p.setDelFlag("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);

			//结束该流程,设为"撤销"状态月
			WorkBorrowMangement borrowMangement = new WorkBorrowMangement();
			borrowMangement.setId(id);
			borrowMangement.setState("3");
			borrowMangement.setProcessInstanceId(workBorrowMangement.getProcessInstanceId());
			borrowMangement.preUpdate();
			this.updateStateById(borrowMangement);
			actTaskService.endProcessInstance(workBorrowMangement.getProcessInstanceId(), "借用申请-撤回");
		}
	}

	private void updateStateById(WorkBorrowMangement borrowMangement) {
		dao.updateProcessIdAndStatus(borrowMangement);
	}

/*	public Page<WorkItem> findPageItem(Page<WorkItem> page, WorkItem workItem) {
		if(!UserUtils.getUser().isAdmin()) {
			String dataScopeSql = dataScopeFilter(workItem.getCurrentUser(), "o", "u", "s");
			workItem.getSqlMap().put("dsf", dataScopeSql);
		}
		workItem.setPage(page);
		List<WorkItem> list = workItemDao.findList(workItem);
		page.setList(list);
		return page;
}*/
}