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

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jeeplus.common.oss.OSSClientUtil;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.service.CrudService;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.MenuStatusEnum;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.modules.act.service.ActTaskService;
import com.jeeplus.modules.act.utils.ActUtils;
import com.jeeplus.modules.sys.entity.Role;
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.service.WorkattachmentService;
import com.jeeplus.modules.sys.utils.UserUtils;
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.workfullexecute.dao.WorkFullExecuteDao;
import com.jeeplus.modules.workfullexecute.entity.WorkFullExecute;
import com.jeeplus.modules.workfullmanage.dao.WorkFullManageDao;
import com.jeeplus.modules.workfullmanage.entity.WorkFullManage;
import com.jeeplus.modules.workfullmanage.service.WorkFullManageService;
import com.jeeplus.modules.workprojectnotify.entity.WorkProjectNotify;
import com.jeeplus.modules.workprojectnotify.service.WorkProjectNotifyService;
import org.activiti.engine.ActivitiObjectNotFoundException;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 项目实施Service
 * @author fgy
 * @version 2017-10-27
 */
@SuppressWarnings("all")
@Service
@Transactional(readOnly = true)
public class WorkFullExecuteService extends CrudService<WorkFullExecuteDao, WorkFullExecute> {

	@Autowired
	private WorkProjectNotifyService workProjectNotifyService;
	@Autowired
	private ActTaskService actTaskService;
	@Autowired
	private WorkActivityMenuService workActivityMenuService;
	@Autowired
	private WorkActivityProcessService workActivityProcessService;
	@Autowired
	private ActivityService activityService;
	@Autowired
	private RuntimeService runtimeService;
	@Autowired
	private IdentityService identityService;
	@Autowired
	private WorkFullManageService workFullManageService ;
	@Autowired
	private WorkFullExecuteDao workFullExecuteDao;
	@Autowired
	private WorkattachmentService workattachmentService;
	@Autowired
	private WorkFullManageDao workFullManageDao;
	@Autowired
	private OfficeService officeService;
	private Lock lock = new ReentrantLock();

	public WorkFullExecute get(String id) {
		WorkFullExecute workFullExecute = super.get(id);
		if(workFullExecute != null){
			WorkFullManage workFullManage = workFullManageService.get(workFullExecute.getWorkFullManageId());
			if(workFullManage != null){
				workFullExecute.setWorkFullManage(workFullManage);
				workFullExecute.setWorkFullManageId(workFullManage.getId());
			}
			List<Workattachment> executeFileList = workattachmentService.getListByAttachmentIdAndFlag(workFullExecute.getId(),"2");
			if(executeFileList!=null && executeFileList.size()>0){
				for (int i = 0; i < executeFileList.size(); i++) {
					Workattachment executeFile = executeFileList.get(i);
					if(executeFile != null){
						executeFile.setAttachmentUser(UserUtils.get(executeFile.getAttachmentUser()).getName());
					}
				}
				workFullExecute.setExecuteFile(executeFileList);
			}
			List<Workattachment> manuscriptFileList = workattachmentService.getListByAttachmentIdAndFlag(workFullExecute.getId(),"3");
			if(manuscriptFileList!=null && manuscriptFileList.size()>0){
				for (int i = 0; i < manuscriptFileList.size(); i++) {
					Workattachment manuscriptFile = manuscriptFileList.get(i);
					if(manuscriptFile != null){
						manuscriptFile.setAttachmentUser(UserUtils.get(manuscriptFile.getAttachmentUser()).getName());
					}
				}
				workFullExecute.setManuscriptFile(manuscriptFileList);
			}

			//流程结束state=false，未结束state=true
			boolean state = true;
			if(StringUtils.isNotBlank(workFullExecute.getProcessInstanceId())){
				state = actTaskService.isProcessEnd(workFullExecute.getProcessInstanceId());
			}else{
				//如果是项目负责人，不用审核，没有流程实例
				state = false;
			}
			workFullExecute.setProcessEnded(state);

		}
		return workFullExecute ;
	}
	
