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

import com.google.common.collect.Maps;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.service.CrudService;
import com.jeeplus.common.utils.MenuStatusEnum;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.websocket.onchat.ChatServerPool;
import com.jeeplus.modules.act.service.ActTaskService;
import com.jeeplus.modules.act.utils.ActUtils;
import com.jeeplus.modules.projectrecord.entity.ProjectRecords;
import com.jeeplus.modules.projectrecord.service.ProjectRecordsService;
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.service.OfficeService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workactivity.dao.WorkActivityProcessDao;
import com.jeeplus.modules.workactivity.entity.Activity;
import com.jeeplus.modules.workactivity.entity.WorkActivityProcess;
import com.jeeplus.modules.workactivity.service.ActivityService;
import com.jeeplus.modules.workactivity.service.WorkActivityProcessService;
import com.jeeplus.modules.workactivitymenu.entity.WorkActivityMenu;
import com.jeeplus.modules.workactivitymenu.service.WorkActivityMenuService;
import com.jeeplus.modules.workinvoice.entity.WorkInvoice;
import com.jeeplus.modules.workinvoice.service.WorkInvoiceService;
import com.jeeplus.modules.workinvoicedetail.dao.WorkInvoiceDetailDao;
import com.jeeplus.modules.workinvoicedetail.entity.WorkInvoiceDetail;
import com.jeeplus.modules.workinvoicedetail.service.WorkInvoiceDetailService;
import com.jeeplus.modules.workinvoicereturn.entity.WorkInvoiceReturn;
import com.jeeplus.modules.workinvoicereturn.service.WorkInvoiceReturnService;
import com.jeeplus.modules.workinvoicereturnalter.dao.WorkInvoiceReturnAlterDao;
import com.jeeplus.modules.workinvoicereturnalter.entity.WorkInvoiceReturnAlter;
import com.jeeplus.modules.workprojectnotify.entity.WorkProjectNotify;
import com.jeeplus.modules.workprojectnotify.service.WorkProjectNotifyService;
import com.jeeplus.modules.workprojectnotify.util.UtilNotify;
import org.activiti.engine.ActivitiObjectNotFoundException;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.java_websocket.WebSocket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 退票管理Service
 * @author lw
 * @version 2018-06-15
 */
@Service
@Transactional(readOnly = true)
public class WorkInvoiceReturnAlterService extends CrudService<WorkInvoiceReturnAlterDao, WorkInvoiceReturnAlter> {
	@Autowired
	private SerialNumTplService serialNumTplService;
	@Autowired
	private WorkInvoiceDetailDao workInvoiceDetailDao;

	@Autowired
	private IdentityService identityService;
	@Autowired
	private WorkActivityMenuService workActivityMenuService;
	@Autowired
	private WorkInvoiceService workInvoiceService;
	@Autowired
	private WorkProjectNotifyService workProjectNotifyService;
	@Autowired
	private RuntimeService runtimeService;

	@Autowired
	private WorkActivityProcessService workActivityProcessService;
	@Autowired
	private ActTaskService actTaskService;
	@Autowired
	private ActivityService activityService;
	@Autowired
	private WorkActivityProcessDao workActivityProcessDao;
	@Autowired
	private WorkInvoiceDetailService workInvoiceDetailService;
	@Autowired
	private ProjectRecordsService projectRecordsService;
	@Autowired
	private WorkInvoiceReturnAlterDao workInvoiceReturnAlterDao;
	@Autowired
	private WorkInvoiceReturnService workInvoiceReturnService;
	@Autowired
	private OfficeService officeService;


