/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.workfullproprietorsheet.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.workfullmanage.dao.WorkFullManageDao;
import com.jeeplus.modules.workfullmanage.entity.WorkFullManage;
import com.jeeplus.modules.workfullmanage.service.WorkFullManageService;
import com.jeeplus.modules.workfullproprietorsheet.dao.WorkFullProprietorsheetDao;
import com.jeeplus.modules.workfullproprietorsheet.entity.WorkFullProprietorsheet;
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-06
 */
@SuppressWarnings("all")
@Service
@Transactional(readOnly = true)
public class WorkFullProprietorsheetService extends CrudService<WorkFullProprietorsheetDao, WorkFullProprietorsheet> {

	@Autowired
	private WorkProjectNotifyService workProjectNotifyService;
	@Autowired
	private ActTaskService actTaskService;
	@Autowired
	private RuntimeService runtimeService;
	@Autowired
	private IdentityService identityService;
	@Autowired
	private WorkattachmentService workattachmentService;
	@Autowired
	private WorkFullManageService workFullManageService;
	@Autowired
	private WorkFullProprietorsheetDao workFullProprietorsheetDao;
	@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 WorkFullProprietorsheet get(String id) {

		WorkFullProprietorsheet workFullProprietorsheet = super.get(id);
		if(workFullProprietorsheet != null){
			WorkFullManage workFullManage = workFullManageService.get(workFullProprietorsheet.getWorkFullManageId());
			if(workFullManage != null){
				workFullProprietorsheet.setWorkFullManage(workFullManage);
				workFullProprietorsheet.setWorkFullManageId(workFullManage.getId());
			}

			List<Workattachment> attachmentList = workattachmentService.getListByAttachmentIdAndFlag(workFullProprietorsheet.getId(),"48");
			if(attachmentList!=null && attachmentList.size()>0){
				for (int i = 0; i < attachmentList.size(); i++) {
					Workattachment attachment = attachmentList.get(i);
					if(attachment != null){
						attachment.setAttachmentUser(UserUtils.get(attachment.getAttachmentUser()).getName());
					}
				}
				workFullProprietorsheet.setWorkAttachments(attachmentList);
			}
			//流程结束state=false，未结束state=true
			boolean state = true;
			if(StringUtils.isNotBlank(workFullProprietorsheet.getProcessInstanceId())){
				state = actTaskService.isProcessEnd(workFullProprietorsheet.getProcessInstanceId());
			}else{
				//如果是项目负责人，不用审核，没有流程实例
				state = false;
			}
			workFullProprietorsheet.setProcessEnded(state);
		}

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

	private List<WorkFullProprietorsheet> findListBelongtoWorkfullmanage(WorkFullProprietorsheet workFullProprietorsheet) {
		if(StringUtils.isBlank(workFullProprietorsheet.getWorkFullManageId())){
			return null ;
		}
		List<WorkFullProprietorsheet> proprietorsheetList = workFullProprietorsheetDao.findList(workFullProprietorsheet);
		if(proprietorsheetList != null && proprietorsheetList.size()>0){
			for(WorkFullProprietorsheet proprietorsheet : proprietorsheetList){
				WorkFullManage workFullManage = workFullManageService.get(proprietorsheet.getWorkFullManageId());
				proprietorsheet.setWorkFullManage(workFullManage);
				proprietorsheet.setWorkFullManageId(workFullManage.getId());

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

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

			if(StringUtils.isBlank(id)){
				List<Workattachment> workattachments = workFullProprietorsheet.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(workFullProprietorsheet.getCompanyId());
							w.setAttachmentUser(UserUtils.getUser().getId());
							w.setAttachmentId(workFullProprietorsheet.getId());
							w.setId("");
							workattachmentService.save(w);
						}
					}
				}
			}
			//uploadFile(attachment_file,workFullProprietorsheet,"48");
		}

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

