/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.workfulldesignchange.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.workfulldesignchange.dao.WorkFullDesignchangeDao;
import com.jeeplus.modules.workfulldesignchange.entity.WorkFullDesignchange;
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 java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 设计变更Service
 * @author fgy
 * @version 2017-11-03
 */
@SuppressWarnings("all")
@Service
@Transactional(readOnly = true)
public class WorkFullDesignchangeService extends CrudService<WorkFullDesignchangeDao, WorkFullDesignchange> {

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


	public WorkFullDesignchange get(String id) {
		WorkFullDesignchange workFullDesignchange = super.get(id);
		if(workFullDesignchange != null){
			WorkFullManage workFullManage = workFullManageService.get(workFullDesignchange.getWorkFullManageId());
			if(workFullManage != null){
				workFullDesignchange.setWorkFullManage(workFullManage);
				workFullDesignchange.setWorkFullManageId(workFullManage.getId());
			}

			List<Workattachment> attachmentList = workattachmentService.getListByAttachmentIdAndFlag(workFullDesignchange.getId(),"46");
			if(attachmentList != null && attachmentList.size()>0){
				for (int i = 0; i < attachmentList.size(); i++) {
					Workattachment attachment = attachmentList.get(i);
					attachment.setAttachmentUser(UserUtils.get(attachment.getAttachmentUser()).getName());
				}
				workFullDesignchange.setWorkAttachments(attachmentList);
			}

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

		return workFullDesignchange ;

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

	public List<WorkFullDesignchange> findListBelongtoWorkfullmanage(WorkFullDesignchange workFullDesignchange) {
		if(StringUtils.isBlank(workFullDesignchange.getWorkFullManageId())){
			return null ;
		}
		List<WorkFullDesignchange> designList = workFullDesignchangeDao.findList(workFullDesignchange);
		if(designList != null && designList.size()>0){
			for(WorkFullDesignchange design : designList){
				WorkFullManage workFullManage = workFullManageService.get(design.getWorkFullManageId());
				design.setWorkFullManage(workFullManage);
				design.setWorkFullManageId(workFullManage.getId());

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

			}
		}
		return designList;
	}

	@Transactional(readOnly = false)
	public WorkFullDesignchange save(WorkFullDesignchange workFullDesignchange, String workFullManageId, String submit) {
		//(0暂存，1审核中，2已通过，3未通过、4已撤销)
		String id = workFullDesignchange.getId();
		//提交、暂存、重新申请，执行保存，撤销不执行保存
		if("submit".equals(submit) || "toStore".equals(submit)|| "reapply".equals(submit)){
			if(StringUtils.isBlank(workFullDesignchange.getId())){
				workFullDesignchange.setStatus("0");
			}
			workFullDesignchange.setWorkFullManageId(workFullManageId);
			workFullDesignchange.setCompanyId(UserUtils.getSelectCompany().getId());
			workFullDesignchange.setOfficeId(UserUtils.getSelectOffice().getId());
			super.save(workFullDesignchange);

			if(StringUtils.isBlank(id)){
				List<Workattachment> workAttachments = workFullDesignchange.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.setCompanyId(workFullDesignchange.getCompanyId());
							w.setAttachmentId(workFullDesignchange.getId());
							w.setAttachmentUser(UserUtils.getUser().getId());
							w.setId("");
							workattachmentService.save(w);
						}
					}
				}
			}
		}

