
package com.jeeplus.modules.workcontractinfo.service;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.oss.OSSClientUtil;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.service.CrudService;
import com.jeeplus.common.utils.*;
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.act.utils.ProcessDefCache;
import com.jeeplus.modules.alterinfo.entity.AlterInfo;
import com.jeeplus.modules.alterinfo.service.AlterInfoService;
import com.jeeplus.modules.contractclient.dao.WorkContractClientDao;
import com.jeeplus.modules.contractclient.entity.WorkContractClient;
import com.jeeplus.modules.contractclient.service.WorkContractClientService;
import com.jeeplus.modules.isignature.service.ISignatureDocumentService;
import com.jeeplus.modules.serialnum.service.SerialNumTplService;
import com.jeeplus.modules.sys.dao.RoleDao;
import com.jeeplus.modules.sys.entity.MainDictDetail;
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.DictUtils;
import com.jeeplus.modules.sys.utils.RoleActivityEnname;
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.dao.WorkBidProjectDao;
import com.jeeplus.modules.workbidproject.entity.WorkBidProject;
import com.jeeplus.modules.workclientinfo.dao.WorkClientAttachmentDao;
import com.jeeplus.modules.workclientinfo.entity.WorkClientAttachment;
import com.jeeplus.modules.workclientinfo.entity.WorkClientInfo;
import com.jeeplus.modules.workclientinfo.service.WorkClientInfoService;
import com.jeeplus.modules.workcontractinfo.dao.*;
import com.jeeplus.modules.workcontractinfo.entity.WorkContractInfo;
import com.jeeplus.modules.workcontractinfo.entity.WorkContractInfoCopy;
import com.jeeplus.modules.workcontractinfo.entity.WorkContractListInfo;
import com.jeeplus.modules.workcontractinfo.entity.WorkContractReview;
import com.jeeplus.modules.workfullmanage.dao.WorkFullRecordDao;
import com.jeeplus.modules.workfullmanage.entity.WorkFullManage;
import com.jeeplus.modules.workfullmanage.entity.WorkFullRecord;
import com.jeeplus.modules.workinvoicedetail.dao.WorkInvoiceDetailDao;
import com.jeeplus.modules.workinvoicedetail.entity.WorkInvoiceDetail;
import com.jeeplus.modules.workprojectnotify.entity.WorkProjectNotify;
import com.jeeplus.modules.workprojectnotify.service.WorkProjectNotifyService;
import com.jeeplus.modules.workprojectnotify.util.UtilNotify;
import org.activiti.engine.ActivitiObjectNotFoundException;
import org.activiti.engine.HistoryService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricTaskInstanceQuery;
import org.activiti.engine.runtime.ProcessInstance;
import org.apache.commons.beanutils.BeanUtils;
import org.java_websocket.WebSocket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

/**
 * 合同管理Service
 * @author 丁旭
 * @version 2017-03-21
 */
@SuppressWarnings("all")
@Service
@Transactional(readOnly = true)
public class WorkContractInfoService extends CrudService<WorkContractInfoDao, WorkContractInfo> {

	@Autowired
	private AlterInfoService alterInfoService;
	@Autowired
	private WorkActivityProcessDao workActivityProcessDao;
	@Autowired
	private WorkContractAnnexDao workContractAnnexDao;
	@Autowired
	private WorkInvoiceDetailDao workInvoiceDetailDao;
	@Autowired
	private IdentityService identityService;
	@Autowired
	private RuntimeService runtimeService;
	@Autowired
	private WorkContractInfoDao workContractInfoDao;
	@Autowired
	private WorkClientAttachmentDao workClientAttachmentDao;
	@Autowired
	protected HistoryService historyService;
	@Autowired
	private WorkProjectNotifyService workProjectNotifyService;
	@Autowired
	private RoleDao roleDao;
	@Autowired
	private WorkFullRecordDao workFullRecordDao;
	@Autowired
	private OfficeService officeService;
	@Autowired
	private ActTaskService actTaskService;
	@Autowired
	private WorkActivityMenuService workActivityMenuService;
	@Autowired
	private WorkActivityProcessService workActivityProcessService;
	@Autowired
	private ActivityService activityService;
	@Autowired
	private WorkContractReviewDao workContractReviewDao;
	@Autowired
	private ISignatureDocumentService signatureDocumentService;
	@Autowired
	private WorkContractInfoCopyDao workContractInfoCopyDao;
	@Autowired
	private SerialNumTplService serialNumTplService;
	@Autowired
	private WorkContractClientService workContractClientService;
	@Autowired
	private WorkContractClientDao workContractClientDao;
	@Autowired
	private WorkClientInfoService workClientInfoService;
	@Autowired
	private WorkContractListInfoDao workContractListInfoDao;
	@Autowired
	private WorkBidProjectDao workBidProjectDao;

	public WorkContractInfo get(String id) {
		WorkContractInfo workContractInfo = super.get(id);
		/*合同投标项目，则查投标。不是投标项目，不去查*/
		if (workContractInfo != null && "0".equals(workContractInfo.getExt()) && workContractInfo.getProject()!=null && StringUtils.isNotBlank(workContractInfo.getProject().getId())) {
			WorkBidProject workBidProject = workBidProjectDao.get(workContractInfo.getProject().getId());
			if (workBidProject != null) {
				workContractInfo.setProject(workBidProject);
				workContractInfo.setProjectName(workBidProject.getProjectName());
			}
		}

		if(workContractInfo != null){
			WorkClientAttachment workClientAttachment = new WorkClientAttachment();
			workClientAttachment.setAttachmentId(id);
			workClientAttachment.setAttachmentFlag("44");
			workContractInfo.setWorkAttachments(workClientAttachmentDao.findList(workClientAttachment));
			WorkClientAttachment workClientAttachment2 = new WorkClientAttachment();
			workClientAttachment2.setAttachmentId(id);
			workClientAttachment2.setAttachmentFlag("81");
			workContractInfo.setWorkAttachmentAlters(workClientAttachmentDao.findList(workClientAttachment2));
			if(StringUtils.isNotBlank(workContractInfo.getAlterBeforeId())){
				WorkContractInfo oldWorkContractInfo = this.getInfo(workContractInfo.getAlterBeforeId());
				workContractInfo.setOldWorkContractInfo(oldWorkContractInfo);
			}
			String totalContractId = workContractInfo.getTotalContractId();
			if(!Strings.isNullOrEmpty(totalContractId)){
				WorkContractInfo wc = workContractInfoDao.get(totalContractId);
				if(wc != null){
					workContractInfo.setTotalContractName(wc.getName());
				}
			}
			WorkContractReview workContractReview = workContractReviewDao.getByContractId(workContractInfo.getId());
			if (workContractReview!=null){
				WorkClientAttachment clientAttachment = new WorkClientAttachment();
				clientAttachment.setAttachmentId(workContractReview.getId());
				clientAttachment.setAttachmentFlag("80");
				workContractReview.setWorkAttachments(workClientAttachmentDao.findList(clientAttachment));
				workContractInfo.setWorkContractReview(workContractReview);
			}
			AlterInfo alterInfo = new AlterInfo();
			alterInfo.setBeforeId(workContractInfo.getId());
			List<AlterInfo> list = alterInfoService.findList(alterInfo);
			if(list!=null && list.size()>0){
				workContractInfo.setAlterInfo(list.get(0));
			}
			WorkContractClient workContractClient = new WorkContractClient();
			workContractClient.setContractId(workContractInfo.getId());
			List<WorkContractClient> list1 = workContractClientService.findList(workContractClient);
			List<WorkClientInfo> list2 = new ArrayList<>();
			if(list1!=null && list1.size()>0){
				for(WorkContractClient w :list1){
					WorkClientInfo workClientInfo = workClientInfoService.get(w.getClientId());
					list2.add(workClientInfo);
				}
			}
			if ("5".equals(workContractInfo.getContractState())){
				WorkInvoiceDetail invoice = new WorkInvoiceDetail();
				invoice.setId(id);
				List<WorkInvoiceDetail> invoiceDetails =workInvoiceDetailDao.findListByContractInfo(invoice);
				List<WorkInvoiceDetail> invoiceDetailList =new ArrayList<>();
				if (invoiceDetails!=null && invoiceDetails.size()!=0){
					WorkInvoiceDetail workInvoiceDetailTotal = new WorkInvoiceDetail();
					BigDecimal totalMoneys = new BigDecimal("0.00");
					BigDecimal taxMoneys = new BigDecimal("0.00");
					BigDecimal taxRates = new BigDecimal("0.00");
					BigDecimal incomeMoneys = new BigDecimal("0.00");
					workInvoiceDetailTotal.setCode("合计");
					for (WorkInvoiceDetail workInvoiceDetail :invoiceDetails){
						totalMoneys = totalMoneys.add(new BigDecimal(StringUtils.isBlank(workInvoiceDetail.getTotalMoney())?"0.00":workInvoiceDetail.getTotalMoney()));
						taxMoneys = incomeMoneys.add(new BigDecimal(StringUtils.isBlank(workInvoiceDetail.getTaxMoney())?"0.00":workInvoiceDetail.getTaxMoney()));
						taxRates = taxRates.add(new BigDecimal(StringUtils.isBlank(workInvoiceDetail.getTaxRate())?"0.00":workInvoiceDetail.getTaxRate()));
						incomeMoneys = incomeMoneys.add(new BigDecimal(StringUtils.isBlank(workInvoiceDetail.getIncomeMoney())?"0.00":workInvoiceDetail.getIncomeMoney()));
						invoiceDetailList.add(workInvoiceDetail);
					}
					workInvoiceDetailTotal.setTotalMoney(totalMoneys+"");
					workInvoiceDetailTotal.setTaxMoney(taxMoneys+"");
					workInvoiceDetailTotal.setTaxRate(taxRates+"");
					workInvoiceDetailTotal.setIncomeMoney(incomeMoneys+"");
					invoiceDetailList.add(workInvoiceDetailTotal);
					workContractInfo.setInvoiceDetails(invoiceDetailList);
				}
			}
			workContractInfo.setWorkClientInfoList(list2);
		}
		return workContractInfo;
	}
	public String getTotal(String id) {
		WorkContractInfo workContractInfo = super.get(id);
		String str = "";
		if(workContractInfo != null){
			if ("5".equals(workContractInfo.getContractState())){
				WorkInvoiceDetail invoice = new WorkInvoiceDetail();
				invoice.setId(id);
				List<WorkInvoiceDetail> invoiceDetails =workInvoiceDetailDao.findListByContractInfo(invoice);
				if (invoiceDetails!=null && invoiceDetails.size()!=0){
					WorkInvoiceDetail workInvoiceDetailTotal = new WorkInvoiceDetail();
					BigDecimal incomeMoneys = new BigDecimal("0.00");
					workInvoiceDetailTotal.setCode("合计");
					for (WorkInvoiceDetail workInvoiceDetail :invoiceDetails){
						incomeMoneys = incomeMoneys.add(new BigDecimal(StringUtils.isBlank(workInvoiceDetail.getIncomeMoney())?"0.00":workInvoiceDetail.getIncomeMoney()));
					}
					str = incomeMoneys+"";
				}
			}
		}
		if(StringUtils.isBlank(str)){
			str = "0.00";
		}
		return str;
	}
	public WorkContractInfo getInfo(String id) {
		WorkContractInfo workContractInfo = super.get(id);

		if(workContractInfo != null){
			WorkClientAttachment workClientAttachment = new WorkClientAttachment();
			workClientAttachment.setAttachmentId(id);
			workClientAttachment.setAttachmentFlag("44");
			workContractInfo.setWorkAttachments(workClientAttachmentDao.findList(workClientAttachment));
			WorkClientAttachment workClientAttachment2 = new WorkClientAttachment();
			workClientAttachment2.setAttachmentId(id);
			workClientAttachment2.setAttachmentFlag("81");
			workContractInfo.setWorkAttachmentAlters(workClientAttachmentDao.findList(workClientAttachment2));
			String totalContractId = workContractInfo.getTotalContractId();
			if(!Strings.isNullOrEmpty(totalContractId)){
				WorkContractInfo wc = workContractInfoDao.get(totalContractId);
				if(wc != null){
					workContractInfo.setTotalContractName(wc.getName());
				}
			}
			WorkContractReview workContractReview = workContractReviewDao.getByContractId(workContractInfo.getId());
			if (workContractReview!=null){
				WorkClientAttachment clientAttachment = new WorkClientAttachment();
				clientAttachment.setAttachmentId(workContractReview.getId());
				clientAttachment.setAttachmentFlag("80");
				workContractReview.setWorkAttachments(workClientAttachmentDao.findList(clientAttachment));
				workContractInfo.setWorkContractReview(workContractReview);
			}
			AlterInfo alterInfo = new AlterInfo();
			alterInfo.setBeforeId(workContractInfo.getId());
			List<AlterInfo> list = alterInfoService.findList(alterInfo);
			if(list!=null && list.size()>0){
				workContractInfo.setAlterInfo(list.get(0));
			}
			WorkContractClient workContractClient = new WorkContractClient();
			workContractClient.setContractId(workContractInfo.getId());
			List<WorkContractClient> list1 = workContractClientService.findList(workContractClient);
			List<WorkClientInfo> list2 = new ArrayList<>();
			if(list1!=null && list1.size()>0){
				for(WorkContractClient w :list1){
					WorkClientInfo workClientInfo = workClientInfoService.get(w.getClientId());
					list2.add(workClientInfo);
				}
			}
			workContractInfo.setWorkClientInfoList(list2);
		}
		return workContractInfo;
	}
	public WorkContractInfo getByBeforeId(String id) {
		WorkContractInfo workContractInfo = workContractInfoDao.getByBeforeId(id);

		if(workContractInfo != null){
			WorkClientAttachment workClientAttachment = new WorkClientAttachment();
			workClientAttachment.setAttachmentId(id);
			workClientAttachment.setAttachmentFlag("44");
			workContractInfo.setWorkAttachments(workClientAttachmentDao.findList(workClientAttachment));
			WorkClientAttachment workClientAttachment2 = new WorkClientAttachment();
			workClientAttachment2.setAttachmentId(workContractInfo.getId());
			workClientAttachment2.setAttachmentFlag("81");
			workContractInfo.setWorkAttachmentAlters(workClientAttachmentDao.findList(workClientAttachment2));

			String totalContractId = workContractInfo.getTotalContractId();
			if(!Strings.isNullOrEmpty(totalContractId)){
				WorkContractInfo wc = workContractInfoDao.get(totalContractId);
				if(wc != null){
					workContractInfo.setTotalContractName(wc.getName());
				}
			}
			WorkContractReview workContractReview = workContractReviewDao.getByContractId(workContractInfo.getId());
			if (workContractReview!=null){
				WorkClientAttachment clientAttachment = new WorkClientAttachment();
				clientAttachment.setAttachmentId(workContractReview.getId());
				clientAttachment.setAttachmentFlag("80");
				workContractReview.setWorkAttachments(workClientAttachmentDao.findList(clientAttachment));
				workContractInfo.setWorkContractReview(workContractReview);
			}
			AlterInfo alterInfo = new AlterInfo();
			if(StringUtils.isNotBlank(workContractInfo.getAlterBeforeId())){
				alterInfo.setBeforeId(workContractInfo.getAlterBeforeId());
			}else{
				alterInfo.setBeforeId(workContractInfo.getId());
			}
			List<AlterInfo> list = alterInfoService.findList(alterInfo);
			if(list!=null && list.size()>0){
				workContractInfo.setAlterInfo(list.get(0));
			}
		}
		return workContractInfo;
	}

