/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.workitemcollar.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.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.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.workborrowmangement.entity.WorkBorrowMangement;
import com.jeeplus.modules.workcatalogueitem.dao.WorkCatalogueItemDao;
import com.jeeplus.modules.workcatalogueitem.entity.WorkCatalogueItem;
import com.jeeplus.modules.workclientinfo.dao.WorkClientAttachmentDao;
import com.jeeplus.modules.workclientinfo.entity.WorkClientAttachment;
import com.jeeplus.modules.workitem.dao.WorkItemDao;
import com.jeeplus.modules.workitem.entity.WorkItem;
import com.jeeplus.modules.workitem.service.WorkItemService;
import com.jeeplus.modules.workitemcollar.dao.WorkItemCollarCatalogDao;
import com.jeeplus.modules.workitemcollar.dao.WorkItemCollarItemDao;
import com.jeeplus.modules.workitemcollar.entity.WorkItemCollarCatalog;
import com.jeeplus.modules.workitemcollar.entity.WorkItemCollarItem;
import com.jeeplus.modules.workmonthlyplan.entity.WorkMonthlyPlan;
import com.jeeplus.modules.workmonthlyplan.entity.WorkMonthlyPlanThis;
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.workitemcollar.entity.WorkItemCollar;
import com.jeeplus.modules.workitemcollar.dao.WorkItemCollarDao;

/**
 * 领用管理Service
 * @author chenyuping
 * @version 2018-07-16
 */
@Service
@Transactional(readOnly = true)
public class WorkItemCollarService extends CrudService<WorkItemCollarDao, WorkItemCollar> {
	@Autowired
	private WorkItemCollarCatalogDao workItemCollarCatalogDao;
	@Autowired
	private WorkItemCollarItemDao workItemCollarItemDao;
	@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;
	@Autowired
	private WorkCatalogueItemDao workCatalogueItemDao;

	public WorkItemCollar get(String id) {
		return super.get(id);
	}

	public List<WorkItemCollar> findList(WorkItemCollar workItemCollar) {

		return super.findList(workItemCollar);
	}
	@Transactional(readOnly = false)
	public void delete(WorkItemCollar workItemCollar) {
		super.delete(workItemCollar);
		//删除子表数据
		if(workItemCollar.getWorkItemCollarItemList()!=null&&workItemCollar.getWorkItemCollarItemList().size()>0){
			for (WorkItemCollarItem workItemCollarItem : workItemCollar.getWorkItemCollarItemList()) {
				workItemCollarItemDao.delete(workItemCollarItem);
			}
		}
		//删除子表数据
		if(workItemCollar.getWorkItemCollarCatalogList()!=null&&workItemCollar.getWorkItemCollarCatalogList().size()>0){
			for (WorkItemCollarCatalog workItemCollarCatalog : workItemCollar.getWorkItemCollarCatalogList()) {
				workItemCollarCatalogDao.delete(workItemCollarCatalog);
			}
		}
		WorkProjectNotify notify = new WorkProjectNotify();
		notify.setNotifyId(workItemCollar.getId());
		List<User> users = workProjectNotifyService.readByNotifyId(notify);
		if (users!=null && users.size()!=0){
			for (User user:users){
				UserUtils.pushMeIm(user.getId());
			}
		}
	}
	public Page<WorkItemCollar> findPage(Page<WorkItemCollar> page, WorkItemCollar workItemCollar) {
		workItemCollar.getSqlMap().put("dsf", dataScopeFilter(workItemCollar.getCurrentUser(), "o", "u","s", MenuStatusEnum.WORK_ITEMCOLLAR.getValue()));
		int count = dao.queryCount(workItemCollar);
		page.setCount(count);
		page.setCountFlag(false);
		workItemCollar.setPage(page);
		page.setList(findList(workItemCollar));
		return page;
	}

	@Transactional(readOnly = false)
	public void save(WorkItemCollar workItemCollar) {
		super.save(workItemCollar);
		updateItemCollar(workItemCollar);
		updateItemAssets(workItemCollar);
	}