		//新添加数据：先保存，后启动流程；暂存数据：只保存，不启动流程；
		//重新申请：先保存数据，后执行审核；撤销：不保存，但是执行审核
		if("submit".equals(submit)){
			Map<String,Object> variables = new HashMap<String,Object>();
			startProcess(workFullDesignchange,variables);
		}else if("reapply".equals(submit) || "repeal".equals(submit)){
			auditSave(workFullDesignchange);
		}
		return workFullDesignchange;
	}
	@Transactional(readOnly = false)
	public void uploadFile(MultipartFile file, WorkFullDesignchange workFullDesignchange, String attachmentFlag) {
		if(file!=null && !file.isEmpty() && file.getSize()>0){
			//后一次上传前先删除前一次上传的文件
			delFile(workFullDesignchange,attachmentFlag);

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

	@Transactional(readOnly = false)
	public void delFile(WorkFullDesignchange workFullDesignchange, String attachmentFlag) {

		Workattachment workattachment = workattachmentService.get(workFullDesignchange.getRemarks());
		if(workattachment != null){
			doDelFile(workattachment);
		}
	}
	@Transactional(readOnly = false)
	public void doDelFile(Workattachment workattachment) {
		workattachmentService.deleteFileFromAliyun(workattachment,workattachment==null?"":workattachment.getUrl());
		workattachmentService.delete(workattachment);
	}
	@Transactional(readOnly = false)
	public void startProcess(WorkFullDesignchange workFullDesignchange, Map<String, Object> variables) {
		System.err.print("==========审核流程开始=========");
		//用来设置启动流程的人员的id，引擎会自动把人员的id保存到activiti:initiator中
		identityService.setAuthenticatedUserId(workFullDesignchange.getCurrentUser().getId());
		WorkActivityMenu workActivityMenu = workActivityMenuService.findByParentAndOffice("c2660a7b49e14a70b411ed36535662d4",officeService.get(workFullDesignchange.getOfficeId()));
		//启动流程
		String businessKey = workFullDesignchange.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_WORKFULLDESIGNCHANGE[0];
			variables.put("type", processType);
			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",workFullDesignchange.getRemarks());

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

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

		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("f8628ba6301d4674becc8a846636b7de"));
			workActivityProcessService.save(workActivityProcess);
		}

		//发起通知给审批人
		WorkProjectNotify workProjectNotify = new WorkProjectNotify();
		workProjectNotify.setTitle("您有新的设计变更待审批");
		workProjectNotify.setNotifyId(workFullDesignchange.getId());
		workProjectNotify.setCompanyId(workFullDesignchange.getCompanyId());
		workProjectNotify.setContent("审批任务-设计变更");
		workProjectNotify.setRemarks("待审批");
		workProjectNotify.setType("9");
		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(WorkFullDesignchange workFullDesignchange) {
		workFullDesignchangeDao.updateStatus(workFullDesignchange);
	}

	@Transactional(readOnly = false)
	public void delete(WorkFullDesignchange workFullDesignchange) {
		delFile(workFullDesignchange,"46");
		super.delete(workFullDesignchange);
		//逻辑删除相关的通知记录
		WorkProjectNotify notify = new WorkProjectNotify();
		notify.setNotifyId(workFullDesignchange.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);
		List<WorkFullManage> list = Lists.newArrayList();
		workFullManage.setIsTotal("1");
		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);
		//WorkFullManageService.sortList(list,getListOfWorkFullManage(workFullManage),"0",true);
		page.setList(list);
		return page ;
	}


	public List<WorkFullManage> getListOfWorkFullManage(WorkFullManage workFullManage) {
		List<WorkFullManage> workFullManageList = workFullDesignchangeDao.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 WorkFullDesignchange getByProcessInstanceId(String processInstanceId) {
		return workFullDesignchangeDao.getByProcessInstanceId(processInstanceId);
	}
	//部门负责人审核或创建人重申、撤销(0暂存，1审核中，2通过，3未通过，4已撤销)
	@Transactional(readOnly = false)
	public String auditSave(WorkFullDesignchange workFullDesignchange) {
		try {
			String userId = UserUtils.getUser().getId();
			actTaskService.claim(workFullDesignchange.getAct().getTaskId(), userId);
			// 设置意见
			String comment = "";
			if(workFullDesignchange.getStatus().equals("3")){//如果是被驳回状态
				comment = ("yes".equals(workFullDesignchange.getAct().getFlag())?"[重新申请] ":"[已撤销] ");
			}else{
				comment = ("yes".equals(workFullDesignchange.getAct().getFlag())?"[同意] ":"[驳回] ")+workFullDesignchange.getAct().getComment();
			}
			workFullDesignchange.getAct().setComment(comment);
			workFullDesignchange.setStatus("1");

			System.err.println("comment======"+workFullDesignchange.getAct().getComment());
			WorkProjectNotify workProjectNotify = new WorkProjectNotify();
			workProjectNotify.setNotifyId(workFullDesignchange.getId());
			workProjectNotifyService.readByNotifyId(workProjectNotify);

			// 对不同环节的业务逻辑进行操作
			String taskDefKey = workFullDesignchange.getAct().getTaskDefKey();
			System.err.println("taskDefKey======"+taskDefKey);
			//业务逻辑对应的条件表达式
			String exp = "";

			//WorkActivityMenu workActivityMenu2 = workActivityMenuService.findByParentAndOffice("c2660a7b49e14a70b411ed36535662d4",officeService.get(workFullDesignchange.getOfficeId()));
			List<Activity> activitieList = activityService.getByProcessInstanceId(workFullDesignchange.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(workFullDesignchange.getProcessInstanceId());
			List<WorkActivityProcess> workActivityProcesses = workActivityProcessService.findList(selectedProcess);

			//是自定义流程
			boolean isCustomProcess = StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals(ActUtils.PD_WORKFULLDESIGNCHANGE[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","");

					if(taskDefKey.contains("audit") && (activityProcess.getCount()+"").contains(count)){
						taskCount = count ;
						exp = "pass";
						workActivityProcess.setId("");
						workActivityProcess.setCount(0);
						if (!"yes".equals(workFullDesignchange.getAct().getFlag())) {
							workFullDesignchange.setStatus("4");
							workActivityProcess.setIsApproval("2");
						}else {
							workFullDesignchange.setStatus("1");
							workActivityProcess.setIsApproval("1");
							workProjectNotify.setTitle("设计变更：重新申请");
							workProjectNotify.setRemarks("重新申请");
						}
					}
					else if ((activityProcess.getCount()+"").contains(count)){
						taskCount = count ;
						workActivityProcess = activityProcess;
						workActivityProcess.setRemarks(comment);

						if (!activityProcess.getIsApproval().equals("0")){
							workActivityProcess.setId("");
						}
						exp = "pass";
						if (!"yes".equals(workFullDesignchange.getAct().getFlag())) {
							workFullDesignchange.setStatus("3");
							workActivityProcess.setIsApproval("2");
							workProjectNotify.setTitle("您的设计变更审请被驳回!");
							workProjectNotify.setNotifyRole("");
							workProjectNotify.setUser(workFullDesignchange.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_WORKFULLDESIGNCHANGE[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(workFullDesignchange.getAct().getFlag())){
							workActivityProcess.setIsApproval("1");
							workFullDesignchange.setStatus("2");
							workProjectNotify.setTitle("您的设计变更申请已通过");
							workProjectNotify.setRemarks("待通知");
							workProjectNotify.setNotifyRole("");
							workProjectNotify.setUser(workFullDesignchange.getCreateBy());
						}else{
							workActivityProcess.setIsApproval("2");

							workFullDesignchange.setStatus("3");
							workProjectNotify.setRemarks("重新申请");
							workProjectNotify.setTitle("设计变更申请被驳回!");
							workProjectNotify.setNotifyRole("");
							workProjectNotify.setUser(workFullDesignchange.getCreateBy());
						}
					}else if("reapply".equals(taskDefKey)){
						workActivityProcess.setId("");
						workActivityProcess.setCount(0);
						exp="pass";
						if("yes".equals(workFullDesignchange.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("待审批");
							workFullDesignchange.setStatus("1");
						}else{
							workActivityProcess.setIsApproval("2");
							workFullDesignchange.setStatus("4");
						}
						break;
					}
					// 未知环节
				}
			}

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


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

			// 提交流程任务
			Map<String, Object> vars = Maps.newHashMap();
			vars.put(exp, "yes".equals(workFullDesignchange.getAct().getFlag()) ?true : false );
			System.err.println("vars======"+vars.toString());
			// 提交流程任务
			actTaskService.complete(workFullDesignchange.getAct().getTaskId(), workFullDesignchange.getAct().getProcInsId(), workFullDesignchange.getAct().getComment(), vars);
			boolean state = actTaskService.isProcessEnd(workFullDesignchange.getAct().getProcInsId());
			if (!state){

				if(isCustomProcess){
					if("yes".equals(workFullDesignchange.getAct().getFlag())){
						workFullDesignchange.setStatus("2");
					}else{
						if(! "3".equals(workFullDesignchange.getStatus()))
							workFullDesignchange.setStatus("4");
					}
				}

				if("2".equals(workFullDesignchange.getStatus())){
					workProjectNotify.setTitle("您的设计变更申请已通过");
				}
				if("3".equals(workFullDesignchange.getStatus())){
					workProjectNotify.setTitle("您的设计变更申请被驳回");
				}
				workProjectNotify.setRemarks("待通知");
				workProjectNotify.setNotifyRole("");
				workProjectNotify.setUser(workFullDesignchange.getCreateBy());
			}else{
				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(workFullDesignchange.getAct().getFlag())){

						workProjectNotify.setRemarks("重新申请");
						activity = new Activity();
					}

					else {
						activity = activities.get(Integer.parseInt(count));
						workProjectNotify.setRemarks("待审批");
					}

					if(StringUtils.isNotBlank(activity.getId())){
						workProjectNotify.setUser(activity.getUser());
						workProjectNotify.setNotifyRole(activity.getRole().getEnname());
					}
				}
				else{

				}
			}

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

			System.err.println("设计变更审批正常");
			return "审核执行成功";
			//如果是撤销操作，更改与此相关的所有通知的已读状态，不再显示
			//如果是同意或驳回操作：将前面发给审批人的所有通知变更为已读；
			//如果是重新申请操作：将前面发给申请人的所有通知变更为已读；
			//如果是同意操作，发送审批通过的通知给申请人；申请人在阅读完成后，变更已读状态；
//			WorkProjectNotify notify = new WorkProjectNotify();
//			notify.setNotifyId(workFullDesignchange.getId());
//			if("4".equals(workFullDesignchange.getStatus())){
//				workProjectNotifyService.readByNotifyId(notify);
//			}
//			else if("2".equals(workFullDesignchange.getStatus()) ||"3".equals(workFullDesignchange.getStatus())){
//				String roleEnname = DateUtils.getByEnnme(UserUtils.getSelectRole().getEnname())+"bmzr";
//				notify.setNotifyRole(roleEnname);
//				workProjectNotifyService.readByNotifyIdAndNotifyRole(notify);
//			}else if("1".equals(workFullDesignchange.getStatus())){
//				notify.setUser(workFullDesignchange.getCreateBy());
//				workProjectNotifyService.readByNotifyIdAndNotifyUser(notify);
//			}

		}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 "审核执行失败！！";
		}
	}

}