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

import java.lang.reflect.InvocationTargetException;
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.*;
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.serialnum.service.SerialNumTplService;
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.workcatalogueitem.entity.WorkCatalogueItem;
import com.jeeplus.modules.workcatalogueitemstock.dao.WorkCatalogueItemStockDao;
import com.jeeplus.modules.workcatalogueitemstock.entity.WorkCatalogueItemStock;
import com.jeeplus.modules.workcatalogueitemstock.service.WorkCatalogueItemStockService;
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.workitem.dao.WorkItemDao;
import com.jeeplus.modules.workitem.entity.WorkItem;
import com.jeeplus.modules.workitem.service.WorkItemService;
import com.jeeplus.modules.workitemstock.dao.WorkItemStockDao;
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 com.jeeplus.modules.workreimbursement.entity.WorkAccount;
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.apache.commons.beanutils.BeanUtils;
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.workstock.entity.WorkStock;
import com.jeeplus.modules.workstock.dao.WorkStockDao;

/**
 * 物品采购Service
 * @author lw
 * @version 2018-07-13
 */
@Service
@Transactional(readOnly = true)
public class WorkStockService extends CrudService<WorkStockDao, WorkStock> {
	@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 WorkStockDao workStockDao;
	@Autowired
	private ActTaskService actTaskService;
	@Autowired
	private ActivityService activityService;
	@Autowired
	private WorkActivityProcessDao workActivityProcessDao;
	@Autowired
	private SerialNumTplService serialNumTplService;
	@Autowired
	private WorkCatalogueItemStockDao workCatalogueItemStockDao;
	@Autowired
	private WorkItemStockDao workItemStockDao;
	@Autowired
	private WorkCatalogueItemStockService workCatalogueItemStockService;
	@Autowired
	private WorkItemStockService workItemStockService;
	@Autowired
	private WorkItemDao workItemDao;
	@Autowired
	private WorkItemService workItemService;


	public WorkStock get(String id) {
		WorkStock workStock = super.get(id);
		//附件
		WorkClientAttachment workClientAttachment = new WorkClientAttachment();
		workClientAttachment.setAttachmentId(id);
		workClientAttachment.setAttachmentFlag("106");
		workStock.setWorkAttachments(workClientAttachmentDao.findList(workClientAttachment));
		if(workStock!=null){
			WorkCatalogueItemStock workCatalogueItemStock = new WorkCatalogueItemStock();
			WorkItemStock workItemStock = new WorkItemStock();
			workCatalogueItemStock.setStockId(workStock.getId());
			workItemStock.setStockId(workStock.getId());
			List<WorkCatalogueItemStock> buyDetailsList1 = workCatalogueItemStockService.findList(workCatalogueItemStock);
			List<WorkItemStock> buyDetailsList2 = workItemStockService.findList(workItemStock);
			//物品申请列表
			workStock.setWorkCatalogueItemStocks(buyDetailsList1);
			//物品验收列表
			workStock.setWorkItemStocks(buyDetailsList2);
		}
		return workStock;
	}
	
	public List<WorkStock> findList(WorkStock workStock) {
		return super.findList(workStock);
	}
	
	public Page<WorkStock> findPage(Page<WorkStock> page, WorkStock workStock) {
		workStock.getSqlMap().put("dsf", dataScopeFilter(workStock.getCurrentUser(), "o", "u","s", MenuStatusEnum.WORK_STOCK.getValue()));
		workStock.setPage(page);
		page.setList(findList(workStock));
		return page;
	}
	