	public List<WorkFullExecute> findList(WorkFullExecute workFullExecute) {
		return super.findList(workFullExecute);
	}
	
	public Page<WorkFullExecute> findPage(Page<WorkFullExecute> page, WorkFullExecute workFullExecute) {
		workFullExecute.setPage(page);
		page.setList(findListBelongtoWorkfullmanage(workFullExecute));
		return page;
	}

	//一个项目有多个项目实施文件
	private List<WorkFullExecute> findListBelongtoWorkfullmanage(WorkFullExecute workFullExecute) {
		if(StringUtils.isBlank(workFullExecute.getWorkFullManageId())){
			return new ArrayList<>();
		}
		List<WorkFullExecute> executeList = workFullExecuteDao.findList(workFullExecute);
		if(executeList != null && executeList.size()>0){
			for(int i=0 ; i< executeList.size();i++){
				WorkFullExecute execute = executeList.get(i);

				//流程结束state=false，未结束state=true
				boolean state = true;
				if(StringUtils.isNotBlank(execute.getProcessInstanceId())){
					state = actTaskService.isProcessEnd(execute.getProcessInstanceId());
				}else{
					//如果是项目负责人，不用审核，没有流程实例
					state = false;
				}
				execute.setProcessEnded(state);

				List<Workattachment> attachmentList = workattachmentService.getListByAttachmentIdAndFlag(execute.getId(),"2");
				if(attachmentList != null && attachmentList.size()>0){
					for (int j = 0; j < attachmentList.size(); j++) {
						Workattachment attachment = attachmentList.get(j);
						if(StringUtils.isNotBlank(attachment.getAttachmentUser())){
							attachment.setAttachmentUser(UserUtils.get(attachment.getAttachmentUser()).getName());
						}
					}
					// TODO 现在限制一条实施记录里面有多个实施文件，万一保留了多个，就不好不好跟列表对应，暂时取第一个文件；
					execute.setExeFile(attachmentList.get(0));
				}
			}
		}

		return executeList;
	}

	@Transactional(readOnly = false)
	public WorkFullExecute save(WorkFullExecute workFullExecute, String workFullManageId , String submit ,HttpServletRequest request) {
		//(0暂存，1审核中，2已通过，3未通过、4已撤销)

		String id = workFullExecute.getId();
		//提交、重新申请，执行保存，撤销不执行保存
		if("submit".equals(submit) ||  "reapply".equals(submit)){
			//先保存项目实施信息
			if(StringUtils.isBlank(workFullExecute.getId())){
				workFullExecute.setStatus("0");

				//如果是项目负责人，直接"通过"
				if(workFullManageService.get(workFullManageId).getHostMaster().contains(UserUtils.getUser().getId())){
					workFullExecute.setStatus("2");
				}
			}
			workFullExecute.setWorkFullManageId(workFullManageId);
			workFullExecute.setCompanyId(UserUtils.getSelectCompany().getId());
			workFullExecute.setOfficeId(UserUtils.getSelectOffice().getId());
			super.save(workFullExecute);

			if(StringUtils.isBlank(id)){
				List<Workattachment> workAttachments = workFullExecute.getWorkAttachments();
				if(workAttachments!=null && workAttachments.size()>0){
					for (int i = 0; i < workAttachments.size(); i++) {
						Workattachment w = workAttachments.get(i);
						if (StringUtils.isNotBlank(w.getUrl()) && !w.getUrl().equals("null")) {
							w.setAttachmentUser(UserUtils.getUser().getId());
							w.setAttachmentId(workFullExecute.getId());
							w.setCompanyId(workFullExecute.getCompanyId());
							w.setId("");
							//实施文件只有一个，底稿可以多个
							if("2".equals(w.getAttachmentFlag())){
								delFile(workFullExecute,w.getAttachmentFlag());
							}

							workattachmentService.save(w);
						}
					}
				}
			}

//			//再上传项目实施文件(2)和底稿(3)
//			MultiValueMap<String, MultipartFile> multiFileMap = request.getMultiFileMap();
//			List<MultipartFile> execute_file = multiFileMap.get("execute_file");
//			if(execute_file!=null&&execute_file.size()>0){
//				for(int i=0;i<execute_file.size();i++){
//					MultipartFile multipartFile = execute_file.get(0);
//					if(multipartFile!=null && !multipartFile.isEmpty()&& multipartFile.getSize()>0){
//						uploadFile(multipartFile,workFullExecute,"2");
//					}
//				}
//			}
//			List<MultipartFile> manuscript_file = multiFileMap.get("manuscript_file");
//			if(manuscript_file!=null&&manuscript_file.size()>0){
//				for(int i=0;i<manuscript_file.size();i++){
//					MultipartFile multipartFile = manuscript_file.get(0);
//					if(multipartFile!=null && !multipartFile.isEmpty()&&multipartFile.getSize()>0){
//						uploadFile(multipartFile,workFullExecute,"3");
//					}
//				}
//			}

			//如果是项目负责人，不用审核
			if(workFullManageService.get(workFullManageId).getHostMaster().contains(UserUtils.getUser().getId())){
				return workFullExecute;
			}

		}

		///新添加数据：先保存，后启动流程；
		//重新申请：先保存数据，后执行审核；撤销：不保存，但是执行审核
		if("submit".equals(submit)){
			Map<String,Object> variables = new HashMap<String,Object>();
			startProcess(workFullExecute,variables);
		}else if("reapply".equals(submit) || "repeal".equals(submit)){
			auditSave(workFullExecute);
		}
		return workFullExecute;
	}

