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

import com.google.common.collect.Maps;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.service.CrudService;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.MenuStatusEnum;
import com.jeeplus.common.utils.MyBeanUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.websocket.onchat.ChatServerPool;
import com.jeeplus.modules.act.entity.Act;
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.Role;
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.workbidproject.entity.WorkBidProject;
import com.jeeplus.modules.workclientinfo.entity.WorkClientInfo;
import com.jeeplus.modules.workinvoice.entity.WorkInvoice;
import com.jeeplus.modules.workinvoice.service.WorkInvoiceService;
import com.jeeplus.modules.workinvoicealter.dao.WorkInvoiceAlterDao;
import com.jeeplus.modules.workinvoicealter.entity.WorkInvoiceAlter;
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.workprojectnotify.entity.WorkProjectNotify;
import com.jeeplus.modules.workprojectnotify.service.WorkProjectNotifyService;
import com.jeeplus.modules.workprojectnotify.util.UtilNotify;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.java_websocket.WebSocket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 开票管理Service
 * @author 孟祥越
 * @version 2017-05-05
 */
@Service
@Transactional(readOnly = true)
@Lazy
public class WorkInvoiceAlterService extends CrudService<WorkInvoiceAlterDao, WorkInvoiceAlter> {

	@Autowired
	private ActTaskService actTaskService;
	@Autowired
	private RuntimeService runtimeService;
	@Autowired
	private OfficeService officeService;
	@Autowired
	private ActivityService activityService;
	@Autowired
	private WorkInvoiceDetailDao workInvoiceDetailDao;
	@Autowired
	private WorkActivityProcessDao workActivityProcessDao;
	@Autowired
	private WorkInvoiceService workInvoiceService;

	@Autowired
	protected TaskService taskService;
	@Autowired
	protected HistoryService historyService;
	@Autowired
	protected RepositoryService repositoryService;
	@Autowired
	protected WorkActivityMenuService workActivityMenuService;
	@Autowired
	protected WorkInvoiceAlterDao workInvoiceAlterDao;

	@Autowired
	private IdentityService identityService;
	@Autowired
	protected WorkActivityProcessService workActivityProcessService;
	@Autowired
	protected ProjectRecordsService projectRecordsService;
	@Autowired
	@Lazy
	protected WorkInvoiceDetailService workInvoiceDetailService;
	@Autowired
	protected SerialNumTplService serialNumTplService;
	@Autowired
	protected WorkInvoiceService invoiceService;

	@Autowired
	protected WorkProjectNotifyService workProjectNotifyService;
	public WorkInvoiceAlter getByProcInsId(String procInsId) {
		return dao.getByProcInsId(procInsId);
	}
	
	public WorkInvoiceAlter get(String id) {
		WorkInvoiceAlter workInvoice = new WorkInvoiceAlter();
		if(StringUtils.isNotBlank(id)){
			workInvoice = super.get(id);
		}
		if(workInvoice!=null){
			if(StringUtils.isNotBlank(workInvoice.getProcessInstanceId())){
				workInvoice.setAct(getByAct(workInvoice.getProcessInstanceId()));
			}
			if(workInvoice.getProject()!=null){
				ProjectRecords project = projectRecordsService.getInfo(workInvoice.getProject().getId());
				workInvoice.setProject(project);
			}
			if(StringUtils.isNotBlank(workInvoice.getId())){
				WorkInvoiceDetail workInvoiceDetail = new WorkInvoiceDetail();
				workInvoiceDetail.setAinvoiceId(workInvoice.getId());
				List<WorkInvoiceDetail> list = workInvoiceDetailDao.afindList(workInvoiceDetail);
				workInvoice.setWorkAccountList(list);
			}
		}
		return workInvoice;
	}
	public Act getByAct(String processInstanceId){
		Act act = new Act();
		HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
		ProcessInstance processInstance = actTaskService.getProcIns(processInstanceId);
		if (processInstance!=null) {
			List<Task> taskList = actTaskService.getCurrentTaskList(processInstance);
			if(taskList!=null && taskList.size()>1){
				for (Task taskInfok:taskList) {
					if (taskInfok.getAssignee().equals(UserUtils.getUser().getId())) {
						act.setTaskId(taskInfok.getId());
						act.setTaskName(taskInfok.getName());
						act.setTaskDefKey(taskInfok.getTaskDefinitionKey());
						act.setProcDefId(taskInfok.getProcessDefinitionId());
						act.setProcInsId(taskInfok.getProcessInstanceId());
						act.setTask(taskInfok);
					}
				}
			}else {
				Task task = actTaskService.getCurrentTaskInfo(processInstance);
				act.setTaskId(task.getId());
				act.setTaskName(task.getName());
				act.setTaskDefKey(task.getTaskDefinitionKey());
				act.setProcDefId(task.getProcessDefinitionId());
				act.setProcInsId(task.getProcessInstanceId());
				act.setTask(task);
			}
		}
		return  act;
		/*if (processInstance!=null) {
			Task taskInfok = actTaskService.getCurrentTaskInfo(processInstance);
			Act act = new Act();
			act.setTaskId(taskInfok.getId());
			act.setTaskName(taskInfok.getName());
			act.setTaskDefKey(taskInfok.getTaskDefinitionKey());
			act.setProcDefId(taskInfok.getProcessDefinitionId());
			act.setProcInsId(taskInfok.getProcessInstanceId());
			act.setTask(taskInfok);
			return act;
		}else {
			return null;
		}*/
	}
	public List<WorkInvoiceAlter> findList(WorkInvoiceAlter workInvoice) {
		return super.findList(workInvoice);
	}
	