	@Transactional(readOnly = false)
	public String saveCollar(WorkItemCollar workItemCollar) {
		User createBy = workItemCollar.getCreateBy();
		if(createBy != null){
			createBy = UserUtils.get(createBy.getId());
		}else {
			createBy = UserUtils.getUser();
			workItemCollar.setCreateBy(createBy);
		}
		if(StringUtils.isBlank(workItemCollar.getLeader())){
			workItemCollar.setLeader(UserUtils.getUser().getId());
		}
		if(StringUtils.isBlank(workItemCollar.getNumber())){
			workItemCollar.setNumber(serialNumTplService.genSerialNum(createBy.getCompany(),"18"));
		}
		if(StringUtils.isBlank(workItemCollar.getOfficeId())){
			workItemCollar.setOfficeId(UserUtils.getSelectOffice().getId());
		}
		if(workItemCollar.getCompanyId()==null||StringUtils.isBlank(workItemCollar.getCompanyId())){
			workItemCollar.setCompanyId(UserUtils.getSelectCompany().getId());
		}
		this.save(workItemCollar);
		return this.startAudit(workItemCollar,workItemCollar.getProcessInstanceId());
	}
	/**
	 * 判断是否有固定资产
	 */
	public static boolean isAssets(WorkItemCollar workItemCollar){
		boolean flat=false;
		if(workItemCollar.getWorkItemCollarCatalogList()!=null&&workItemCollar.getWorkItemCollarCatalogList().size()>0){
			for(WorkItemCollarCatalog workItemCollarCatalog:workItemCollar.getWorkItemCollarCatalogList()){
				if("0".equals(workItemCollarCatalog.getDelFlag())){
					if("是".equals(workItemCollarCatalog.getWorkCatalogueItem().getIsAssets())){
						flat=true;
						break;
					}
				}
			}
		}
		return flat;
	}
	/**
	 * 启动审批流程
	 */
	@Transactional(readOnly = false)
	public String startAudit(WorkItemCollar workItemCollar, String processInstanceId){
		if(workItemCollar.getProcessInstanceId()!=null){
			workActivityProcessService.deleteyProcess(workItemCollar.getProcessInstanceId());
		}

		Map<String, Object> variables = new HashMap<String, Object>();
		identityService.setAuthenticatedUserId(workItemCollar.getCurrentUser().getId());
		User createUser = UserUtils.getUser();
		String contentStr = "领用编号："+ workItemCollar.getNumber()+"，领用日期："+ DateUtils.formatDate(workItemCollar.getCollarDate());
		String titleStr = "领用人："+createUser.getName();

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

		List<User> users = new ArrayList<>();
		List<User> ywbzrList = UserUtils.getByRoleActivityEnname("bmzr",2,office.getId(),"17",workItemCollar.getCreateBy());
		List<User> xzzgList = UserUtils.getByRoleActivityEnname("xzzg",3,office.getId(),"17",workItemCollar.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(),"17",workItemCollar.getCreateBy());
					if (enusers.size()==0){
						workItemCollar.setState("1");
						this.save(workItemCollar);
						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(),"17",workItemCollar.getCreateBy());
				}
				//人员审批
				if (StringUtils.isNotBlank(activity.getUser().getId())) {
					users.add(activity.getUser());
				}
			}
			workProjectNotify.setId("");
		} else {
			//有固定资产
			if(isAssets(workItemCollar)){
				if (ywbzrList.size()==0 || xzzgList.size()==0){
					workItemCollar.setState("1");
					this.save(workItemCollar);
				}
				if (ywbzrList.size()==0){
					return "流程审批人不能为空,角色业务部负责人下无用户,请联系管理员！";
				}

				processType = "workItemCollar";
				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","64");
					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("pass1", true);
				variables.put("title", "审批单：" + workItemCollar.getNumber());//设置标题；
			}else{
				if (xzzgList.size()==0){
					workItemCollar.setState("1");
					this.save(workItemCollar);
				}
				if (xzzgList.size()==0){
					return "流程审批人不能为空,角色行政主管下无用户,请联系管理员！";
				}
				processType = "workItemCollar";
				users.addAll(xzzgList);
				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","64");
					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("pass1", false);
				variables.put("title", "审批单：" + workItemCollar.getNumber());//设置标题；
			}
		}
		ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processType, businessKey, variables);
		if (org.apache.commons.lang3.StringUtils.isNotBlank(processInstanceId)) {
			workActivityProcessService.updateProcessInstanceId(processInstance.getId(),processInstanceId);
			workActivityProcessService.deleteProcessInstanceId(processInstanceId);
			workActivityProcessService.deleteProcessIdAuditUsers(processInstanceId);
		}
		if(isAssets(workItemCollar)){
			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.setCount(1);
				workActivityProcess.setProcessInstanceId(processInstance.getId());
				workActivityProcess.setIsApproval("0");
				workActivityProcessService.insert(workActivityProcess);
				workActivityProcess.setCount(2);
				workActivityProcessService.insert(workActivityProcess);
				workActivityProcessService.save(workActivityProcess);
				workActivityProcessService.insertAuditsByType(ywbzrList,processInstance.getId(),1,1);
				workActivityProcessService.insertAuditsByType(xzzgList,processInstance.getId(),2,0);

			}
		}else{
			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.setCount(2);
				workActivityProcess.setProcessInstanceId(processInstance.getId());
				workActivityProcess.setIsApproval("0");
				workActivityProcessService.insert(workActivityProcess);
				workActivityProcessService.insertAuditsByType(xzzgList,processInstance.getId(),2,0);
			}
		}
		workItemCollar.setProcessInstanceId(processInstance.getId());
		workItemCollar.setState("2");
		dao.updateProcessIdAndStatus(workItemCollar);
		return "";
	}
	/**
	 * 审核流程
	 */
	@Transactional(readOnly = false)
	public String auditSave(WorkItemCollar workItemCollar,List<User> auditUsers) {
		// 对不同环节的业务逻辑进行操作
		String taskDefKey = workItemCollar.getAct().getTaskDefKey();
		if (!"modifyApply".equals(taskDefKey) && !taskDefKey.contains("audit")) {
			actTaskService.claim(workItemCollar.getAct().getTaskId(), UserUtils.getUser().getId());
		}else {
			workItemCollar.getAct().setFlag("yes");
			this.save(workItemCollar);
		}
		String comment = "";
		if ("4".equals(workItemCollar.getState()) ){
			comment = ("yes".equals(workItemCollar.getAct().getFlag())?"[重新申请] ":"[已撤销] ");
		}else {
			comment = ("yes".equals(workItemCollar.getAct().getFlag())?"[同意] ":"[驳回] ")+ workItemCollar.getAct().getComment();
		}
		//yes 的时候状态为审核通过 否则为未通过
		//1 审核中 2 未通过
		workItemCollar.setState(("yes".equals(workItemCollar.getAct().getFlag()) ? "2" : "4"));
		String buffer = UserUtils.getRoleActivityEnname(UserUtils.getSelectCompany().getId(), workItemCollar.getCreateBy());
		Map<String, Object> vars = Maps.newHashMap();
		//业务逻辑对应的条件表达式
		String exp = "";
		String taskCount = "";
		String notifyRole = "";
		int key = 0;
		String enname = "";
		String str="领用编号："+ workItemCollar.getNumber()+"，领用日期："+ DateUtils.formatDate(workItemCollar.getCollarDate());
		User createUser = userDao.get(workItemCollar.getLeader());
		String title ="领用人："+createUser.getName();
		String notifyTitle ="领用编号："+ workItemCollar.getNumber();
		List<Activity> activitieList = activityService.getByProcessInstanceId(workItemCollar.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(workItemCollar.getProcessInstanceId());
		List<WorkActivityProcess> workActivityProcesses = workActivityProcessService.findList(selectProcess);
		List<Activity> activities = workActivityMenu.getActivities();
		if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("workItemCollar")) {
			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(workItemCollar.getAct().getFlag())) {
						workItemCollar.setState("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(workItemCollar.getAct().getFlag())) {
						workItemCollar.setState("3");
						workActivityProcess.setIsApproval("2");
					} else {
						workActivityProcess.setIsApproval("1");
					}
					break;
				}
			}
		} else {
			workActivityMenu.setProcessType("workItemCollar");
			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)) {
					workActivityProcessService.insertAuditsByType(auditUsers,workItemCollar.getProcessInstanceId(),2,1);
					taskCount = "1";
					exp = "pass";
					if ("yes".equals(workItemCollar.getAct().getFlag())) {
						notifyRole = "行政主管审核";
						workActivityProcess.setIsApproval("1");
						enname = buffer + "xzzg";
						//TODO 创建日常事务
					} else {
						notifyRole = "调整申请";
						workActivityProcess.setIsApproval("2");
					}
					break;
				} else if ("xzzg".equals(taskDefKey) ) {
					taskCount = "2";
					exp = "pass";
					if ("yes".equals(workItemCollar.getAct().getFlag())) {
						notifyRole = "审批通过";
						workActivityProcess.setIsApproval("1");
						//修改物品一览表领用状态
						if(workItemCollar.getWorkItemCollarItemList()!=null&&workItemCollar.getWorkItemCollarItemList().size()>0){
							for(WorkItemCollarItem workItemCollarItem:workItemCollar.getWorkItemCollarItemList()){
								if(!"1".equals(workItemCollarItem.getDelFlag())){
									WorkItem workItem=workItemDao.get(workItemCollarItem.getItemId());
									workItem.setState("3");//被领用
									workItem.setEndUser(workItemCollar.getLeader());//领用人
									workItem.setUserDate(workItemCollar.getCollarDate());//领用日期
									workItem.setUserOfficeId(workItemCollar.getOfficeId());//领用部门
									workItemDao.update(workItem);
								}
							}
						}
						//修改物品一览表物品数量
						if(workItemCollar.getWorkItemCollarCatalogList()!=null&&workItemCollar.getWorkItemCollarCatalogList().size()>0){
							for(WorkItemCollarCatalog workItemCollarCatalog:workItemCollar.getWorkItemCollarCatalogList()){
								if(!"1".equals(workItemCollarCatalog.getDelFlag())){
									WorkItem workItem=workItemDao.getFindItem(workItemCollarCatalog.getWorkCatalogueItem().getId());
									if(workItem!=null){
										WorkCatalogueItem catalog=workCatalogueItemDao.get(workItem.getCatalogueItemId());
										int grantNum=Integer.parseInt(workItemCollarCatalog.getGrantNum());//发放数量
										int itemcount=workItem.getItemCount();//库存数量
										if(itemcount-grantNum<0){
											return "物品："+catalog.getName()+"的库存数量为"+itemcount+" ，本次发放数量为"+grantNum+"，库存数量不足，请修改发放数量";
										}else{
											workItem.setItemCount(itemcount-grantNum);
										}
										workItemDao.update(workItem);
									}

								}
							}
						}
					} else {
						notifyRole = "调整领用信息";
						workActivityProcess.setIsApproval("2");
					}
					break;
				} else if ("modifyApply".equals(taskDefKey)&& count.contains("0")) {

					if(isAssets(workItemCollar)){
						notifyRole = "业务部负责人审批";
						taskCount = "0";
						exp = "pass";
						workActivityProcess.setCount(0);
						enname = buffer + "bmzr";
						workItemCollar.getAct().setFlag("yes");
					}else {
						notifyRole = "行政主管审批";
						taskCount = "0";
						exp = "pass";
						workActivityProcess.setCount(0);
						enname = buffer + "xzzg";
						workItemCollar.getAct().setFlag("no");
					}
					break;
				} else if ("apply_end".equals(taskDefKey)) {
				}

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

			} else {
				WorkProjectNotify notify = new WorkProjectNotify();
				notify.setNotifyId(workItemCollar.getId());
				userList = workProjectNotifyService.readByNotifyId(notify);
				if (!"3".equals( workItemCollar.getState())){
					workItemCollar.setState("4");
					workProjectNotifyService
							.save(UtilNotify
									.saveNotify(workItemCollar.getId(),
											workItemCollar.getCreateBy(),
											workItemCollar.getCompanyId(),
											notifyTitle,
											str,
											"64",
											"0",
											"待通知",
											notifyRole));
				}
			}
			workActivityProcessService.deleteProcessIdAuditUsers(workItemCollar.getProcessInstanceId());

		} else {
			if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("workItemCollar")) {
				WorkProjectNotify notify = new WorkProjectNotify();
				notify.setNotifyId(workItemCollar.getId());
				userList = workProjectNotifyService.readByNotifyId(notify);
				//users.addAll(userList);
				WorkProjectNotify workProjectNotify = UtilNotify
						.saveNotify(workItemCollar.getId(),
								new User(),
								workItemCollar.getCompanyId(),
								title,
								str,
								"64",
								"0",
								"待审批",
								notifyRole);
				List<WorkProjectNotify> workProjectNotifys = activityService.getByFlagAndTaskDefKeyList(
						activities,
						workProjectNotify,
						taskDefKey,
						workItemCollar.getAct().getFlag(),
						taskCount,
						workItemCollar.getCreateBy(),
						workItemCollar.getOfficeId(),
						"64");
				for (WorkProjectNotify workProjectNotify1:workProjectNotifys){
					users.add(workProjectNotify1.getUser());
					workProjectNotify1.setId("");
					workProjectNotify1.setIsNewRecord(false);
					workProjectNotifyService
							.save(workProjectNotify1);
				}

			} else {
				if (!"yes".equals(workItemCollar.getAct().getFlag())) {
					WorkProjectNotify notify = new WorkProjectNotify();
					notify.setNotifyId(workItemCollar.getId());
					userList = workProjectNotifyService.readByNotifyId(notify);
					//users.addAll(userList);
					workProjectNotifyService
							.save(UtilNotify
									.saveNotify(workItemCollar.getId(),
											workItemCollar.getCreateBy(),
											workItemCollar.getCompanyId(),
											title,
											str,
											"64",
											"0",
											"重新申请",
											notifyRole));
					users.add( workItemCollar.getCreateBy());
				} else {
					if (StringUtils.isNotBlank(enname)) {
						WorkProjectNotify notify = new WorkProjectNotify();
						notify.setNotifyId(workItemCollar.getId());
						userList = workProjectNotifyService.readByNotifyId(notify);
						//users.addAll(userList1);
						WorkProjectNotify workProjectNotify = UtilNotify
								.saveNotify(workItemCollar.getId(),
										new User(),
										workItemCollar.getCompanyId(),
										title,
										str,
										"64",
										"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","64");
							extras.put("id",workProjectNotify.getId());
							UserUtils.pushInfoToApp(title,str,extras,user1.getId());
						}
					}else {
						WorkProjectNotify notify = new WorkProjectNotify();
						notify.setNotifyId(workItemCollar.getId());
						userList = workProjectNotifyService.readByNotifyId(notify);
						users.addAll(userList);
						users.add(workItemCollar.getCreateBy());
						workProjectNotifyService
								.save(UtilNotify
										.saveNotify(workItemCollar.getId(),
												workItemCollar.getCreateBy(),
												workItemCollar.getCompanyId(),
												title,
												str,
												"64",
												"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(workItemCollar);
		updateItemCollar(workItemCollar);
		updateItemAssets(workItemCollar);
		return "保存审核意见成功！";
	}


	@Transactional(readOnly = false)
	public void updateItemCollar(WorkItemCollar workItemCollar) {
		if(workItemCollar.getWorkItemCollarCatalogList()!=null&&workItemCollar.getWorkItemCollarCatalogList().size()>0){
			for (WorkItemCollarCatalog workItemCollarCatalog : workItemCollar.getWorkItemCollarCatalogList()) {
				if (StringUtils.isBlank(workItemCollarCatalog.getId()) ) {
					workItemCollarCatalog.preInsert();
					if(workItemCollarCatalog.getWorkCatalogueItem()!=null){
						workItemCollarCatalog.setItemCollarId(workItemCollar.getId());//领用表主键
						workItemCollarCatalog.setItemCatalogId(workItemCollarCatalog.getWorkCatalogueItem().getId());//物品目录表主键
						if(StringUtils.isNotBlank(workItemCollarCatalog.getItemCatalogId())){
							workItemCollarCatalogDao.insert(workItemCollarCatalog);
						}
					}

				} else {
					if(workItemCollarCatalog.getWorkCatalogueItem()!=null){
						workItemCollarCatalog.preUpdate();
						workItemCollarCatalog.setItemCollarId(workItemCollar.getId());//领用表主键
						workItemCollarCatalog.setItemCatalogId(workItemCollarCatalog.getWorkCatalogueItem().getId());//物品目录表主键
						if(StringUtils.isNotBlank(workItemCollarCatalog.getItemCatalogId())){
							workItemCollarCatalogDao.update(workItemCollarCatalog);
						}
					}
				}
			}
		}

	}

	@Transactional(readOnly = false)
	public void updateItemAssets(WorkItemCollar workItemCollar) {
		if(workItemCollar.getWorkItemCollarItemList()!=null&&workItemCollar.getWorkItemCollarItemList().size()>0){
			for (WorkItemCollarItem workItemCollarItem : workItemCollar.getWorkItemCollarItemList()) {
				if (StringUtils.isBlank(workItemCollarItem.getId()) ) {
					workItemCollarItem.preInsert();
					workItemCollarItem.setWorkCollarId(workItemCollar.getId());//领用表主键
					//workItemCollarItem.setItemId(workItemCollarItem.getWorkCatalogueItem().getId());//物品目录表主键
					if(StringUtils.isNotBlank(workItemCollarItem.getWorkCollarId())){
						workItemCollarItemDao.insert(workItemCollarItem);
					}
				} else {
					workItemCollarItem.preUpdate();
					workItemCollarItem.setWorkCollarId(workItemCollar.getId());//领用表主键
					//workItemCollarItem.setItemCatalogId(workItemCollarItem.getWorkCatalogueItem().getId());//物品目录表主键
					if(StringUtils.isNotBlank(workItemCollarItem.getWorkCollarId())){
						workItemCollarItemDao.update(workItemCollarItem);
					}

				}
			}
		}

	}
	//查询物品目录子表数据
	public List<WorkItemCollarCatalog> findWorkItemCollarCatalogList(WorkItemCollar workItemCollar) {
		List<WorkItemCollarCatalog> workItemCollarCatalogList=workItemCollarCatalogDao.findByWorkItemCollarId(workItemCollar);
		return workItemCollarCatalogList;
	}
	//查询物品一览表子表数据
	public List<WorkItemCollarItem> findWorkItemCollarItemList(WorkItemCollar workItemCollar) {
		List<WorkItemCollarItem> workItemCollarItemList=workItemCollarItemDao.findAssetsWorkItemCollarId(workItemCollar);
		return workItemCollarItemList;
	}


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

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

	private void updateStateById(WorkItemCollar itemCollar) {
		dao.updateProcessIdAndStatus(itemCollar);
	}


	public void updateWorkItem(WorkItemCollar workItemCollar){
		if(isAssets(workItemCollar)){


		}
	}
}