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

import com.google.common.collect.Maps;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.service.CrudService;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.websocket.onchat.ChatServerPool;
import com.jeeplus.modules.act.entity.Act;
import com.jeeplus.modules.act.service.ActTaskService;
import com.jeeplus.modules.projectcontentinfo.dao.ProjectBasedDataDao;
import com.jeeplus.modules.projectcontentinfo.dao.ProjectContentDataDao;
import com.jeeplus.modules.projectcontentinfo.dao.ProjectReportChangeDao;
import com.jeeplus.modules.projectcontentinfo.entity.ProjectReportData;
import com.jeeplus.modules.projectcontentinfo.entity.ProjectReportRecord;
import com.jeeplus.modules.projectrecord.entity.ProjectRecords;
import com.jeeplus.modules.projectrecord.service.ProjectRecordsService;
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 java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

	@Autowired
	private WorkattachmentDao workattachmentDao;
	@Autowired
	private RuntimeService runtimeService;
	@Autowired
	protected TaskService taskService;
	@Autowired
	private ProjectBasedDataDao projectBasedDataDao;
	@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 ProjectReportRecordService projectReportRecordService;
	@Autowired
	private ProjectRecordsService projectRecordsService;
	@Autowired
	private OfficeService officeService;
	@Autowired
	private WorkReviewAuditDao workReviewAuditDao;

	public ProjectReportData get(String id) {
		ProjectReportData projectReportData = super.get(id);
		if (projectReportData!=null && StringUtils.isNotBlank(projectReportData.getId())) {
			List<Workattachment> list = new ArrayList<>();
			Workattachment workattachment = new Workattachment();
			workattachment.setAttachmentId(id);
			workattachment.setAttachmentFlag("87");
			list.addAll(workattachmentDao.findList(workattachment));
			Workattachment attachment = new Workattachment();
			attachment.setAttachmentId(projectReportData.getReportId());
			attachment.setAttachmentFlag("86");
			list.addAll(workattachmentDao.findList(attachment));
			projectReportData.setWorkAttachments(list);
			/*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(), "2"));
			projectReportData.setProjectBasedDataList(projectBasedDataDao.findReportBased(projectReportData.getId(),"4"));
			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())) {
			List<Workattachment> list = new ArrayList<>();
			Workattachment workattachment = new Workattachment();
			workattachment.setAttachmentId(id);
			workattachment.setAttachmentFlag("87");
			list.addAll(workattachmentDao.findList(workattachment));
			Workattachment attachment = new Workattachment();
			attachment.setAttachmentId(projectReportData.getReportId());
			attachment.setAttachmentFlag("86");
			list.addAll(workattachmentDao.findList(attachment));
			return list;
		}else {
			return new ArrayList<>();
		}
	}

	public ProjectReportData getBefore(String id) {
		ProjectReportData projectReportData = super.get(id);
		List<Workattachment> list = new ArrayList<>();
		Workattachment attachment = new Workattachment();
		String reportId = projectReportData.getReportId();
		if (StringUtils.isBlank(reportId)){
			reportId = id;
		}
		attachment.setAttachmentId(reportId);
		attachment.setAttachmentFlag("86");
		list.addAll(workattachmentDao.findList(attachment));
		projectReportData.setWorkAttachments(list);
		/*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()));
		}*/
		if (reportId.equals(id)){
			projectReportData.setProjectContentDataList(projectContentDataDao.findReportContent(reportId,"1"));
			projectReportData.setProjectBasedDataList(projectBasedDataDao.findReportBased(projectReportData.getId(),"3"));
		}else {
			projectReportData.setProjectContentDataList(projectContentDataDao.findReportContent(reportId,"2"));
			projectReportData.setProjectBasedDataList(projectBasedDataDao.findReportBased(projectReportData.getId(),"4"));
		}
		/*projectReportData.setProjectContentDataList(projectContentDataDao.findReportContent(projectReportData.getId(), "2"));
		projectReportData.setProjectBasedDataList(projectBasedDataDao.findReportBased(projectReportData.getId(),"4"));*/
		WorkReviewAudit workReviewAudit = new WorkReviewAudit();
		workReviewAudit.setType("1");
		workReviewAudit.setReportId(projectReportData.getId());
		workReviewAudit.setCompanyId(projectReportData.getCompanyId());
		projectReportData.setProjectReviewList(workReviewAuditDao.findList(workReviewAudit));
		return projectReportData;
	}
	public ProjectReportData findByBefore(ProjectReportData reportData) {
		ProjectReportData projectReportData = dao.findByBefore(reportData);

		return projectReportData;
	}

	public List<ProjectReportData> findList(ProjectReportData projectReportData) {
		return super.findList(projectReportData);
	}
	
	public Page<ProjectReportData> findPage(Page<ProjectReportData> page, ProjectReportData projectReportData) {
		return super.findPage(page, projectReportData);
	}


	@Transactional(readOnly = false)
	public void reportNumber(String reportId,String number) {
		dao.reportNumber(reportId,number);
	}

	@Transactional(readOnly = false)
	public void save(ProjectReportData projectReportData) {
		super.save(projectReportData);
	}
	@Transactional(readOnly = false)
	public void update(ProjectReportData projectReportData) {
		projectReportData.preUpdate();
		dao.update(projectReportData);
	}
	@Transactional(readOnly = false)
	public void insert(ProjectReportData projectReportData) {
		dao.insert(projectReportData);
	}
	@Transactional(readOnly = false)
	public void saveInvalid(ProjectReportData projectReportData) {
		dao.saveInvalid(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());
	}
	@Transactional(readOnly = false)
	public void deleteTree(ProjectReportData projectReportData) {
		dao.deleteTree(projectReportData);
	}
	@Transactional(readOnly = false)
	public void changeProjectReportData(ProjectReportData projectReportData) {
		projectReportData.setId(projectReportData.getReportId());
		dao.changeProjectReportData(projectReportData);
	}

	/**
	 * 提交存储
	 * @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;
		}
		ProjectRecords projectRecords = projectRecordsService.get(projectReportData.getProject());
		Office recordsOffice =officeService.get(projectRecords.getOffice());
		String title = "报告名称:"+projectReportData.getName();
		String str =  "变更编号"+projectReportData.getNumber()+",报告名称:"+projectReportData.getName()+",工作内容类型:"+ WorkContentTypeController.getContentTypeName(projectReportData.getType(),"")+",项目所属部门:"+recordsOffice.getName()+",负责人:"+user.getName();

		//String title = "报告变更变更发起人："+user.getName()+",报告变更名称:"+projectReportData.getName()+"待审批!";
		//String str =  "报告变更变更发起人："+user.getName()+",报告变更名称:"+projectReportData.getName()+",报告变更编号："+projectReportData.getNumber()+" 待审批!";
		// 用来设置启动流程的人员ID，引擎会自动把用户ID保存到activiti:initiator中
		identityService.setAuthenticatedUserId(user.getId());
		// 启动流程
		String businessKey = projectReportData.getId().toString();
		WorkActivityMenu workActivityMenu = workActivityMenuService.findByParentAndOffice("9864872f45b84acd893010e66a3db2c8", recordsOffice);
		// 启动流程
		String processType = workActivityMenu.getProcessType();
		StringBuffer buffer = new StringBuffer();
		Activity activity = new Activity();
		WorkProjectNotify workProjectNotify = UtilNotify
				.saveNotify(projectReportData.getId(),
						null,
						projectReportData.getCompanyId(),
						title,
						str,
						"46",
						"0",
						"待审批",
						""
				);
		List<User> users = new ArrayList<>();
		if (insert) {
			this.insert(projectReportData);
		}else {
			this.save(projectReportData);
		}
		List<User> bmzrs = UserUtils.getByRoleActivityEnname("bmzr",2,recordsOffice.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("gzr",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(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("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);*/
			if (masters.size()==0 ){
				projectReportData.setStatus("1");
				this.save(projectReportData);
			}
			if (masters.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("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 = "reportChangeReview";
			users.addAll(masters);
		}
		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","46");
			UserUtils.pushInfoToApp(title,str,extras,u.getId());
			UserUtils.pushIm(u.getId(),"报告变更变更发起人:\" + user.getName() + \",报告变更名称:\"+ projectReportData.getName() + \" 待审批!");
		}
		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.setCount(1);
			workActivityProcess.setProcessKey(processType);
			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(masters,processInstance.getId(),1,1);
			workActivityProcessService.insertAuditsByType(bmzrs,processInstance.getId(),2,0);
			workActivityProcessService.insertAuditsByType(bzshbygs,processInstance.getId(),3,0);
			workActivityProcessService.insertAuditsByType(bzshbs,processInstance.getId(),4,0);
			workActivityProcessService.insertAuditsByType(fglds,processInstance.getId(),5,0);
			workActivityProcessService.insertAuditsByType(fgzlfzs,processInstance.getId(),6,0);
			workActivityProcessService.insertAuditsByType(glydas,processInstance.getId(),7,0);
			workActivityProcessService.insertAuditsByType(gzrs,processInstance.getId(),8,0);
		}
		return "true";
	}

	/**
	 * 合同作废：强制撤销
	 * @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());
				}
			}
			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();
		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 {
			projectReportData = reportData;
			flag = "yes";
		}
		User user= UserUtils.get(projectReportData.getCreateBy().getId());
		ProjectRecords projectRecords = projectRecordsService.get(projectReportData.getProject());
		projectRecordsService.getQueryProjectMasters(projectRecords);
		Office recordsOffice =officeService.get(projectRecords.getOffice());
		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.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("reportChangeReview")) {
			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.setStatus("4");
						String returnBack = "-1";
						workActivityProcess.setIsApproval("2");
						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(flag)) {
						projectReportData.setStatus("3");
						workActivityProcess.setIsApproval("2");
					} else {
						workActivityProcess.setIsApproval("1");
					}
					break;
				}
			}
		} else {
			workActivityMenu.setProcessType("reportChangeReview");
			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 = "bmzr";
					} else {
						notifyRole = "调整报告";
						workActivityProcess.setIsApproval("2");
					}
					break;
				}
				// 审核环节
				else if ("bmzr".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 = "bzshbyg";
					} else {
						notifyRole = "调整报告";
						workActivityProcess.setIsApproval("2");
					}
					break;
				} else if ("bzshbyg".equals(taskDefKey) && count.contains("3")) {
					taskCount = "3";
					exp = "pass";
					if ("yes".equals(flag)) {
						workActivityProcessService.insertAuditsByType(auditUsers,reportData.getProcessInstanceId(),4,1);

						notifyRole = "部门分管领导审核";
						workActivityProcess.setIsApproval("1");
						enname = "bzshb";
					} else {
						notifyRole = "调整报告";
						workActivityProcess.setIsApproval("2");
					}
					break;
				}else if ("bzshb".equals(taskDefKey) && count.contains("4")) {
					taskCount = "4";
					exp = "pass";
					if ("yes".equals(flag)) {
						workActivityProcessService.insertAuditsByType(auditUsers,reportData.getProcessInstanceId(),5,1);

						notifyRole = "部门分管领导审核";
						workActivityProcess.setIsApproval("1");
						enname = "fgld";
					} else {
						notifyRole = "调整报告";
						workActivityProcess.setIsApproval("2");
					}
					break;
				}else if ("fgld".equals(taskDefKey) && count.contains("4")) {
					taskCount = "5";
					exp = "pass";
					if ("yes".equals(flag)) {
						workActivityProcessService.insertAuditsByType(auditUsers,reportData.getProcessInstanceId(),6,1);

						notifyRole = "分管质量副总审核";
						workActivityProcess.setIsApproval("1");
						enname = "zlfgld";
					} else {
						notifyRole = "调整报告";
						workActivityProcess.setIsApproval("2");
					}
					break;
				} else if ("fgzlfz".equals(taskDefKey) && count.contains("5")) {
					taskCount = "6";
					exp = "pass";
					if ("yes".equals(flag)) {
						workActivityProcessService.insertAuditsByType(auditUsers,reportData.getProcessInstanceId(),7,1);

						notifyRole = "档案管理员审核";
						workActivityProcess.setIsApproval("1");
						enname = "bggdgly";
					} else {
						notifyRole = "调整报告";
						workActivityProcess.setIsApproval("2");
					}
					break;
				} else if ("glyda".equals(taskDefKey) && count.contains("6")) {
					taskCount = "7";
					exp = "pass";
					if ("yes".equals(flag)) {
						workActivityProcessService.insertAuditsByType(auditUsers,reportData.getProcessInstanceId(),8,1);

						notifyRole = "盖章人盖章";
						workActivityProcess.setIsApproval("1");
						enname = "gzr";
					} else {
						workActivityProcess.setIsApproval("2");
						notifyRole = "调整报告";
					}
					break;
				} else if ("gzr".equals(taskDefKey) && count.contains("7")) {
					taskCount = "8";
					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<>();
		boolean status = false;
		if (!state) {
//            str = "yes".equals(flag)?"您的报销单审核：已通过":"您的报销单审核：未通过";
			users.add(projectReportData.getCreateBy());
			if ("yes".equals(flag)) {
				str =  "变更编号"+projectReportData.getNumber()+",报告名称:"+projectReportData.getName()+",工作内容类型:"+ WorkContentTypeController.getContentTypeName(projectReportData.getType(),"")+",项目所属部门:"+recordsOffice.getName();

				projectReportData.setStatus("5");
				status = true;
				WorkProjectNotify notify = new WorkProjectNotify();
				notify.setNotifyId(projectReportData.getId());
				userList = workProjectNotifyService.readByNotifyId(notify);
				workProjectNotifyService
						.save(UtilNotify
								.saveNotify(projectReportData.getId(),
										projectReportData.getCreateBy(),
										projectReportData.getCompanyId(),
										title,
										str,
										"46",
										"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,
											"46",
											"0",
											"待通知",
											notifyRole));
				}
			}
			workActivityProcessService.deleteProcessIdAuditUsers(projectReportData.getProcessInstanceId());
		} else {
			if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("reportChangeReview")) {
				WorkProjectNotify notify = new WorkProjectNotify();
				notify.setNotifyId(projectReportData.getId());
				userList = workProjectNotifyService.readByNotifyId(notify);
				WorkProjectNotify workProjectNotify = UtilNotify
						.saveNotify(projectReportData.getId(),
								new User(),
								projectReportData.getCompanyId(),
								title,
								str,
								"46",
								"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","46");
						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,
											"46",
											"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,
										"46",
										"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 ("zlfgld".equals(taskDefKey)  ){
									extras.put("type","7002");
								}else if("glyda".equals(taskDefKey)  ){
									extras.put("type","7003");
								}else {
									extras.put("type","7001");
								}
								extras.put("id",workProjectNotify.getId());
								extras.put("procDefKey","46");
								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,
												"46",
												"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());
			}
		}
		dao.update(projectReportData);
		if (status){
			List<Workattachment> attachmentList = projectReportData.getWorkAttachments();
			for (Workattachment workattachment : attachmentList){
				if (workattachment.DEL_FLAG_NORMAL.equals(workattachment.getDelFlag())) {
					workattachment.setAttachmentId(projectReportData.getReportId());
					workattachment.setAttachmentFlag("86");
					workattachment.setAttachmentUser(UserUtils.getUser().getId());
					if (StringUtils.isBlank(workattachment.getId()) || "null".equals(workattachment.getId())) {
						workattachment.preInsert();
						workattachmentDao.insert(workattachment);
					} else {
						workattachment.preUpdate();
						workattachmentDao.update(workattachment);
					}
				} else {
					workattachmentDao.delete(workattachment);
				}
			}
			ProjectReportRecord projectReportRecord = new ProjectReportRecord();
			projectReportRecord.setReport(new ProjectReportData(projectReportData.getReportId()));
			List<ProjectReportRecord> projectReportRecords = projectReportRecordService.findList(projectReportRecord);
			if (projectReportRecords!=null && projectReportRecords.size()!=0){
				for (ProjectReportRecord reportRecord:projectReportRecords){
					if (!"5".equals(reportRecord.getStatus())){
						projectReportData.setFileStatus("2");
						if ("2".equals(reportRecord.getStatus())){
							projectReportRecordService.cancelInvalidate(reportRecord);
						}
					}
				}
			}
			if (StringUtils.isBlank(projectReportData.getFileStatus())){
				projectReportData.setFileStatus("1");
			}
			projectReportData.setId(projectReportData.getReportId());
			dao.changeBerforProjectReportData(projectReportData);

		}
		if (!"yes".equals(flag)){
			workReviewAuditDao.delReviewAudit(projectReportData.getId());
		}
		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;
	}



}