	public Page<WorkInvoiceAlter> findPage(Page<WorkInvoiceAlter> page, WorkInvoiceAlter workInvoice) {
		workInvoice.getSqlMap().put("dsf", dataScopeFilter(workInvoice.getCurrentUser(), "o", "u","s", MenuStatusEnum.WORK_INVOICERETURNALTER.getValue()));
		workInvoice.setPage(page);
		page.setList(findList(workInvoice));
		return page;

	}

	/**
	 * 暂存
	 * @param workInvoice
	 */
	@Transactional(readOnly = false)
	public  void save(WorkInvoiceAlter workInvoice){
		super.save(workInvoice);
		updateWorkInvoiceInfo(workInvoice);
	}

	@Transactional(readOnly = false)
	public void updateWorkInvoiceInfo(WorkInvoiceAlter workInvoice) {
		try {
		for (WorkInvoiceDetail buyDetails : workInvoice.getWorkAccountList()){
			if (buyDetails.getId() == null){
				continue;
			}
			if (buyDetails.DEL_FLAG_NORMAL.equals(buyDetails.getDelFlag())){
				buyDetails.setAinvoiceId(workInvoice.getId());
				buyDetails.setComId(workInvoice.getCompanyId());
				buyDetails.setOfficeId(workInvoice.getOffice().getId());
				if(workInvoice.getInvoiceDate()!=null){
					buyDetails.setDate(workInvoice.getInvoiceDate());
				}else{
					buyDetails.setDate(workInvoice.getUpdateDate());
				}
				if (StringUtils.isBlank(buyDetails.getId())){
					buyDetails.preInsert();
					workInvoiceDetailDao.insert(buyDetails);
				}else{
					if(buyDetails!=null){
						WorkInvoiceDetail w1 = workInvoiceDetailDao.get(buyDetails.getId());//从数据库取出记录的值
						MyBeanUtils.copyBeanNotNull2Bean(buyDetails, w1);//将编辑表单中的非NULL值覆盖数据库记录中的值
						buyDetails.preUpdate();
						workInvoiceDetailDao.update(w1);
					}
				}
			}else{
				workInvoiceDetailDao.delete(buyDetails);
			}
		}
		}catch (Exception e){
			logger.info(e.getMessage());
		}
	}

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

		ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processType, businessKey, variables);
		workInvoice.setProcessInstance(processInstance);
		if (StringUtils.isNotBlank(processInstanceId)) {
			workActivityProcessService.updateProcessInstanceId(processInstance.getId(),processInstanceId);
			workActivityProcessService.deleteProcessInstanceId(processInstanceId);
			workActivityProcessService.deleteProcessIdAuditUsers(processInstanceId);
		}
		// 更新流程实例ID
		workInvoice.setProcessInstanceId(processInstance.getId());
		workInvoiceAlterDao.updateProcessInstanceId(workInvoice);
		List<Activity> list = workActivityMenu.getActivities();
		if (list != null && list.size() != 0) {
			workActivityProcessService.saveList(list, processInstance.getId());
		} else {
			WorkActivityProcess workActivityProcess = new WorkActivityProcess();
			workActivityProcess.setProcessKey("workinvoicealter");
			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(WorkInvoiceAlter workInvoice) {
		super.delete(workInvoice);
		for (WorkInvoiceDetail workAccount : workInvoice.getWorkAccountList()){
			workInvoiceDetailDao.delete(workAccount);
		}
		WorkProjectNotify notify = new WorkProjectNotify();
		notify.setNotifyId(workInvoice.getId());
		workProjectNotifyService.readByNotifyId(notify);
		if(workInvoice.getWorkInvoice()!= null){
			if(StringUtils.isNotBlank(workInvoice.getWorkInvoice().getId())){
				WorkInvoice w = workInvoiceService.get(workInvoice.getWorkInvoice().getId());
				w.setInvoiceState("5");
				workInvoiceService.save(w);
			}
		}
	}
	
	public Page<WorkClientInfo> findPageByclient(Page<WorkClientInfo> page, WorkClientInfo client) {
		client.setPage(page);
		page.setList(dao.findListByclient(client));
		return page;
	}
	public Page<WorkBidProject> findPageByproject(Page<WorkBidProject> page, WorkBidProject project) {
		project.setPage(page);
		page.setList(dao.findListByproject(project));
		return page;
	}

	/**
	 * 审核流程
	 * @param workInvoice
	 */
	@Transactional(readOnly = false)
	public String auditSave(WorkInvoiceAlter workInvoice,List<User> auditUsers) {
		String  str ="";
		//所属部门
		Office office = officeService.get(workInvoice.getOffice().getId());
		String userName = UserUtils.get(workInvoice.getCreateBy().getId()).getName();
		str = "发票申请编号："+workInvoice.getNumber()+",实际开票单位："+workInvoice.getClient().getName()+",创建人："+userName+",所属部门:"+office.getName();
		String title = "实际开票单位:"+workInvoice.getClient().getName();
		// 对不同环节的业务逻辑进行操作
		String taskDefKey = workInvoice.getAct().getTaskDefKey();
		if (!"modifyApply".equals(taskDefKey)) {
			actTaskService.claim(workInvoice.getAct().getTaskId(), UserUtils.getUser().getId());
		}else {
			workInvoice.getAct().setFlag("yes");
			updateWorkInvoiceInfo(workInvoice);
		}
		String comment = "";
		if (workInvoice.getInvoiceState().equals("4")){
			comment = ("yes".equals(workInvoice.getAct().getFlag())?"[重新申请] ":"[已撤销] ");
		}else {
			comment = ("yes".equals(workInvoice.getAct().getFlag())?"[同意] ":"[驳回] ")+workInvoice.getAct().getComment();
		}
		//yes 的时候状态为审核通过 否则为未通过
		//2 审核中 4 驳回
		workInvoice.setInvoiceState(("yes".equals(workInvoice.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(workInvoice.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(workInvoice.getProcessInstanceId());
		List<WorkActivityProcess> workActivityProcesses = workActivityProcessService.findList(selectProcess);
		List<Activity> activities = workActivityMenu.getActivities();
		if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("workinvoicealter")) {
			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(workInvoice.getAct().getFlag())) {
						workInvoice.setInvoiceState("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(workInvoice.getAct().getFlag())) {
						workInvoice.setInvoiceState("3");
						workActivityProcess.setIsApproval("2");
					} else {
						workActivityProcess.setIsApproval("1");
					}
					break;
				}
			}
		} else {
			workActivityMenu.setProcessType("workinvoicealter");
			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(workInvoice.getAct().getFlag()) &&("1").equals(workInvoice.getExt())) {
						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 = "cwzg";
					if (!"yes".equals(workInvoice.getAct().getFlag())) {
						workInvoice.setInvoiceState("3");
					}
					break;
				} else if ("apply_end".equals(taskDefKey)) {
				}

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

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

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

							}
						}
					}else {
						WorkProjectNotify notify = new WorkProjectNotify();
						notify.setNotifyId(workInvoice.getId());
						userList = workProjectNotifyService.readByNotifyId(notify);
						users.addAll(userList);
						users.add(workInvoice.getCreateBy());
						workProjectNotifyService
								.save(UtilNotify
										.saveNotify(workInvoice.getId(),
												workInvoice.getCreateBy(),
												workInvoice.getCompanyId(),
												title,
												str,
												"48",
												"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());
			}
		}
		workInvoiceAlterDao.update(workInvoice);
		if("5".equals(workInvoice.getInvoiceState())){
			if(workInvoice.getWorkInvoice()!=null){
				WorkInvoice workInvoice1 = invoiceService.get(workInvoice.getWorkInvoice().getId());
				workInvoice1.setInvoiceState("5");
				invoiceService.save(workInvoice1);
				List<WorkInvoiceDetail> list2 = workInvoice1.getWorkAccountList();
				if(list2!=null && list2.size()>0){
					for (WorkInvoiceDetail w:
						 list2) {
						workInvoiceDetailService.delete(w);
					}
				}
				if(StringUtils.isNotBlank(workInvoice.getId())){
					WorkInvoiceDetail workInvoiceDetail = new WorkInvoiceDetail();
					workInvoiceDetail.setAinvoiceId(workInvoice.getId());
					List<WorkInvoiceDetail> list = workInvoiceDetailDao.afindList(workInvoiceDetail);
					for(WorkInvoiceDetail workInvoiceDetail1 : list){
						workInvoiceDetail1.setInvoiceId(workInvoice.getWorkInvoice().getId());
						workInvoiceDetailService.save(workInvoiceDetail1);
					}
				}
			}
		}
		return "保存审核意见成功！";
	}



	/**
	 * 获取流程详细信息
	 * @param processInstanceId
	 */
	@SuppressWarnings("unchecked")
	public WorkInvoiceAlter getByProcessInstanceId(String processInstanceId) {
		WorkInvoiceAlter workInvoice = dao.getByProcInsId(processInstanceId);
		if(workInvoice!=null&&!workInvoice.equals("")){
			if(workInvoice.getCreateBy()!=null&&!workInvoice.getCreateBy().equals("")){
			if(StringUtils.isNotBlank(workInvoice.getCreateBy().getId())){
				User u = UserUtils.get(workInvoice.getCreateBy().getId());
				if(u!=null &&!u.equals("")){
					workInvoice.setCreateBy(u);
				}
			}
			}
		}
		return workInvoice;
	}
	@Transactional(readOnly = false)
	public void update(WorkInvoiceAlter workInvoice) {
		workInvoice.preUpdate();
		dao.update(workInvoice);
	}

	/**
	 * 强制撤销
	 * @param workInvoice
	 */
	@Transactional(readOnly = false)
	public void cancelInvalidate(WorkInvoiceAlter workInvoice) {
		String invalidateProcessInstanceId = workInvoice.getProcessInstanceId();
		try {
			//将流程图中尚未走到的task的流程追踪信息逻辑删除，添加一条"撤销"流程追踪信息
			WorkActivityProcess process = new WorkActivityProcess();
			process.setProcessInstanceId(workInvoice.getProcessInstanceId());
			process.setIsApproval("0");
			WorkActivityProcess workActivityProcess = new WorkActivityProcess();
			workActivityProcess.setProcessInstanceId(workInvoice.getProcessInstanceId());
			List<WorkActivityProcess> processList = workActivityProcessService.findList(workActivityProcess);
			WorkProjectNotify notify = new WorkProjectNotify();
			notify.setNotifyId(workInvoice.getId());
			workProjectNotifyService.readByNotifyId(notify);
			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, "发票变更申请-撤销");
			workInvoice.setInvoiceState("3");
			workInvoice.preUpdate();
			workInvoiceAlterDao.update(workInvoice);
		} catch (ActivitiObjectNotFoundException e) {
			System.err.println("撤销发票变更申请异常，因为这个流程已不存在!");
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}