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

import java.awt.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.*;
import java.util.List;

import com.google.common.collect.Maps;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.oss.OSSClientUtil;
import com.jeeplus.common.utils.MenuStatusEnum;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.WordToPic;
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.projectcontentinfo.dao.ProjectBasedDataDao;
import com.jeeplus.modules.projectcontentinfo.dao.ProjectContentDataDao;
import com.jeeplus.modules.projectrecord.entity.ProjectRecords;
import com.jeeplus.modules.projectrecord.service.ProjectRecordsService;
import com.jeeplus.modules.projectreportnum.entity.ReportNum;
import com.jeeplus.modules.projectreportnum.service.ProjectReportNumService;
import com.jeeplus.modules.serialnum.service.SerialNumTplService;
import com.jeeplus.modules.sys.dao.WorkattachmentDao;
import com.jeeplus.modules.sys.entity.Office;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.entity.Workattachment;
import com.jeeplus.modules.sys.service.OfficeService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workactivity.dao.WorkActivityProcessDao;
import com.jeeplus.modules.workactivity.entity.Activity;
import com.jeeplus.modules.workactivity.entity.WorkActivityProcess;
import com.jeeplus.modules.workactivity.service.ActivityService;
import com.jeeplus.modules.workactivity.service.WorkActivityProcessService;
import com.jeeplus.modules.workactivitymenu.entity.WorkActivityMenu;
import com.jeeplus.modules.workactivitymenu.service.WorkActivityMenuService;
import com.jeeplus.modules.workcontent.web.WorkContentTypeController;
import com.jeeplus.modules.workprojectnotify.entity.WorkProjectNotify;
import com.jeeplus.modules.workprojectnotify.service.WorkProjectNotifyService;
import com.jeeplus.modules.workprojectnotify.util.UtilNotify;
import com.jeeplus.modules.workreview.dao.WorkReviewAuditDao;
import com.jeeplus.modules.workreview.entity.WorkReviewAudit;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.java_websocket.WebSocket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.service.CrudService;
import com.jeeplus.modules.projectcontentinfo.entity.ProjectReportData;
import com.jeeplus.modules.projectcontentinfo.dao.ProjectReportDataDao;

/**
 * 报告详情Service
 * @author yangfan
 * @version 2018-06-05
 */
@Service
@Transactional(readOnly = true)
public class ProjectReportDataService extends CrudService<ProjectReportDataDao, ProjectReportData> {

	@Autowired
	private WorkattachmentDao workattachmentDao;
	@Autowired
	private RuntimeService runtimeService;
	@Autowired
	protected TaskService taskService;
	@Autowired
	protected HistoryService historyService;
	@Autowired
	protected RepositoryService repositoryService;
	@Autowired
	private IdentityService identityService;
	@Autowired
	private ActTaskService actTaskService;
	@Autowired
	private WorkProjectNotifyService workProjectNotifyService;
	@Autowired
	private WorkActivityMenuService workActivityMenuService;
	@Autowired
	private WorkActivityProcessService workActivityProcessService;
	@Autowired
	private ActivityService activityService;
	@Autowired
	private WorkActivityProcessDao workActivityProcessDao;
	@Autowired
	private ProjectContentDataDao projectContentDataDao;
	@Autowired
	private ProjectBasedDataDao projectBasedDataDao;
	@Autowired
	private ProjectRecordsService projectRecordsService;
	@Autowired
	private OfficeService officeService;
	@Autowired
	private WorkReviewAuditDao workReviewAuditDao;
	@Autowired
	private SerialNumTplService serialNumTplService;
	@Autowired
	private ProjectReportNumService projectReportNumService;

	public ProjectReportData get(String id) {
		ProjectReportData projectReportData = super.get(id);
		if (projectReportData!=null && StringUtils.isNotBlank(projectReportData.getId())){
			Workattachment workattachment = new Workattachment();
			workattachment.setAttachmentFlag("86");
			workattachment.setAttachmentId(id);
			projectReportData.setWorkAttachments(workattachmentDao.findList(workattachment));
			/*if (projectReportData.getSignCostOne()!=null && StringUtils.isNotBlank(projectReportData.getSignCostOne().getId())){
				projectReportData.setSignCostOne(UserUtils.get(projectReportData.getSignCostOne().getId()));
			}
			if (projectReportData.getSignCostTwo()!=null && StringUtils.isNotBlank(projectReportData.getSignCostTwo().getId())){
				projectReportData.setSignCostTwo(UserUtils.get(projectReportData.getSignCostTwo().getId()));
			}*/
			projectReportData.setProjectContentDataList(projectContentDataDao.findReportContent(projectReportData.getId(),"1"));
			projectReportData.setProjectBasedDataList(projectBasedDataDao.findReportBased(projectReportData.getId(),"3"));
            WorkReviewAudit workReviewAudit = new WorkReviewAudit();
            workReviewAudit.setType("1");
            workReviewAudit.setReportId(projectReportData.getId());
            workReviewAudit.setCompanyId(projectReportData.getCompanyId());
			projectReportData.setProjectReviewList(workReviewAuditDao.findList(workReviewAudit));
		}
		return projectReportData;
	}
	public List<Workattachment> getWorkattachments(String id) {
		ProjectReportData projectReportData = super.get(id);
		if (projectReportData!=null && StringUtils.isNotBlank(projectReportData.getId())){
			Workattachment workattachment = new Workattachment();
			workattachment.setAttachmentId(id);
			workattachment.setAttachmentFlag("86");
			return workattachmentDao.findList(workattachment);
		}else {
			return new ArrayList<>();
		}
	}
	public ProjectReportData getNoInvalid(String id) {
		ProjectReportData projectReportData = dao.getNoInvalid(id);
		Workattachment workattachment = new Workattachment();
		workattachment.setAttachmentId(id);
		workattachment.setAttachmentFlag("86");
		projectReportData.setWorkAttachments(workattachmentDao.findList(workattachment));
		if (projectReportData.getSignCostOne()!=null && StringUtils.isNotBlank(projectReportData.getSignCostOne().getId())){
			projectReportData.setSignCostOne(UserUtils.get(projectReportData.getSignCostOne().getId()));
		}
		if (projectReportData.getSignCostTwo()!=null && StringUtils.isNotBlank(projectReportData.getSignCostTwo().getId())){
			projectReportData.setSignCostTwo(UserUtils.get(projectReportData.getSignCostTwo().getId()));
		}
		return projectReportData;
	}