	public List<WorkContractInfo> findList(WorkContractInfo workContractInfo) {
		if (StringUtils.isNotBlank(workContractInfo.getTotalContractIds())){
			workContractInfo.setTotalContractIds(","+workContractInfo.getTotalContractIds()+",");
		}
		return super.findList(workContractInfo);
	}

	public Page<WorkContractInfo> findPage(Page<WorkContractInfo> page, WorkContractInfo workContractInfo) {
		if (StringUtils.isNotBlank(workContractInfo.getTotalContractIds())){
			workContractInfo.setTotalContractIds(","+workContractInfo.getTotalContractIds()+",");
		}
		String companyId = UserUtils.getUser().getComId();
//		workContractInfo.getSqlMap().put("dsf", dataScopeFilter(workContractInfo.getCurrentUser(), "o", "u","s", MenuStatusEnum.WORK_CONTRACT_INFO.getValue()));
		workContractInfo.getSqlMap().put("dsf","and (a.company_id='"+companyId+"')");
		int count = dao.queryCount(workContractInfo);
		page.setCount(count);
		page.setCountFlag(false);
		workContractInfo.setPage(page);
		List<WorkContractInfo> list = super.findList(workContractInfo);
		//List<WorkContractInfo> workContracts = new ArrayList<>();
		/*for (WorkContractInfo contractInfo:workContractInfos){
			WorkContractInfo workContractInfo1 = new WorkContractInfo();
			workContractInfo1.setTotalContractId(contractInfo.getId());
			List<WorkContractInfo> workContractInfoList = super.findList(workContractInfo1);
			if (workContractInfoList!=null && workContractInfoList.size()!=0){
				workContracts.addAll(workContractInfoList);
			}
		}*/
		//workContracts.addAll(workContractInfos);
		//sortList(list,workContracts,"0",true);
		//sortList(list,dao.findList(workContractInfo),"0",true);
		page.setList(list);
		return page;
	}
	public Page<WorkContractInfo> findPageReceipts(Page<WorkContractInfo> page, WorkContractInfo workContractInfo) {
		if (StringUtils.isNotBlank(workContractInfo.getTotalContractIds())){
			workContractInfo.setTotalContractIds(","+workContractInfo.getTotalContractIds()+",");
		}
		workContractInfo.setPage(page);
		List<WorkContractInfo> list = Lists.newArrayList();
		String companyId = UserUtils.getUser().getComId();
		workContractInfo.setCompanyId(companyId);
		List<WorkContractInfo> workContractInfos = workContractInfoDao.findListReceipts(workContractInfo);
		page.setList(workContractInfos);
		return page;
	}

	public Page<WorkContractInfo> afindPage(Page<WorkContractInfo> page, WorkContractInfo workContractInfo) {
		if (StringUtils.isNotBlank(workContractInfo.getTotalContractIds())){
			workContractInfo.setTotalContractIds(","+workContractInfo.getTotalContractIds()+",");
		}
        String companyId = UserUtils.getUser().getComId();
//		workContractInfo.getSqlMap().put("dsf", dataScopeFilter(workContractInfo.getCurrentUser(), "o", "u","s", MenuStatusEnum.WORK_CONTRACT_INFO.getValue()));
        workContractInfo.getSqlMap().put("dsf","and (a.company_id='"+companyId+"')");
		workContractInfo.setPage(page);
		List<WorkContractInfo> list = Lists.newArrayList();
		List<WorkContractInfo> workContractInfos = workContractInfoDao.afindList(workContractInfo);
		page.setList(workContractInfos);
		return page;
	}

	public Page<WorkContractInfo> ifindPage(Page<WorkContractInfo> page, WorkContractInfo workContractInfo) {
		if (StringUtils.isNotBlank(workContractInfo.getTotalContractIds())){
			workContractInfo.setTotalContractIds(","+workContractInfo.getTotalContractIds()+",");
		}
//		workContractInfo.getSqlMap().put("dsf", dataScopeFilter(workContractInfo.getCurrentUser(), "o", "u","s", MenuStatusEnum.WORK_CONTRACT_INFO.getValue()));
        String companyId = UserUtils.getUser().getComId();
        workContractInfo.getSqlMap().put("dsf","and (a.company_id='"+companyId+"')");
		workContractInfo.setPage(page);
		List<WorkContractInfo> list = Lists.newArrayList();
		List<WorkContractInfo> workContractInfos = workContractInfoDao.ifindList(workContractInfo);
		page.setList(workContractInfos);
		return page;
	}
	public Page<WorkContractInfoCopy> findAlterPage(Page<WorkContractInfoCopy> page, WorkContractInfoCopy workContractInfoCopy) {
		if (StringUtils.isNotBlank(workContractInfoCopy.getTotalContractIds())){
			workContractInfoCopy.setTotalContractIds(","+workContractInfoCopy.getTotalContractIds()+",");
		}
		workContractInfoCopy.getSqlMap().put("dsf", dataScopeFilter(workContractInfoCopy.getCurrentUser(), "o", "u","s", MenuStatusEnum.WORK_CONTRACT_INFO.getValue()));
		workContractInfoCopy.setPage(page);
		List<WorkContractInfoCopy> list = Lists.newArrayList();
		List<WorkContractInfoCopy> workContractInfos = workContractInfoCopyDao.findList(workContractInfoCopy);
		/*List<WorkContractInfoCopy> workContracts = new ArrayList<>();
		for (WorkContractInfoCopy contractInfo:workContractInfos){
			WorkContractInfoCopy workContractInfo1 = new WorkContractInfoCopy();
			workContractInfo1.setTotalContractId(contractInfo.getId());
			List<WorkContractInfoCopy> workContractInfoList = workContractInfoCopyDao.findList(workContractInfo1);
			if (workContractInfoList!=null && workContractInfoList.size()!=0){
				workContracts.addAll(workContractInfoList);
			}
		}
		workContracts.addAll(workContractInfos);
		sortLists(list,workContracts,"0",true);*/
		page.setList(workContractInfos);
		return page;
	}
	public Page<WorkContractInfo> findPages(Page<WorkContractInfo> page, WorkContractInfo workContractInfo) {
		if (StringUtils.isNotBlank(workContractInfo.getTotalContractIds())){
			workContractInfo.setTotalContractIds(","+workContractInfo.getTotalContractIds()+",");
		}
		workContractInfo.setPage(page);
		List<WorkContractInfo> list = Lists.newArrayList();
		List<WorkContractInfo> workContractInfos = workContractInfoDao.findLists(workContractInfo);
		/*List<WorkContractInfo> workContracts = new ArrayList<>();
		for (WorkContractInfo contractInfo:workContractInfos){
			WorkContractInfo workContractInfo1 = new WorkContractInfo();
			workContractInfo1.setTotalContractId(contractInfo.getId());
			List<WorkContractInfo> workContractInfoList = dao.findList(workContractInfo1);
			if (workContractInfoList!=null && workContractInfoList.size()!=0){
				workContracts.addAll(workContractInfoList);
			}
		}
		workContracts.addAll(workContractInfos);
		sortList(list,workContracts,"0",true);
		//sortList(list,dao.findList(workContractInfo),"0",true);*/
		page.setList(workContractInfos);
		return page;
	}
	public static void sortList(List<WorkContractInfo> list, List<WorkContractInfo> sourcelist, String parentId, boolean cascade){
		for (int i=0; i<sourcelist.size(); i++){
			WorkContractInfo e = sourcelist.get(i);
			if (e.getTotalContractId()!=null && e.getTotalContractId().equals(parentId)){
				list.add(e);
				if (cascade){
					// 判断是否还有子节点, 有则继续获取子节点
					for (int j=0; j<sourcelist.size(); j++){
						WorkContractInfo child = sourcelist.get(j);
						if (child.getTotalContractId()!=null && child.getTotalContractId().equals(e.getId())){
							sortList(list, sourcelist, e.getId(), true);
							break;
						}
					}
				}
			}
		}
	}
	public static void sortLists(List<WorkContractInfoCopy> list, List<WorkContractInfoCopy> sourcelist, String parentId, boolean cascade){
		for (int i=0; i<sourcelist.size(); i++){
			WorkContractInfoCopy e = sourcelist.get(i);
			if (e.getTotalContractId()!=null && e.getTotalContractId().equals(parentId)){
				list.add(e);
				if (cascade){
					// 判断是否还有子节点, 有则继续获取子节点
					for (int j=0; j<sourcelist.size(); j++){
						WorkContractInfoCopy child = sourcelist.get(j);
						if (child.getTotalContractId()!=null && child.getTotalContractId().equals(e.getId())){
							sortLists(list, sourcelist, e.getId(), true);
							break;
						}
					}
				}
			}
		}
	}
	public Page<WorkContractInfo> findWaitAndFinishList(Page<WorkContractInfo>page, WorkContractInfo workContractInfo,String procInsIds,List <Act> actList ){
		Map<Object,Object> map = new HashMap<Object,Object>();
		List <WorkContractInfo> list =new <WorkContractInfo>ArrayList();
		map.put("procInsIds",procInsIds);
		map.put("workContractInfo",workContractInfo);
		workContractInfo.setPage(page);
		list=workContractInfoDao.findWaitAndFinishList(map);
		for (WorkContractInfo temp :list) {
			for (int i=0;i<actList.size();i++){
				if(temp.getProcessInstanceId().equals(actList.get(i).getProcInsId())){
					temp.setAct(actList.get(i));
				}
			}
		}
		page.setList(list);
		return page;
	}
	@Transactional(readOnly = false)
	public int saveContractPrice(WorkContractInfo workContractInfo) {
		return dao.saveContractPrice(workContractInfo);
	}