	public WorkInvoiceReturnAlter get(String id) {
		WorkInvoiceReturnAlter workInvoiceReturn = super.get(id);
		if(workInvoiceReturn!=null){
			String wId = workInvoiceReturn.getInvoiceDetail().getId();
			if(StringUtils.isNotBlank(wId)){
				WorkInvoiceDetail workInvoiceDetail = workInvoiceDetailService.get(wId);
				if(workInvoiceDetail!=null){
					if(workInvoiceDetail.getWorkInvoice()!=null){
						String wId2 = workInvoiceDetail.getWorkInvoice().getId();
						if(StringUtils.isNotBlank(wId2)){
							WorkInvoice workInvoice = workInvoiceService.get(wId2);
							if(workInvoice!=null){
								workInvoiceDetail.setWorkInvoice(workInvoice);
								if(workInvoice.getProject()!=null){
									ProjectRecords projectRecords = workInvoice.getProject();
										if(projectRecords!=null){
											//设置项目组成员
											projectRecordsService.queryUserNames(projectRecords);
										/*	if(projectRecords.getProjectLeaders()!=null&&projectRecords.getProjectLeaders().size()>0){
												if(projectRecords.getProjectLeaders().size() == 1){
													StringBuffer name = new StringBuffer();
													for (User u:
															projectRecords.getProjectLeaders()) {
														name.append(u.getName());
													}
													projectRecords.setLeaderNameStr(name.toString());
												}else{
													StringBuffer name = new StringBuffer();
													for (User u:
															projectRecords.getProjectLeaders()) {
														name.append(","+u.getName());
													}
													projectRecords.setLeaderNameStr(name.toString());
												}
										}*/

									}
								}
							}
						}
					}
					workInvoiceReturn.setInvoiceDetail(workInvoiceDetail);
				}
			}
		}
		return workInvoiceReturn;
	}
	
	public List<WorkInvoiceReturnAlter> findList(WorkInvoiceReturnAlter workInvoiceReturn) {
		return super.findList(workInvoiceReturn);
	}
	
	public Page<WorkInvoiceReturnAlter> findPage(Page<WorkInvoiceReturnAlter> page, WorkInvoiceReturnAlter workInvoiceReturn) {
		workInvoiceReturn.getSqlMap().put("dsf", dataScopeFilter(workInvoiceReturn.getCurrentUser(), "o", "u","s", MenuStatusEnum.WORK_INVOICERETURNALTER.getValue()));
		workInvoiceReturn.setPage(page);
		page.setList(findList(workInvoiceReturn));
		return page;
	}
	
	@Transactional(readOnly = false)
	public void save(WorkInvoiceReturnAlter workInvoiceReturn) {
		if (StringUtils.isBlank(workInvoiceReturn.getReturnNumber())) {
			User user = UserUtils.getUser();
			workInvoiceReturn.setReturnNumber(serialNumTplService.genSerialNum(user.getCompany(), workInvoiceReturn.SERIAL_BIZCODE));
		}
		super.save(workInvoiceReturn);
	}