	@Transactional(readOnly = false)
	public void reportNumber(String reportId,String number) {
		long time = System.currentTimeMillis();
		String picNamePhoto = time + ".png";
		ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
		WordToPic.TextToAliyunPic(number, 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);
		String url=Global.getAliyunUrl()+"/"+Global.getContractNumPath()+picNamePhoto;
		dao.reportNumber(reportId,number,url);
	}
	@Transactional(readOnly = false)
	public String getChangeId(String id) {
		return dao.getChangeId(id);
	}


	public String getNumber(ProjectRecords projectRecords) {
		if (projectRecords!=null && StringUtils.isNotBlank(projectRecords.getId())){
			ProjectReportData projectReportData = new ProjectReportData();
			projectReportData.setProject(projectRecords);
			ProjectReportData value = dao.getNumber(projectReportData);
			if (value==null || StringUtils.isBlank(value.getNumber())){
				return "001";
			}else {
				return UserUtils.getNumber(value.getNumber());
			}
		}else {
			return "001";
		}

	}

	public List<ProjectReportData> findList(ProjectReportData projectReportData) {
		return super.findList(projectReportData);
	}

	public Page<ProjectReportData> findPage(Page<ProjectReportData> page, ProjectReportData projectReportData) {
		return super.findPage(page, projectReportData);
	}
	public Page<ProjectReportData> findInfoPage(Page<ProjectReportData> page, ProjectReportData projectReportData) {
		projectReportData.setPage(page);
		projectReportData.getSqlMap().put("dsf", dataScopeFilter(projectReportData.getCurrentUser(), "o", "u","s", MenuStatusEnum.PROJECT_REPORTDATA.getValue()));
		List<ProjectReportData> projectReportDatas = dao.findInfoList(projectReportData);
		for (ProjectReportData reportData:projectReportDatas){
			String projectMaster = projectRecordsService.getMasterStr(reportData.getProject().getId());
			reportData.setProjectMaster(projectMaster);
		}
		page.setList(projectReportDatas);
		return page;
	}
	public Page<ProjectReportData> findInfoPageByStatus(Page<ProjectReportData> page, ProjectReportData projectReportData) {
		projectReportData.setPage(page);
//		projectReportData.getSqlMap().put("dsf", dataScopeFilter(projectReportData.getCurrentUser(), "o", "u","s", MenuStatusEnum.PROJECT_REPORTDATA.getValue()));
		User user = UserUtils.getUser();
		projectReportData.setCreateBy(user);
		List<ProjectReportData> projectReportDatas = dao.findInfoListByStatus(projectReportData);
//		for (ProjectReportData reportData:projectReportDatas){
//			String projectMaster = projectRecordsService.getMasterStr(reportData.getProject().getId());
//			reportData.setProjectMaster(projectMaster);
//		}
		page.setList(projectReportDatas);
		return page;
	}

	public Page<ProjectReportData> findInvalidPage(Page<ProjectReportData> page, ProjectReportData entity) {
		entity.setPage(page);
		page.setList(dao.findInvalidList(entity));
		return page;
	}

	@Transactional(readOnly = false)
	public void save(ProjectReportData projectReportData) {
		if (projectReportData.getIsNewRecord()){
			projectReportData.preInsert();
			projectReportData.setCreateDate(new Date());
			dao.insert(projectReportData);
		}else{
			projectReportData.preUpdate();
			dao.update(projectReportData);
		}
		if (StringUtils.isBlank(projectReportData.getFileStatus())){
			projectReportData.setFileStatus("1");
		}
		dao.updateFileStatus(projectReportData);
	}
	@Transactional(readOnly = false)
	public void update(ProjectReportData projectReportData) {
		projectReportData.preUpdate();
		dao.update(projectReportData);
		if (StringUtils.isBlank(projectReportData.getFileStatus())) {
			projectReportData.setFileStatus("1");
		}
		dao.updateFileStatus(projectReportData);
	}
	@Transactional(readOnly = false)
	public void  updateFileStatus(ProjectReportData projectReportData) {
		if (StringUtils.isBlank(projectReportData.getFileStatus())) {
			projectReportData.setFileStatus("1");
		}
		dao.updateFileStatus(projectReportData);
	}
	@Transactional(readOnly = false)
	public void updateInvalidProcessInstanceId(ProjectReportData projectReportData) {
		dao.updateInvalidProcessInstanceId(projectReportData);
	}
	@Transactional(readOnly = false)
	public void insert(ProjectReportData projectReportData) {
		projectReportData.setCreateDate(new Date());
		dao.insert(projectReportData);
	}
	@Transactional(readOnly = false)
	public void saveInvalid(ProjectReportData projectReportData) {
		dao.saveInvalid(projectReportData);
		//projectReportData.setFileStatus("1");
		//dao.updateFileStatus(projectReportData);
	}

	@Transactional(readOnly = false)
	public void delete(ProjectReportData projectReportData) {
		//dao.deleteContentChange(projectReportData.getId());
		dao.deleteReportDataInfo(projectReportData.getId());
		super.delete(projectReportData);
	}

	@Transactional(readOnly = false)
	public void deleteReportDataInfo(ProjectReportData projectReportData) {
		dao.deleteReportDataInfo(projectReportData.getId());
	}
	@Transactional(readOnly = false)
	public void deleteReportDataBased(ProjectReportData projectReportData) {
		dao.deleteReportDataBased(projectReportData.getId());
	}