	@Transactional(readOnly = false)
	public void save(WorkStock workStock) {
		super.save(workStock);
		updateWorkReimbursementInfo(workStock);
	}
	@Transactional(readOnly = false)
	public void updateWorkReimbursementInfo(WorkStock workStock) {
		//申请列表
		for (WorkCatalogueItemStock buyDetails : workStock.getWorkCatalogueItemStocks()){
			if (buyDetails.getId() == null){
				continue;
			}
			if (buyDetails.DEL_FLAG_NORMAL.equals(buyDetails.getDelFlag())){
				buyDetails.setStockId(workStock.getId());
				if(StringUtils.isNotBlank(buyDetails.getType()) && buyDetails.getType().contains(",")){
					buyDetails.setType(buyDetails.getType().replace(",",""));
				}
				if(StringUtils.isNotBlank(buyDetails.getPrimaryUnit()) && buyDetails.getPrimaryUnit().contains(",")){
					buyDetails.setPrimaryUnit(buyDetails.getPrimaryUnit().replace(",",""));
				}
				if(StringUtils.isNotBlank(buyDetails.getName()) && buyDetails.getName().contains(",")){
					buyDetails.setName(buyDetails.getName().replace(",",""));
				}
				if(StringUtils.isNotBlank(buyDetails.getNumber()) && buyDetails.getNumber().contains(",")){
					buyDetails.setNumber(buyDetails.getNumber().replace(",",""));
				}
				if(StringUtils.isNotBlank(buyDetails.getModel()) && buyDetails.getModel().contains(",")){
					buyDetails.setModel(buyDetails.getModel().replace(",",""));
				}
				if (StringUtils.isBlank(buyDetails.getId())){
					buyDetails.preInsert();
					workCatalogueItemStockDao.insert(buyDetails);
				}else{
					buyDetails.preUpdate();
					workCatalogueItemStockDao.update(buyDetails);
				}
			}else{
				workCatalogueItemStockDao.delete(buyDetails);
			}
		}
		//验收列表
		for (WorkItemStock buyDetails : workStock.getWorkItemStocks()){
			if (buyDetails.getId() == null){
				continue;
			}
			if (buyDetails.DEL_FLAG_NORMAL.equals(buyDetails.getDelFlag())){
				buyDetails.setStockId(workStock.getId());
				if (StringUtils.isBlank(buyDetails.getId())){
					buyDetails.preInsert();
					workItemStockDao.insert(buyDetails);
				}else{
					buyDetails.preUpdate();
					workItemStockDao.update(buyDetails);
				}
			}else{
				workItemStockDao.delete(buyDetails);
			}
		}
		//固定资产列表
		for (WorkItemStock buyDetails : workStock.getWorkItemStockAssets()){
			if (buyDetails.getId() == null){
				continue;
			}
			if (buyDetails.DEL_FLAG_NORMAL.equals(buyDetails.getDelFlag())){
				if (StringUtils.isBlank(buyDetails.getId())){
				}else{
					buyDetails.preUpdate();
					workItemStockDao.updateNumber(buyDetails);
				}
			}
		}
		//附件信息
		for (WorkClientAttachment workClientAttachment : workStock.getWorkAttachments()) {
			if (workClientAttachment.getId() == null) {
				continue;
			}
			if (WorkClientAttachment.DEL_FLAG_NORMAL.equals(workClientAttachment.getDelFlag())) {
				workClientAttachment.setAttachmentId(workStock.getId());
				workClientAttachment.setAttachmentFlag("106");
				workClientAttachment.setAttachmentUser(UserUtils.getUser().getId());
				if (StringUtils.isBlank(workClientAttachment.getId()) || "null".equals(workClientAttachment.getId())) {
					workClientAttachment.preInsert();
					workClientAttachmentDao.insert(workClientAttachment);
				} else {
					workClientAttachment.preUpdate();
					workClientAttachmentDao.update(workClientAttachment);
				}
			} else {
				workClientAttachmentDao.delete(workClientAttachment);
			}
		}
	}