	@Transactional(readOnly = false)
	public void startProcess(WorkFullExecute workFullExecute, Map<String, Object> variables) {

		//用来设置启动流程的人员的id，引擎会自动把人员的id保存到activiti:initiator中
		identityService.setAuthenticatedUserId(workFullExecute.getCurrentUser().getId());
		WorkActivityMenu workActivityMenu = workActivityMenuService.findByParentAndOffice("190aeda1d370481ab80387a71080f93c",officeService.get(workFullExecute.getOfficeId()));
		//启动流程
		String businessKey = workFullExecute.getId().toString();
		String processType = workActivityMenu.getProcessType();
		StringBuffer buffer1 = new StringBuffer();
		Activity activity = new Activity();
		if(StringUtils.isNotBlank(workActivityMenu.getId())){
			workActivityMenu = workActivityMenuService.get(workActivityMenu.getId());
			List<Activity> activities = workActivityMenu.getActivities();
			for (Activity a:activities){
				//审批任务的第一个人(角色)
				if (a.getDelFlag().equals("0") && a.getCount() == 1){
					activity = a;
					break;
				}
			}
			buffer1.append(activity.getRole().getEnname());
			variables.put("type", workActivityMenu.getProcessType());
		}else{
			processType= ActUtils.PD_WORKFULLEXECUTE[0];
			variables.put("type", "workFullExecute");
			Role role = UserUtils.getSelectRole().get(0);
			buffer1 = DateUtils.getByEnnme(role.getEnname());
			buffer1.append("bmzr");
			variables.put("bmzr", buffer1.toString());
		}

		variables.put("businessId",businessKey);
		variables.put("title",workFullExecute.getRemarks());

		ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processType,businessKey,variables);
		workFullExecute.setProcessInstance(processInstance);
		workFullExecute.setProcessInstanceId(processInstance.getId());
		workFullExecuteDao.updateProcessInstanceId(workFullExecute);

		workFullExecute.setStatus("1");
		updateStatus(workFullExecute);

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