	@Transactional(readOnly = false)
	private void startProcess(WorkFullProprietorsheet workFullProprietorsheet, Map<String, Object> variables) {
		System.err.print("==========审核流程开始=========");
		//用来设置启动流程的人员的id，引擎会自动把人员的id保存到activiti:initiator中
		identityService.setAuthenticatedUserId(workFullProprietorsheet.getCurrentUser().getId());
		WorkActivityMenu workActivityMenu = workActivityMenuService.findByParentAndOffice("5ed1aca14c2a47aba1ccc22b08c831fc", officeService.get(workFullProprietorsheet.getOfficeId()));
		//启动流程
		String businessKey = workFullProprietorsheet.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_WORKFULLPROPRIETORSHEET[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",workFullProprietorsheet.getProprietorsheetTopic());

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

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

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

		//发起通知给审批人
		WorkProjectNotify workProjectNotify = new WorkProjectNotify();
		workProjectNotify.setTitle("您有新的业主联系单待审批");
		workProjectNotify.setNotifyId(workFullProprietorsheet.getId());
		workProjectNotify.setCompanyId(workFullProprietorsheet.getCompanyId());
		workProjectNotify.setContent("审批任务-业主联系单");
		workProjectNotify.setRemarks("待审批");
		workProjectNotify.setType("11");
		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(WorkFullProprietorsheet workFullProprietorsheet) {
		workFullProprietorsheetDao.updateStatus(workFullProprietorsheet);
	}

	@Transactional(readOnly = false)
	private void uploadFile(MultipartFile file, WorkFullProprietorsheet workFullProprietorsheet, String attachmentFlag) {
		if(file!=null && !file.isEmpty() && file.getSize()>0){
			//后一次上传前先删除前一次上传的文件
			delFile(workFullProprietorsheet,attachmentFlag);

			OSSClientUtil ossClientUtil = new OSSClientUtil();
			String fileName = file.getOriginalFilename();
			String fileType = fileName.substring(fileName.lastIndexOf(".")+1);
			String url = ossClientUtil.uploadFile2OSS(file,"workFullProprietorsheet");
			Workattachment workattachment = new Workattachment();
			workattachment.setUrl(url);
			workattachment.setType(fileType);
			workattachment.setAttachmentName(fileName);
			workattachment.setAttachmentUser(UserUtils.getUser().getId());
			workattachment.setAttachmentId(workFullProprietorsheet.getId());
			workattachment.setAttachmentFlag(attachmentFlag);
			workattachmentService.save(workattachment);
		}
	}
	@Transactional(readOnly = false)
	public void delFile(WorkFullProprietorsheet workFullProprietorsheet, String attachmentFlag) {
		Workattachment workattachment = workattachmentService.get(workFullProprietorsheet.getRemarks());
		if(workattachment != null){
			doDelFile(workattachment);
		}
	}

	@Transactional(readOnly = false)
	private void doDelFile(Workattachment workattachment) {
		workattachmentService.deleteFileFromAliyun(workattachment,workattachment==null?"":workattachment.getUrl());
		workattachmentService.delete(workattachment);
	}

	@Transactional(readOnly = false)
	public void delete(WorkFullProprietorsheet workFullProprietorsheet) {
		delFile(workFullProprietorsheet,"48");
		super.delete(workFullProprietorsheet);
		//逻辑删除相关的通知记录
		WorkProjectNotify notify = new WorkProjectNotify();
		notify.setNotifyId(workFullProprietorsheet.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;
    }

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

			System.err.println("comment======"+workFullProprietorsheet.getAct().getComment());
			WorkProjectNotify workProjectNotify = new WorkProjectNotify();
			workProjectNotify.setNotifyId(workFullProprietorsheet.getId());
			workProjectNotifyService.readByNotifyId(workProjectNotify);
			// 对不同环节的业务逻辑进行操作
			String taskDefKey = workFullProprietorsheet.getAct().getTaskDefKey();
			System.err.println("taskDefKey======"+taskDefKey);
			//业务逻辑对应的条件表达式
			String exp = "";
			// 审核环节
			//WorkActivityMenu workActivityMenu = workActivityMenuService.findByParentAndOffice("5ed1aca14c2a47aba1ccc22b08c831fc",officeService.get(workFullProprietorsheet.getOfficeId()));
			List<Activity> activitieList = activityService.getByProcessInstanceId(workFullProprietorsheet.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(workFullProprietorsheet.getProcessInstanceId());
			List<WorkActivityProcess> workActivityProcesses = workActivityProcessService.findList(selectedProcess);

			//是自定义流程
			boolean isCustomProcess = StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals(ActUtils.PD_WORKFULLPROPRIETORSHEET[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(workFullProprietorsheet.getAct().getFlag())) {
							workFullProprietorsheet.setStatus("4");
							workActivityProcess.setIsApproval("2");
						}else {
							workFullProprietorsheet.setStatus("1");
							workActivityProcess.setIsApproval("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(workFullProprietorsheet.getAct().getFlag())) {
							workFullProprietorsheet.setStatus("3");
							workActivityProcess.setIsApproval("2");
							workProjectNotify.setTitle("您的业主联系单申请被驳回!");
							workProjectNotify.setNotifyRole("");
							workProjectNotify.setUser(workFullProprietorsheet.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_WORKFULLPROPRIETORSHEET[0]);
				for (int i = 0; i < workActivityProcesses.size(); i++) {
					WorkActivityProcess activityProcess = workActivityProcesses.get(i);
					String count = activityProcess.getCount() + "";

					taskCount = "1" ; // 默认流程只有一个审批环节
					if ("audit".equals(taskDefKey) && count.equals("1")){
						workActivityProcess.setCount(1); //默认流程里部门负责人是第一个环节
						exp = "pass";
						if("yes".equals(workFullProprietorsheet.getAct().getFlag())){
							workActivityProcess.setIsApproval("1");
							workFullProprietorsheet.setStatus("2");
							workProjectNotify.setTitle("您的业主联系单申请已通过");
							workProjectNotify.setRemarks("待通知");
							workProjectNotify.setNotifyRole("");
							workProjectNotify.setUser(workFullProprietorsheet.getCreateBy());
						}else{
							workActivityProcess.setIsApproval("2");

							workFullProprietorsheet.setStatus("3");
							workProjectNotify.setRemarks("重新申请");
							workProjectNotify.setTitle("业主联系单申请被驳回!");
							workProjectNotify.setNotifyRole("");
							workProjectNotify.setUser(workFullProprietorsheet.getCreateBy());
						}
					}
					//重申|撤销
					else if("reapply".equals(taskDefKey) && count.equals("0")){
						workActivityProcess.setId("");
						workActivityProcess.setCount(0);
						exp = "pass";
						if("yes".equals(workFullProprietorsheet.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("待审批");
							workFullProprietorsheet.setStatus("1");
						}else{
							workActivityProcess.setIsApproval("2");
							workFullProprietorsheet.setStatus("4");//撤销
						}
						break;
					}
					// 未知环节
				}
			}

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

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

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

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

				//终审之后，发送通知给创建人
				if("2".equals(workFullProprietorsheet.getStatus())){
					workProjectNotify.setTitle("您的业主联系单申请已通过");
				}
				if("3".equals(workFullProprietorsheet.getStatus())){
					workProjectNotify.setTitle("您的业主联系单申请被驳回");
				}
				workProjectNotify.setRemarks("待通知");
				workProjectNotify.setNotifyRole("");
				workProjectNotify.setUser(workFullProprietorsheet.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(workFullProprietorsheet.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(workFullProprietorsheet.getCompanyId());
			workProjectNotify.setContent(workFullProprietorsheet.getAct().getComment());
			workProjectNotify.setType("11");
			workProjectNotify.setStatus("0");
			//创建人如果做了撤销操作，无需发送通知
			if (!workFullProprietorsheet.getStatus().equals("4")) {
				workProjectNotifyService.save(workProjectNotify);
			}

			//更新业主联系单审核状态
			workFullProprietorsheetDao.updateStatus(workFullProprietorsheet);

			System.err.println("业主联系单审批正常");

			return "审核执行成功";

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

}