	/**
	 * 提交存储
	 * @param
	 * @param variables
	 */
	@Transactional(readOnly = false)
	public String save(WorkStock workStock, Map<String, Object> variables, String processInstanceId) {
			User user = UserUtils.getUser();
			if(StringUtils.isBlank(workStock.getNumber())){
				workStock.setNumber(serialNumTplService.genSerialNum(user.getCompany(), workStock.SERIAL_BIZCODE));
			}
			super.save(workStock);
			String str = "采购编号："+workStock.getNumber()+",采购日期:"+ DateUtils.formatDate(workStock.getCreateDate());
			String title = "采购申请人："+user.getName()+",所属部门："+workStock.getOfficeName();
			updateWorkReimbursementInfo(workStock);
			// 用来设置启动流程的人员ID，引擎会自动把用户ID保存到activiti:initiator中
			identityService.setAuthenticatedUserId(user.getId());
			// 启动流程
			String businessKey = workStock.getId().toString();
			Office office = UserUtils.getSelectOffice();
			WorkActivityMenu workActivityMenu = workActivityMenuService.findByParentAndOffice("ggh3125f1f194c82bdeocggldc750904", office);
			// 启动流程
			String processType = workActivityMenu.getProcessType();
			StringBuffer buffer = new StringBuffer();
			Activity activity = new Activity();
			WorkProjectNotify workProjectNotify = UtilNotify
					.saveNotify(workStock.getId(),
							null,
							workStock.getCompanyId(),
							title,
							str,
							"61",
							"0",
							"待审批",
							""
					);
			List<User> users = new ArrayList<>();
			List<User> zjls = UserUtils.getByRoleActivityEnname("zjl",3,office.getId(),"14",workStock.getCreateBy());
			List<User> xzzgs = UserUtils.getByRoleActivityEnname("xzzg",3,office.getId(),"14",workStock.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(),"14",workStock.getCreateBy());
						if (enusers.size()==0){
							workStock.setStatus("1");
							this.save(workStock);
							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(),"14",workStock.getCreateBy());
					}
					//人员审批
					if (StringUtils.isNotBlank(activity.getUser().getId())) {
						users.add(activity.getUser());
					}
				}
				workProjectNotify.setId("");
			} else {
				variables.put("zjlList", zjls);
				//variables.put("xzzgList", xzzgs);
				//variables.put("xzzgsList", xzzgs);
				if (zjls.size()==0 || xzzgs.size()==0){
					workStock.setStatus("1");
					this.save(workStock);
				}
				if (zjls.size()==0){
					return "流程审批人不能为空,角色总经理下无用户,请联系管理员！";
				}
				/*if (xzzgs.size()==0){
					return "流程审批人不能为空,角色行政主管下无用户,请联系管理员！";
				}*/
				variables.put("zjlcount",zjls.size());
				variables.put("xzzgcount",xzzgs.size());
				variables.put("xzzgscount",xzzgs.size());
				processType = "workstock";
				users.addAll(zjls);
			}
			for (User u : users){
				workProjectNotify.setUser(u);
				workProjectNotify.setId("");
				workProjectNotify.setNotifyRole("总经理审批");
				workProjectNotifyService
						.save(workProjectNotify);
				Map<String,Object> extras = new HashMap<>();
				extras.put("type","7001");
				extras.put("id",workProjectNotify.getId());
				extras.put("procDefKey","61");
				UserUtils.pushInfoToApp(title,str,extras,u.getId());
				UserUtils.pushIm(u.getId(),str);
			}
			variables.put("type", processType);
			variables.put("busId", businessKey);
			variables.put("title", "审批单：" + workStock.getNumber());//设置标题；

			ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processType, businessKey, variables);
			workStock.setProcessInstance(processInstance);
			if (StringUtils.isNotBlank(processInstanceId)) {
				workActivityProcessService.updateProcessInstanceId(processInstance.getId(),processInstanceId);
				workActivityProcessService.deleteProcessInstanceId(processInstanceId);
				workActivityProcessService.deleteProcessIdAuditUsers(processInstanceId);
			}
			// 更新流程实例ID
			workStock.setProcessInstanceId(processInstance.getId());
			workStockDao.updateProcessInstanceId(workStock);
			List<Activity> list = workActivityMenu.getActivities();
			if (list != null && list.size() != 0) {
				workActivityProcessService.saveList(list, processInstance.getId());
			} else {
				WorkActivityProcess workActivityProcess = new WorkActivityProcess();
				workActivityProcess.setProcessKey("workstock");
				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(zjls,processInstance.getId(),1,1);
				workActivityProcessService.insertAuditsByType(xzzgs,processInstance.getId(),2,0);
				workActivityProcessService.insertAuditsByType(xzzgs,processInstance.getId(),3,0);
			}
			logger.debug("start process of {key={}, bkey={}, pid={}, variables={}}", new Object[]{
					ActUtils.PD_REIMBURSEMENT[0], businessKey, processInstance.getId(), variables});
		return "";
	}
	@Transactional(readOnly = false)
	public void delete(WorkStock workStock) {
		super.delete(workStock);
		for (WorkCatalogueItemStock workAccount : workStock.getWorkCatalogueItemStocks()){
			workCatalogueItemStockDao.delete(workAccount);
		} for (WorkItemStock workAccount : workStock.getWorkItemStocks()){
			workItemStockDao.delete(workAccount);
		}
		WorkProjectNotify notify = new WorkProjectNotify();
		notify.setNotifyId(workStock.getId());
		workProjectNotifyService.readByNotifyId(notify);
	}

	/**
	 * 审核流程
	 * @param
	 */
	@Transactional(readOnly = false)
	public String auditSave(WorkStock workStock,List<User> auditUsers) {
			String userName = UserUtils.get(workStock.getCreateBy().getId()).getName();
			String str = "采购编号："+workStock.getNumber()+",采购日期:"+ DateUtils.formatDate(workStock.getCreateDate());
			String title = "采购申请人："+userName+",所属部门："+workStock.getOfficeName();
			// 对不同环节的业务逻辑进行操作
			String taskDefKey = workStock.getAct().getTaskDefKey();
			if ("zjl".equals(taskDefKey)) {
				actTaskService.claim(workStock.getAct().getTaskId(), UserUtils.getUser().getId());
			}else if("xzzg".equals(taskDefKey) || "xzzgs".equals(taskDefKey)){
				workStock.getAct().setFlag("yes");
				updateWorkReimbursementInfo(workStock);
			} else {
				workStock.getAct().setFlag("yes");
				updateWorkReimbursementInfo(workStock);
			}
			String comment = "";
			if (workStock.getStatus().equals("4")){
				comment = ("yes".equals(workStock.getAct().getFlag())?"[重新申请] ":"[已撤销] ");
			}else {
				comment = ("yes".equals(workStock.getAct().getFlag())?"[同意] ":"[驳回] ")+workStock.getAct().getComment();
			}
			//yes 的时候状态为审核通过 否则为未通过
			workStock.setStatus(("yes".equals(workStock.getAct().getFlag()) ? "2" : "4"));
			//String buffer = UserUtils.getRoleActivityEnname(UserUtils.getSelectCompany().getId(),workStock.getCreateBy());
			Map<String, Object> vars = Maps.newHashMap();
			//业务逻辑对应的条件表达式
			String exp = "";
			String taskCount = "";
			String notifyRole = "";
			int sign = 0;
			int key = 0;
			String enname = "";
			List<Activity> activitieList = activityService.getByProcessInstanceId(workStock.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(workStock.getProcessInstanceId());
			List<WorkActivityProcess> workActivityProcesses = workActivityProcessService.findList(selectProcess);
			List<Activity> activities = workActivityMenu.getActivities();
			if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("workstock")) {
				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(workStock.getAct().getFlag())) {
							workStock.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(workStock.getAct().getFlag())) {
							workStock.setStatus("3");
							workActivityProcess.setIsApproval("2");
						} else {
							workActivityProcess.setIsApproval("1");
						}
						break;
					}
				}
			} else {
				workActivityMenu.setProcessType("workstock");
				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 ("zjl".equals(taskDefKey) && count.contains("1")) {
						taskCount = "1";
						exp = "pass";
						if ("yes".equals(workStock.getAct().getFlag())) {
							vars.put("xzzgList", auditUsers);
							vars.put("xzzgcount",auditUsers.size());
							workActivityProcessService.insertAuditsByType(auditUsers,workStock.getProcessInstanceId(),2,1);
							notifyRole = "行政主管";
							workActivityProcess.setIsApproval("1");
							enname = "xzzg";
						} else {
							notifyRole = "调整申请";
							workActivityProcess.setIsApproval("2");
						}
						break;
					} else if ("xzzg".equals(taskDefKey) && count.contains("2")) {
						taskCount = "2";
						exp = "pass";
						int type = 0;
						List<WorkItemStock> list = workStock.getWorkItemStocks();
						if(list!=null && list.size()>0){
							for (WorkItemStock w:
								 list) {
								//是固定资产
								if("1".equals(w.getIsAssets())){
                                    type +=1;
                                    int _count = Integer.parseInt(w.getCount());//固定资产数量
									for(int a=0; a<_count ;a++){
										WorkItemStock workItemStock = new WorkItemStock();
										try {
											MyBeanUtils.copyBean2Bean(workItemStock,w);
											workItemStock.setId(IdGen.uuid());
										} catch (Exception e) {
											e.printStackTrace();
										}
										workItemStock.setAssetsNumber(serialNumTplService.genSerialNum(UserUtils.getUser().getCompany(), w.SERIAL_BIZCODE));
										workItemStock.preInsert();
										workItemStock.setSign("1");
										workItemStock.setCount("1");
										workItemStockDao.insert(workItemStock);
									}
								}
							}
						}
						//根据是否固定资产做判断  是-行政主管验收编码
						if (type>0) {
							vars.put("xzzgsList", auditUsers);
							vars.put("xzzgscount",auditUsers.size());
							workActivityProcessService.insertAuditsByType(auditUsers,workStock.getProcessInstanceId(),3,1);
							notifyRole = "行政主管";
							workActivityProcess.setIsApproval("1");
							enname = "xzzg";
						} else {
							//否-流程结束
							workStock.getAct().setFlag("no");
							sign +=1;
							notifyRole = "审批通过";
							workActivityProcess.setIsApproval("1");
						}
						break;
					} else if ("xzzgs".equals(taskDefKey) && count.contains("3")) {
						taskCount = "3";
						exp = "pass";
						if ("yes".equals(workStock.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 = "zjl";
						if (!"yes".equals(workStock.getAct().getFlag())) {
							workStock.setStatus("3");
						}
						break;
					} else if ("apply_end".equals(taskDefKey)) {
					}

				}
			}
			// 设置意见
			workStock.getAct().setComment(("yes".equals(workStock.getAct().getFlag()) ? "[同意] " : "[驳回] ") + workStock.getAct().getComment());
			workStock.preUpdate();
			// 提交流程任务
			vars.put(exp, "yes".equals(workStock.getAct().getFlag()) ? true : false);
			vars.put("passs", true);
			if(sign >0){
				workStock.getAct().setFlag("yes");
				workActivityProcessService.updateProcess(workActivityProcess,workActivityMenu,key,taskCount,workStock.getProcessInstanceId(),taskDefKey,"modifyApply",workStock.getAct().getFlag(),comment, activities);
				WorkActivityProcess workActivityP = new WorkActivityProcess();
				workActivityP.setProcessInstanceId(workStock.getProcessInstanceId());
				List<WorkActivityProcess> processList = workActivityProcessService.findList(workActivityP);
				if(processList!=null && processList.size()>0){
					for (int i =0;i<processList.size();i++) {
						WorkActivityProcess p = processList.get(i);
						if(3 == p.getCount()){
							p.setDelFlag("1");
							p.setIsApproval("-1");
							workActivityProcessDao.updateDelFlagAndIsApproval(p);
						}
					}
				}
				workStock.getAct().setFlag("no");
			}else {
				workActivityProcessService.updateProcess(workActivityProcess,workActivityMenu,key,taskCount,workStock.getProcessInstanceId(),taskDefKey,"modifyApply",workStock.getAct().getFlag(),comment, activities);
			}
			// 提交流程任务
			actTaskService.complete(workStock.getAct().getTaskId(), workStock.getAct().getProcInsId(), workStock.getAct().getComment(), vars);
			boolean state = actTaskService.isProcessEnd(workStock.getAct().getProcInsId());
			List<User> users = new ArrayList<>();
			List<User> userList = new ArrayList<>();
			if (!state) {
				title =  "采购编号"+workStock.getNumber();
				str = "采购编号："+workStock.getNumber()+",采购日期:"+ DateUtils.formatDate(workStock.getCreateDate());
				users.add(workStock.getCreateBy());
				/*if ("yes".equals(workStock.getAct().getFlag())) {*/
					workStock.setStatus("5");
					WorkProjectNotify notify = new WorkProjectNotify();
					notify.setNotifyId(workStock.getId());
					userList = workProjectNotifyService.readByNotifyId(notify);
					users.addAll(userList);
					workProjectNotifyService
							.save(UtilNotify
									.saveNotify(workStock.getId(),
											workStock.getCreateBy(),
											workStock.getCompanyId(),
											title,
											str,
											"61",
											"0",
											"待通知",
											notifyRole));

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

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

								}
							}
						}else {
							WorkProjectNotify notify = new WorkProjectNotify();
							notify.setNotifyId(workStock.getId());
							userList = workProjectNotifyService.readByNotifyId(notify);
							users.addAll(userList);
							users.add(workStock.getCreateBy());
							workProjectNotifyService
									.save(UtilNotify
											.saveNotify(workStock.getId(),
													workStock.getCreateBy(),
													workStock.getCompanyId(),
													title,
													str,
													"61",
													"0",
													"重新申请",
													notifyRole));
						}
					}
				}
			}
		if (StringUtils.isNotBlank(title) && users!=null && users.size()!=0) {
			for (User u : users) {
				UserUtils.pushIm(u.getId(),title);
			}
		}
		if (StringUtils.isNotBlank(title) && userList!=null && userList.size()!=0) {
			for (User u : userList) {
				UserUtils.pushMeIm(u.getId());
			}
		}
			workStockDao.update(workStock);
			if("5".equals(workStock.getStatus())){
				List<WorkItemStock> list = workStock.getWorkItemStocks();
				if(list!=null && list.size()>0){
					for (WorkItemStock w:
						 list) {
						//非固定资产更改数量
						if("0".equals(w.getIsAssets())){
							if(StringUtils.isNotBlank(w.getCatalogueItemId())){
								WorkItem workItem=workItemDao.getFindItem(w.getCatalogueItemId());
								//存在做数量增操作
								if(workItem!=null){
									int itemcount=workItem.getItemCount();//库存数量
									if(StringUtils.isNotBlank(w.getCount())){
										int count = Integer.parseInt(w.getCount());
										workItem.setItemCount(itemcount+count);
										workItemDao.update(workItem);
									}
								}else{
									//添加新值
									WorkItem wItem = new WorkItem();
									wItem.setIsAssets("0");
									wItem.setCompanyId(UserUtils.getSelectCompany().getId());
									wItem.setOfficeId(UserUtils.getSelectOffice().getId());
									wItem.setCatalogueItemId(w.getCatalogueItemId());
									wItem.setState("1");//正常
									if(StringUtils.isNotBlank(w.getCount())){
										wItem.setItemCount(Integer.parseInt(w.getCount()));
									}
									wItem.setId("");
									wItem.preInsert();
									wItem.setDelFlag("0");
									workItemDao.insert(wItem);
								}
							}
						}
					}
				}
				List<WorkItemStock> list2 = workStock.getWorkItemStockAssets();
				if(list2!=null && list2.size()>0){
					for (WorkItemStock w:
							list2) {
						//固定资产添加新值
						WorkItem workItem = new WorkItem();
						workItem.setIsAssets("1");
						workItem.setCompanyId(UserUtils.getSelectCompany().getId());
						workItem.setOfficeId(UserUtils.getSelectOffice().getId());
						workItem.setCatalogueItemId(w.getCatalogueItemId());
						workItem.setState("1");//正常
						if(StringUtils.isNotBlank(w.getCount())){
							workItem.setItemCount(Integer.parseInt(w.getCount()));
						}
						workItem.setNumber(w.getAssetsNumber());
						workItem.setId("");
						workItem.preInsert();
						workItem.setDelFlag("0");
						workItemDao.insert(workItem);
					}
				}
			}
			return "保存审核意见成功！";
	}

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

	/**
	 * 强制撤销
	 * @param
	 */
	@Transactional(readOnly = false)
	public void cancelInvalidate(WorkStock workStock) {
		String invalidateProcessInstanceId = workStock.getProcessInstanceId();
		try {
			//将流程图中尚未走到的task的流程追踪信息逻辑删除，添加一条"撤销"流程追踪信息
			WorkActivityProcess process = new WorkActivityProcess();
			process.setProcessInstanceId(workStock.getProcessInstanceId());
			process.setIsApproval("0");
			WorkActivityProcess workActivityProcess = new WorkActivityProcess();
			workActivityProcess.setProcessInstanceId(workStock.getProcessInstanceId());
			List<WorkActivityProcess> processList = workActivityProcessService.findList(workActivityProcess);
			WorkProjectNotify notify = new WorkProjectNotify();
			notify.setNotifyId(workStock.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()+",归档编号:"+workStock.getNumber()+" 强制撤销!\"," +
								"\"useType\":\"sys\"}";
						ChatServerPool.sendMessageToUser(toUserConn, message);//同时向本人发送消息
					}*/
					UserUtils.pushIm(u.getId(),"物品采购申请人:"+ user.getName()+",归档编号:"+workStock.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.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,"物品采购申请-强制撤销");
			workStock.setStatus("3");
			workStock.preUpdate();
			workStockDao.update(workStock);

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