		//发起通知给审批角色或人员
		WorkProjectNotify workProjectNotify = new WorkProjectNotify();
		workProjectNotify.setTitle("您有新的项目实施待审批");
		workProjectNotify.setNotifyId(workFullExecute.getId());
		workProjectNotify.setCompanyId(workFullExecute.getCompanyId());
		workProjectNotify.setContent("审批任务-项目实施申请");
		workProjectNotify.setRemarks("待审批");
		workProjectNotify.setType("7");
		workProjectNotify.setStatus("0");
		workProjectNotify.setNotifyRole("");
		workProjectNotify.setUser(new User(""));

		if(workActivityMenu!=null&&StringUtils.isNotBlank(workActivityMenu.getId())&&StringUtils.isNotBlank(activity.getId())){
			//角色审批
			if(StringUtils.isNotBlank(activity.getRole().getEnname())){
				workProjectNotify.setNotifyRole(buffer1.toString());
			}
			//人员审批
			if(StringUtils.isNotBlank(activity.getUser().getId())){
				workProjectNotify.setUser(new User(activity.getUser().getId()));
			}
		}else {
			workProjectNotify.setNotifyRole(buffer1.toString());
		}
		workProjectNotifyService.save(workProjectNotify);
	}

	@Transactional(readOnly = false)
	private void updateStatus(WorkFullExecute workFullExecute) {
		workFullExecuteDao.updateStatus(workFullExecute);
	}

	@Transactional(readOnly = false)
	private void uploadFile(MultipartFile file, WorkFullExecute workFullExecute,String attachmentFlag) {
		if(file!=null && !file.isEmpty() && file.getSize()>0){

			//后一次上传前先删除前一次上传的文件
			delFile(workFullExecute,attachmentFlag);

			OSSClientUtil ossClientUtil = new OSSClientUtil();
			String fileName = file.getOriginalFilename();
			String fileType = fileName.substring(fileName.lastIndexOf(".")+1);
			String url = ossClientUtil.uploadFile2OSS(file,"workFullExecute");
			Workattachment workattachment = new Workattachment();
			workattachment.setUrl(url);
			workattachment.setType(fileType);
			workattachment.setAttachmentName(fileName);
			workattachment.setAttachmentUser(UserUtils.getUser().getId());
			workattachment.setAttachmentId(workFullExecute.getId());
			workattachment.setAttachmentFlag(attachmentFlag);
			workattachmentService.save(workattachment);
		}
	}

	@Transactional(readOnly = false)
	public void delete(WorkFullExecute workFullExecute) {
		delFile(workFullExecute,"2");
		delFile(workFullExecute,"3");
		super.delete(workFullExecute);
		//逻辑删除相关的通知记录
		WorkProjectNotify notify = new WorkProjectNotify();
		notify.setNotifyId(workFullExecute.getId());
		workProjectNotifyService.modifyDelflag(notify);
	}

	//查询待实施项目列表
    public Page<WorkFullManage> findListOfWorkFullManage(Page<WorkFullManage> page, WorkFullManage workFullManage) {
		if (StringUtils.isNotBlank(workFullManage.getTotalFullIds())){
			workFullManage.setTotalFullIds(","+workFullManage.getTotalFullIds()+",");
		}
		workFullManage.getSqlMap().put("dsf", dataScopeFilterOR(workFullManage.getCurrentUser(), "o", "u","s", MenuStatusEnum.END.getValue()));
		workFullManage.setPage(page);
		workFullManage.setIsTotal("1");
		List<WorkFullManage> list = Lists.newArrayList();
		List<WorkFullManage> totals = getListOfWorkFullManage(workFullManage);
		List<WorkFullManage> workFullManages = new ArrayList<>();
		for (WorkFullManage fullManage:totals){
			WorkFullManage wfm = new WorkFullManage();
			wfm.setTotalFullId(fullManage.getId());
			List<WorkFullManage> workEngineeringProjectLists = getListOfWorkFullManage(wfm);
			if (workEngineeringProjectLists!=null && workEngineeringProjectLists.size()!=0){
				workFullManages.addAll(workEngineeringProjectLists);
			}
		}
		workFullManages.addAll(totals);
		WorkFullManageService.sortList(list,workFullManages,"0",true);
		/*List<WorkFullManage> list = Lists.newArrayList();
		WorkFullManageService.sortList(list,getListOfWorkFullManage(workFullManage),"0",true);*/
		page.setList(list);
		return page ;
    }

	private List<WorkFullManage> getListOfWorkFullManage(WorkFullManage workFullManage) {
		List<WorkFullManage> workFullManageList = workFullExecuteDao.getListOfWorkFullManage(workFullManage);
		if (workFullManageList != null && workFullManageList.size()>0){
			for(WorkFullManage w : workFullManageList){
				String hostMasterIds = w.getHostMaster();
				StringBuilder hostMasterName = new StringBuilder();
				String[] idArray = hostMasterIds.split(",");
				if(idArray != null && idArray.length>0){
					for(int i =0 ;i<idArray.length;i++){
						if(StringUtils.isNotBlank(idArray[i])){
							User u = UserUtils.get(idArray[i]);
							hostMasterName.append("，").append(u.getName());
						}
					}
				}
				if(hostMasterName.length()>1){
					w.setHostMasterName(hostMasterName.substring(1));
				}
			}
		}
		return workFullManageList ;
	}
	//获取流程信息
	public WorkFullExecute getByProcessInstanceId(String processInstanceId) {
		return workFullExecuteDao.getByProcessInstanceId(processInstanceId);
	}

	//执行审核操作(0暂存，1审核中，2通过，3未通过，4撤销)
	@Transactional(readOnly = false)
	public String auditSave(WorkFullExecute workFullExecute) {
		try {
			String userId = UserUtils.getUser().getId();
			actTaskService.claim(workFullExecute.getAct().getTaskId(), userId);
			// 设置意见
			String comment = "";
			if(workFullExecute.getStatus().equals("3")){//如果是被驳回状态
				comment = ("yes".equals(workFullExecute.getAct().getFlag())?"[重新申请] ":"[已撤销] ");
			}else{
				comment = ("yes".equals(workFullExecute.getAct().getFlag())?"[同意] ":"[驳回] ")+workFullExecute.getAct().getComment();
			}
			workFullExecute.getAct().setComment(comment);
			workFullExecute.setStatus("1");

			System.err.println("comment======"+workFullExecute.getAct().getComment());
			WorkProjectNotify workProjectNotify = new WorkProjectNotify();
			workProjectNotify.setNotifyId(workFullExecute.getId());
			workProjectNotifyService.readByNotifyId(workProjectNotify);//每执行一步审核操作，都把已发出的通知变更为"已读"
			// 对不同环节的业务逻辑进行操作
			String taskDefKey = workFullExecute.getAct().getTaskDefKey();
			System.err.println("taskDefKey======"+taskDefKey);
			//业务逻辑对应的条件表达式
			String exp = "";

			//WorkActivityMenu workActivityMenu = workActivityMenuService.findByParentAndOffice("190aeda1d370481ab80387a71080f93c", officeService.get(workFullExecute.getOfficeId()));
			List<Activity> activitieList = activityService.getByProcessInstanceId(workFullExecute.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 selectedProcess = new WorkActivityProcess();
			selectedProcess.setProcessInstanceId(workFullExecute.getProcessInstanceId());
			List<WorkActivityProcess> workActivityProcesses = workActivityProcessService.findList(selectedProcess);

			//是自定义流程
			boolean isCustomProcess = StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals(ActUtils.PD_WORKFULLEXECUTE[0]);

			String taskCount = "";
			int key = 0;

			List<Activity> activities = workActivityMenu.getActivities();
			if (isCustomProcess) {
				key = 1;
				for (int i =0;i<workActivityProcesses.size();i++){
					WorkActivityProcess activityProcess = workActivityProcesses.get(i);
					String count = taskDefKey.replace("task","").replace("audit","");

					//重申|撤销 （audit1,2,3... = yes|no）
					if(taskDefKey.contains("audit") && (activityProcess.getCount()+"").contains(count)){
						taskCount = count ;
						exp = "pass";
						workActivityProcess.setId("");
						workActivityProcess.setCount(0);
						if (!"yes".equals(workFullExecute.getAct().getFlag())) {
							workActivityProcess.setIsApproval("2");
							workFullExecute.setStatus("4");//撤销
						}else {
							workActivityProcess.setIsApproval("1");
							workFullExecute.setStatus("1");//重申
							workProjectNotify.setTitle("项目实施：重新申请");
							workProjectNotify.setRemarks("重新申请");//用于在通知页面做审核操作，这一步必须
							//对通知的人(角色)的设定在 提交任务里完成
						}
					}
					//中间审批环节
					else if ((activityProcess.getCount()+"").contains(count)){
						taskCount = count ;
						workActivityProcess = activityProcess;
						workActivityProcess.setRemarks(comment);

						if (!workActivityProcess.getIsApproval().equals("0")){
							workActivityProcess.setId("");
						}
						exp = "pass";
						if (!"yes".equals(workFullExecute.getAct().getFlag())) {
							workActivityProcess.setIsApproval("2");
							workFullExecute.setStatus("3");
							workProjectNotify.setTitle("您的项目实施申请被驳回!");
							workProjectNotify.setNotifyRole("");
							workProjectNotify.setUser(workFullExecute.getCreateBy());
							String returnBack = "-1";
							for (Activity activity:activities){
								if(activity.getCount()==Integer.parseInt(count)){
									returnBack = activity.getReturnBack();
									break;
								}
							}
							if (returnBack.equals("0")) {
								workActivityProcess.setId("");
							}
						}else {
							workActivityProcess.setIsApproval("1");
							workProjectNotify.setTitle("项目实施：待审批");
							//对通知的人(角色)的设定在 提交任务里完成
						}
					}
				}
			}else {
				workActivityMenu.setId(workActivityProcesses.get(0).getId());
				workActivityMenu.setProcessType(ActUtils.PD_WORKFULLEXECUTE[0]);
				for (int i = 0; i < workActivityProcesses.size(); i++) {
					WorkActivityProcess activityProcess = workActivityProcesses.get(i);
					String count = activityProcess.getCount() + "";

					if(! activityProcess.getIsApproval().equals("0")){
						workActivityProcess.setId("");
					}
					taskCount = "1" ; // 默认流程只有一个审批环节

					// 部门负责人审核
					if ("audit".equals(taskDefKey) && count.equals("1")){
						workActivityProcess.setCount(1); //默认流程里部门负责人是第一个环节
						exp = "pass";
						if("yes".equals(workFullExecute.getAct().getFlag())){
							workActivityProcess.setIsApproval("1");
							workFullExecute.setStatus("2");
							workProjectNotify.setTitle("您的项目实施申请已通过");
							workProjectNotify.setRemarks("待通知");
							workProjectNotify.setNotifyRole("");
							workProjectNotify.setUser(workFullExecute.getCreateBy());
						}else{
							workActivityProcess.setIsApproval("2");

							workFullExecute.setStatus("3");//驳回
							//跳转页面的所需，这里只能填"重新申请"
							workProjectNotify.setRemarks("重新申请");
							workProjectNotify.setTitle("项目实施申请被驳回!");
							workProjectNotify.setNotifyRole("");
							workProjectNotify.setUser(workFullExecute.getCreateBy());
						}
					}
					//重申|撤销
					else if("reapply".equals(taskDefKey) && count.equals("0")){
						workActivityProcess.setId("");
						workActivityProcess.setCount(0);
						exp="pass";
						if("yes".equals(workFullExecute.getAct().getFlag())){//重新申请
							workActivityProcess.setIsApproval("1");
							workProjectNotify.setTitle("项目实施重新申请!");
							Role role = UserUtils.getSelectRole().get(0);
							StringBuffer buffer = DateUtils.getByEnnme(role.getEnname());
							buffer.append("bmzr");
							workProjectNotify.setNotifyRole(buffer.toString());//给部门负责人再次发送通知
							workProjectNotify.setUser(new User(""));//如果是重新申请，就不给创建人发通知，只给部门负责人发通知
							workProjectNotify.setRemarks("待审批");
							workFullExecute.setStatus("1");
						}else{
							workActivityProcess.setIsApproval("2");
							workFullExecute.setStatus("4");//撤销
						}
						break;
					}
					// 未知环节
				}
			}


			//更新自定义的流程追踪数据
			String defaultReapply = "reapply"; //默认流程中的重新申请任务标识
			workActivityProcessService.updateProcess(workActivityProcess,workActivityMenu,key,taskCount,workFullExecute.getProcessInstanceId(),taskDefKey,defaultReapply,workFullExecute.getAct().getFlag(),comment, activities);

			// 设置意见
			workFullExecute.getAct().setComment(comment);
			workFullExecute.preUpdate();

			// 提交流程任务
			Map<String, Object> vars = Maps.newHashMap();
			vars.put(exp, "yes".equals(workFullExecute.getAct().getFlag()) ?true : false );
			System.out.println("vars======"+vars.toString());
			// 提交流程任务
			actTaskService.complete(workFullExecute.getAct().getTaskId(), workFullExecute.getAct().getProcInsId(), workFullExecute.getAct().getComment(), vars);
			boolean state = actTaskService.isProcessEnd(workFullExecute.getAct().getProcInsId());
			//state=false流程结束，state=true流程未结束
			if (!state){
				//A：对于默认流程，流程结束时，审批状态已经设定

				//B：对于自定义流程，在中间环节，只能确定一个驳回状态=3，通过状态和撤销状态需要在这里设置
				//终审结束，①可能是"同意=2"，②可能是"驳回=3"（选择了"不可撤销"），③可能是"撤销=4"
				if(isCustomProcess){
					if("yes".equals(workFullExecute.getAct().getFlag())){
						workFullExecute.setStatus("2");
					}else{
						if(! "3".equals(workFullExecute.getStatus()))
							workFullExecute.setStatus("4");
					}
				}

				//终审之后，发送通知给创建人
				if("2".equals(workFullExecute.getStatus())){
					workProjectNotify.setTitle("您的项目实施申请已通过");
				}
				if("3".equals(workFullExecute.getStatus())){
					workProjectNotify.setTitle("您的项目实施申请被驳回");
				}
				workProjectNotify.setRemarks("待通知");//用于在通知页面做查看操作，这一步必须
				workProjectNotify.setNotifyRole("");
				workProjectNotify.setUser(workFullExecute.getCreateBy());
			}else{
				//尚未到终审，
				//workProjectNotify.setRemarks("待审批");//用于在通知页面做审核操作，这一步必须
				//如果是自定义流程，则需要先知道下一步(可能是撤销到某一步)的执行人(角色)是谁
				if (isCustomProcess) {
					String count = taskDefKey.replace("audit","").replace("task","");
					Activity activity = new Activity();
					////撤销到某一步
					if (taskDefKey.contains("audit")) {
						if (activities.size() == 1 || count.equals("1")){
							activity = activities.get(0);
						}else if (activities.size()==Integer.parseInt(count)){
							activity = activities.get(activities.size()-1);
							String returnBack = activity.getReturnBack();
							if (returnBack.equals("1")){
								activity = activities.get(Integer.parseInt(count)-2);
							}else if (returnBack.equals("2")){
								activity = activities.get(0);
							}
						}else {
							activity = activities.get(Integer.parseInt(count)-1);
							String returnBack = activity.getReturnBack();
							if (returnBack.equals("1")){
								activity = activities.get(Integer.parseInt(count)-2);
							}else if (returnBack.equals("2")){
								activity = activities.get(0);
							}
						}
					}
					//中间步骤驳回
					else if(!"yes".equals(workFullExecute.getAct().getFlag())){
						//驳回之后，创建人可以发起重申|撤销;将通知消息归类到审批列表，这一步必须
						//对通知的人（创建人）的设定在前面已完成
						workProjectNotify.setRemarks("重新申请");
						activity = new Activity();//驳回后需将id置空
					}
					//中间某步骤同意
					else {
						//得到下一步要执行的activity
						activity = activities.get(Integer.parseInt(count));
						workProjectNotify.setRemarks("待审批");
					}
					//发送审批消息给下一步的人(角色)
					if(StringUtils.isNotBlank(activity.getId())){//在驳回时不走这一步，判断id为必须
						workProjectNotify.setUser(activity.getUser());
						workProjectNotify.setNotifyRole(activity.getRole().getEnname());
					}
				}
				//如果是默认流程，
				else{
					//下一步的执行人(角色)已在前面设置
				}
			}

			workProjectNotify.setCompanyId(workFullExecute.getCompanyId());
			workProjectNotify.setContent(workFullExecute.getAct().getComment());
			workProjectNotify.setType("7");
			workProjectNotify.setStatus("0");
			//创建人如果做了撤销操作，无需发送通知
			if (!workFullExecute.getStatus().equals("4")) {
				workProjectNotifyService.save(workProjectNotify);
			}
			//更新审核状态
			workFullExecuteDao.updateStatus(workFullExecute);

			System.err.println("项目实施--审核步骤正常");

			return "审核执行成功";

		}catch (ActivitiObjectNotFoundException e){
			e.printStackTrace();
			System.err.println("项目实施--重复审批");
			logger.error("ActivitiObjectNotFoundException -- "+e);
			return "流程已审批，不能重新审批！";
		}
		catch (Exception e) {
			e.printStackTrace();
			System.err.println("项目实施--审核步骤异常");
			logger.error("Exception e:"+e);
			return "审核执行失败！！";
		}
	}
	@Transactional(readOnly = false)
	public int updateWorkFullManageStatus(WorkFullExecute workFullExecute) {
		List<WorkFullExecute> workFullExecuteList = findListBelongtoWorkfullmanage(workFullExecute);
		int flag = 0 ;
		if(workFullExecuteList != null && workFullExecuteList.size()>0){
			for(WorkFullExecute w : workFullExecuteList){
				if(StringUtils.isNotBlank(w.getProcessInstanceId())){
					String processInstanceId = w.getProcessInstanceId();
					ProcessInstance processInstance = actTaskService.getProcIns(processInstanceId);
					if(processInstance!=null){
						flag++;
						break;
					}
				}
			}
		}
		if(flag==0){
			updateStatusOfWorkFullManage(workFullExecute.getWorkFullManageId());
		}
		return flag;
	}
	@Transactional(readOnly = false)
	private void updateStatusOfWorkFullManage(String workFullManageId) {
		String updateBy = "";
		User user = UserUtils.getUser();
		if(StringUtils.isNotBlank(user.getId())){
			updateBy = user.getId();
		}
		Date updateDate = new Date();
		Map<String,Object> map = new HashMap<>();
		map.put("updateBy",updateBy);
		map.put("updateDate",updateDate);
		map.put("id",workFullManageId);
		map.put("fullProjectStatus","4");
		workFullExecuteDao.updateStatusOfWorkFullManage(map);
	}


	//删除实施文件或底稿
	@Transactional(readOnly = false)
	public void delFile(WorkFullExecute workFullExecute, String attachmentFlag) {
		Workattachment workattachment = workattachmentService.get(workFullExecute.getRemarks());
		if(workattachment != null){
			doDelFile(workattachment);
		}
	}
	@Transactional(readOnly = false)
	public void doDelFile(Workattachment workattachment){
		workattachmentService.deleteFileFromAliyun(workattachment,workattachment==null?"":workattachment.getUrl());
		workattachmentService.delete(workattachment);
	}

}