	@Transactional(readOnly = false)
	public void save(WorkContractInfo workContractInfo) {
		super.save(workContractInfo);
		for (WorkClientAttachment workClientAttachment : workContractInfo.getWorkAttachments()){
			if (workClientAttachment.getId() == null){
				continue;
			}
			if (WorkClientAttachment.DEL_FLAG_NORMAL.equals(workClientAttachment.getDelFlag())){
				workClientAttachment.setAttachmentId(workContractInfo.getId());
				workClientAttachment.setAttachmentFlag("44");
				workClientAttachment.setAttachmentUser(UserUtils.getUser().getId());
				if (StringUtils.isBlank(workClientAttachment.getId()) || "null".equals(workClientAttachment.getId())){
					workClientAttachment.preInsert();
					workClientAttachmentDao.insert(workClientAttachment);
					signatureDocumentService.createIsignature(workClientAttachment.getUrl(),workClientAttachment.getAttachmentName(),workClientAttachment.getId(),workContractInfo.getName());
				}else{
					workClientAttachment.preUpdate();
					workClientAttachmentDao.update(workClientAttachment);
				}
			}else{
				workClientAttachmentDao.delete(workClientAttachment);
			}
		}
	}
	@Transactional(readOnly = false)
	public void saves(WorkContractInfo workContractInfo) {
		super.save(workContractInfo);
		for (WorkClientAttachment workClientAttachment : workContractInfo.getWorkAttachments()){
			if (workClientAttachment.getId() == null){
				continue;
			}
			if (WorkClientAttachment.DEL_FLAG_NORMAL.equals(workClientAttachment.getDelFlag())){
				workClientAttachment.setAttachmentId(workContractInfo.getId());
				workClientAttachment.setAttachmentFlag("44");
				workClientAttachment.setAttachmentUser(UserUtils.getUser().getId());
				if (StringUtils.isBlank(workClientAttachment.getId()) || "null".equals(workClientAttachment.getId())){
					workClientAttachment.preInsert();
					workClientAttachmentDao.insert(workClientAttachment);
					signatureDocumentService.createIsignature(workClientAttachment.getUrl(),workClientAttachment.getAttachmentName(),workClientAttachment.getId(),workContractInfo.getName());
				}else{
					workClientAttachment.preUpdate();
					workClientAttachmentDao.update(workClientAttachment);
				}
			}else{
				workClientAttachmentDao.delete(workClientAttachment);
			}
		}
	}
	//变更附件
	@Transactional(readOnly = false)
	public void altersaves(WorkContractInfo workContractInfo) {
		super.save(workContractInfo);
		for (WorkClientAttachment workClientAttachment : workContractInfo.getWorkAttachments()){
			if (workClientAttachment.getId() == null){
				continue;
			}
			if (WorkClientAttachment.DEL_FLAG_NORMAL.equals(workClientAttachment.getDelFlag())){
				workClientAttachment.setAttachmentId(workContractInfo.getId());
				workClientAttachment.setAttachmentFlag("81");
				workClientAttachment.setAttachmentUser(UserUtils.getUser().getId());
				if (StringUtils.isBlank(workClientAttachment.getId()) || "null".equals(workClientAttachment.getId())){
					workClientAttachment.preInsert();
					workClientAttachmentDao.insert(workClientAttachment);
					signatureDocumentService.createIsignature(workClientAttachment.getUrl(),workClientAttachment.getAttachmentName(),workClientAttachment.getId(),workContractInfo.getName());
				}else{
					workClientAttachment.preUpdate();
					workClientAttachmentDao.update(workClientAttachment);
				}
			}else{
				workClientAttachmentDao.delete(workClientAttachment);
			}
		}
	}
	@Transactional(readOnly = false)
	public String save(WorkContractInfo workContractInfo,Map<String, Object> variables, String contextPath,String urls) {
		long begin = System.currentTimeMillis();
		String processInstanceId = workContractInfo.getProcessInstanceId();
		String contractTypeCode = workContractInfo.getContractTypeDoc();
		String contractType = "";
		List<MainDictDetail> list1 = DictUtils.getMainDictList("contract_info_type");
		for(MainDictDetail mainDictDetail:list1){
			if(mainDictDetail.getValue().equals(contractTypeCode)){
				  contractType = mainDictDetail.getLabel();
			}
		}
		if (StringUtils.isBlank(workContractInfo.getContractNum())) {
			workContractInfo.setContractNum(serialNumTplService.genSerialNum(UserUtils.get(workContractInfo.getCreateBy().getId()).getCompany(), WorkContractInfo.SERIAL_BIZCODE).replace("TYPE",contractType));
			long end2 = System.currentTimeMillis();
			logger.info("合同送审-项目编码设置任务结束，共耗时：[" + (end2-begin) / 1000 + "]秒");
		}
		long begin2 = System.currentTimeMillis();
		if (StringUtils.isBlank(workContractInfo.getContractNumPath())) {
			String num=workContractInfo.getContractNum();
			long time = System.currentTimeMillis();
			String picNamePhoto = time + ".png";
			ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
			WordToPic.TextToAliyunPic(num, 500, 80, 25,new Color(0,188,212), byteArrayOutputStream);

			byte[] buf = byteArrayOutputStream.toByteArray();
			ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(buf);
			OSSClientUtil ossUtil = new OSSClientUtil();
			ossUtil.uploadFile2OSS(byteArrayInputStream, Global.getContractNumPath(), picNamePhoto);
			workContractInfo.setContractNumPath(Global.getAliyunUrl()+"/"+Global.getContractNumPath()+picNamePhoto);
		}
		workContractInfo.setContractState("2");
		this.save(workContractInfo);
		Office office = officeService.get(workContractInfo.getChargeCompany());
		String str = "合同申请人：" + UserUtils.get(workContractInfo.getCreateBy().getId()).getName() + ",主委托方：" + workContractInfo.getClient().getName() + ",合同所属部门:"+office.getName();
		String title = "合同名称:"+workContractInfo.getName();
		identityService.setAuthenticatedUserId(workContractInfo.getCreateBy().getId());
		String businessKey = workContractInfo.getId().toString();
		WorkActivityMenu workActivityMenu = workActivityMenuService.findByParentAndOffice("zth3125f1f194c82bdea93555c750905", office);
		// 启动流程
		String processType = workActivityMenu.getProcessType();
		StringBuffer buffer = new StringBuffer();
		Activity activity = new Activity();
		WorkProjectNotify workProjectNotify = UtilNotify
				.saveNotify(workContractInfo.getId(),
						null,
						workContractInfo.getCompanyId(),
						title,
						str,
						"16",
						"0",
						"待审批",
						""
				);
		List<User> users = new ArrayList<>();
		String officeId = UserUtils.getSelectOffice().getId();
		List<User>  bmzrs = UserUtils.getByRoleActivityEnname("bmzr",2,office.getId(),"2",workContractInfo.getCreateBy());
//		List<User>  scyfglbzrs = UserUtils.getByRoleActivityEnname("scyfglbzr",1,office.getId(),"2",workContractInfo.getCreateBy());
//		List<User>  fglds = UserUtils.getByRoleActivityEnname("scfgld",3,office.getId(),"2",workContractInfo.getCreateBy());
		long end3 = System.currentTimeMillis();
		logger.info("合同送审-查找人员审核任务结束，共耗时：[" + (end3-begin2) / 1000 + "]秒");
		long begin3 = System.currentTimeMillis();
		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(), "2", workContractInfo.getCreateBy());
					if (enusers.size() == 0) {
						workContractInfo.setContractState("1");
						this.save(workContractInfo);
						return "流程审批人不能为空,角色部门负责人下无用户,请联系管理员！";
					}
					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(), "2", workContractInfo.getCreateBy());
				}
				//人员审批
				if (StringUtils.isNotBlank(activity.getUser().getId())) {
					users.add(activity.getUser());
				}
			}
			workProjectNotify.setId("");
		} else {
			processType = "contractCheck";
			if(bmzrs==null||bmzrs.size()==0){
				workContractInfo.setContractState("1");
				this.save(workContractInfo);
				return "流程审批人不能为空,角色部门负责人下无用户,请联系管理员！";
			}
			variables.put("bmzrList", bmzrs);
			variables.put("bmzrCount",bmzrs.size());
			users.addAll(bmzrs);
		}

		for (User u : users) {
			workProjectNotify.setUser(u);
			workProjectNotify.setId("");
			workProjectNotify.setNotifyRole("部门主任审批");
			workProjectNotifyService
					.save(workProjectNotify);
			Map<String,Object> extras = new HashMap<>();
			extras.put("type","7002");
			extras.put("id",workProjectNotify.getId());
			extras.put("procDefKey","16");
			UserUtils.pushInfoToApp(title,str,extras,u.getId());
			UserUtils.pushIm(u.getId(),str);
		}
		variables.put("type", processType);
		variables.put("busId", businessKey);