	@Transactional(readOnly = false)
	public String save(WorkInvoiceReturnAlter workInvoiceReturn, Map<String, Object> variables, String processInstanceId) {
			User user = UserUtils.getUser();
			if (StringUtils.isBlank(workInvoiceReturn.getReturnNumber())) {
				workInvoiceReturn.setReturnNumber(serialNumTplService.genSerialNum(user.getCompany(), workInvoiceReturn.SERIAL_BIZCODE));
			}
			WorkInvoice workInvoice = new WorkInvoice();
			Office office = officeService.get(workInvoiceReturn.getOfficeId());
			if(workInvoiceReturn.getInvoiceDetail()!=null){
				if(workInvoiceReturn.getInvoiceDetail().getWorkInvoice()!=null){
					if(StringUtils.isNotBlank(workInvoiceReturn.getInvoiceDetail().getWorkInvoice().getId())){
						workInvoice = workInvoiceService.get(workInvoiceReturn.getInvoiceDetail().getWorkInvoice());
						if(workInvoice!=null && workInvoice.getOffice()!=null){
							String oId = workInvoice.getOffice().getId();
							if(StringUtils.isNotBlank(oId)){
								office = officeService.get(oId);
							}
						}
					}
				}
			}
			super.save(workInvoiceReturn);
			String str =  "被退票号："+workInvoiceReturn.getInvoiceDetail().getNumber()+",实际开票单位:"+workInvoice.getClient().getName()+",申请人:"+user.getName()+",所属部门:"+office.getName();
			String title = "实际开票单位:"+workInvoice.getClient().getName();
			// 用来设置启动流程的人员ID，引擎会自动把用户ID保存到activiti:initiator中
			identityService.setAuthenticatedUserId(user.getId());
			String businessKey = workInvoiceReturn.getId().toString();
			WorkActivityMenu workActivityMenu = workActivityMenuService.findByParentAndOffice("wgh3125f1f194eeeeknjlp05c750905", office);//menuid
			// 启动流程
			String processType = workActivityMenu.getProcessType();
			StringBuffer buffer = new StringBuffer();
			Activity activity = new Activity();
			WorkProjectNotify workProjectNotify = UtilNotify
					.saveNotify(workInvoiceReturn.getId(),
							null,
							workInvoiceReturn.getCompanyId(),
							title,
							str,
							"49",
							"0",
							"待审批",
							""
					);
			List<User> users = new ArrayList<>();
			List<User> cwzgs = new ArrayList<>();
			if(workInvoice!=null){
				//1总公司0分公司
				if("1".equals(workInvoice.getExt())){
					cwzgs = UserUtils.getByRoleActivityEnname("cwzg",1,office.getId(),"6",workInvoiceReturn.getCreateBy());
				}else if("0".equals(workInvoice.getExt())){
					cwzgs = UserUtils.getByRoleActivityEnname("cwzg",3,office.getId(),"6",workInvoiceReturn.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(),"6",workInvoiceReturn.getCreateBy());
						if (enusers.size()==0){
							workInvoiceReturn.setStatus("1");
							this.save(workInvoiceReturn);
							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(),"6",workInvoiceReturn.getCreateBy());
					}
					//人员审批
					if (StringUtils.isNotBlank(activity.getUser().getId())) {
						users.add(activity.getUser());
					}
				}
				workProjectNotify.setId("");
			} else {
				if (cwzgs.size()==0 ){
					workInvoiceReturn.setStatus("1");
					this.save(workInvoiceReturn);
				}
				if (cwzgs.size()==0){
					return "流程审批人不能为空,角色财务主管下无用户,请联系管理员！";
				}
				variables.put("cwzgcount",cwzgs.size());
				variables.put("cwzgList",cwzgs);
				processType = "workinvoicereturnalter";
				users.addAll(cwzgs);
			}
			for (User u : users){
				workProjectNotify.setUser(u);
				workProjectNotify.setId("");
				workProjectNotifyService
						.save(workProjectNotify);
				Map<String,Object> extras = new HashMap<>();
				extras.put("type","7001");
				extras.put("id",workProjectNotify.getId());
				extras.put("procDefKey","49");
				UserUtils.pushInfoToApp(title,str,extras,u.getId());
				UserUtils.pushIm(u.getId(),str);
			}
			variables.put("type", processType);
			variables.put("busId", businessKey);
			variables.put("title", "审批单：" + workInvoiceReturn.getNumber());//设置标题；

			ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processType, businessKey, variables);
			workInvoiceReturn.setProcessInstance(processInstance);
			if (StringUtils.isNotBlank(processInstanceId)) {
				workActivityProcessService.updateProcessInstanceId(processInstance.getId(),processInstanceId);
				workActivityProcessService.deleteProcessInstanceId(processInstanceId);
				workActivityProcessService.deleteProcessIdAuditUsers(processInstanceId);
			}
			// 更新流程实例ID
			workInvoiceReturn.setProcessInstanceId(processInstance.getId());
			workInvoiceReturnAlterDao.updateProcessInstanceId(workInvoiceReturn);
			List<Activity> list = workActivityMenu.getActivities();
			if (list != null && list.size() != 0) {
				workActivityProcessService.saveList(list, processInstance.getId());
			} else {
				WorkActivityProcess workActivityProcess = new WorkActivityProcess();
				workActivityProcess.setProcessKey("workinvoicereturnalter");
				workActivityProcess.setCount(1);
				workActivityProcess.setProcessInstanceId(processInstance.getId());
				workActivityProcess.setIsApproval("0");
				workActivityProcessService.save(workActivityProcess);
				workActivityProcessService.insertAuditsByType(cwzgs,processInstance.getId(),1,1);
			}
			logger.debug("start process of {key={}, bkey={}, pid={}, variables={}}", new Object[]{
					ActUtils.PD_REIMBURSEMENT[0], businessKey, processInstance.getId(), variables});
		return "";
	}
	@Transactional(readOnly = false)
	public void delete(WorkInvoiceReturnAlter workInvoiceReturn) {
		if(workInvoiceReturn.getWorkInvoiceReturn()!=null){
			WorkInvoiceReturn workInvoiceReturn1 = workInvoiceReturnService.get(workInvoiceReturn.getWorkInvoiceReturn().getId());
			workInvoiceReturn1.setStatus("5");
			workInvoiceReturnService.save(workInvoiceReturn1);
		}
		super.delete(workInvoiceReturn);
		WorkProjectNotify notify = new WorkProjectNotify();
		notify.setNotifyId(workInvoiceReturn.getId());
		List<User> users = workProjectNotifyService.readByNotifyId(notify);
		if (users!=null && users.size()!=0){
			for (User user:users){
				UserUtils.pushMeIm(user.getId());
			}
		}
	}

	/**
	 * 审核流程
	 * @param
	 */
	@Transactional(readOnly = false)
	public String auditSave(WorkInvoiceReturnAlter workInvoiceReturn,List<User> auditUsers) {
		WorkInvoice workInvoice = new WorkInvoice();
		Office office = officeService.get(workInvoiceReturn.getOfficeId());
		if(workInvoiceReturn.getInvoiceDetail()!=null){
			if(workInvoiceReturn.getInvoiceDetail().getWorkInvoice()!=null){
				if(StringUtils.isNotBlank(workInvoiceReturn.getInvoiceDetail().getWorkInvoice().getId())){
					workInvoice = workInvoiceService.get(workInvoiceReturn.getInvoiceDetail().getWorkInvoice());
					if(workInvoice!=null && workInvoice.getOffice()!=null){
						String oId = workInvoice.getOffice().getId();
						if(StringUtils.isNotBlank(oId)){
							office = officeService.get(oId);
						}
					}
				}
			}
		}

		String userName = UserUtils.get(workInvoiceReturn.getCreateBy().getId()).getName();
		String str =  "被退票号："+workInvoiceReturn.getInvoiceDetail().getNumber()+",实际开票单位:"+workInvoice.getClient().getName()+",申请人:"+userName+",所属部门:"+office.getName();
		String title = "实际开票单位:"+workInvoice.getClient().getName();
			// 对不同环节的业务逻辑进行操作
			String taskDefKey = workInvoiceReturn.getAct().getTaskDefKey();
			if (!"modifyApply".equals(taskDefKey)) {
				actTaskService.claim(workInvoiceReturn.getAct().getTaskId(), UserUtils.getUser().getId());
			}else {
				workInvoiceReturn.getAct().setFlag("yes");
			}

			String comment = "";
			if (workInvoiceReturn.getStatus().equals("4")){
				comment = ("yes".equals(workInvoiceReturn.getAct().getFlag())?"[重新申请] ":"[已撤销] ");
			}else {
				comment = ("yes".equals(workInvoiceReturn.getAct().getFlag())?"[同意] ":"[驳回] ")+workInvoiceReturn.getAct().getComment();
			}
			//yes 的时候状态为审核通过 否则为未通过
			//1 审核中 2 未通过
			workInvoiceReturn.setStatus(("yes".equals(workInvoiceReturn.getAct().getFlag()) ? "2" : "4"));
			Map<String, Object> vars = Maps.newHashMap();
			//业务逻辑对应的条件表达式
			String exp = "";
			String taskCount = "";
			String notifyRole = "";
			int key = 0;
			String enname = "";
			List<Activity> activitieList = activityService.getByProcessInstanceId(workInvoiceReturn.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(workInvoiceReturn.getProcessInstanceId());
			List<WorkActivityProcess> workActivityProcesses = workActivityProcessService.findList(selectProcess);
			List<Activity> activities = workActivityMenu.getActivities();
			if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("workinvoicereturnalter")) {
				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(workInvoiceReturn.getAct().getFlag())) {
							workInvoiceReturn.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(workInvoiceReturn.getAct().getFlag())) {
							workInvoiceReturn.setStatus("3");
							workActivityProcess.setIsApproval("2");
						} else {
							workActivityProcess.setIsApproval("1");
						}
						break;
					}
				}
			} else {
				workActivityMenu.setProcessType("workinvoicereturnalter");
				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 ("cwzg".equals(taskDefKey) && count.contains("1")) {
						taskCount = "1";
						exp = "pass";
						if ("yes".equals(workInvoiceReturn.getAct().getFlag())) {
							notifyRole = "审核通过";
							workActivityProcess.setIsApproval("1");
						} else {
							notifyRole = "调整申请";
							workActivityProcess.setIsApproval("2");
						}
						break;
					} else if ("modifyApply".equals(taskDefKey)&& count.contains("0")) {
						taskCount = "0";
						exp = "pass";
						workActivityProcess.setCount(0);
						enname = "cwzg";
						if (!"yes".equals(workInvoiceReturn.getAct().getFlag())) {
							workInvoiceReturn.setStatus("3");
						}
						break;
					} else if ("apply_end".equals(taskDefKey)) {
					}

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

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

						}
					}

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

								}
							}
						}else {
							WorkProjectNotify notify = new WorkProjectNotify();
							notify.setNotifyId(workInvoiceReturn.getId());
							userList = workProjectNotifyService.readByNotifyId(notify);
							users.addAll(userList);
							users.add(workInvoiceReturn.getCreateBy());
							workProjectNotifyService
									.save(UtilNotify
											.saveNotify(workInvoiceReturn.getId(),
													workInvoiceReturn.getCreateBy(),
													workInvoiceReturn.getCompanyId(),
													title,
													str,
													"49",
													"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());
			}
		}
			if("5".equals(workInvoiceReturn.getStatus())){
				if(workInvoiceReturn.getWorkInvoiceReturn()!=null){
					WorkInvoiceReturn workInvoiceReturn1 = workInvoiceReturnService.get(workInvoiceReturn.getWorkInvoiceReturn().getId());
					if(workInvoiceReturn1!=null){
						workInvoiceReturn1.setStatus("5");//code  number   returnType    returnDate
						String code = workInvoiceReturn1.getCode();
						String number = workInvoiceReturn1.getNumber();
						String returnType = workInvoiceReturn1.getReturnType();
						Date returnDate = workInvoiceReturn1.getReturnDate();
						if(StringUtils.isNotBlank(workInvoiceReturn.getCode())){
							workInvoiceReturn1.setCode(workInvoiceReturn.getCode());
						}
						if(StringUtils.isNotBlank(workInvoiceReturn.getNumber())){
							workInvoiceReturn1.setNumber(workInvoiceReturn.getNumber());
						}
						if(StringUtils.isNotBlank(workInvoiceReturn.getReturnType())){
							workInvoiceReturn1.setReturnType(workInvoiceReturn.getReturnType());
						}
						if(workInvoiceReturn.getReturnDate()!=null){
							workInvoiceReturn1.setReturnDate(workInvoiceReturn.getReturnDate());
						}
						workInvoiceReturnService.save(workInvoiceReturn1);

						//更新冲销发票
						if("1".equals(workInvoiceReturn.getCancleReturn())){
							if(StringUtils.isNotBlank(code)&& StringUtils.isNotBlank(number)){
								WorkInvoiceDetail workInvoiceDetail = new WorkInvoiceDetail();
								workInvoiceDetail.setCode(code);
								workInvoiceDetail.setNumber(number);
								List<WorkInvoiceDetail> list = workInvoiceDetailDao.findByCode(workInvoiceDetail);
								for (WorkInvoiceDetail workInvoiceDetail2:
										list) {
									workInvoiceDetail2.setCode(workInvoiceReturn.getCode());
									workInvoiceDetail2.setNumber(workInvoiceReturn.getNumber());
									workInvoiceDetailDao.updateByCode(workInvoiceDetail2);
								}
							}
						}
						//更新退票信息
						workInvoiceReturn.setCode(code);
						workInvoiceReturn.setNumber(number);
						workInvoiceReturn.setReturnType(returnType);
						workInvoiceReturn.setReturnDate(returnDate);
					}
				}
			}
			workInvoiceReturnAlterDao.update(workInvoiceReturn);
			return "保存审核意见成功！";
	}

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

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

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