	/**
	 * 提交存储
	 * @param projectReportData
	 * @param variables
	 */
	@Transactional(readOnly = false)
	public String save(ProjectReportData projectReportData,Map<String, Object> variables,String processInstanceId,List<User> masters) {
	    User user = UserUtils.getUser();
		Boolean insert = false;
		if (StringUtils.isBlank(projectReportData.getId())){
			projectReportData.preInsert();
			insert = true;
		}
		if(StringUtils.isBlank(projectReportData.getNumber())){
			ProjectRecords projectRecords = projectRecordsService.get(projectReportData.getProject().getId());
			projectReportData.setNumber(projectRecords.getProjectId());
		}
		ProjectRecords projectRecords = projectRecordsService.get(projectReportData.getProject());
		Office recordsOffice =officeService.get(projectRecords.getOffice());
		String title = "报告名称:"+projectReportData.getName();
		String str =  "报告名称:"+projectReportData.getName()+",工作内容类型:"+ WorkContentTypeController.getContentTypeName(projectReportData.getType(),"")+",项目所属部门:"+recordsOffice.getName()+",负责人:"+user.getName();
		// 用来设置启动流程的人员ID，引擎会自动把用户ID保存到activiti:initiator中
		identityService.setAuthenticatedUserId(user.getId());
		// 启动流程
		String businessKey = projectReportData.getId().toString();
		WorkActivityMenu workActivityMenu = workActivityMenuService.findByParentAndOffice("9764872f45b84acd893010e66a3db2c8", recordsOffice);
		// 启动流程
		String processType = workActivityMenu.getProcessType();
		StringBuffer buffer = new StringBuffer();
		Activity activity = new Activity();
		WorkProjectNotify workProjectNotify = UtilNotify
				.saveNotify(projectReportData.getId(),
						null,
						projectReportData.getCompanyId(),
						title,
						str,
						"45",
						"0",
						"待审批",
						""
				);
		List<User> users = new ArrayList<>();
		if (insert) {
			this.insert(projectReportData);
		}else {
			this.save(projectReportData);
		}
		List<User> bmzrs = UserUtils.getByRoleActivityEnname("bmzr",2,user.getOffice().getId(),"12",projectReportData.getCreateBy());
//		List<User> bzshbygs = UserUtils.getByRoleActivityEnname("bzshbyg",3,recordsOffice.getId(),"12",projectReportData.getCreateBy());
		List<User> bzshbs = UserUtils.getByRoleActivityEnname("bzshb",3,recordsOffice.getId(),"12",projectReportData.getCreateBy());
//		List<User> fglds = UserUtils.getByRoleActivityEnname("fgld",2,recordsOffice.getId(),"12",projectReportData.getCreateBy());
//		List<User> fgzlfzs = UserUtils.getByRoleActivityEnname("zlfgld",3,recordsOffice.getId(),"12",projectReportData.getCreateBy());
//		List<User> glydas = UserUtils.getByRoleActivityEnname("bggdgly",3,recordsOffice.getId(),"12",projectReportData.getCreateBy());
		List<User> gzrs = UserUtils.getByRoleActivityEnname("zjl",3,recordsOffice.getId(),"12",projectReportData.getCreateBy());
		List<User> glydas  = UserUtils.getByRoleActivityEnname("fzjl",3,recordsOffice.getId(),"12",projectReportData.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(),recordsOffice.getId(),"8",projectReportData.getCreateBy());
					if (enusers.size()==0){
							/*dao.delete(projectReportData);
							for (Workattachment workattachment : projectReportData.getWorkAttachments()) {
								workattachmentDao.delete(workattachment);
							}*/
						projectReportData.setStatus("1");
						this.save(projectReportData);
						return "流程审批人不能为空,角色"+a.getRole().getName()+"下无用户,请联系管理员！";
					}
					variables.put(encount, enusers.size());
					variables.put(enlist, enusers);
				}
				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.getUser().getId())) {
					users.add(activity.getUser());
				}
				//角色审批
				if (StringUtils.isNotBlank(activity.getRole().getEnname())) {
					users = UserUtils.getByRoleActivityEnnames(activity.getRole().getEnname(),recordsOffice.getId(),"8",projectReportData.getCreateBy());
				}
			}
			workProjectNotify.setId("");
		} else {
			//variables.put("masterList", masters);
				/*variables.put("bmzrList", bmzrs);
				variables.put("bzshbList", bzshbs);
				variables.put("fgldList", fglds);
				variables.put("fgzlfzList", fgzlfzs);
				variables.put("glydaList", glydas);
				variables.put("gzrList", gzrs);*/
			//|| bmzrs.size()==0 || fglds.size()==0 || bzshbs.size()==0 || fgzlfzs.size()==0 || glydas.size()==0 || gzrs.size()==0
			if (bmzrs.size()==0 ){
				projectReportData.setStatus("1");
				this.save(projectReportData);
			}
			if (bzshbs.size()==0){
				return "流程审批人不能为空,项目负责人下无用户,请联系管理员！";
			}
				/*if (bmzrs.size()==0){
					return "流程审批人不能为空,角色部门负责人下无用户,请联系管理员！";
				}
				if (fglds.size()==0){
					return "流程审批人不能为空,角色分管领导下无用户,请联系管理员！";
				}
				if (bzshbs.size()==0){
					return "流程审批人不能为空,标准审核部下无用户,请联系管理员！";
				}
				if (fgzlfzs.size()==0){
					return "流程审批人不能为空分管质量副总下无用户,请联系管理员！";
				}
				if (glydas.size()==0){
					return "流程审批人不能为空,档案管理员下无用户,请联系管理员！";
				}
				if (gzrs.size()==0){
					return "流程审批人不能为空,盖章人下无用户,请联系管理员！";
				}*/
			//variables.put("mastercount",masters.size());
				/*variables.put("bmzrcount",bmzrs.size());
				variables.put("bzshbcount",bzshbs.size());
				variables.put("fgldcount",fglds.size());
				variables.put("fgzlfzcount",fgzlfzs.size());
				variables.put("glydacount",glydas.size());
				variables.put("gzrcount",gzrs.size());*/
			processType = "reportAudit";
			users.addAll(bmzrs);
			variables.put("masterList", bmzrs);
			variables.put("mastercount", bmzrs.size());
		}
		for (User u : users){
			workProjectNotify.setUser(u);
			workProjectNotify.setNotifyRole("部门负责人审批");
			workProjectNotify.setId("");
			workProjectNotifyService
					.save(workProjectNotify);
			Map<String,Object> extras = new HashMap<>();
			extras.put("type","7001");
			extras.put("id",workProjectNotify.getId());
			extras.put("procDefKey","45");
			UserUtils.pushInfoToApp(title,str,extras,u.getId());
			UserUtils.pushIm(u.getId(),str);
				/*List<WebSocket> toUserConns = ChatServerPool.getWebSocketByUser(u.getId());
				for (WebSocket toUserConn:toUserConns) {
					String message = "{\"to\":\""+u.getId()+"\"," +
							"\"msg\":\"审批信息 报告发起人:" + user.getName() + ",报告名称:"+ projectReportData.getName() + " 待审批!\"," +
							"\"useType\":\"sys\"}";
					ChatServerPool.sendMessageToUser(toUserConn, message);//同时向本人发送消息
				}*/
		}
		variables.put("type", processType);
		variables.put("busId", businessKey);
		variables.put("title", "审批单：" + projectReportData.getNumber());//设置标题；

		ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processType, businessKey, variables);
		projectReportData.setProcessInstance(processInstance);
		if (StringUtils.isNotBlank(processInstanceId)) {
            workActivityProcessService.updateProcessInstanceId(processInstance.getId(),processInstanceId);
            workActivityProcessService.deleteProcessInstanceId(processInstanceId);
            workActivityProcessService.deleteProcessIdAuditUsers(processInstanceId);
        }
		// 更新流程实例ID
		projectReportData.setProcessInstanceId(processInstance.getId());
		dao.updateProcessInstanceId(projectReportData);
		List<Activity> list = workActivityMenu.getActivities();
		if (list != null && list.size() != 0) {
			workActivityProcessService.saveList(list, processInstance.getId());
		} else {
			WorkActivityProcess workActivityProcess = new WorkActivityProcess();
			workActivityProcess.setProcessKey(processType);
			workActivityProcess.setCount(1);
			workActivityProcess.setProcessInstanceId(processInstance.getId());
			workActivityProcess.setIsApproval("0");
			workActivityProcessService.insert(workActivityProcess);
			workActivityProcess.setCount(2);
			workActivityProcessService.insert(workActivityProcess);
			workActivityProcess.setCount(3);
			workActivityProcessService.insert(workActivityProcess);
			workActivityProcess.setCount(4);
			workActivityProcessService.insert(workActivityProcess);
//			workActivityProcess.setCount(5);
//			workActivityProcessService.insert(workActivityProcess);
//			workActivityProcess.setCount(6);
//			workActivityProcessService.insert(workActivityProcess);
//			workActivityProcess.setCount(7);
//			workActivityProcessService.insert(workActivityProcess);
//			workActivityProcess.setCount(8);
//			workActivityProcessService.insert(workActivityProcess);
			workActivityProcessService.insertAuditsByType(bmzrs,processInstance.getId(),1,1);
//			workActivityProcessService.insertAuditsByType(bmzrs,processInstance.getId(),2,0);
//			workActivityProcessService.insertAuditsByType(bzshbygs,processInstance.getId(),3,0);
			workActivityProcessService.insertAuditsByType(bzshbs,processInstance.getId(),2,0);
//			workActivityProcessService.insertAuditsByType(fglds,processInstance.getId(),5,0);
//			workActivityProcessService.insertAuditsByType(fgzlfzs,processInstance.getId(),6,0);
			workActivityProcessService.insertAuditsByType(glydas,processInstance.getId(),3,0);
			workActivityProcessService.insertAuditsByType(gzrs,processInstance.getId(),4,0);
		}
       /* logger.info("保存数据："+(s2-s1)+"[ms],查询每个节点的审批用户列表"+(s3-s2)+
                "[ms],工作流加入参数:"+(s4-s3)+"[ms],发送推送IM APP消息："+(s5-s4)+
                "[ms],判断是否存在流程实例数据并进行修改:"+(s6-s5)+"[ms],更新流程实例："+(s7-s6)+
                "[ms],保存流程追踪，流程审批人数据:"+(s7-s6)+"[ms],启动流程耗时"+(s12-s5)+"[ms]");*/
		return "true";
	}

	/**
	 * 提交存储
	 * @param id，remakrs
	 * @param variables
	 */
	@Transactional(readOnly = false)
	public String saveInvalid(String id,String remarks,Map<String, Object> variables,String invalidProcessInstanceId) {
		try {
			ProjectReportData projectReportData = get(id);
			projectReportData.setRemarks(remarks);
			projectReportData.setInvalidStatus("2");
			projectReportData.setStatus("6");
			User user = UserUtils.getUser();
			ProjectRecords projectRecords = projectRecordsService.get(projectReportData.getProject());
			Office recordsOffice =officeService.get(projectRecords.getOffice());
			//String str = "报告作废发起人："+user.getName()+",报告名称:"+projectReportData.getName()+",报告编号："+projectReportData.getNumber();
			String title = "报告名称:"+projectReportData.getName();
			String str =  "报告编号:"+projectReportData.getNumber()+",报告名称:"+projectReportData.getName()+",工作内容类型:"+ WorkContentTypeController.getContentTypeName(projectReportData.getType(),"")+",项目所属部门:"+recordsOffice.getName()+",负责人:"+user.getName();
			// 用来设置启动流程的人员ID，引擎会自动把用户ID保存到activiti:initiator中
			identityService.setAuthenticatedUserId(user.getId());
			// 启动流程
			String businessKey = projectReportData.getId().toString();
			WorkActivityMenu workActivityMenu = workActivityMenuService.findByParentAndOffice("9964872f45b84acd893010e66a3db2c8", recordsOffice);
			// 启动流程
			String processType = workActivityMenu.getProcessType();
			StringBuffer buffer = new StringBuffer();
			Activity activity = new Activity();
			WorkProjectNotify workProjectNotify = UtilNotify
					.saveNotify(projectReportData.getId(),
							null,
							projectReportData.getCompanyId(),
							title,
							str,
							"47",
							"0",
							"待审批",
							""
					);
			List<User> users = new ArrayList<>();
			List<User> bmzrs = UserUtils.getByRoleActivityEnname("bmzr",2,recordsOffice.getId(),"12",projectReportData.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(),recordsOffice.getId(),"8",projectReportData.getCreateBy());
						if (enusers.size()==0){
							/*dao.delete(projectReportData);
							for (Workattachment workattachment : projectReportData.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(),recordsOffice.getId(),"8",projectReportData.getCreateBy());
					}
					//人员审批
					if (StringUtils.isNotBlank(activity.getUser().getId())) {
						users.add(activity.getUser());
					}
				}
				workProjectNotify.setId("");
			} else {
				variables.put("bmzrList", bmzrs);
				if (bmzrs.size()==0) {
					return "流程审批人不能为空,角色部门负责人下无用户,请联系管理员！";
				}
				variables.put("bmzrcount",bmzrs.size());
				users.addAll(bmzrs);
				processType = "reportInvalidReview";
			}
			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","47");
				UserUtils.pushInfoToApp(title,str,extras,u.getId());
				UserUtils.pushIm(u.getId(),str);
			}
			variables.put("type", processType);
			variables.put("busId", businessKey);
			variables.put("title", "审批单：" + projectReportData.getNumber());//设置标题；

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

			projectReportData.setProcessInstance(processInstance);
			if (StringUtils.isNotBlank(invalidProcessInstanceId)) {
				workActivityProcessService.updateProcessInstanceId(processInstance.getId(),invalidProcessInstanceId);
				workActivityProcessService.deleteProcessInstanceId(invalidProcessInstanceId);
				workActivityProcessService.deleteProcessIdAuditUsers(invalidProcessInstanceId);
			}
			// 更新流程实例ID
			projectReportData.setInvalidProcessInstanceId(processInstance.getId());
			dao.updateInvalidProcessInstanceId(projectReportData);
			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);
				workActivityProcessService.insertAuditsByType(bmzrs,processInstance.getId(),1,1);
			}
			projectReportData.preUpdate();
			update(projectReportData);
		}catch (Exception e){
			logger.info("Exception e:"+e);
			return "Exception e:"+e;
		}
		return "true";
	}

	/**
	 * 报告作废：强制撤销
	 * @param projectReportData
	 */
	@Transactional(readOnly = false)
	public void cancelInvalid(ProjectReportData projectReportData) {
		try {
			String invalidateProcessInstanceId = projectReportData.getInvalidProcessInstanceId();
			//将流程图中尚未走到的task的流程追踪信息逻辑删除，添加一条"撤销"流程追踪信息
			WorkActivityProcess process = new WorkActivityProcess();
			process.setProcessInstanceId(invalidateProcessInstanceId);
			process.setIsApproval("0");
			//List<WorkActivityProcess> processList1 = workActivityProcessService.findByProcInsId(process);
			WorkActivityProcess workActivityProcess = new WorkActivityProcess();
			workActivityProcess.setProcessInstanceId(invalidateProcessInstanceId);
			List<WorkActivityProcess> processList = workActivityProcessService.findList(workActivityProcess);
			WorkProjectNotify notify = new WorkProjectNotify();
			notify.setNotifyId(projectReportData.getId());
			List<User> userList = workProjectNotifyService.readByNotifyId(notify);
			if (userList!=null && userList.size()!=0) {
				for (User u : userList) {
					User user = UserUtils.get(u.getId());
					UserUtils.pushMeIm(user.getId());
				}
			}
			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,"报告作废-强制撤销");
			projectReportData.setInvalidStatus("3");
			update(projectReportData);

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

	}

	/**
	 * 报告：强制撤销
	 * @param projectReportData
	 */
	@Transactional(readOnly = false)
	public void cancelInvalidate(ProjectReportData projectReportData) {
		try {
			String invalidateProcessInstanceId = projectReportData.getProcessInstanceId();
			//将流程图中尚未走到的task的流程追踪信息逻辑删除，添加一条"撤销"流程追踪信息
			WorkActivityProcess process = new WorkActivityProcess();
			process.setProcessInstanceId(projectReportData.getProcessInstanceId());
			process.setIsApproval("0");
			//List<WorkActivityProcess> processList1 = workActivityProcessService.findByProcInsId(process);
			WorkActivityProcess workActivityProcess = new WorkActivityProcess();
			workActivityProcess.setProcessInstanceId(projectReportData.getProcessInstanceId());
			List<WorkActivityProcess> processList = workActivityProcessService.findList(workActivityProcess);
			WorkProjectNotify notify = new WorkProjectNotify();
			notify.setNotifyId(projectReportData.getId());
			List<User> userList = workProjectNotifyService.readByNotifyId(notify);
			if (userList!=null && userList.size()!=0) {
				for (User u : userList) {
					User user = UserUtils.get(u.getId());
					UserUtils.pushMeIm(user.getId());
					/*List<WebSocket> toUserConns = ChatServerPool.getWebSocketByUser(u.getId());
					for (WebSocket toUserConn : toUserConns) {
						String message = "{\"to\":\""+u.getId()+"\"," +
								"\"msg\":\"审批信息 报销人:"+ user.getName()+",报销编号:"+workReimbursement.getNumber() +" 强制撤销!\"," +
								"\"useType\":\"sys\"}";
						ChatServerPool.sendMessageToUser(toUserConn, message);//同时向本人发送消息
						//ChatServerPool.sendMessageToUser(toUserConn, u.getId() + "_sys_审批信息 " + "报销人:" + user.getName() + ",报销编号:" + workReimbursement.getNumber() + " 强制撤销!");//同时向本人发送消息
					}*/
				}
			}
			if(processList!=null && processList.size()>0){
				for (int i =0;i<processList.size();i++) {
					WorkActivityProcess p = processList.get(i);
					if(StringUtils.isNotBlank(p.getIsApproval()) && "0".equals(p.getIsApproval())){
						p.setDelFlag("1");
						p.setIsApproval("-1");
						workActivityProcessDao.updateDelFlagAndIsApproval(p);
					}
				}
				WorkActivityProcess pro = new WorkActivityProcess();
				pro.setId("");
				pro.preInsert();
				pro.setDelFlag("0");
				pro.setRemarks("[强制撤销]");
				pro.setProcessKey(processList.get(0).getProcessKey());
				pro.setIsApproval("1");
				pro.setProcessInstanceId(processList.get(0).getProcessInstanceId());
				pro.setCount(0);
				workActivityProcessDao.insert(pro);
			}

			//结束该流程,设为"撤销"状态
			actTaskService.endProcessInstance(invalidateProcessInstanceId,"报告-强制撤销");
			projectReportData.setStatus("3");
			update(projectReportData);

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

	}

	/**
	 * 审核流程
	 * @param reportData
	 */
	@Transactional(readOnly = false)
	public String auditSave(ProjectReportData reportData,List<User> auditUsers) {
		String flag = reportData.getAct().getFlag();
		// 对不同环节的业务逻辑进行操作
		Act act = reportData.getAct();
		String taskDefKey = act.getTaskDefKey();
		ProjectReportData projectReportData = null;
		if (!"modifyApply".equals(taskDefKey) && !taskDefKey.contains("audit")  ) {
			actTaskService.claim(act.getTaskId(), UserUtils.getUser().getId());
			projectReportData = get(reportData.getId());
		}else {
			projectReportData = reportData;
			flag = "yes";
		}
		User user= UserUtils.get(projectReportData.getCreateBy().getId());
		ProjectRecords projectRecords = projectRecordsService.get(projectReportData.getProject());
		Office recordsOffice =officeService.get(projectRecords.getOffice());
		String title = "报告名称:"+projectReportData.getName();
		String str =  "报告名称:"+projectReportData.getName()+",工作内容类型:"+ WorkContentTypeController.getContentTypeName(projectReportData.getType(),"")+",项目所属部门:"+recordsOffice.getName()+",负责人:"+user.getName();

		if (StringUtils.isBlank(act.getComment())){
			act.setComment(flag.equals("yes")?"同意":"驳回");
		}
		String comment = "";
		if (projectReportData.getStatus().equals("4")){
			comment = ("yes".equals(flag)?"[重新申请] ":"[已撤销] ");
		}else {
			comment = ("yes".equals(flag)?"[同意] ":"[驳回] ")+act.getComment();
		}
		//yes 的时候状态为审核通过 否则为未通过
		//1 审核中 2 未通过
		projectReportData.setStatus(("yes".equals(flag) ? "2" : "4"));
		Map<String, Object> vars = Maps.newHashMap();
		//业务逻辑对应的条件表达式
		String exp = "";
		String taskCount = "";
		String notifyRole = "";
		int key = 0;
		String enname = "";
		List<Activity> activitieList = activityService.getByProcessInstanceId(projectReportData.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(projectReportData.getProcessInstanceId());
		List<WorkActivityProcess> workActivityProcesses = workActivityProcessService.findList(selectProcess);
		List<Activity> activities = workActivityMenu.getActivities();
		if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("reportAudit")) {
			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(flag)) {
						workActivityProcess.setIsApproval("2");
						projectReportData.setStatus("4");
						String returnBack = "-1";
						for (Activity activity : activities) {
							if (activity.getCount() == activityProcess.getCount()) {
								returnBack = activity.getReturnBack();
								notifyRole = activity.getName();
								break;
							}
						}
						if (returnBack.equals("0")) {
							workActivityProcess.setId("");
						}

					} else {
						workActivityProcess.setIsApproval("1");
					}
				}else if(taskDefKey.equals("modifyApply")){
					notifyRole = "调整报告";
					taskCount = "0";
					exp = "pass";
					workActivityProcess.setId("");
					workActivityProcess.setCount(0);
					if (!"yes".equals(flag)) {
						projectReportData.setStatus("3");
						workActivityProcess.setIsApproval("2");
					} else {
						workActivityProcess.setIsApproval("1");
					}
					break;
				}
			}
		} else {
			workActivityMenu.setProcessType("reportAudit");
			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 ("master".equals(taskDefKey) && count.contains("1")) {
					taskCount = "1";
					exp = "pass";
					if ("yes".equals(flag)) {
						workActivityProcessService.insertAuditsByType(auditUsers,reportData.getProcessInstanceId(),2,1);

						notifyRole = "专家评审";
						workActivityProcess.setIsApproval("1");
						enname = "bzshb";
						vars.put("bzshbList", auditUsers);
						vars.put("bzshbcount",auditUsers.size());
					} else {
						notifyRole = "调整报告";
						//部门主任驳回审核（没操作一次驳回，在数据库中添加一条记录）
						dao.updateDirectorRejectedNum(reportData.getId());
						workActivityProcess.setIsApproval("2");
					}
					break;
				}else if ("bzshb".equals(taskDefKey) && count.contains("2")) {
					taskCount = "2";
					exp = "pass";
					if ("yes".equals(flag)) {
						workActivityProcessService.insertAuditsByType(auditUsers,reportData.getProcessInstanceId(),3,1);

						notifyRole = "副总经理审核";
						workActivityProcess.setIsApproval("1");
						enname = "glyda";
						vars.put("glydaList", auditUsers);
						vars.put("glydacount",auditUsers.size());
					} else {
						notifyRole = "调整报告";
						dao.updateeventuallyRejectedNum(reportData.getId());
						workActivityProcess.setIsApproval("2");
					}
					break;
				} else if ("glyda".equals(taskDefKey) && count.contains("3")) {
					taskCount = "3";
					exp = "pass";
					if ("yes".equals(flag)) {
						workActivityProcessService.insertAuditsByType(auditUsers,reportData.getProcessInstanceId(),3,1);

						notifyRole = "副总经理审核";
						workActivityProcess.setIsApproval("1");
						enname = "gzr";
						vars.put("gzrList", auditUsers);
						vars.put("gzrcount",auditUsers.size());
					} else {
						notifyRole = "调整报告";
						workActivityProcess.setIsApproval("2");
					}
					break;
				}else if ("gzr".equals(taskDefKey) && count.contains("4")) {
					taskCount = "4";
					exp = "pass";
					if ("yes".equals(flag)) {
						notifyRole = "审批通过";
						workActivityProcess.setIsApproval("1");
					} else {
						notifyRole = "调整报告";
						workActivityProcess.setIsApproval("2");
					}
					break;
				} else if ("modifyApply".equals(taskDefKey)&& count.contains("0")) {
					notifyRole = "负责人审批";
					taskCount = "0";
					exp = "pass";
					workActivityProcess.setCount(0);
					enname = "master";
					if (!"yes".equals(flag)) {
						projectReportData.setStatus("3");
					}
					break;
				}
			}
		}
		// 设置意见
		act.setComment(("yes".equals(flag) ? "[同意] " : "[驳回] ") + act.getComment());
		projectReportData.preUpdate();
		// 提交流程任务
		vars.put(exp, "yes".equals(flag) ? true : false);
		vars.put("passs", true);
		workActivityProcessService.updateProcess(workActivityProcess,workActivityMenu,key,taskCount,projectReportData.getProcessInstanceId(),taskDefKey,"modifyApply",flag,comment, activities);
		// 提交流程任务
		actTaskService.complete(act.getTaskId(), act.getProcInsId(), act.getComment(), vars);
		boolean state = actTaskService.isProcessEnd(act.getProcInsId());
		List<User> users = new ArrayList<>();
		List<User> userList = new ArrayList<>();
		if (!state) {
//            str = "yes".equals(flag)?"您的报销单审核：已通过":"您的报销单审核：未通过";
			users.add(projectReportData.getCreateBy());
			if ("yes".equals(flag)) {
				str =  "报告名称:"+projectReportData.getName()+",工作内容类型:"+ WorkContentTypeController.getContentTypeName(projectReportData.getType(),"")+",项目所属部门:"+recordsOffice.getName();
				projectReportData.setStatus("5");
				WorkProjectNotify notify = new WorkProjectNotify();
				notify.setNotifyId(projectReportData.getId());
				userList = workProjectNotifyService.readByNotifyId(notify);
				workProjectNotifyService
						.save(UtilNotify
								.saveNotify(projectReportData.getId(),
										projectReportData.getCreateBy(),
										projectReportData.getCompanyId(),
										title,
										str,
										"45",
										"0",
										"待通知",
										notifyRole));

			} else {
				WorkProjectNotify notify = new WorkProjectNotify();
				notify.setNotifyId(projectReportData.getId());
				userList = workProjectNotifyService.readByNotifyId(notify);
				if (StringUtils.isNotBlank(projectReportData.getStatus()) && !projectReportData.getStatus().equals("3")){
					projectReportData.setStatus("4");
					workProjectNotifyService
							.save(UtilNotify
									.saveNotify(projectReportData.getId(),
											projectReportData.getCreateBy(),
											projectReportData.getCompanyId(),
											title,
											str,
											"45",
											"0",
											"待通知",
											notifyRole));
				}
			}
			workActivityProcessService.deleteProcessIdAuditUsers(projectReportData.getProcessInstanceId());
		} else {
			if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("reportAudit")) {
				WorkProjectNotify notify = new WorkProjectNotify();
				notify.setNotifyId(projectReportData.getId());
				userList = workProjectNotifyService.readByNotifyId(notify);
				WorkProjectNotify workProjectNotify = UtilNotify
						.saveNotify(projectReportData.getId(),
								new User(),
								projectReportData.getCompanyId(),
								title,
								str,
								"45",
								"0",
								"待审批",
								notifyRole);
				List<WorkProjectNotify> workProjectNotifys = activityService.getByFlagAndTaskDefKeyList(
						activities,
						workProjectNotify,
						taskDefKey,
						flag,
						taskCount,
						projectReportData.getCreateBy(),
						user.getOffice().getId(),
						"8");
				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 ("glyda".equals(taskDefKey)){
							extras.put("type","7003");
						}else if("zlfgld".equals(taskDefKey)  ){
							extras.put("type","7002");
						}else {
							extras.put("type","7001");
						}
						extras.put("id",workProjectNotify.getId());
						extras.put("procDefKey","45");
						UserUtils.pushInfoToApp(title,str,extras,workProjectNotify1.getUser().getId());

					}
				}

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

							}
						}
					}else {
						WorkProjectNotify notify = new WorkProjectNotify();
						notify.setNotifyId(projectReportData.getId());
						userList = workProjectNotifyService.readByNotifyId(notify);
						users.add(projectReportData.getCreateBy());
						workProjectNotifyService
								.save(UtilNotify
										.saveNotify(projectReportData.getId(),
												projectReportData.getCreateBy(),
												projectReportData.getCompanyId(),
												title,
												str,
												"45",
												"0",
												"重新申请",
												notifyRole));
					}
				}
			}
		}
		if (users!=null && users.size()!=0) {
			for (User u : users) {
				UserUtils.pushIm(u.getId(),title);
			}
		}
		if (users!=null && userList.size()!=0) {
			for (User u : userList) {
				UserUtils.pushMeIm(u.getId());
			}
		}
		if (!"yes".equals(flag)){
			workReviewAuditDao.delReviewAudit(projectReportData.getId());
		}
		dao.update(projectReportData);
		return "保存审核意见成功！";
	}

	/**
	 * 审核流程
	 * @param reportData
	 */
	@Transactional(readOnly = false)
	public String auditInvalidSave(ProjectReportData reportData,List<User> auditUsers) {
		String flag = reportData.getAct().getFlag();
		Act act = reportData.getAct();
		ProjectReportData projectReportData = null;
		// 对不同环节的业务逻辑进行操作
		String taskDefKey = act.getTaskDefKey();
		if (!"modifyApply".equals(taskDefKey) && !taskDefKey.contains("audit")  ) {
			actTaskService.claim(act.getTaskId(), UserUtils.getUser().getId());
			projectReportData = get(reportData.getId());
		}else {
			flag = "yes";
			projectReportData = reportData;
		}
		User user= UserUtils.get(projectReportData.getCreateBy().getId());
		ProjectRecords projectRecords = projectRecordsService.get(projectReportData.getProject());
		Office recordsOffice =officeService.get(projectRecords.getOffice());
		//String str = "报告作废发起人："+user.getName()+",报告名称:"+projectReportData.getName()+",报告编号："+projectReportData.getNumber();
		String title = "报告名称:"+projectReportData.getName();
		String str =  "报告编号:"+projectReportData.getNumber()+",报告名称:"+projectReportData.getName()+",工作内容类型:"+ WorkContentTypeController.getContentTypeName(projectReportData.getType(),"")+",项目所属部门:"+recordsOffice.getName()+",负责人:"+user.getName();

		if (StringUtils.isBlank(act.getComment())){
			act.setComment(flag.equals("yes")?"同意":"驳回");
		}
		String comment = "";
		if (projectReportData.getStatus().equals("4")){
			comment = ("yes".equals(flag)?"[重新申请] ":"[已撤销] ");
		}else {
			comment = ("yes".equals(flag)?"[同意] ":"[驳回] ")+act.getComment();
		}
		//yes 的时候状态为审核通过 否则为未通过
		//1 审核中 2 未通过
		projectReportData.setInvalidStatus(("yes".equals(flag) ? "2" : "4"));
		Map<String, Object> vars = Maps.newHashMap();
		//业务逻辑对应的条件表达式
		String exp = "";
		String taskCount = "";
		String notifyRole = "";
		int key = 0;
		String enname = "";
		List<Activity> activitieList = activityService.getByProcessInstanceId(projectReportData.getInvalidProcessInstanceId());
		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(projectReportData.getInvalidProcessInstanceId());
		List<WorkActivityProcess> workActivityProcesses = workActivityProcessService.findList(selectProcess);
		List<Activity> activities = workActivityMenu.getActivities();
		if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("reportInvalidReview")) {
			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(flag)) {
						projectReportData.setInvalidStatus("4");
						workActivityProcess.setIsApproval("2");
						String returnBack = "-1";
						for (Activity activity : activities) {
							if (activity.getCount() == activityProcess.getCount()) {
								returnBack = activity.getReturnBack();
								notifyRole = activity.getName();
								break;
							}
						}
						if (returnBack.equals("0")) {
							workActivityProcess.setId("");
						}

					} else {
						workActivityProcess.setIsApproval("1");
					}
				}else if(taskDefKey.equals("modifyApply")){
					notifyRole = "调整报告作废";
					taskCount = "0";
					exp = "pass";
					workActivityProcess.setId("");
					workActivityProcess.setCount(0);
					if (!"yes".equals(flag)) {
						projectReportData.setInvalidStatus("3");
						workActivityProcess.setIsApproval("2");
					} else {
						workActivityProcess.setIsApproval("1");
					}
					break;
				}
			}
		} else {
			workActivityMenu.setProcessType("reportInvalidReview");
			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(flag)) {
						notifyRole = "审批通过";
						workActivityProcess.setIsApproval("1");
					} else {
						workActivityProcess.setIsApproval("2");
						notifyRole = "调整报告作废";
					}
					break;
				} else if ("modifyApply".equals(taskDefKey)&& count.contains("0")) {
					notifyRole = "负责人审批";
					taskCount = "0";
					exp = "pass";
					workActivityProcess.setCount(0);
					enname = "bmzr";
					if (!"yes".equals(flag)) {
						projectReportData.setInvalidStatus("3");
					}
					break;
				} else if ("apply_end".equals(taskDefKey)) {
				}

			}
		}
		// 设置意见
		act.setComment(("yes".equals(flag) ? "[同意] " : "[驳回] ") + act.getComment());
		projectReportData.preUpdate();
		// 提交流程任务
		vars.put(exp, "yes".equals(flag) ? true : false);
		vars.put("passs", true);
		workActivityProcessService.updateProcess(workActivityProcess,workActivityMenu,key,taskCount,projectReportData.getInvalidProcessInstanceId(),taskDefKey,"modifyApply",flag,comment, activities);
		// 提交流程任务
		actTaskService.complete(act.getTaskId(), act.getProcInsId(), act.getComment(), vars);
		boolean state = actTaskService.isProcessEnd(act.getProcInsId());
		List<User> users = new ArrayList<>();
		List<User> userList = new ArrayList<>();
		if (!state) {
//            str = "yes".equals(flag)?"您的报销单审核：已通过":"您的报销单审核：未通过";
			users.add(projectReportData.getCreateBy());
			projectReportData.setStatus("7");
			if ("yes".equals(flag)) {
				str =  "报告编号:"+projectReportData.getNumber()+",报告名称:"+projectReportData.getName()+",工作内容类型:"+ WorkContentTypeController.getContentTypeName(projectReportData.getType(),"")+",项目所属部门:"+recordsOffice.getName();
				projectReportData.setInvalidStatus("5");
				WorkProjectNotify notify = new WorkProjectNotify();
				notify.setNotifyId(projectReportData.getId());
				userList = workProjectNotifyService.readByNotifyId(notify);
				workProjectNotifyService
						.save(UtilNotify
								.saveNotify(projectReportData.getId(),
										projectReportData.getCreateBy(),
										projectReportData.getCompanyId(),
										title,
										str,
										"47",
										"0",
										"待通知",
										notifyRole));

			} else {
				WorkProjectNotify notify = new WorkProjectNotify();
				notify.setNotifyId(projectReportData.getId());
				userList = workProjectNotifyService.readByNotifyId(notify);
				if (StringUtils.isNotBlank(projectReportData.getStatus()) && !projectReportData.getStatus().equals("3")){
					projectReportData.setInvalidStatus("4");
					workProjectNotifyService
							.save(UtilNotify
									.saveNotify(projectReportData.getId(),
											projectReportData.getCreateBy(),
											projectReportData.getCompanyId(),
											title,
											str,
											"47",
											"0",
											"待通知",
											notifyRole));
				}
			}
			workActivityProcessService.deleteProcessIdAuditUsers(projectReportData.getInvalidProcessInstanceId());
		} else {
			if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("reportInvalidReview")) {
				WorkProjectNotify notify = new WorkProjectNotify();
				notify.setNotifyId(projectReportData.getId());
				userList = workProjectNotifyService.readByNotifyId(notify);
				WorkProjectNotify workProjectNotify = UtilNotify
						.saveNotify(projectReportData.getId(),
								new User(),
								projectReportData.getCompanyId(),
								title,
								str,
								"47",
								"0",
								"待审批",
								notifyRole);
				List<WorkProjectNotify> workProjectNotifys = activityService.getByFlagAndTaskDefKeyList(
						activities,
						workProjectNotify,
						taskDefKey,
						flag,
						taskCount,
						projectReportData.getCreateBy(),
						user.getOffice().getId(),
						"8");
				for (WorkProjectNotify workProjectNotify1:workProjectNotifys){
					workProjectNotify1.setId("");
					workProjectNotify1.setIsNewRecord(false);
					users.add(workProjectNotify1.getUser());
					workProjectNotifyService
							.save(workProjectNotify1);
				}

			} else {
				if (!"yes".equals(flag)) {
					WorkProjectNotify notify = new WorkProjectNotify();
					notify.setNotifyId(projectReportData.getId());
					userList = workProjectNotifyService.readByNotifyId(notify);
					workProjectNotifyService
							.save(UtilNotify
									.saveNotify(projectReportData.getId(),
											projectReportData.getCreateBy(),
											projectReportData.getCompanyId(),
											title,
											str,
											"47",
											"0",
											"重新申请",
											notifyRole));
					users.add( projectReportData.getCreateBy());
				} else {
					if (StringUtils.isNotBlank(enname)) {
						WorkProjectNotify notify = new WorkProjectNotify();
						notify.setNotifyId(projectReportData.getId());
						userList = workProjectNotifyService.readByNotifyId(notify);
						WorkProjectNotify workProjectNotify = UtilNotify
								.saveNotify(projectReportData.getId(),
										new User(),
										projectReportData.getCompanyId(),
										title,
										str,
										"47",
										"0",
										"待审批",
										notifyRole);
						users.addAll(auditUsers);
						for (User user1 : users) {
							workProjectNotify.setId("");
							workProjectNotify.setUser(user1);
							workProjectNotify.setIsNewRecord(false);
							workProjectNotifyService
									.save(workProjectNotify);
						}
					}else {
						WorkProjectNotify notify = new WorkProjectNotify();
						notify.setNotifyId(projectReportData.getId());
						userList = workProjectNotifyService.readByNotifyId(notify);
						users.add(projectReportData.getCreateBy());
						workProjectNotifyService
								.save(UtilNotify
										.saveNotify(projectReportData.getId(),
												projectReportData.getCreateBy(),
												projectReportData.getCompanyId(),
												title,
												str,
												"47",
												"0",
												"重新申请",
												notifyRole));
					}
				}
			}
		}
		if (StringUtils.isNotBlank(title) && users!=null && users.size()!=0) {
			for (User u : users) {
				UserUtils.pushIm(u.getId(),title);
			}
		}
		if (StringUtils.isNotBlank(title) && users!=null && userList.size()!=0) {
			for (User u : userList) {
				UserUtils.pushMeIm(u.getId());
			}
		}
		dao.update(projectReportData);
		return "保存审核意见成功！";
	}

	public Act getByAct(String processInstanceId){
		Act act = new Act();
		HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
		ProcessInstance processInstance = actTaskService.getProcIns(processInstanceId);
		if (processInstance!=null) {
			List<Task> taskList = actTaskService.getCurrentTaskList(processInstance);
			if(taskList!=null && taskList.size()>1){
				for (Task taskInfok:taskList) {
					if (taskInfok.getAssignee().equals(UserUtils.getUser().getId())) {
						act.setTaskId(taskInfok.getId());
						act.setTaskName(taskInfok.getName());
						act.setTaskDefKey(taskInfok.getTaskDefinitionKey());
						act.setProcDefId(taskInfok.getProcessDefinitionId());
						act.setProcInsId(taskInfok.getProcessInstanceId());
						act.setTask(taskInfok);
					}
				}
			}else {
				Task task = actTaskService.getCurrentTaskInfo(processInstance);
				act.setTaskId(task.getId());
				act.setTaskName(task.getName());
				act.setTaskDefKey(task.getTaskDefinitionKey());
				act.setProcDefId(task.getProcessDefinitionId());
				act.setProcInsId(task.getProcessInstanceId());
				act.setTask(task);
			}
		}
		return  act;
	}



}