//		variables.put("count",users.size());
//		variables.put("assigneeList",users);
		variables.put("title", "合同名称:" + workContractInfo.getName());//设置标题；
		long s1 = System.currentTimeMillis();
		ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processType, businessKey, variables);
		long s2 = System.currentTimeMillis();
		workContractInfo.setProcessInstance(processInstance);
		if (StringUtils.isNotBlank(processInstanceId)) {
			workActivityProcessService.updateProcessInstanceId(processInstance.getId(),processInstanceId);
			workActivityProcessService.deleteProcessInstanceId(processInstanceId);
			workActivityProcessService.deleteProcessIdAuditUsers(processInstanceId);
		}
		// 更新流程实例ID
		workContractInfo.setProcessInstanceId(processInstance.getId());
		workContractInfoDao.updateProcessInstanceId(workContractInfo);

		List<Activity> list = workActivityMenu.getActivities();
		if (list != null && list.size() != 0) {
			workActivityProcessService.saveList(list, processInstance.getId());
		} else {
			WorkActivityProcess workActivityProcess = new WorkActivityProcess();
			workActivityProcess.setProcessKey("contractCheck");
			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(bmzrs,processInstance.getId(),1,1);
//			workActivityProcessService.insertAuditsByType(scyfglbzrs,processInstance.getId(),2,0);
//			workActivityProcessService.insertAuditsByType(fglds,processInstance.getId(),3,0);
		}
		long end = System.currentTimeMillis();
		logger.info("合同送审任务结束，共耗时：[" + (end-begin) / 1000 + "]秒,流程启动时间："+(s2-s1)+"ms");
		return "";
	}
	/**
	 * 合同变更启动流程
	 * @param
	 */
	@Transactional(readOnly = false)
	public void startProcess(WorkContractInfo workContractInfo, Map<String, Object> variables) {
		// 用来设置启动流程的人员ID，引擎会自动把用户ID保存到activiti:initiator中
		identityService.setAuthenticatedUserId(workContractInfo.getCurrentUser().getId());
		WorkActivityMenu workActivityMenu = workActivityMenuService.findByParentAndOffice("1663125f1f194c82bdea93555c750904",officeService.get(workContractInfo.getChargeCompany()));
		// 启动流程
		String businessKey = workContractInfo.getId().toString();
		String processType = workActivityMenu.getProcessType();
		String buffer = UserUtils.getRoleActivityEnname(workContractInfo.getCompanyId(),workContractInfo.getCreateBy());
		Activity activity = new Activity();
		if (StringUtils.isNotBlank(workActivityMenu.getId())){
			workActivityMenu = workActivityMenuService.get(workActivityMenu.getId());
			List<Activity> activities = workActivityMenu.getActivities();
			for (Activity a:activities){
				if (a.getDelFlag().equals("0") && a.getCount() == 1){
					activity = a;
				}
			}
			buffer = activity.getRole().getEnname();
			/*variables.put("type", workActivityMenu.getProcessType());*/
		}else {
			processType= "contractChange";
			/*variables.put("type", "caseInfo");*/
			buffer += RoleActivityEnname.SCBZR;
			List<String> assigneeList=new ArrayList<String>(); //分配任务的人员
			String officeId = UserUtils.getSelectOffice().getId();
			String enname = UserUtils.getRoleActivityEnname(UserUtils.getSelectCompany().getId(),workContractInfo.getCreateBy());
			List<User>  uList = UserUtils.getByRoleActivityEnname(enname + RoleActivityEnname.BMZR,2,officeId,"2",workContractInfo.getCreateBy());
			if(uList!=null&&uList.size()>0){
				for (User u:
						uList) {
					assigneeList.add(u.getId());
				}
			}
		}
		variables.put("type", processType);
		variables.put("busId", businessKey);
		variables.put("title", workContractInfo.getRemarks());//设置标题；
		ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processType, businessKey, variables);
		workContractInfo.setProcessInstance(processInstance);
		// 更新流程实例ID
		workContractInfo.setProcessInstanceId(processInstance.getId());
		dao.updateProcessInstanceId(workContractInfo);

		List<Activity> list= workActivityMenu.getActivities();
		if (list!=null && list.size()!=0){
			workActivityProcessService.saveList(list,processInstance.getId());
		}else {
			WorkActivityProcess workActivityProcess = new WorkActivityProcess();
			workActivityProcess.setProcessKey("contractChange");
			workActivityProcess.setCount(1);
			workActivityProcess.setProcessInstanceId(processInstance.getId());
			workActivityProcess.setIsApproval("0");
			workActivityProcess.setActivity(new Activity("166qqqqf1f194c82bdea93555c750904"));
			workActivityProcessService.save(workActivityProcess);
		}

		WorkProjectNotify workProjectNotify = new WorkProjectNotify();
		workProjectNotify.setTitle("合同变更申请");
		workProjectNotify.setNotifyId(workContractInfo.getId());
		workProjectNotify.setCompanyId(workContractInfo.getCompanyId());
		workProjectNotify.setContent(UserUtils.get(workContractInfo.getCreateBy().getId()).getName()+"发起合同变更,请审批!");
		workProjectNotify.setType("16");//通知类型
		workProjectNotify.setStatus("0");
		workProjectNotify.setRemarks("待审批");
		if(workActivityMenu!=null&&StringUtils.isNotBlank(workActivityMenu.getId())&&StringUtils.isNotBlank(activity.getId())){
			//角色审批
			if(StringUtils.isNotBlank(activity.getRole().getEnname())){
				workProjectNotify.setNotifyRole(buffer);
			}
			//人员审批
			if(StringUtils.isNotBlank(activity.getUser().getId())){
				workProjectNotify.setUser(new User(activity.getUser().getId()));
			}
			workProjectNotifyService.save(workProjectNotify);
		}else {
			String enname = UserUtils.getRoleActivityEnname(UserUtils.getSelectCompany().getId(),workContractInfo.getCreateBy());
			//List<String> assigneeLists=new ArrayList<String>(); //分配任务的人员
			//businessType 1:全平台   2:合同模块 	3:合同归档 	4:项目登记 	5:开票管理
			// 6:退票管理 	7:收入管理 	8:报销管理 	9:月度计划管理 ; 1公司2部门3分公司
			String officeId = UserUtils.getSelectOffice().getId();
			List<User>  uList = UserUtils.getByRoleActivityEnname(enname + RoleActivityEnname.BMZR,2,officeId,"2",workContractInfo.getCreateBy());
			if(uList!=null&&uList.size()>0){
				for (User u:
						uList) {
					workProjectNotify.setUser(new User(u.getId()));
					workProjectNotifyService.save(workProjectNotify);
				}
			}
		}

	}
	@Transactional(readOnly = false)
	public void delete(WorkContractInfo workContractInfo) {
		super.delete(workContractInfo);
//		WorkClientAttachment workClientAttachment=workContractInfo.getWorkContractAnnexList().get(0);


	}
	@Transactional(readOnly = false)
	public void abandoned(WorkContractInfo workContractInfo) {
		super.save(workContractInfo);
//		workContractAnnexDao.delete(new WorkContractAnnex(workContractInfo));
	}

	public Page<WorkClientInfo> findPageByclient(Page<WorkClientInfo> page, WorkClientInfo client) {
		client.setPage(page);
		page.setList(dao.findListByclient(client));
		return page;
	}
	public WorkContractInfo getByProcessInstanceId(String processInstanceId){
		WorkContractInfo workClientInfo = workContractInfoDao.getByProcessInstanceId(processInstanceId);
		return workClientInfo;
	}
	/**
	 * 工单执行（完成任务）
	 * @param workContractInfo
	 * @param
	 * @return
	 */
	@Transactional(readOnly = false)
	public String auditSave(WorkContractInfo workContractInfo,String [] status,List<User> auditUsers){
		Office office = officeService.get(workContractInfo.getChargeCompany());
		String str = "合同申请人：" + UserUtils.get(workContractInfo.getCreateBy().getId()).getName() + ",主委托方：" + workContractInfo.getClient().getName() + ",合同所属部门:"+office.getName();
		String title = "合同名称:"+workContractInfo.getName();
		// 对不同环节的业务逻辑进行操作
		String taskDefKey = workContractInfo.getAct().getTaskDefKey();
		if (!"modifyApply".equals(taskDefKey)) {
			actTaskService.claim(workContractInfo.getAct().getTaskId(), UserUtils.getUser().getId());
		}else {
			workContractInfo.getAct().setFlag("yes");
			updateWorkContractInfo(workContractInfo);
		}
		String comment = "";
		if (workContractInfo.getContractState().equals("3")){
			comment = ("yes".equals(workContractInfo.getAct().getFlag())?"[重新申请] ":"[已撤销] ");
		}else {
			if(StringUtils.isNotBlank(workContractInfo.getAct().getComment())){
				comment = ("yes".equals(workContractInfo.getAct().getFlag())?"[同意] ":"[驳回] ")+workContractInfo.getAct().getComment();
			}else{
				comment = ("yes".equals(workContractInfo.getAct().getFlag())?"[同意] ":"[驳回] ");
			}
		}
		//yes 的时候状态为审核通过 否则为未通过
		workContractInfo.setContractState(("yes".equals(workContractInfo.getAct().getFlag())?"2":"4"));
		//String buffer = UserUtils.getRoleActivityEnname(workContractInfo.getCompanyId(),workContractInfo.getCreateBy());
		Map<String, Object> vars = Maps.newHashMap();
		//业务逻辑对应的条件表达式
		String exp = "";
		String taskCount = "";
		String notifyRole = "";
		int key = 0;
		String enname = "";
		List<Activity> activitieList = activityService.getByProcessInstanceId(workContractInfo.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(workContractInfo.getProcessInstanceId());
		List<WorkActivityProcess> workActivityProcesses = workActivityProcessService.findList(selectProcess);
		List<Activity> activities = workActivityMenu.getActivities();
		if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("contractCheck")) {
			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(workContractInfo.getAct().getFlag())) {
						workContractInfo.setContractState("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(workContractInfo.getAct().getFlag())) {
						workContractInfo.setContractState("3");
						workActivityProcess.setIsApproval("2");
					} else {
						workActivityProcess.setIsApproval("1");
					}
					break;
				}
			}
		}else {
			workActivityMenu.setProcessType("contractCheck");
			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 ("bmzr".equals(taskDefKey) && count.contains("1")) {
					taskCount = "1";
					exp = "pass";
					if("yes".equals(workContractInfo.getAct().getFlag())){
						notifyRole = "审核通过";
						workActivityProcess.setIsApproval("1");
					}else{
						notifyRole = "调整申请";
						workActivityProcess.setIsApproval("2");
					}
				}else if ("modifyApply".equals(taskDefKey)&& count.contains("0")) {
					notifyRole = "部门主任审批";
					taskCount = "0";
					exp = "pass";
					workActivityProcess.setCount(0);
					enname = "bmzr";
					if (!"yes".equals(workContractInfo.getAct().getFlag())) {
						workContractInfo.setContractState("3");
					}
					break;
				}
			}
		}
		//workActivityProcessService.updateProcess(workActivityProcess,workActivityMenu,key,taskCount,workContractInfo.getProcessInstanceId(),taskDefKey,"modifyApply",workContractInfo.getAct().getFlag(),comment, activities);
		// 设置意见
		workContractInfo.getAct().setComment(("yes".equals(workContractInfo.getAct().getFlag()) ? "[同意] " : "[驳回] ") + workContractInfo.getAct().getComment());
		workContractInfo.preUpdate();
		// 提交流程任务
		vars.put(exp, "yes".equals(workContractInfo.getAct().getFlag())? true : false);
		vars.put("passs", true);
		workActivityProcessService.updateProcess(workActivityProcess,workActivityMenu,key,taskCount,workContractInfo.getProcessInstanceId(),taskDefKey,"modifyApply",workContractInfo.getAct().getFlag(),comment, activities);
		// 提交流程任务
		actTaskService.complete(workContractInfo.getAct().getTaskId(), workContractInfo.getAct().getProcInsId(), workContractInfo.getAct().getComment(), vars);
		boolean state = actTaskService.isProcessEnd(workContractInfo.getAct().getProcInsId());
		List<User> users = new ArrayList<>();
		List<User> userList = new ArrayList<>();
		if(!state) {
			str = "合同编号：" + workContractInfo.getContractNum() + ",主委托方：" + workContractInfo.getClient().getName() + ",合同所属部门:"+office.getName();
			title = "合同名称:"+workContractInfo.getName();
			users.add(workContractInfo.getCreateBy());
			if ("yes".equals(workContractInfo.getAct().getFlag())) {
				workContractInfo.setContractState("5");
				WorkProjectNotify notify = new WorkProjectNotify();
				notify.setNotifyId(workContractInfo.getId());
				userList = workProjectNotifyService.readByNotifyId(notify);
				workProjectNotifyService
						.save(UtilNotify
								.saveNotify(workContractInfo.getId(),
										workContractInfo.getCreateBy(),
										workContractInfo.getCompanyId(),
										title,
										str,
										"16",
										"0",
										"待通知",
										notifyRole));

			} else {
				WorkProjectNotify notify = new WorkProjectNotify();
				notify.setNotifyId(workContractInfo.getId());
				userList = workProjectNotifyService.readByNotifyId(notify);
				if (StringUtils.isNotBlank(workContractInfo.getContractState()) && !("3").equals(workContractInfo.getContractState())){
					workContractInfo.setContractState("4");
					workProjectNotifyService
							.save(UtilNotify
									.saveNotify(workContractInfo.getId(),
											workContractInfo.getCreateBy(),
											workContractInfo.getCompanyId(),
											title,
											str,
											"16",
											"0",
											"待通知",
											notifyRole));
				}
			}
			workActivityProcessService.deleteProcessIdAuditUsers(workContractInfo.getProcessInstanceId());
		}else{
			if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("contractCheck")) {
				WorkProjectNotify notify = new WorkProjectNotify();
				notify.setNotifyId(workContractInfo.getId());
				userList = workProjectNotifyService.readByNotifyId(notify);
				//users.addAll(userList);
				WorkProjectNotify workProjectNotify = UtilNotify
						.saveNotify(workContractInfo.getId(),
								new User(),
								workContractInfo.getCompanyId(),
								title,
								str,
								"16",
								"0",
								"待审批",
								notifyRole);
				List<WorkProjectNotify> workProjectNotifys = activityService.getByFlagAndTaskDefKeyList(
						activities,
						workProjectNotify,
						taskDefKey,
						workContractInfo.getAct().getFlag(),
						taskCount,
						workContractInfo.getCreateBy(),
						workContractInfo.getChargeCompany(),
						"2");
				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<>();
						if ("gzr".equals(taskDefKey)){
							extras.put("type","7001");
						}else {
							extras.put("type","7002");
						}
						extras.put("id",workProjectNotify.getId());
						extras.put("procDefKey","16");
						UserUtils.pushInfoToApp(title,str,extras,workProjectNotify1.getUser().getId());

					}
				}

			} else {
				if (!"yes".equals(workContractInfo.getAct().getFlag())) {
					WorkProjectNotify notify = new WorkProjectNotify();
					notify.setNotifyId(workContractInfo.getId());
					userList = workProjectNotifyService.readByNotifyId(notify);
					//users.addAll(userList);
					workProjectNotifyService
							.save(UtilNotify
									.saveNotify(workContractInfo.getId(),
											workContractInfo.getCreateBy(),
											workContractInfo.getCompanyId(),
											title,
											str,
											"16",
											"0",
											"重新申请",
											notifyRole));
					users.add( workContractInfo.getCreateBy());
				} else {
					if (StringUtils.isNotBlank(enname)) {
						WorkProjectNotify notify = new WorkProjectNotify();
						notify.setNotifyId(workContractInfo.getId());
						userList = workProjectNotifyService.readByNotifyId(notify);
						//users.addAll(userList1);
						WorkProjectNotify workProjectNotify = UtilNotify
								.saveNotify(workContractInfo.getId(),
										new User(),
										workContractInfo.getCompanyId(),
										title,
										str,
										"16",
										"0",
										"待审批",
										notifyRole);
						users.addAll(auditUsers);
						for (User user1:auditUsers){
							workProjectNotify.setUser(user1);
							workProjectNotify.setId("");
							workProjectNotify.setIsNewRecord(false);
							workProjectNotifyService
									.save(workProjectNotify);
							if (!"modifyApply".equals(taskDefKey)){
								Map<String,Object> extras = new HashMap<>();
								if ("gzr".equals(taskDefKey)){
									extras.put("type","7001");
								}else {
									extras.put("type","7002");
								}
								extras.put("id",workProjectNotify.getId());
								extras.put("procDefKey","16");
								UserUtils.pushInfoToApp(title,str,extras,user1.getId());

							}
						}
					}else {
						WorkProjectNotify notify = new WorkProjectNotify();
						notify.setNotifyId(workContractInfo.getId());
						userList = workProjectNotifyService.readByNotifyId(notify);
						users.addAll(userList);
						users.add(workContractInfo.getCreateBy());
						workProjectNotifyService
								.save(UtilNotify
										.saveNotify(workContractInfo.getId(),
												workContractInfo.getCreateBy(),
												workContractInfo.getCompanyId(),
												title,
												str,
												"16",
												"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());
			}
		}
		workContractInfoDao.update(workContractInfo);
		return "保存审核意见成功！";
	}
	/**
	 * 工单执行（完成任务）
	 * @param workContractInfo
	 * @param
	 * @return
	 */
	@Transactional(readOnly = false)
	public String saveAuditCompletion(WorkContractInfo workContractInfo,String [] status,List<User> auditUsers){
		Office office = officeService.get(workContractInfo.getChargeCompany());
		User user = UserUtils.getUser();
		String title = "合同名称:"+workContractInfo.getName();
		WorkInvoiceDetail invoice = new WorkInvoiceDetail();
		invoice.setId(workContractInfo.getId());
		List<WorkInvoiceDetail> invoiceDetails =workInvoiceDetailDao.findListByContractInfo(invoice);
		String str ="合同所属部门:"+office.getName()+ "合同申请人:" + UserUtils.get(workContractInfo.getCreateBy().getId()).getName() + ",主委托方:" + workContractInfo.getClient().getName() +",收款金额:"+getTotal(workContractInfo.getId());

		// 对不同环节的业务逻辑进行操作
		String taskDefKey = workContractInfo.getAct().getTaskDefKey();
		if (!"modifyApply".equals(taskDefKey)) {
			actTaskService.claim(workContractInfo.getAct().getTaskId(), UserUtils.getUser().getId());
		}else {
			workContractInfo.getAct().setFlag("yes");
			//updateWorkContractInfo(workContractInfo);
		}
		String comment = "";
		if (workContractInfo.getContractState().equals("3")){
			comment = ("yes".equals(workContractInfo.getAct().getFlag())?"[重新申请] ":"[已撤销] ");
		}else {
			if(StringUtils.isNotBlank(workContractInfo.getAct().getComment())){
				comment = ("yes".equals(workContractInfo.getAct().getFlag())?"[同意] ":"[驳回] ")+workContractInfo.getAct().getComment();
			}else{
				comment = ("yes".equals(workContractInfo.getAct().getFlag())?"[同意] ":"[驳回] ");
			}
		}
		//yes 的时候状态为审核通过 否则为未通过
		workContractInfo.setCompletionStatus(("yes".equals(workContractInfo.getAct().getFlag())?"2":"4"));
		//String buffer = UserUtils.getRoleActivityEnname(workContractInfo.getCompanyId(),workContractInfo.getCreateBy());
		Map<String, Object> vars = Maps.newHashMap();
		//业务逻辑对应的条件表达式
		String exp = "";
		String taskCount = "";
		String notifyRole = "";
		int key = 0;
		String enname = "";
		List<Activity> activitieList = activityService.getByProcessInstanceId(workContractInfo.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(workContractInfo.getProcessInstanceId());
		List<WorkActivityProcess> workActivityProcesses = workActivityProcessService.findList(selectProcess);
		List<Activity> activities = workActivityMenu.getActivities();
		if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("contractComplete")) {
			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(workContractInfo.getAct().getFlag())) {
						workContractInfo.setCompletionStatus("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(workContractInfo.getAct().getFlag())) {
						workContractInfo.setCompletionStatus("3");
						workActivityProcess.setIsApproval("2");
					} else {
						workActivityProcess.setIsApproval("1");
					}
					break;
				}
			}
		}else {
			workActivityMenu.setProcessType("contractComplete");
			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 ("bmzr".equals(taskDefKey) && count.contains("1")) {
					taskCount = "1";
					exp = "pass";
					if ("yes".equals(workContractInfo.getAct().getFlag())) {
						notifyRole = "审核通过";
						workActivityProcess.setIsApproval("1");
					} else {
						notifyRole = "调整申请";
						workActivityProcess.setIsApproval("2");
					}
				}
				else if ("modifyApply".equals(taskDefKey)&& count.contains("0")) {
					notifyRole = "部门主任确认";
					taskCount = "0";
					exp = "pass";
					workActivityProcess.setCount(0);
					enname = "bmzr";

					if (!"yes".equals(workContractInfo.getAct().getFlag())) {
						workContractInfo.setCompletionStatus("3");
					}

					break;
				}
			}
		}
		//workActivityProcessService.updateProcess(workActivityProcess,workActivityMenu,key,taskCount,workContractInfo.getProcessInstanceId(),taskDefKey,"modifyApply",workContractInfo.getAct().getFlag(),comment, activities);
		// 设置意见
		workContractInfo.getAct().setComment(("yes".equals(workContractInfo.getAct().getFlag()) ? "[同意] " : "[驳回] ") + workContractInfo.getAct().getComment());
		workContractInfo.preUpdate();
		vars.put("passs", true);
		// 提交流程任务
		vars.put(exp, "yes".equals(workContractInfo.getAct().getFlag())? true : false);
		workActivityProcessService.updateProcess(workActivityProcess,workActivityMenu,key,taskCount,workContractInfo.getProcessInstanceId(),taskDefKey,"modifyApply",workContractInfo.getAct().getFlag(),comment, activities);
		// 提交流程任务
		actTaskService.complete(workContractInfo.getAct().getTaskId(), workContractInfo.getAct().getProcInsId(), workContractInfo.getAct().getComment(), vars);
		boolean state = actTaskService.isProcessEnd(workContractInfo.getAct().getProcInsId());
		List<User> users = new ArrayList<>();
		List<User> userList = new ArrayList<>();
		if(!state) {
			str = "合同编号：" + workContractInfo.getContractNum() + ",主委托方：" + workContractInfo.getClient().getName() ;
			title = "合同名称:"+workContractInfo.getName();
			users.add(workContractInfo.getCreateBy());
			if ("yes".equals(workContractInfo.getAct().getFlag())) {
				workContractInfo.setCompletionStatus("5");
				workContractInfo.setContractState("10");
				WorkProjectNotify notify = new WorkProjectNotify();
				notify.setNotifyId(workContractInfo.getId());
				userList = workProjectNotifyService.readByNotifyId(notify);
				workProjectNotifyService
						.save(UtilNotify
								.saveNotify(workContractInfo.getId(),
										workContractInfo.getCreateBy(),
										workContractInfo.getCompanyId(),
										title,
										str,
										"72",
										"0",
										"待通知",
										notifyRole));

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

					}
				}

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

	/* * 变更审核审批保存
	 * @param testAudit
	 */
	@Transactional(readOnly = false)
	public String auditAlterSave(WorkContractInfo workContractInfo,List<User> auditUsers) {
		Office office = officeService.get(workContractInfo.getChargeCompany());
		String str = "合同变更编号"+workContractInfo.getContractNum()+",变更申请人：" + UserUtils.get(workContractInfo.getCreateBy().getId()).getName() + ",主委托方：" + workContractInfo.getClient().getName() + ",合同所属部门:"+office.getName();
		String title = "合同名称:"+workContractInfo.getName();
		// 对不同环节的业务逻辑进行操作
		String taskDefKey = workContractInfo.getAct().getTaskDefKey();
		if (!"modifyApply".equals(taskDefKey) &&!taskDefKey.contains("gzr") ) {
			actTaskService.claim(workContractInfo.getAct().getTaskId(), UserUtils.getUser().getId());
		}else {
			workContractInfo.getAct().setFlag("yes");
			updateWorkContractInfo(workContractInfo);
		}
		String comment = "";
		if (workContractInfo.getAlterState().equals("3")){
			comment = ("yes".equals(workContractInfo.getAct().getFlag())?"[重新申请] ":"[已撤销] ");
		}else {
			comment = ("yes".equals(workContractInfo.getAct().getFlag())?"[同意] ":"[驳回] ")+workContractInfo.getAct().getComment();
		}
		//yes 的时候状态为审核通过 否则为未通过
		workContractInfo.setAlterState(("yes".equals(workContractInfo.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(workContractInfo.getAlterProcessInstanceId());
		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(workContractInfo.getAlterProcessInstanceId());
		List<WorkActivityProcess> workActivityProcesses = workActivityProcessService.findList(selectProcess);
		List<Activity> activities = workActivityMenu.getActivities();
		if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("contractChange")) {
			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(workContractInfo.getAct().getFlag())) {
						workContractInfo.setAlterState("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(workContractInfo.getAct().getFlag())) {
						workContractInfo.setAlterState("3");
						workActivityProcess.setIsApproval("2");
					} else {
						workActivityProcess.setIsApproval("1");
					}
					break;
				}
			}
		}else {
			workActivityMenu.setProcessType("contractChange");
			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 ("bmzr".equals(taskDefKey) && count.contains("1")) {
					taskCount = "1";
					exp = "pass";
					if("yes".equals(workContractInfo.getAct().getFlag())){
						notifyRole = "审核通过";
						workActivityProcess.setIsApproval("1");
					}else{
						notifyRole = "调整申请";
						workActivityProcess.setIsApproval("2");
					}
				}
				else if ("modifyApply".equals(taskDefKey)&& count.contains("0")) {
					notifyRole = "部门主任审批";
					taskCount = "0";
					exp = "pass";
					workActivityProcess.setCount(0);
					enname =  "bmzr";
					if (!"yes".equals(workContractInfo.getAct().getFlag())) {
						workContractInfo.setAlterState("3");
					}
					break;
				}
			}
		}
		//workActivityProcessService.updateProcess(workActivityProcess,workActivityMenu,key,taskCount,workContractInfo.getProcessInstanceId(),taskDefKey,"modifyApply",workContractInfo.getAct().getFlag(),comment, activities);
		// 设置意见
		workContractInfo.getAct().setComment(("yes".equals(workContractInfo.getAct().getFlag()) ? "[同意] " : "[驳回] ") + workContractInfo.getAct().getComment());
		workContractInfo.preUpdate();
		// 提交流程任务
		vars.put(exp, "yes".equals(workContractInfo.getAct().getFlag())? true : false);
		vars.put("passs", true);
		workActivityProcessService.updateProcess(workActivityProcess,workActivityMenu,key,taskCount,workContractInfo.getAlterProcessInstanceId(),taskDefKey,"modifyApply",workContractInfo.getAct().getFlag(),comment, activities);
		// 提交流程任务
		actTaskService.complete(workContractInfo.getAct().getTaskId(), workContractInfo.getAct().getProcInsId(), workContractInfo.getAct().getComment(), vars);
		boolean state = actTaskService.isProcessEnd(workContractInfo.getAct().getProcInsId());
		List<User> users = new ArrayList<>();
		List<User> userList = new ArrayList<>();
		if(!state) {
			str = "合同变更编号"+workContractInfo.getContractNum()+",主委托方：" + workContractInfo.getClient().getName() + ",合同所属部门:"+office.getName();
			title = "合同名称:"+workContractInfo.getName();
			users.add(workContractInfo.getCreateBy());
			if ("yes".equals(workContractInfo.getAct().getFlag())) {
				workContractInfo.setAlterState("5");
				WorkProjectNotify notify = new WorkProjectNotify();
				notify.setNotifyId(workContractInfo.getId());
				userList = workProjectNotifyService.readByNotifyId(notify);
				workProjectNotifyService
						.save(UtilNotify
								.saveNotify(workContractInfo.getId(),
										workContractInfo.getCreateBy(),
										workContractInfo.getCompanyId(),
										title,
										str,
										"44",
										"0",
										"待通知",
										notifyRole));

			} else {
				WorkProjectNotify notify = new WorkProjectNotify();
				notify.setNotifyId(workContractInfo.getId());
				userList = workProjectNotifyService.readByNotifyId(notify);
				if (StringUtils.isNotBlank(workContractInfo.getAlterState()) && !("3").equals(workContractInfo.getAlterState())){
					workContractInfo.setAlterState("4");
					workProjectNotifyService
							.save(UtilNotify
									.saveNotify(workContractInfo.getId(),
											workContractInfo.getCreateBy(),
											workContractInfo.getCompanyId(),
											title,
											str,
											"44",
											"0",
											"待通知",
											notifyRole));
				}
			}
			workActivityProcessService.deleteProcessIdAuditUsers(workContractInfo.getAlterProcessInstanceId());
		}else{
			if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("contractChange")) {
				WorkProjectNotify notify = new WorkProjectNotify();
				notify.setNotifyId(workContractInfo.getId());
				userList = workProjectNotifyService.readByNotifyId(notify);
				WorkProjectNotify workProjectNotify = UtilNotify
						.saveNotify(workContractInfo.getId(),
								new User(),
								workContractInfo.getCompanyId(),
								title,
								str,
								"44",
								"0",
								"待审批",
								notifyRole);
				List<WorkProjectNotify> workProjectNotifys = activityService.getByFlagAndTaskDefKeyList(
						activities,
						workProjectNotify,
						taskDefKey,
						workContractInfo.getAct().getFlag(),
						taskCount,
						workContractInfo.getCreateBy(),
						workContractInfo.getChargeCompany(),
						"2");
				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<>();
						if ("gzr".equals(taskDefKey) ){
							extras.put("type","7001");
						}else {
							extras.put("type","7002");
						}
						extras.put("id",workProjectNotify.getId());
						extras.put("procDefKey","44");
						UserUtils.pushInfoToApp(title,str,extras,workProjectNotify1.getUser().getId());
					}
				}

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

							}
						}
					}else {
						WorkProjectNotify notify = new WorkProjectNotify();
						notify.setNotifyId(workContractInfo.getId());
						userList = workProjectNotifyService.readByNotifyId(notify);
						users.addAll(userList);
						users.add(workContractInfo.getCreateBy());
						workProjectNotifyService
								.save(UtilNotify
										.saveNotify(workContractInfo.getId(),
												workContractInfo.getCreateBy(),
												workContractInfo.getCompanyId(),
												title,
												str,
												"44",
												"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());
			}
		}
		workContractInfo.preUpdate();
		workContractInfoDao.update(workContractInfo);
		String oldid = workContractInfo.getAlterBeforeId();
		if("5".equals(workContractInfo.getAlterState())){
			workContractInfo.setContractState("5");//已签
			workContractInfo.setRecordState("1");//变为待归档
			workContractInfo.setAlterState(null);
			workContractInfo.setProcessInstanceId(workContractInfo.getAlterProcessInstanceId());//更新流程id
			workContractInfo.preUpdate();
			workContractInfoDao.update(workContractInfo);
			if(StringUtils.isNotBlank(oldid)){
				WorkContractInfo w = this.get(oldid);
				w.setAlterState("5");
				w.setContractState("5");
				w.preUpdate();
				workContractInfoDao.update(w);
				//获取附件列表
				List<WorkClientAttachment> list3 = w.getWorkAttachments();
				//获取子表
				WorkContractClient workContractClient = new WorkContractClient();
				workContractClient.setContractId(w.getId());
				List<WorkContractClient> list1 = workContractClientService.findList(workContractClient);
				WorkContractClient workContractClient2 = new WorkContractClient();
				workContractClient2.setContractId(workContractInfo.getId());
				List<WorkContractClient> list2 = workContractClientService.findList(workContractClient2);
				//合并附件
				for (WorkClientAttachment workClientAttachment : workContractInfo.getWorkAttachmentAlters()){
					if("81".equals(workClientAttachment.getAttachmentFlag())){
						workClientAttachment.setAttachmentId(oldid);
						workClientAttachment.setAttachmentFlag("44");
						workClientAttachmentDao.update(workClientAttachment);
					}
				}
				//更换原数据id
				String uuid = IdGen.uuid();
				workContractInfoDao.updateId(w.getId(),uuid);
				//将变更后数据主键换为原数据Id
				workContractInfoDao.updateId(workContractInfo.getId(),oldid);
				//更新数据	beforeid
				workContractInfoDao.updateBeforeId(oldid,uuid);
				//更新子表
				if (list1!=null&&list1.size()>0) {
					for (WorkContractClient contractClient:
							list1) {
						contractClient.setContractId(uuid);
						workContractClientDao.update(contractClient);
					}
				}
				if (list2!=null&&list2.size()>0) {
					for (WorkContractClient contractClient:
							list2) {
						contractClient.setContractId(oldid);
						workContractClientDao.update(contractClient);
					}
				}
				if(list3!=null&&list3.size()>0){
					for (WorkClientAttachment workClientAttachment:
							list3) {
						WorkClientAttachment workClientAttachment1 = new WorkClientAttachment();
						try {
							BeanUtils.copyProperties(workClientAttachment1,workClientAttachment);
							workClientAttachment1.setId(IdGen.uuid());
							workClientAttachment1.setAttachmentId(uuid);
							workClientAttachmentDao.insert(workClientAttachment1);
						} catch (IllegalAccessException e) {
							e.printStackTrace();
						} catch (InvocationTargetException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
		return "保存审核意见成功！";
	}
	@Transactional(readOnly = false)
	public void update(WorkContractInfo workContractInfo) {
		workContractInfo.preUpdate();
		dao.update(workContractInfo);
	}

	/**
	 * 上传单个文件
	 * @param request
	 * @param upload_files
	 */
	public WorkClientAttachment uploadFileSingle(HttpServletRequest request, CommonsMultipartFile upload_files, String ClientId, String attachmentFlag){
		String  uploadFolder = request.getSession().getServletContext().getRealPath("local_upload/notify/"+System.currentTimeMillis());
		InputStream inputStream = null;
		WorkClientAttachment workClientAttachment = new WorkClientAttachment();
		try {
			new File(uploadFolder).mkdirs();
			String imageName = System.nanoTime()+upload_files.getOriginalFilename();
			String imageNewName = uploadFolder+"/"+imageName;
			upload_files.transferTo(new File(imageNewName));
			inputStream = new FileInputStream(new File(imageNewName));
			OSSClientUtil ossUtil = new OSSClientUtil();
			String suffix = imageNewName.substring(imageNewName.lastIndexOf("."));
			String name = System.nanoTime() + suffix;
			ossUtil.uploadFile2OSS(inputStream, Global.getNotifyData(), name);
			workClientAttachment.setUrl(Global.getAliyunUrl()+"/"+Global.getNotifyData()+name);
			workClientAttachment.setAttachmentUser(UserUtils.getUser().getId());
			workClientAttachment.setAttachmentName(upload_files.getOriginalFilename()); //name
			workClientAttachment.setAttachmentId(ClientId);
			workClientAttachment.setType(suffix);
			workClientAttachment.setAttachmentFlag(attachmentFlag);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (inputStream != null)
					inputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return workClientAttachment;
	}
	public WorkClientInfo getClinetInfo(String clientId){
		WorkClientInfo client=workContractInfoDao.getClientInfoByClientId(clientId);
		return client;
	}

	@Transactional(readOnly = false)
	public void deleteFile(String fileUrl,String id){
		new OSSClientUtil().deleteSingleObject(fileUrl);
//		workContractInfoDao.deleteFile(id);
	}


	/**
	 * 获取已办任务
	 * @return
	 */
	public List<WorkContractInfo> historicList(Act act){
		String userId = UserUtils.getUser().getId();//ObjectUtils.toString(UserUtils.getUser().getId());
//        HistoricTaskInstanceQuery histTaskQuery = historyService.createHistoricTaskInstanceQuery().taskAssignee(userId).finished()
//                .includeProcessVariables().orderByHistoricTaskInstanceEndTime().desc();
		HistoricTaskInstanceQuery query = historyService.createHistoricTaskInstanceQuery().finished().taskAssignee(userId);
		// 设置查询条件
		if (StringUtils.isNotBlank(act.getProcDefKey())){
			query.processDefinitionKey(act.getProcDefKey());
		}
		if (act.getBeginDate() != null){
			query.taskCompletedAfter(act.getBeginDate());
		}
		if (act.getEndDate() != null){
			query.taskCompletedBefore(act.getEndDate());
		}
		List<HistoricTaskInstance> list = query.list();

		//重新申请|撤销 不要
		Iterator<HistoricTaskInstance> it = list.iterator();
		while (it.hasNext()){
			HistoricTaskInstance hti = it.next();
			if("reapply".equals(hti.getTaskDefinitionKey())){
				it.remove();
			}
		}

		List<WorkContractInfo> list1 = new ArrayList<>();
		Office office = UserUtils.getSelectCompany();
		String companyId = office==null?"":office.getId();
		for (HistoricTaskInstance histTask : list) {
			WorkContractInfo workContractInfo = this.getByProcessInstanceId(histTask.getProcessInstanceId());
			if (workContractInfo != null && workContractInfo.getCompanyId().equals(companyId)) {
				workContractInfo.setCreateBy(UserUtils.get(workContractInfo.getCreateBy().getId()));
				historyService.getHistoricIdentityLinksForProcessInstance(histTask.getProcessInstanceId());
				act.setHistTask(histTask);
				act.setVars(histTask.getProcessVariables());
				act.setProcDef(ProcessDefCache.get(histTask.getProcessDefinitionId()));
				act.setStatus("finish");
				workContractInfo.setAct(act);
				workContractInfo.setAuditType("合同申请");
				list1.add(workContractInfo);
			}

			//合同作废审批
			if(workContractInfo==null){
				workContractInfo = this.getByInvalidateProcessInstanceId(histTask.getProcessInstanceId());
				if(workContractInfo!=null){
					workContractInfo.setAct(act);
					workContractInfo.setAuditType("合同作废");
					list1.add(workContractInfo);
				}
			}
		}
		return list1;
	}

	public List<WorkContractInfo> findByList(WorkContractInfo workContractInfo) {
		return dao.findByList(workContractInfo);
	}

	//作废合同申请
	@Transactional(readOnly = false)
	public String contractInvalidateStart(WorkContractInfo workContractInfo,String reason) {
		String processInstanceId = workContractInfo.getInvalidateProcessInstanceId();
		if(StringUtils.isNotBlank(reason)){
			AlterInfo alterInfo = alterInfoService.getByContractInfo(workContractInfo);
			if(alterInfo==null){
				alterInfo = new AlterInfo();
				alterInfo.setType("1");
				alterInfo.setStyle("1");
				alterInfo.setBeforeId(workContractInfo.getId());
			}
			alterInfo.setReason(reason);
			alterInfoService.save(alterInfo);
		}
		Office office = officeService.get(workContractInfo.getChargeCompany());
		String str = "合同编号"+workContractInfo.getContractNum()+",作废申请人：" + UserUtils.get(workContractInfo.getCreateBy().getId()).getName() + ",主委托方：" + workContractInfo.getClient().getName() + ",合同所属部门:"+office.getName();
		String title = "合同名称:"+workContractInfo.getName();
		Map<String ,Object> variables = new HashMap<>();
		identityService.setAuthenticatedUserId(UserUtils.getUser().getId());
		WorkActivityMenu workActivityMenu = workActivityMenuService.findByParentAndOffice("bbecad5bdefd46c48591166170fe6dce",office);
		String businessKey = workContractInfo.getId().toString();
		String processType = workActivityMenu.getProcessType();
		StringBuffer buffer = new StringBuffer();
		Activity activity = new Activity();
		WorkProjectNotify workProjectNotify = UtilNotify
				.saveNotify(workContractInfo.getId(),
						null,
						workContractInfo.getCompanyId(),
						title,
						str,
						"43",
						"0",
						"待审批",
						""
				);
		List<User> users = new ArrayList<>();
		List<User> bmzrs = UserUtils.getByRoleActivityEnname("bmzr",2,office.getId(),"2",workContractInfo.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(),"2",workContractInfo.getCreateBy());
					if (enusers.size()==0){
						logger.info("流程审批人不能为空,角色"+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(),"2",workContractInfo.getCreateBy());
				}
				//人员审批
				if (StringUtils.isNotBlank(activity.getUser().getId())) {
					users.add(activity.getUser());
				}
			}
			workProjectNotify.setId("");
		}else{
			if (bmzrs.size()==0){
				logger.info("流程审批人不能为空,角色部门负责人下无用户,请联系管理员！");
			}
			processType = "contractInvalid";
			users.addAll(bmzrs);
			variables.put("bmzrList", bmzrs);
			variables.put("bmzrCount",bmzrs.size());
		}
		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","43");
			UserUtils.pushInfoToApp(title,str,extras,u.getId());
			UserUtils.pushIm(u.getId(),str);
		}
		variables.put("type", processType);
		variables.put("busId", businessKey);
		variables.put("title","合同作废申请");

		ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processType, businessKey, variables);
		workContractInfo.setProcessInstance(processInstance);
		workContractInfo.setInvalidateProcessInstanceId(processInstance.getId());
		workContractInfoDao.updateInvalidateProcessInstanceId(workContractInfo);
		/**
		 * 合同作废状态：
		 *  当合同是通过状态（contract_state=2）时可以发起合同作废流程，当合同作废申请被批准后，合同状态更改为"已作废(contract_state=6)"
		 *  空：当前合同未发起作废申请，即：该状态下可以发起合同作废申请；
		 *  1：合同作废流程进行中，即：该状态下不能重复发起合同作废申请；
		 *  2：合同作废申请被批准，即：该状态下不能重复发起合同作废申请；
		 *  3: 合同作废申请被驳回，即：申请人可以选择撤销或重新申请；
		 *  4：合同作废申请人选择了撤销，即：可以再次申请；
		 */
		//更新合同作废流程id和发起人
		workContractInfo.setInvalidateStatus("1");
		workContractInfo.setInvalidateUserId(UserUtils.getUser().getId());
		workContractInfoDao.updateInvalidateStatusAndUser(workContractInfo);

		//更新合同状态为"作废中"
		workContractInfo.setContractState("6");
		workContractInfo.preUpdate();
		workContractInfoDao.update(workContractInfo);
		if (org.apache.commons.lang3.StringUtils.isNotBlank(processInstanceId)) {
			workActivityProcessService.updateProcessInstanceId(processInstance.getId(),processInstanceId);
			workActivityProcessService.deleteProcessInstanceId(processInstanceId);
			workActivityProcessService.deleteProcessIdAuditUsers(processInstanceId);
		}
		List<Activity> list= workActivityMenu.getActivities();
		if (list!=null && list.size()!=0){
			workActivityProcessService.saveList(list,processInstance.getId());
		}else {
			WorkActivityProcess workActivityProcess = new WorkActivityProcess();
			workActivityProcess.setProcessKey(processType);
			workActivityProcess.setCount(1);
			workActivityProcess.setProcessInstanceId(processInstance.getId());
			workActivityProcess.setIsApproval("0");
			workActivityProcess.setActivity(new Activity("cc5fc1e2c8a241aeae8b8e5b572c8735"));
			workActivityProcessService.save(workActivityProcess);
			workActivityProcessService.insertAuditsByType(bmzrs,processInstance.getId(),1,1);
		}
		return "";
	}
	//根据合同作废流程id获取合同信息
	public WorkContractInfo getByInvalidateProcessInstanceId(String invalidateProcessInstanceId){
		WorkContractInfo workClientInfo = workContractInfoDao.getByInvalidateProcessInstanceId(invalidateProcessInstanceId);
		return workClientInfo;
	}

	//合同作废审批
	@Transactional(readOnly = false)
	public String invalidateContractSaveAudit(WorkContractInfo workContractInfo,List<User> auditUsers) {
		try {
			Office office = officeService.get(workContractInfo.getChargeCompany());
			String str = "合同编号"+workContractInfo.getContractNum()+",作废申请人：" + UserUtils.get(workContractInfo.getCreateBy().getId()).getName() + ",主委托方：" + workContractInfo.getClient().getName() + ",合同所属部门:"+office.getName();
			String title = "合同名称:"+workContractInfo.getName();
			// 对不同环节的业务逻辑进行操作
			String taskDefKey = workContractInfo.getAct().getTaskDefKey();
			if (!"modifyApply".equals(taskDefKey) ) {
				actTaskService.claim(workContractInfo.getAct().getTaskId(), UserUtils.getUser().getId());
			}else {
				workContractInfo.getAct().setFlag("yes");
				if(workContractInfo.getAlterInfo()!=null){
					if(StringUtils.isNotBlank(workContractInfo.getAlterInfo().getReason())){
						AlterInfo alterInfo = alterInfoService.getByContractInfo(workContractInfo);
						if(alterInfo==null){
							alterInfo = new AlterInfo();
							alterInfo.setType("1");
							alterInfo.setStyle("1");
							alterInfo.setBeforeId(workContractInfo.getId());
						}
						alterInfo.setReason(workContractInfo.getAlterInfo().getReason());
						alterInfoService.save(alterInfo);
					}
				}
			}
			String comment = "";
			if(workContractInfo.getInvalidateStatus().equals("3")){//如果是被驳回状态
				comment = ("yes".equals(workContractInfo.getAct().getFlag())?"[重新申请] ":"[已撤销] ");
			}else{
				comment = ("yes".equals(workContractInfo.getAct().getFlag())?"[同意] ":"[驳回] ")+workContractInfo.getAct().getComment();
			}
			//yes 的时候状态为审核通过 否则为未通过
			//workContractInfo.setInvalidateStatus(("yes".equals(workContractInfo.getAct().getFlag()) ? "1" : "2"));
			Map<String, Object> vars = Maps.newHashMap();
			//业务逻辑对应的条件表达式
			String exp = "";
			String taskCount = "";
			String notifyRole = "";
			int key = 0;
			String enname = "";
			List<Activity> activitieList = activityService.getByProcessInstanceId(workContractInfo.getInvalidateProcessInstanceId());
			WorkActivityMenu workActivityMenu = new WorkActivityMenu();
			if (activitieList != null && activitieList.size() != 0) {
				workActivityMenu.setProcessType(activitieList.get(0).getProcessKey());
				workActivityMenu.setActivities(activitieList);
			}

			WorkActivityProcess workActivityProcess = new WorkActivityProcess();
			WorkActivityProcess selectedProcess = new WorkActivityProcess();
			selectedProcess.setProcessInstanceId(workContractInfo.getInvalidateProcessInstanceId());
			List<WorkActivityProcess> workActivityProcesses = workActivityProcessService.findList(selectedProcess);
			List<Activity> activities = workActivityMenu.getActivities();
			if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("contractInvalid")) {
				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(workContractInfo.getAct().getFlag())) {
							workContractInfo.setInvalidateStatus("1");
							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(workContractInfo.getAct().getFlag())) {
							workContractInfo.setInvalidateStatus("4");
							workActivityProcess.setIsApproval("2");
						} else {
							workActivityProcess.setIsApproval("1");
						}
						break;
					}
				}
				workActivityProcessService.deleteProcessIdAuditUsers(workContractInfo.getInvalidateProcessInstanceId());
			} else {
				workActivityMenu.setProcessType("contractInvalid");
				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 ("bmzr".equals(taskDefKey) && count.contains("1")) {
						taskCount = "1";
						exp = "pass";
						if ("yes".equals(workContractInfo.getAct().getFlag())) {
							notifyRole = "合同作废";
							workContractInfo.setInvalidateStatus("2");
							workActivityProcess.setIsApproval("1");
						} else {
							notifyRole = "调整申请";
							workContractInfo.setInvalidateStatus("3");
							workActivityProcess.setIsApproval("2");
						}
						break;
					} else if ("modifyApply".equals(taskDefKey)&& count.contains("0")) {
						notifyRole = "部门主任审批";
						taskCount = "0";
						exp = "pass";
						workActivityProcess.setCount(0);
						enname = "bmzr";
						workContractInfo.setInvalidateStatus("1");
						if (!"yes".equals(workContractInfo.getAct().getFlag())) {
							workContractInfo.setInvalidateStatus("4");
						}
						str += " 待审批!";
						break;
					} else if ("apply_end".equals(taskDefKey)) {
					}

				}
			}
			// 设置意见
			workContractInfo.getAct().setComment(("yes".equals(workContractInfo.getAct().getFlag()) ? "[同意] " : "[驳回] ") + workContractInfo.getAct().getComment());
			workContractInfo.preUpdate();
			// 提交流程任务
			vars.put(exp, "yes".equals(workContractInfo.getAct().getFlag()) ? true : false);
			vars.put("passs", true);
			workActivityProcessService.updateProcess(workActivityProcess,workActivityMenu,key,taskCount,workContractInfo.getInvalidateProcessInstanceId(),taskDefKey,"modifyApply",workContractInfo.getAct().getFlag(),comment, activities);
			// 提交流程任务
			actTaskService.complete(workContractInfo.getAct().getTaskId(), workContractInfo.getAct().getProcInsId(), workContractInfo.getAct().getComment(), vars);
			boolean state = actTaskService.isProcessEnd(workContractInfo.getAct().getProcInsId());
			List<User> users = new ArrayList<>();
			List<User> userList = new ArrayList<>();
			if (!state) {
				str = "合同编号"+workContractInfo.getContractNum() + ",主委托方：" + workContractInfo.getClient().getName() + ",合同所属部门:"+office.getName();
				title = "合同名称:"+workContractInfo.getName();
				users.add(workContractInfo.getCreateBy());
				if ("yes".equals(workContractInfo.getAct().getFlag())) {
					workContractInfo.setInvalidateStatus("2");
					workContractInfo.setContractState("7");
					WorkProjectNotify notify = new WorkProjectNotify();
					notify.setNotifyId(workContractInfo.getId());
					userList = workProjectNotifyService.readByNotifyId(notify);
					workProjectNotifyService
							.save(UtilNotify
									.saveNotify(workContractInfo.getId(),
											workContractInfo.getCreateBy(),
											workContractInfo.getCompanyId(),
											title,
											str,
											"43",
											"0",
											"待通知",
											notifyRole));

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

						}
					}

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

								}
							}
						}else {
							WorkProjectNotify notify = new WorkProjectNotify();
							notify.setNotifyId(workContractInfo.getId());
							userList = workProjectNotifyService.readByNotifyId(notify);
							users.addAll(userList);
							users.add(workContractInfo.getCreateBy());
							workProjectNotifyService
									.save(UtilNotify
											.saveNotify(workContractInfo.getId(),
													workContractInfo.getCreateBy(),
													workContractInfo.getCompanyId(),
													title,
													str,
													"43",
													"0",
													"重新申请",
													notifyRole));
						}
					}
				}
			}
			if (StringUtils.isNotBlank(title) && users!=null && users.size()!=0) {
				for (User u : users) {
					UserUtils.pushIm(u.getId(),title);
				}
			}
			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());
				}
			}
			workContractInfoDao.update(workContractInfo);
			//更新审核状态
			workContractInfoDao.updateInvalidateStatusAndUser(workContractInfo);
			return "保存审核意见成功！";
		}catch (ActivitiObjectNotFoundException e){
			logger.error("ActivitiObjectNotFoundException e:"+e);
			return "流程已审批，不能重新审批！";
		}catch (Exception e){
			logger.error("Exception e:"+e);
			return "保存审核意见失败！！";
		}
	}

	/**
	 * 合同作废：强制撤销
	 * @param workContractInfo
	 */
	@Transactional(readOnly = false)
	public void cancelInvalidate(WorkContractInfo workContractInfo) {
		String invalidateProcessInstanceId = workContractInfo.getInvalidateProcessInstanceId();
		try {
			//将流程图中尚未走到的task的流程追踪信息逻辑删除，添加一条"撤销"流程追踪信息
			WorkActivityProcess process = new WorkActivityProcess();
			process.setProcessInstanceId(workContractInfo.getInvalidateProcessInstanceId());
			process.setIsApproval("0");
			//List<WorkActivityProcess> processList1 = workActivityProcessService.findByProcInsId(process);
			WorkActivityProcess workActivityProcess = new WorkActivityProcess();
			workActivityProcess.setProcessInstanceId(workContractInfo.getInvalidateProcessInstanceId());
			List<WorkActivityProcess> processList = workActivityProcessService.findList(workActivityProcess);
			WorkProjectNotify notify = new WorkProjectNotify();
			notify.setNotifyId(workContractInfo.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()+",合同名称:"+workContractInfo.getName() +" 强制撤销!\"," +
								"\"useType\":\"sys\"}";
						ChatServerPool.sendMessageToUser(toUserConn, message);//同时向本人发送消息
					}*/
					UserUtils.pushIm(u.getId(),"合同作废申请人:"+ user.getName()+",合同名称:"+workContractInfo.getName() +" 强制撤销!");
				}
			}
			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,"合同作废-强制撤销");
			workContractInfo.setInvalidateStatus("4");
			workContractInfo.preUpdate();
			workContractInfoDao.updateInvalidateStatusAndUser(workContractInfo);

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

	}
	@Transactional(readOnly = false)
	public void deleteInvalidate(WorkContractInfo workContractInfo) {
		//删除合同作废信息前，以防万一可以先尝试撤销这个流程
		try {
			boolean state = actTaskService.isProcessEnd(workContractInfo.getInvalidateProcessInstanceId());
			if(state){
				this.cancelInvalidate(workContractInfo);
			}
			workContractInfo.setInvalidateStatus("");
			workContractInfo.setInvalidateUserId("");
			workContractInfo.setInvalidateProcessInstanceId("");
			//合同还原为"已签"状态
			workContractInfo.setContractState("5");

			workContractInfo.preUpdate();
			workContractInfoDao.update(workContractInfo);

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public Page<WorkContractInfo> findSignedPage(Page<WorkContractInfo> page, WorkContractInfo workContractInfo) {
		if (StringUtils.isNotBlank(workContractInfo.getTotalContractIds())){
			workContractInfo.setTotalContractIds(","+workContractInfo.getTotalContractIds()+",");
		}
		workContractInfo.getSqlMap().put("dsf", dataScopeFilter(workContractInfo.getCurrentUser(), "o", "u", "s", MenuStatusEnum.WORK_CONTRACT_INFO.getValue()));
		workContractInfo.setPage(page);
		List<WorkContractInfo> workContractInfos = dao.findList(workContractInfo);
		//sortList(list,dao.findList(workContractInfo),"0",true);
		page.setList(workContractInfos);
		return page;
	}

	//客户列表
	@Transactional(readOnly = false)
	public void updateWorkContractInfo(WorkContractInfo workContractInfo) {
		String contractId = workContractInfo.getId();
		WorkContractClient workContractClient1 = new WorkContractClient();
		workContractClient1.setContractId(contractId);
		List<WorkContractClient> list1 =workContractClientService.findList(workContractClient1);
		if(list1!=null && list1.size()>0){
			for(WorkContractClient w :list1){
				workContractClientService.delete(w);
			}
			for (WorkClientInfo workClientInfo : workContractInfo.getWorkClientInfoList()){
				if(workClientInfo.DEL_FLAG_NORMAL.equals(workClientInfo.getDelFlag())){
					String clientId = workClientInfo.getId();
					if (clientId == null){
						continue;
					}
					WorkContractClient workContractClient = new WorkContractClient();
					workContractClient.setContractId(contractId);
					workContractClient.setClientId(clientId);
					List<WorkContractClient> list2 =workContractClientService.findList(workContractClient);
					if(list2!=null&&list2.size()>0){
						logger.info("无法重复添加关联关系");
					}else{
						//第一次新增
						workContractClientService.save(workContractClient);
					}
				}
			}
		}else{
			for (WorkClientInfo workClientInfo : workContractInfo.getWorkClientInfoList()){
				String clientId = workClientInfo.getId();
				if (clientId == null){
					continue;
				}
				WorkContractClient workContractClient = new WorkContractClient();
				workContractClient.setContractId(contractId);
				workContractClient.setClientId(clientId);
				List<WorkContractClient> list2 =workContractClientService.findList(workContractClient);
				if(list2!=null&&list2.size()>0){
					logger.info("无法重复添加关联关系");
				}else{
					//第一次新增
					workContractClientService.save(workContractClient);
				}
			}
		}
	}
	@Transactional(readOnly = false)
	public void auditInvalidate(WorkContractInfo workContractInfo) throws Exception {
		String invalidateProcessInstanceId = workContractInfo.getProcessInstanceId();
		//将流程图中尚未走到的task的流程追踪信息逻辑删除，添加一条"撤销"流程追踪信息
		WorkActivityProcess process = new WorkActivityProcess();
		process.setProcessInstanceId(workContractInfo.getProcessInstanceId());
		process.setIsApproval("0");
		//List<WorkActivityProcess> processList1 = workActivityProcessService.findByProcInsId(process);
		WorkActivityProcess workActivityProcess = new WorkActivityProcess();
		workActivityProcess.setProcessInstanceId(workContractInfo.getProcessInstanceId());
		List<WorkActivityProcess> processList = workActivityProcessService.findList(workActivityProcess);
		WorkProjectNotify notify = new WorkProjectNotify();
		notify.setNotifyId(workContractInfo.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()+",合同名称:"+workContractInfo.getName() +" 强制撤销!\"," +
								"\"useType\":\"sys\"}";
						ChatServerPool.sendMessageToUser(toUserConn, message);//同时向本人发送消息
					}*/
				UserUtils.pushIm(u.getId(),"申请人:"+ user.getName()+",合同名称:"+workContractInfo.getName() +" 强制撤销!");
			}
		}
		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,"合同申请-强制撤销");
		workContractInfo.setContractState("3");
		workContractInfo.preUpdate();
		workContractInfoDao.update(workContractInfo);



	}
	@Transactional(readOnly = false)
	public void auditCompletionInvalidate(WorkContractInfo workContractInfo) throws Exception {
		String invalidateProcessInstanceId = workContractInfo.getProcessInstanceId();
		//将流程图中尚未走到的task的流程追踪信息逻辑删除，添加一条"撤销"流程追踪信息
		WorkActivityProcess process = new WorkActivityProcess();
		process.setProcessInstanceId(workContractInfo.getProcessInstanceId());
		process.setIsApproval("0");
		//List<WorkActivityProcess> processList1 = workActivityProcessService.findByProcInsId(process);
		WorkActivityProcess workActivityProcess = new WorkActivityProcess();
		workActivityProcess.setProcessInstanceId(workContractInfo.getProcessInstanceId());
		List<WorkActivityProcess> processList = workActivityProcessService.findList(workActivityProcess);
		WorkProjectNotify notify = new WorkProjectNotify();
		notify.setNotifyId(workContractInfo.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()+",合同名称:"+workContractInfo.getName() +" 强制撤销!\"," +
							"\"useType\":\"sys\"}";
					ChatServerPool.sendMessageToUser(toUserConn, message);//同时向本人发送消息
				}*/
				UserUtils.pushIm(u.getId(),"申请人:"+ user.getName()+",合同名称:"+workContractInfo.getName() +" 强制撤销!");
			}
		}
		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,"合同申请-强制撤销");
		workContractInfo.setCompletionStatus("");
		workContractInfo.setContractState("5");
		workContractInfo.preUpdate();
		workContractInfoDao.update(workContractInfo);
	}

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

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

	}
	@Transactional(readOnly = false)
	public String alterSave(WorkContractInfo workContractInfo,Map<String, Object> variables,String processInstanceId) {
		User user = UserUtils.getUser();
		this.altersaves(workContractInfo);
		Office office = officeService.get(workContractInfo.getChargeCompany());
		String str = "合同变更编号"+workContractInfo.getContractNum()+",变更申请人：" + UserUtils.get(workContractInfo.getCreateBy().getId()).getName() + ",主委托方：" + workContractInfo.getClient().getName() + ",合同所属部门:"+office.getName();
		String title = "合同名称:"+workContractInfo.getName();
		updateWorkContractInfo(workContractInfo);
		//变更附件
		for (WorkClientAttachment workClientAttachment : workContractInfo.getWorkAttachments()) {
			if (workClientAttachment.getId() == null) {
				continue;
			}
			if (WorkClientAttachment.DEL_FLAG_NORMAL.equals(workClientAttachment.getDelFlag())) {
				workClientAttachment.setAttachmentId(workContractInfo.getId());
				workClientAttachment.setAttachmentFlag("81");
				workClientAttachment.setAttachmentUser(UserUtils.getUser().getId());
				if (StringUtils.isBlank(workClientAttachment.getId()) || "null".equals(workClientAttachment.getId())) {
					workClientAttachment.preInsert();
					workClientAttachmentDao.insert(workClientAttachment);
					signatureDocumentService.createIsignature(workClientAttachment.getUrl(),workClientAttachment.getAttachmentName(),workClientAttachment.getId(),workContractInfo.getName());
				} else {
					workClientAttachment.preUpdate();
					workClientAttachmentDao.update(workClientAttachment);
				}
			} else {
				workClientAttachmentDao.delete(workClientAttachment);
			}
		}
		// 用来设置启动流程的人员ID，引擎会自动把用户ID保存到activiti:initiator中
		identityService.setAuthenticatedUserId(user.getId());
		// 启动流程
		String businessKey = workContractInfo.getId().toString();
		WorkActivityMenu workActivityMenu = workActivityMenuService.findByParentAndOffice("1663125f1f194c82bdea93555c750904", office);
		// 启动流程
		String processType = workActivityMenu.getProcessType();
		StringBuffer buffer = new StringBuffer();
		Activity activity = new Activity();
		WorkProjectNotify workProjectNotify = UtilNotify
				.saveNotify(workContractInfo.getId(),
						null,
						workContractInfo.getCompanyId(),
						title,
						str,
						"44",
						"0",
						"待审批",
						""
				);
		List<User> users = new ArrayList<>();
		List<User> bmzrs = UserUtils.getByRoleActivityEnname("bmzr",2,office.getId(),"2",workContractInfo.getCreateBy());
//		List<User> ywbzrs = UserUtils.getByRoleActivityEnname("scyfglbzr",1,office.getId(),"2",workContractInfo.getCreateBy());
//		List<User> fglds = UserUtils.getByRoleActivityEnname("scfgld",3,office.getId(),"2",workContractInfo.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(),"2",workContractInfo.getCreateBy());
					if (enusers.size()==0){
						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(),"2",workContractInfo.getCreateBy());
				}
				//人员审批
				if (StringUtils.isNotBlank(activity.getUser().getId())) {
					users.add(activity.getUser());
				}
			}
			workProjectNotify.setId("");
		} else {
			if (bmzrs.size()==0){
				return "流程审批人不能为空,角色部门负责人下无用户,请联系管理员！";
			}
			processType = "contractChange";
			variables.put("bmzrList", bmzrs);
			variables.put("bmzrCount",bmzrs.size());
			users.addAll(bmzrs);
		}
		for (User u : users){
			workProjectNotify.setUser(u);
			workProjectNotify.setId("");
			workProjectNotify.setNotifyRole("部门主任审批");
			workProjectNotifyService
					.save(workProjectNotify);
			Map<String,Object> extras = new HashMap<>();
			extras.put("type","7002");
			extras.put("id",workProjectNotify.getId());
			extras.put("procDefKey","44");
			UserUtils.pushInfoToApp(title,str,extras,u.getId());
			UserUtils.pushIm(u.getId(),str);
		}
		variables.put("type", processType);
		variables.put("busId", businessKey);
		variables.put("title", "审批单：" + workContractInfo.getName());//设置标题；

		ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processType, businessKey, variables);
		workContractInfo.setProcessInstance(processInstance);
		if (StringUtils.isNotBlank(processInstanceId)) {
			workActivityProcessService.updateProcessInstanceId(processInstance.getId(),processInstanceId);
			workActivityProcessService.deleteProcessInstanceId(processInstanceId);
			workActivityProcessService.deleteProcessIdAuditUsers(processInstanceId);
		}
		// 更新流程实例ID
		workContractInfo.setAlterProcessInstanceId(processInstance.getId());
		workContractInfoDao.updatealterProcessInstanceId(workContractInfo);

		List<Activity> list = workActivityMenu.getActivities();
		if (list != null && list.size() != 0) {
			workActivityProcessService.saveList(list, processInstance.getId());
		} else {
			WorkActivityProcess workActivityProcess = new WorkActivityProcess();
			workActivityProcess.setProcessKey("contractChange");
			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(bmzrs,processInstance.getId(),1,1);
//			workActivityProcessService.insertAuditsByType(ywbzrs,processInstance.getId(),2,0);
//			workActivityProcessService.insertAuditsByType(fglds,processInstance.getId(),3,0);
		}
		logger.debug("start process of {key={}, bkey={}, pid={}, variables={}}", new Object[]{
				ActUtils.PD_REIMBURSEMENT[0], businessKey, processInstance.getId(), variables});
		return "";
	}

	/**
	 * 提交存储
	 * @param id，remakrs
	 * @param variables
	 */
	@Transactional(readOnly = false)
	public String saveCompletion(WorkContractInfo workContractInfo,Map<String,Object> variables) {
		int count = workContractInfoDao.findByReport(workContractInfo.getId());
		if (count>0){
			return "发起合同完成失败,该合同报告未归档";
		}else {
			String processInstanceId = workContractInfo.getProcessInstanceId();
			workContractInfo.setCompletionStatus("2");
			workContractInfo.setContractState("9");
			User user = UserUtils.getUser();
			Office office = officeService.get(workContractInfo.getChargeCompany());
			String title = "合同名称:" + workContractInfo.getName();
			WorkInvoiceDetail invoice = new WorkInvoiceDetail();
			invoice.setId(workContractInfo.getId());
			List<WorkInvoiceDetail> invoiceDetails = workInvoiceDetailDao.findListByContractInfo(invoice);
			String str = "合同所属部门:" + office.getName() + "合同申请人:" + UserUtils.get(workContractInfo.getCreateBy().getId()).getName() + ",主委托方:" + workContractInfo.getClient().getName() + ",收款金额:" + getTotal(workContractInfo.getId());
			// 用来设置启动流程的人员ID，引擎会自动把用户ID保存到activiti:initiator中
			identityService.setAuthenticatedUserId(user.getId());
			// 启动流程
			String businessKey = workContractInfo.getId().toString();
			WorkActivityMenu workActivityMenu = workActivityMenuService.findByParentAndOffice("1663125f1f194c82bdea93555c750204", office);
			// 启动流程
			String processType = workActivityMenu.getProcessType();
			StringBuffer buffer = new StringBuffer();
			Activity activity = new Activity();
			WorkProjectNotify workProjectNotify = UtilNotify
					.saveNotify(workContractInfo.getId(),
							null,
							workContractInfo.getCompanyId(),
							title,
							str,
							"72",
							"0",
							"待审批",
							""
					);
			List<User> users = new ArrayList<>();
			List<User> bmzrs = UserUtils.getByRoleActivityEnname("bmzr", 2, office.getId(), "2", workContractInfo.getCreateBy());
//			List<User> scyfglbzrs = UserUtils.getByRoleActivityEnname("scyfglbzr", 1, office.getId(), "2", workContractInfo.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(), "2", workContractInfo.getCreateBy());
						if (enusers.size() == 0) {
							/*dao.delete(workContractInfo);
							for (Workattachment workattachment : workContractInfo.getWorkAttachments()) {
								workattachmentDao.delete(workattachment);
							}*/
							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(), "8", workContractInfo.getCreateBy());
					}
					//人员审批
					if (StringUtils.isNotBlank(activity.getUser().getId())) {
						users.add(activity.getUser());
					}
				}
				workProjectNotify.setId("");
			} else {
				if (bmzrs.size() == 0) {
					return "流程审批人不能为空,角色部门负责人下无用户,请联系管理员！";
				}
				users.addAll(bmzrs);
				processType = "contractComplete";
				variables.put("bmzrList", bmzrs);
				variables.put("bmzrCount",bmzrs.size());
			}
			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", "72");
				UserUtils.pushInfoToApp(title, str, extras, u.getId());
				UserUtils.pushIm(u.getId(), str);
			}
			variables.put("type", processType);
			variables.put("busId", businessKey);
			variables.put("title", "合同名称：" + workContractInfo.getName());//设置标题；

			ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processType, businessKey, variables);

			workContractInfo.setProcessInstance(processInstance);
			if (StringUtils.isNotBlank(processInstanceId)) {
				workActivityProcessService.updateProcessInstanceId(processInstance.getId(), processInstanceId);
				workActivityProcessService.deleteProcessInstanceId(processInstanceId);
				workActivityProcessService.deleteProcessIdAuditUsers(processInstanceId);
			}
			// 更新流程实例ID
			workContractInfo.setProcessInstanceId(processInstance.getId());
			dao.updateProcessInstanceId(workContractInfo);
			List<Activity> list = workActivityMenu.getActivities();
			if (list != null && list.size() != 0) {
				workActivityProcessService.saveList(list, processInstance.getId());
			} else {
				WorkActivityProcess workActivityProcess = new WorkActivityProcess();
				workActivityProcess.setProcessKey(processType);
				workActivityProcess.setCount(1);
				workActivityProcess.setIsApproval("0");
				workActivityProcess.setProcessInstanceId(processInstance.getId());
				workActivityProcessService.insert(workActivityProcess);
//				workActivityProcess.setCount(2);
//				workActivityProcess.setIsApproval("0");
//				workActivityProcessService.insert(workActivityProcess);
				workActivityProcessService.insertAuditsByType(bmzrs, processInstance.getId(), 1, 1);
//				workActivityProcessService.insertAuditsByType(scyfglbzrs, processInstance.getId(), 2, 0);
			}
			workContractInfo.preUpdate();
			update(workContractInfo);
			return "true";
		}
	}

	public Page<WorkContractListInfo> findListPage(Page<WorkContractListInfo> page, WorkContractListInfo workContractListInfo) {
		if(workContractListInfo.getBeginContractDate()==null){
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			SimpleDateFormat format3 = new SimpleDateFormat("yyyy");
			String time1 = format3.format(new Date());
			Date startTime = null;
			try {
				startTime = format.parse(time1 + "-01-01");
			} catch (ParseException e) {
				e.printStackTrace();
			}
			workContractListInfo.setBeginContractDate(startTime);
		}
		if(workContractListInfo.getEndContractDate()==null){
			workContractListInfo.setEndContractDate(new Date());
		}
		String companyId = UserUtils.getUser().getComId();
		workContractListInfo.getSqlMap().put("dsf","and (a.company_id='"+companyId+"')");
//		workContractListInfo.getSqlMap().put("dsf", dataScopeFilter(workContractListInfo.getCurrentUser(), "o", "u","s", MenuStatusEnum.WORK_CONTRACT_LIST_INFO.getValue()));
		workContractListInfo.setPage(page);
		List<WorkContractListInfo> list = Lists.newArrayList();
		List<WorkContractListInfo> workContractListInfos = workContractListInfoDao.findList(workContractListInfo);
		page.setList(workContractListInfos);
		return page;
	}
	public List<WorkContractListInfo> findListList(WorkContractListInfo workContractListInfo) {
		if(workContractListInfo.getBeginContractDate()==null){
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			SimpleDateFormat format3 = new SimpleDateFormat("yyyy");
			String time1 = format3.format(new Date());
			Date startTime = null;
			try {
				startTime = format.parse(time1 + "-01-01");
			} catch (ParseException e) {
				e.printStackTrace();
			}
			workContractListInfo.setBeginContractDate(startTime);
		}
		if(workContractListInfo.getEndContractDate()==null){
			workContractListInfo.setEndContractDate(new Date());
		}
		workContractListInfo.getSqlMap().put("dsf", dataScopeFilter(workContractListInfo.getCurrentUser(), "o", "u","s", MenuStatusEnum.WORK_CONTRACT_LIST_INFO.getValue()));
		List<WorkContractListInfo> list = Lists.newArrayList();
		List<WorkContractListInfo> workContractListInfos = workContractListInfoDao.findList(workContractListInfo);
		return workContractListInfos;
	}

}