/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.workengineeringproject.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.IdGen;
import com.jeeplus.common.utils.MenuStatusEnum;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.modules.act.service.ActTaskService;
import com.jeeplus.modules.sys.dao.AreaDao;
import com.jeeplus.modules.sys.entity.*;
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.workbidproject.entity.WorkBidProject;
import com.jeeplus.modules.workclientinfo.entity.WorkClientLinkman;
import com.jeeplus.modules.workclientinfo.service.WorkClientInfoService;
import com.jeeplus.modules.workcontractinfo.entity.WorkContractInfo;
import com.jeeplus.modules.workengineeringprice.entity.WorkEngineeringPrice;
import com.jeeplus.modules.workengineeringprice.service.WorkEngineeringPriceService;
import com.jeeplus.modules.workengineeringproject.dao.WorkEngineeringProjectDao;
import com.jeeplus.modules.workengineeringproject.entity.WorkEngineeringProject;
import com.jeeplus.modules.workengineeringproject.entity.WorkProjectPlan;
import com.jeeplus.modules.workengineeringproject.entity.WorkProjectPlanEdit;
import com.jeeplus.modules.workproject.entity.WorkProject;
import com.jeeplus.modules.workproject.service.WorkProjectService;
import com.jeeplus.modules.workprojectnotify.entity.WorkProjectNotify;
import com.jeeplus.modules.workprojectnotify.service.WorkProjectNotifyService;
import com.jeeplus.modules.workprojectnotify.util.UtilNotify;
import org.activiti.engine.*;
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.*;

/**
 * 工程项目信息Service
 * @author 杨帆
 * @version 2017-10-23
 */
@Service
@Transactional(readOnly = true)
public class WorkEngineeringProjectService extends CrudService<WorkEngineeringProjectDao, WorkEngineeringProject> {
	@Autowired
	private WorkEngineeringProjectDao workEngineeringProjectDao;
	@Autowired
	private RuntimeService runtimeService;
	@Autowired
	protected TaskService taskService;
	@Autowired
	protected HistoryService historyService;
	@Autowired
	protected RepositoryService repositoryService;
	@Autowired
	private IdentityService identityService;
	@Autowired
	private ActTaskService actTaskService;
	@Autowired
	private WorkattachmentService workattachmentService;
	@Autowired
	private WorkProjectNotifyService workProjectNotifyService;
	@Autowired
	private OfficeService officeService;
	@Autowired
	private WorkProjectService workProjectService;
	@Autowired
	private WorkEngineeringPriceService workEngineeringPriceService;
	@Autowired
	private WorkClientInfoService workClientInfoService;
	@Autowired
	private WorkActivityMenuService workActivityMenuService;
	@Autowired
	private WorkActivityProcessService workActivityProcessService;
	@Autowired
	private ActivityService activityService;
	@Autowired
	private AreaDao areaDao;

	public WorkEngineeringProject getByPId(WorkProject workProject){
		return workEngineeringProjectDao.getByPId(workProject);
	}
	public WorkEngineeringProject get(String id) {
		WorkEngineeringProject entity = super.get(id);
		WorkEngineeringPrice workEngineeringPrice = new WorkEngineeringPrice();
		workEngineeringPrice.setEngineeringId(id);
		workEngineeringPrice = workEngineeringPriceService.getByEngineeringId(workEngineeringPrice);
		List<WorkClientLinkman> workClientLinkmans = workClientInfoService.findByClientId(entity.getWorkClientInfo().getId());
		if (workClientLinkmans!=null &&workClientLinkmans.size()!=0) {
			entity.setWorkClientLinkman(workClientLinkmans.get(0));
		}
		entity.setWorkEngineeringPrice(workEngineeringPrice);
		String hostOfficeMaster = entity.getHostOfficeMaster();
		String jointlyOfficeMaster = entity.getJointlyOfficeMaster();
		String hostOfficeMember = entity.getHostOfficeMember();
		String jointlyOfficeMember = entity.getJointlyOfficeMember();
		String hostOffice = entity.getHostOffice();
		String jointlyOffice = entity.getJointlyOffice();
		if(StringUtils.isNotBlank(hostOffice)){
			Office office = officeService.get(hostOffice);
			entity.setHostOfficeName(office.getName());
		}
		if(StringUtils.isNotBlank(jointlyOffice)){
			Office office = officeService.get(jointlyOffice);
			entity.setJointlyOfficeName(office.getName());
		}
		if (StringUtils.isNotBlank(hostOfficeMaster)){
			String[] ids = hostOfficeMaster.split(",");
			String name = "";
			for (String str:ids) {
				User user = UserUtils.get(str);
				name += user.getName()+",";
			}
			if (StringUtils.isNotBlank(name)){
				name = name.substring(0,name.length() - 1);
			}
			entity.setHostOfficeMasterName(name);
		}
		if (StringUtils.isNotBlank(jointlyOfficeMaster)){
			String[] ids = jointlyOfficeMaster.split(",");
			String name = "";
			for (String str:ids) {
				User user = UserUtils.get(str);
				name += user.getName()+",";
			}
			if (StringUtils.isNotBlank(name)){
				name = name.substring(0,name.length() - 1);
			}
			entity.setJointlyOfficeMasterName(name);
		}
		if (StringUtils.isNotBlank(hostOfficeMember)){
			String[] ids = hostOfficeMember.split(",");
			String name = "";
			for (String str:ids) {
				User user = UserUtils.get(str);
				name += user.getName()+",";
			}
			if (StringUtils.isNotBlank(name)){
				name = name.substring(0,name.length() - 1);
			}
			entity.setHostOfficeMemberNames(name);

		}
		if (StringUtils.isNotBlank(jointlyOfficeMember)){
			String[] ids = jointlyOfficeMember.split(",");
			String name = "";
			for (String str:ids) {
				User user = UserUtils.get(str);
				name += user.getName()+",";
			}
			if (StringUtils.isNotBlank(name)){
				name = name.substring(0,name.length() -1 );
			}
			entity.setJointlyOfficeMemberNames(name);

		}
		return entity;
	}

	public WorkProjectPlan getProjectPlan(String id) {
		return workEngineeringProjectDao.getProjectPlan(id);
	}

	@Transactional(readOnly = false)
	public int updateProjectPlan(WorkProjectPlan workProjectPlan) {
		return workEngineeringProjectDao.updateProjectPlan(workProjectPlan);
	}

	public List<WorkEngineeringProject> findList(WorkEngineeringProject workEngineeringProject) {
		workEngineeringProject.setCompanyId(UserUtils.getSelectCompany().getId());
		workEngineeringProject.getSqlMap().put("dsf", dataScopeFilterOR(workEngineeringProject.getCurrentUser(), "o", "u","s", MenuStatusEnum.END.getValue()));
		return super.findList(workEngineeringProject);
	}
	public List<WorkProjectPlan> findProjectPlans(WorkEngineeringProject workEngineeringProject) {
		return workEngineeringProjectDao.findProjectPlans(workEngineeringProject);
	}
	public List<WorkProjectPlanEdit> findProjectPlanEdit(WorkEngineeringProject workEngineeringProject) {
		return workEngineeringProjectDao.findProjectPlanEdit(workEngineeringProject);
	}

	public Page<WorkEngineeringProject> findPage(Page<WorkEngineeringProject> page, WorkEngineeringProject workEngineeringProject) {
		if (StringUtils.isNotBlank(workEngineeringProject.getTotalProjectIds())){
			workEngineeringProject.setTotalProjectIds(","+workEngineeringProject.getTotalProjectIds()+",");
		}
		workEngineeringProject.setIsTotal("1");
		workEngineeringProject.getSqlMap().put("dsf", dataScopeFilterOR(workEngineeringProject.getCurrentUser(), "o", "u","s", MenuStatusEnum.END.getValue()));
		workEngineeringProject.setPage(page);
		List<WorkEngineeringProject> list = Lists.newArrayList();
		List<WorkEngineeringProject> totals = dao.findList(workEngineeringProject);
		List<WorkEngineeringProject> workEngineeringProjects = new ArrayList<>();
		for (WorkEngineeringProject engineeringProject:totals){
			WorkEngineeringProject WorkEngineeringProject1 = new WorkEngineeringProject();
			WorkEngineeringProject1.setTotalProjectId(engineeringProject.getId());
			List<WorkEngineeringProject> workEngineeringProjectLists = dao.findList(WorkEngineeringProject1);
			if (workEngineeringProjectLists!=null && workEngineeringProjectLists.size()!=0){
				workEngineeringProjects.addAll(workEngineeringProjectLists);
			}
		}
		workEngineeringProjects.addAll(totals);
		sortList(list,workEngineeringProjects,"0",true);
		page.setList(list);
		return page;
	}

	public static void sortList(List<WorkEngineeringProject> list, List<WorkEngineeringProject> sourcelist, String parentId, boolean cascade){
		for (int i=0; i<sourcelist.size(); i++){
			WorkEngineeringProject e = sourcelist.get(i);
			if (e.getTotalProjectId()!=null && e.getTotalProjectId().equals(parentId)){
				list.add(e);
				if (cascade){
					// 判断是否还有子节点, 有则继续获取子节点
					for (int j=0; j<sourcelist.size(); j++){
						WorkEngineeringProject child = sourcelist.get(j);
						if (child.getTotalProjectId()!=null && child.getTotalProjectId().equals(e.getId())){
							sortList(list, sourcelist, e.getId(), true);
							break;
						}
					}
				}
			}
		}
	}

	public Page<WorkEngineeringProject> findProjectManagementPage(Page<WorkEngineeringProject> page, WorkEngineeringProject workEngineeringProject) {
		if (StringUtils.isNotBlank(workEngineeringProject.getTotalProjectIds())){
			workEngineeringProject.setTotalProjectIds(","+workEngineeringProject.getTotalProjectIds()+",");
		}
		workEngineeringProject.setIsTotal("1");
		workEngineeringProject.getSqlMap().put("dsf", dataScopeFilterOR(workEngineeringProject.getCurrentUser(), "o", "u","s", MenuStatusEnum.END.getValue()));
		workEngineeringProject.setPage(page);
		List<WorkEngineeringProject> list = Lists.newArrayList();
		List<WorkEngineeringProject> totals = dao.findProjectManagementList(workEngineeringProject);
		List<WorkEngineeringProject> workEngineeringProjects = new ArrayList<>();
		for (WorkEngineeringProject engineeringProject:totals){
			WorkEngineeringProject WorkEngineeringProject1 = new WorkEngineeringProject();
			WorkEngineeringProject1.setTotalProjectId(engineeringProject.getId());
			List<WorkEngineeringProject> workEngineeringProjectLists = dao.findList(WorkEngineeringProject1);
			if (workEngineeringProjectLists!=null && workEngineeringProjectLists.size()!=0){
				workEngineeringProjects.addAll(workEngineeringProjectLists);
			}
		}
		workEngineeringProjects.addAll(totals);
		sortList(list,workEngineeringProjects,"0",true);
		//sortList(list,workEngineeringProjectDao.findProjectManagementList(workEngineeringProject),"0",true);
		page.setList(list);
		return page;
	}

	@Transactional(readOnly = false)
	public void save(WorkEngineeringProject workEngineeringProject) {
		Area area = workEngineeringProject.getArea();
		area = areaDao.get(area.getId());
		workEngineeringProject.setArea(area);
		super.save(workEngineeringProject);
	}

	@Transactional(readOnly = false)
	public boolean saveProjectManagement(WorkEngineeringProject workEngineeringProject,Map variables) {
		try {
			WorkEngineeringPrice workEngineeringPrice = workEngineeringProject.getWorkEngineeringPrice();
			workEngineeringPriceService.save(workEngineeringPrice);
			if (StringUtils.isBlank(workEngineeringProject.getProofreadStatus())) {
				workEngineeringProject.setProofreadStatus("2");
				workEngineeringProject.preUpdate();
				update(workEngineeringProject);
				startProofreadProcess(workEngineeringProject, variables);
				return true;
			}else {
				return false;
			}
		}catch (Exception e){
			return false;
		}

	}

	@Transactional(readOnly = false)
	public void insertPlan(WorkEngineeringProject workEngineeringProject) {
		List<WorkProjectPlan> workProjectPlanList = getByStatus(workEngineeringProject,1);
		workEngineeringProject.setWorkProjectPlans(workProjectPlanList);
		workEngineeringProjectDao.insertPlan(workEngineeringProject);
	}
	@Transactional(readOnly = false)
	public void deletePlan(WorkEngineeringProject workEngineeringProject) {
		List<WorkProjectPlan> workProjectPlanList = getByStatus(workEngineeringProject,2);
		workEngineeringProject.setWorkProjectPlans(workProjectPlanList);
		workEngineeringProjectDao.deletePlan(workEngineeringProject);
	}

	@Transactional(readOnly = false)
	public List<WorkProjectPlan> getByStatus(WorkEngineeringProject workEngineeringProject,int type){
		List<WorkProjectPlan> workProjectPlans = workEngineeringProject.getWorkProjectPlans();
		List<WorkProjectPlan> workProjectPlanList = new ArrayList<WorkProjectPlan>();
		List<WorkProjectPlan> workProjectPlanold = workEngineeringProjectDao.findProjectPlans(workEngineeringProject);
		String counts = "";
		if(workProjectPlanold!=null && workProjectPlanold.size()!=0){
			for (WorkProjectPlan workProjectPlan :workProjectPlanold){
				counts += workProjectPlan.getTaskCount()+",";
			}

		}
		for (int i=0; i<workProjectPlans.size();i++){
			WorkProjectPlan projectPlan = workEngineeringProjectDao.getProjectPlan(workProjectPlans.get(i).getId());
			String status = null;
			if (projectPlan!=null) {
				status = projectPlan.getStatus();
			}else {
				workProjectPlans.get(i).setId(IdGen.uuid());
			}
			int y = 99 - i;
			if (type==1){
				if(StringUtils.isNotBlank(counts)){
					String[] arr = counts.split(",");
					for (String count:arr){
						if(count.equals(""+y)) {
							y--;
						}
					}
				}
			}
			if (StringUtils.isBlank(status) || !status.equals("1")) {

				workProjectPlans.get(i).setTaskCount(y + "");
				if (StringUtils.isBlank(workProjectPlans.get(i).getProjectId())){
					workProjectPlans.get(i).setProjectId(workEngineeringProject.getId());
				}
				if (StringUtils.isBlank(workProjectPlans.get(i).getType())) {
					if (!workEngineeringProject.getBusinessType().contains("2") && !workEngineeringProject.getBusinessType().contains("H")) {
						workProjectPlans.get(i).setType("1");
					} else {
						workProjectPlans.get(i).setType("2");
					}
				}
				if (StringUtils.isBlank(workProjectPlans.get(i).getStatus()) ) {
					workProjectPlans.get(i).setStatus("0");
				}
				if (workProjectPlans.get(i).getCompleteUser()!=null && StringUtils.isNotBlank(workProjectPlans.get(i).getCompleteUser().getId()) && workProjectPlans.get(i).getCompleteDate()!=null){
					workProjectPlans.get(i).setStatus("1");
				}
				workProjectPlanList.add(workProjectPlans.get(i));
			}else {
				if (type==1) {
					projectPlan.setTaskCount((99 - i) + "");
					workEngineeringProjectDao.updateProjectPlan(projectPlan);
				}
			}
		}
		return workProjectPlanList;
	}


	@Transactional(readOnly = false)
	public void updateRemakes(WorkEngineeringProject workEngineeringProject) {
		workEngineeringProject.setName(workEngineeringProject.getId());
		workEngineeringProject.preInsert();
		workEngineeringProject.preUpdate();
		workEngineeringProjectDao.updateRemakes(workEngineeringProject);
	}

	/**
	 * 启动流程
	 * @param
	 */
	@Transactional(readOnly = false)
	public void startProcess(WorkEngineeringProject workEngineeringProject, Map<String, Object> variables) {
		try {
			// 用来设置启动流程的人员ID，引擎会自动把用户ID保存到activiti:initiator中
			identityService.setAuthenticatedUserId(workEngineeringProject.getCurrentUser().getId());
			// 启动流程
			String businessKey = workEngineeringProject.getId().toString();
			WorkActivityMenu workActivityMenu = workActivityMenuService.findByParentAndOffice("7854872f45b84acd893010e66a3db2c8",officeService.get(workEngineeringProject.getOffice().getId()));
			// 启动流程
			StringBuffer buffer = new StringBuffer();
			String processType = workActivityMenu.getProcessType();
			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;
					}
				}
				buffer.append(activity.getRole().getEnname());
				variables.put("type", workActivityMenu.getProcessType());
			}else {
				processType = "projectallocation";
				variables.put("type", "projectallocation");
				List<Role> roles = UserUtils.getSelectRole();
				buffer = DateUtils.getByEnnme(roles.get(0).getEnname());
				buffer.append("bmzr");
				variables.put("bmzr", buffer.toString());
			}
			variables.put("busId", businessKey);
			variables.put("title", workEngineeringProject.getRemarks());//设置标题；
			ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processType, businessKey, variables);
			workEngineeringProject.setProcessInstance(processInstance);
			// 更新流程实例ID
			workEngineeringProject.setProcessInstanceId(processInstance.getId());
			dao.updateProcessInstanceId(workEngineeringProject);
			List<Activity> list= workActivityMenu.getActivities();
			if (list!=null && list.size()!=0){
				workActivityProcessService.saveList(list,processInstance.getId());
			}else {
				WorkActivityProcess workActivityProcess = new WorkActivityProcess();
				workActivityProcess.setProcessKey("projectallocation");
				workActivityProcess.setCount(1);
				workActivityProcess.setProcessInstanceId(processInstance.getId());
				workActivityProcess.setIsApproval("0");
				workActivityProcess.setActivity(new Activity("4e62d343e9444a55b5544839eedcaf4e"));
				workActivityProcessService.save(workActivityProcess);
			}
			WorkProjectNotify workProjectNotify = new WorkProjectNotify();
			workProjectNotify.setTitle("工程咨询-项目登记审批申请");
			workProjectNotify.setNotifyId(workEngineeringProject.getId());
			workProjectNotify.setCompanyId(workEngineeringProject.getCompanyId());
			workProjectNotify.setContent(UserUtils.get(workEngineeringProject.getCreateBy().getId()).getName()+"发起工程咨询-项目登记申请,请审批");
			workProjectNotify.setType("2");
			workProjectNotify.setStatus("0");
			workProjectNotify.setRemarks("待审批");
			if(workActivityMenu!=null&&StringUtils.isNotBlank(workActivityMenu.getId())&&StringUtils.isNotBlank(activity.getId())){
				//角色审批
				if(StringUtils.isNotBlank(activity.getRole().getEnname())){
					workProjectNotify.setNotifyRole(buffer.toString());
				}
				//人员审批
				if(StringUtils.isNotBlank(activity.getUser().getId())){
					workProjectNotify.setUser(new User(activity.getUser().getId()));
				}
			}else {
				workProjectNotify.setNotifyRole(buffer.toString());
			}
			workProjectNotifyService.save(workProjectNotify);
		}catch (Exception e){
			logger.error("Exception e:"+e);
		}

	}

	/* * 审核审批保存
     * @param testAudit
     */
	@Transactional(readOnly = false)
	public String auditSave(WorkEngineeringProject workEngineeringProject) {
		try {
			String userId = UserUtils.getUser().getId();
			actTaskService.claim(workEngineeringProject.getAct().getTaskId(), userId);
			String comment = ("yes".equals(workEngineeringProject.getAct().getFlag()) ? "[同意] " : "[驳回] ") + workEngineeringProject.getAct().getComment();
			// 设置意见
			workEngineeringProject.getAct().setComment(comment);
			System.out.println("comment=================" + comment);
			WorkProjectNotify workProjectNotify = new WorkProjectNotify();
			workProjectNotify.setRemarks("待通知");
			workProjectNotify.setUser(workEngineeringProject.getCreateBy());
			// 对不同环节的业务逻辑进行操作
			String taskDefKey = workEngineeringProject.getAct().getTaskDefKey();
			System.out.println("taskDefKey=====================" + taskDefKey);
			//业务逻辑对应的条件表达式
			String exp = "";
			String str = "";
			//WorkActivityMenu workActivityMenu = workActivityMenuService.findByParentAndOffice("7854872f45b84acd893010e66a3db2c8", officeService.get(workEngineeringProject.getOffice().getId()));
			List<Activity> activitieList = activityService.getByProcessInstanceId(workEngineeringProject.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(workEngineeringProject.getProcessInstanceId());
			List<WorkActivityProcess> workActivityProcesses = workActivityProcessService.findList(selectProcess);
			workEngineeringProject.setStatus("2");
			String taskCount = "";
			List<Activity> activities = workActivityMenu.getActivities();
			int key = 0;
			if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("projectallocation")) {
				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(workEngineeringProject.getAct().getFlag())) {
							str = "工程咨询-项目登记:已撤销!";
							workEngineeringProject.setStatus("6");
							workActivityProcess.setIsApproval("2");
						}else {
							str = "工程咨询-项目登记:重新申请!";
							workActivityProcess.setIsApproval("1");
						}
					}else if ((activityProcess.getCount()+"").contains(count)){
						taskCount = count;
						workActivityProcess = activityProcess;
						if (!workActivityProcess.getIsApproval().equals("0")){
							workActivityProcess.setId("");
						}
						exp = "pass";
						if (!"yes".equals(workEngineeringProject.getAct().getFlag())) {
							str = "工程咨询-项目登记:被驳回!";
							workActivityProcess.setIsApproval("2");
							String returnBack = "-1";
							for (Activity activity:activities){
								if(activity.getCount()==Integer.parseInt(count)){
									returnBack = activity.getReturnBack();
									break;
								}
							}
							if (returnBack.equals("0")) {
								workActivityProcess.setId("");
							}
							workEngineeringProject.setRemarks("重新申请");
						}else {
							str = "工程咨询-项目登记:待审批!";
							workActivityProcess.setIsApproval("1");
						}
					}
				}
			}else {
				for (int i = 0; i < workActivityProcesses.size(); i++) {
					workActivityMenu.setId(workActivityProcesses.get(0).getId());
					workActivityMenu.setProcessType("projectallocation");
					WorkActivityProcess activityProcess = workActivityProcesses.get(i);
					String count = activityProcess.getCount() + "";
					if (!activityProcess.getIsApproval().equals("0")){
						workActivityProcess.setId("");
					}
					taskCount = "1";
					// 审核环节
					if ("audit".equals(taskDefKey) && count.contains("1")) {
						workActivityProcess = activityProcess;
						exp = "pass";
						if (!"yes".equals(workEngineeringProject.getAct().getFlag())) {
							workActivityProcess.setIsApproval("2");
							workProjectNotify.setRemarks("重新申请");
							workProjectNotify.setTitle("工程咨询-项目登记:被驳回!");
							workEngineeringProject.setRemarks("重新申请");
						}else {
							workActivityProcess.setIsApproval("1");
						}
					} else if ("audit2".equals(taskDefKey) && count.contains("0")) {
						workActivityProcess.setCount(0);
						if ("yes".equals(workEngineeringProject.getAct().getFlag())) {
							workProjectNotify.setTitle("工程咨询-项目登记:重新申请!");
							List<Role> roles = UserUtils.getSelectRole();
							StringBuffer buffer = DateUtils.getByEnnme(roles.get(0).getEnname());
							buffer.append("bmzr");
							workProjectNotify.setNotifyRole(buffer.toString());
							workProjectNotify.setUser(new User());
							workProjectNotify.setRemarks("待审批");
							workActivityProcess.setIsApproval("1");
						}else {
							workEngineeringProject.setStatus("6");
							workActivityProcess.setIsApproval("2");
						}
						exp = "pass";
						break;
					}
					// 未知环节，直接返回
				}
			}
			// 提交流程任务
			Map<String, Object> vars = Maps.newHashMap();
			vars.put(exp, "yes".equals(workEngineeringProject.getAct().getFlag()) ? true : false);
			System.out.println("vars============" + vars.toString());
			workActivityProcessService.updateProcess(workActivityProcess,workActivityMenu,key,taskCount,workEngineeringProject.getProcessInstanceId(),taskDefKey,"audit2",workEngineeringProject.getAct().getFlag(),comment, activities);

			// 提交流程任务
			actTaskService.complete(workEngineeringProject.getAct().getTaskId(), workEngineeringProject.getAct().getProcInsId(), workEngineeringProject.getAct().getComment(), vars);
			boolean state = actTaskService.isProcessEnd(workEngineeringProject.getAct().getProcInsId());
			workEngineeringProject.setStatus("2");
			if (!state) {
				workProjectNotify.setRemarks("待通知");
				if ("yes".equals(workEngineeringProject.getAct().getFlag())) {
					workEngineeringProject.setStatus("3");
					workProjectNotify.setTitle("工程咨询-项目登记:已通过!");
					StringBuffer reportNumber = new StringBuffer();
					reportNumber.append(workEngineeringProject.getArea().getName().substring(0, 2));
					reportNumber.append(UserUtils.getSelectCompany().getName().substring(0, 2));
					reportNumber.append(workEngineeringProject.getBusinessType());
					Calendar a = Calendar.getInstance();
					reportNumber.append("【" + a.get(Calendar.YEAR) + "】");
					reportNumber.append((int) ((Math.random() * 9 + 1) * 1000));
					workEngineeringProject.setReportNumber(reportNumber.toString());
					workEngineeringProject.setStatus("3");
				} else {
					workEngineeringProject.setStatus("6");
					workProjectNotify.setTitle("工程咨询-项目登记:被驳回!");
				}
			}
			/*workActivityProcess.setRemarks(comment);
			workActivityProcess.setProcessInstanceId(workEngineeringProject.getProcessInstanceId());
			workActivityProcess.setActivity(new Activity(workActivityMenu.getId()));
			workActivityProcess.setProcessKey(workActivityMenu.getProcessType());
			if (workActivityProcess!=null && StringUtils.isNotBlank(workActivityProcess.getIsApproval())){
				workActivityProcessService.save(workActivityProcess);
			}*/
			workProjectNotify.setNotifyId(workEngineeringProject.getId());
			workProjectNotify.setCompanyId(workEngineeringProject.getCompanyId());
			workProjectNotify.setContent(workEngineeringProject.getAct().getComment());
			workProjectNotify.setType("2");
			workProjectNotify.setStatus("0");
			WorkProjectNotify notify = new WorkProjectNotify();
			notify.setNotifyId(workEngineeringProject.getId());
			workProjectNotifyService.readByNotifyId(notify);
			if (!str.contains("已撤销")){
				if (workEngineeringProject.getStatus().equals("3")) {
					Set<String> set = getSet(workEngineeringProject);
					for (String user : set) {
						workProjectNotify.setUser(new User(user));
						workProjectNotify.preInsert();
						workProjectNotifyService.insert(workProjectNotify);
					}
				} else if(!state) {
					workProjectNotify = UtilNotify
							.saveNotify(workEngineeringProject.getId(),
									workEngineeringProject.getCreateBy(),
									workEngineeringProject.getCompanyId(),
									str,
									workEngineeringProject.getAct().getComment(),
									"2",
									"0",
									"待通知",
									"");
					workProjectNotifyService
							.save(workProjectNotify);
				}else{
						if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("projectallocation")) {
							workProjectNotify = UtilNotify
									.saveNotify(workEngineeringProject.getId(),
											new User(),
											workEngineeringProject.getCompanyId(),
											str,
											workEngineeringProject.getAct().getComment(),
											"2",
											"0",
											"待审批",
											"");
							String count = taskDefKey.replace("audit","").replace("task","");

							workProjectNotify = activityService.getByFlagAndTaskDefKey(
									activities,
									workProjectNotify,
									taskDefKey,
									workEngineeringProject.getAct().getFlag(),
									count,
									workEngineeringProject.getCreateBy());
							workProjectNotifyService
									.save(workProjectNotify);
						}else {
							workProjectNotifyService.save(workProjectNotify);
						}
				}
			}
			workEngineeringProject.preUpdate();
			this.update(workEngineeringProject);
			return "保存审核意见成功！";
		}catch (ActivitiObjectNotFoundException e){
			logger.error("ActivitiObjectNotFoundException e:"+e);
			return "流程已审批，不能重新审批！";
		}catch (Exception e){
			logger.error("Exception e:"+e);
			return "保存审核意见失败！！";
		}
	}

	public Set<String> getSet(WorkEngineeringProject workEngineeringProject){
		String hostOfficeMaster = workEngineeringProject.getHostOfficeMaster();
		String projectHostOfficeMember = workEngineeringProject.getHostOfficeMember();
		String jointlyOfficeMaster = workEngineeringProject.getJointlyOfficeMaster();
		String jointlyOfficeMember = workEngineeringProject.getJointlyOfficeMember();
		String[] hostOfficeMasters = hostOfficeMaster.split(",");
		String[] projectHostOfficeMembers = projectHostOfficeMember.split(",");
		String[] jointlyOfficeMasters = jointlyOfficeMaster.split(",");
		String[] jointlyOfficeMembers = jointlyOfficeMember.split(",");
		Set<String> set = new HashSet<>();
		set.addAll(Arrays.asList(hostOfficeMasters));
		set.addAll(Arrays.asList(projectHostOfficeMembers));
		set.addAll(Arrays.asList(jointlyOfficeMasters));
		set.addAll(Arrays.asList(jointlyOfficeMembers));
		set.add(workEngineeringProject.getCreateBy().getId());
		set.remove("");
		return set;
	}

	/* * 审核审批保存
     * @param testAudit
     */
	@Transactional(readOnly = false)
	public String auditProofreadSave(WorkEngineeringProject workEngineeringProject) {
		try{
			String userId = UserUtils.getUser().getId();
			if (StringUtils.isNotBlank(workEngineeringProject.getReject())){
				workEngineeringProject.getAct().setFlag(workEngineeringProject.getReject());
			}
			actTaskService.claim(workEngineeringProject.getAct().getTaskId(), userId);
			if (StringUtils.isNotBlank(workEngineeringProject.getProblem())){
				String str = workEngineeringProject.getProblem() + " : " +workEngineeringProject.getAct().getComment();
				workEngineeringProject.getAct().setComment(str);
			}
			String comment = ("1".equals(workEngineeringProject.getAct().getFlag())?"[同意] ":"[驳回] ")+workEngineeringProject.getAct().getComment();
			// 设置意见
			workEngineeringProject.getAct().setComment(comment);
			System.out.println("comment================="+comment);
			WorkProjectNotify workProjectNotify = new WorkProjectNotify();
			workProjectNotify.setRemarks("待审批");
			// 对不同环节的业务逻辑进行操作
			String taskDefKey = workEngineeringProject.getAct().getTaskDefKey();
			System.out.println("taskDefKey====================="+taskDefKey);
			//业务逻辑对应的条件表达式
			String exp = "";
			String str = "";
			// 审核环节
			List<Role> roles = UserUtils.getSelectRole();
			StringBuffer buffer = DateUtils.getByEnnme(roles.get(0).getEnname());
			StringBuffer glygd = DateUtils.getByEnnme(roles.get(0).getEnname());
			buffer.append("zg");
			glygd.append("glygd");
			//WorkActivityMenu workActivityMenu = workActivityMenuService.findByParentAndOffice("7864872f45b84acd893010e66a3db2c8", officeService.get(workEngineeringProject.getOffice().getId()));
			List<Activity> activitieList = activityService.getByProcessInstanceId(workEngineeringProject.getProcessInstanceProofreadId());
			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(workEngineeringProject.getProcessInstanceProofreadId());
			List<WorkActivityProcess> workActivityProcesses = workActivityProcessService.findList(selectProcess);
			// 提交流程任务
			Map<String, Object> vars = Maps.newHashMap();
			workEngineeringProject.setProofreadStatus("2");
			String taskCount = "";
			int key = 0;
			List<Activity> activities = workActivityMenu.getActivities();
			if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("threeexamination")) {
				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 (!"1".equals(workEngineeringProject.getAct().getFlag())) {
							str = "工程咨询-三级校审:已撤销!";
							workActivityProcess.setIsApproval("2");
							workEngineeringProject.setProofreadStatus("5");
						}else {
							str = "工程咨询-三级校审:重新申请!";
							workActivityProcess.setIsApproval("1");
						}
					}else if ((activityProcess.getCount()+"").contains(count)){
						taskCount = count;
						workActivityProcess = activityProcess;
						if (!workActivityProcess.getIsApproval().equals("0")){
							workActivityProcess.setId("");
						}
						exp = "pass";
						if (!"1".equals(workEngineeringProject.getAct().getFlag())) {
							str = "工程咨询-三级校审:被驳回!";
							workActivityProcess.setIsApproval("2");
							String returnBack = "-1";
							for (Activity activity:activities){
								if(activity.getCount()==Integer.parseInt(count)){
									returnBack = activity.getReturnBack();
									break;
								}
							}
							if (returnBack.equals("0")) {
								workActivityProcess.setId("");
							}
							workEngineeringProject.setProofreadStatus("4");
						}else {
							str = "工程咨询-三级校审:待审批!";
							workActivityProcess.setIsApproval("1");
						}
					}
				}
				vars.put(exp, "1".equals(workEngineeringProject.getAct().getFlag())?true:false );
			}else {
				for (int i = 0; i < workActivityProcesses.size(); i++) {
					workActivityMenu.setProcessType("threeexamination");
					WorkActivityProcess activityProcess = workActivityProcesses.get(i);
					String count = activityProcess.getCount() + "";
					if (!activityProcess.getIsApproval().equals("0")){
						workActivityProcess.setId("");
					}
					// 审核环节
					if ("audit".equals(taskDefKey) && count.contains("0")) {
						workActivityProcess.setCount(0);
						taskCount = "1";
						workEngineeringProject.setProofreadMaster(workEngineeringProject.getHostOfficeMaster());
						workEngineeringProject.setProofreadTotal("");
						workActivityProcess.setId("");
						exp = "pass";
						if ("1".equals(workEngineeringProject.getAct().getFlag())) {
							workActivityProcess.setIsApproval("1");
							workProjectNotify.setTitle("工程咨询-三级校审:重新申请!");
							str = "工程咨询-三级校审:重新申请!";
							workProjectNotify.setUser(new User(workEngineeringProject.getCreateBy().getId()));
						} else {
							workActivityProcess.setIsApproval("2");
							workEngineeringProject.setProofreadStatus("5");
							workProjectNotify.setTitle("工程咨询-三级校审:已撤销!");
							str = "工程咨询-三级校审:已撤销!";
							workProjectNotify.setRemarks("");
						}
						break;
					} else if ("auditMaster".equals(taskDefKey) && count.contains("1")) {
						workActivityProcess = activityProcess;
						taskCount = count;
						exp = "pass";
						if ("1".equals(workEngineeringProject.getAct().getFlag())) {
							workActivityProcess.setIsApproval("1");
							workProjectNotify.setTitle("工程咨询-三级校审:待审批!");
							str = "工程咨询-三级校审:待审批!";
							workEngineeringProject.setProofreadMaster("");
							workEngineeringProject.setProofreadTotal(buffer.toString());
							workProjectNotify.setNotifyRole(buffer.toString());
						} else {
							workEngineeringProject.setProofreadStatus("4");
							workActivityProcess.setIsApproval("2");
							workProjectNotify.setTitle("工程咨询-三级校审:被驳回!");
							str = "工程咨询-三级校审:被驳回!";
							workEngineeringProject.setProofreadMaster("");
							workEngineeringProject.setProofreadTotal("");
							workProjectNotify.setRemarks("重新申请");
							workProjectNotify.setUser(new User(workEngineeringProject.getCreateBy().getId()));
						}

					} else if ("auditTotal".equals(taskDefKey) && count.contains("2")) {
						workActivityProcess = activityProcess;
						taskCount = count;
						exp = "pass";
						workActivityProcess.setIsApproval("2");
						if ("3".equals(workEngineeringProject.getAct().getFlag())) {
							workProjectNotify.setTitle("工程咨询-三级校审:被驳回!");
							str = "工程咨询-三级校审:被驳回!";
							workEngineeringProject.setProofreadMaster(workEngineeringProject.getHostOfficeMaster());
							workEngineeringProject.setProofreadTotal("");
							workProjectNotify.setIds(workEngineeringProject.getHostOfficeMaster());
							workEngineeringProject.setProofreadStatus("4");
						} else {
							if ("2".equals(workEngineeringProject.getAct().getFlag())) {
								workProjectNotify.setTitle("工程咨询-三级校审:被驳回!");
								str = "工程咨询-三级校审:被驳回!";
								workProjectNotify.setRemarks("重新申请");
								workProjectNotify.setIds(workEngineeringProject.getHostOfficeMaster());
								workEngineeringProject.setProofreadStatus("4");
							} else {
								str = "工程咨询-三级校审已经通过!";
								//workProjectNotify.setRemarks("待归档");
								workActivityProcess.setIsApproval("1");
								workProjectNotify.setRemarks("待通知");
								workProjectNotify.setUser(new User(workEngineeringProject.getCreateBy().getId()));
							}
							workEngineeringProject.setProofreadMaster("");
							workEngineeringProject.setProofreadTotal("");
						}
					}
				}
				vars.put(exp, workEngineeringProject.getAct().getFlag() );
			}
			workActivityProcessService.updateProcess(workActivityProcess,workActivityMenu,key,taskCount,workEngineeringProject.getProcessInstanceProofreadId(),taskDefKey,"audit","1".equals(workEngineeringProject.getAct().getFlag())?"yes":"no",comment, activities);

			System.out.println("vars============"+vars.toString());
			// 提交流程任务
			actTaskService.complete(workEngineeringProject.getAct().getTaskId(), workEngineeringProject.getAct().getProcInsId(), workEngineeringProject.getAct().getComment(), vars);
			if (workActivityProcess!=null){
				workActivityProcessService.save(workActivityProcess);
			}
			workActivityProcess.setRemarks(comment);
			workActivityProcess.setProcessInstanceId(workEngineeringProject.getProcessInstanceProofreadId());
			workActivityProcess.setActivity(new Activity(workActivityMenu.getId()));
			workActivityProcess.setProcessKey(workActivityMenu.getProcessType());
			if (workActivityProcess!=null && StringUtils.isNotBlank(workActivityProcess.getIsApproval())){
				workActivityProcessService.save(workActivityProcess);
			}
			boolean state = actTaskService.isProcessEnd(workEngineeringProject.getAct().getProcInsId());
			WorkProjectNotify notify = new WorkProjectNotify();
			notify.setNotifyId(workEngineeringProject.getId());
			workProjectNotifyService.readByNotifyId(notify);
			if (!state) {
				workProjectNotify.setRemarks("待通知");
				if ("1".equals(workEngineeringProject.getAct().getFlag())) {
					workEngineeringProject.setProofreadStatus("3");
					workEngineeringProject.setStatus("5");
					workProjectNotify.setTitle("工程咨询-三级校审已经通过!");
					WorkProject workProject = workProjectService.get(workEngineeringProject.getProjectId().getId());
					workProject.setState("1");//1为能归档
					workProjectService.updateStatus(workProject);
					str = workProjectNotify.getTitle();
				} else {
					workEngineeringProject.setStatus("7");
					if (StringUtils.isNotBlank(workProjectNotify.getRemarks())) {
						workEngineeringProject.setProofreadStatus("5");
					} else {
						workEngineeringProject.setProofreadStatus("4");
					}
				}
			}
			workProjectNotify.setNotifyId(workEngineeringProject.getId());
			//workProjectNotify.setUser(workEngineeringProject.getCreateBy());
			workProjectNotify.setCompanyId(workEngineeringProject.getCompanyId());
			workProjectNotify.setContent(workEngineeringProject.getAct().getComment());
			workProjectNotify.setType("3");
			workProjectNotify.setStatus("0");
			if (!str.contains("已撤销")) {
				if (workEngineeringProject.getProofreadStatus().equals("3")) {
					Set<String> set = getSet(workEngineeringProject);
					for (String user : set) {
						workProjectNotify.setUser(new User(user));
						workProjectNotify.preInsert();
						workProjectNotifyService.insert(workProjectNotify);
					}
					workProjectNotify.setTitle("工程咨询-三级校审已通过,请归档!");
					//workProjectNotify.setRemarks("待归档");
					workProjectNotify.setNotifyRole(glygd.toString());
					workProjectNotify.setUser(new User());
					//workProjectNotify.setType("4");
					workProjectNotify.preInsert();
					workProjectNotify.setCreateBy(workEngineeringProject.getCreateBy());
					workProjectNotifyService.insert(workProjectNotify);
				} else if (!state) {
					workProjectNotify = UtilNotify
							.saveNotify(workEngineeringProject.getId(),
									workEngineeringProject.getCreateBy(),
									workEngineeringProject.getCompanyId(),
									str,
									workEngineeringProject.getAct().getComment(),
									"3",
									"0",
									"待通知",
									"");
					workProjectNotifyService
							.save(workProjectNotify);
				} else {
					if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("threeexamination")) {
						workProjectNotify = UtilNotify
								.saveNotify(workEngineeringProject.getId(),
										new User(),
										workEngineeringProject.getCompanyId(),
										str,
										workEngineeringProject.getAct().getComment(),
										"3",
										"0",
										"待审批",
										"");
						String count = taskDefKey.replace("audit", "").replace("task", "");

						workProjectNotify = activityService.getByFlagAndTaskDefKey(
								activities,
								workProjectNotify,
								taskDefKey,
								"1".equals(workEngineeringProject.getAct().getFlag()) ? "yes" : "no",
								count,
								workEngineeringProject.getCreateBy());
						workProjectNotifyService
								.save(workProjectNotify);
					} else {
						if (StringUtils.isNotBlank(workProjectNotify.getIds())) {
							String idArr[] = workProjectNotify.getIds().split(",");
							for (String id : idArr) {
								workProjectNotify.setUser(new User(id));
								workProjectNotifyService.save(workProjectNotify);
							}
						} else {
							if (StringUtils.isNotBlank(workProjectNotify.getRemarks())) {
								workProjectNotifyService.save(workProjectNotify);
							}
						}
					}

				}

			}
			workEngineeringProject.preUpdate();
			dao.update(workEngineeringProject);
			return "保存审核意见成功！";
		}catch (ActivitiObjectNotFoundException e){
			logger.error("ActivitiObjectNotFoundException e:"+e);
			return "流程已审批，不能重新审批！";
		}catch (Exception e){
			logger.error("Exception e:"+e);
			return "保存审核意见失败！！";
		}
	}

	@Transactional(readOnly = false)
	public void update(WorkEngineeringProject workEngineeringProject) {
		workEngineeringProject.preUpdate();
		dao.update(workEngineeringProject);
	}

	@Transactional(readOnly = false)
	public void delete(WorkEngineeringProject workEngineeringProject) {
		super.delete(workEngineeringProject);
	}

	public Page<WorkContractInfo> findPageBycontractId(Page<WorkContractInfo> page, WorkContractInfo contractId) {
		contractId.setPage(page);
		//contractId.getSqlMap().put("dsf", dataScopeFilterOR(contractId.getCurrentUser(), "o", "u","s"));
		page.setList(dao.findListBycontractId(contractId));
		return page;
	}
	public Page<WorkBidProject> findPageByprojectId(Page<WorkBidProject> page, WorkBidProject projectId) {
		projectId.setPage(page);
		page.setList(dao.findListByprojectId(projectId));
		return page;
	}

	@Transactional(readOnly = false)
	boolean uploadFile(MultipartFile file, WorkEngineeringProject workEngineeringProject,String srcName,String attachmentFlag) {
		boolean b = false;
		if(!file.isEmpty() && file.getSize()>0){
			OSSClientUtil ossClientUtil = new OSSClientUtil();
			String fileName = file.getOriginalFilename();
			String fileType = fileName.substring(fileName.lastIndexOf(".")+1);
			String url = ossClientUtil.uploadFile2OSS(file,srcName);
			Workattachment workattachment = new Workattachment();
			workattachment.setUrl(url);
			workattachment.setType(fileType);
			workattachment.setAttachmentName(fileName);
			workattachment.setAttachmentUser(UserUtils.getUser().getId());
			workattachment.setAttachmentId(workEngineeringProject.getId());
			workattachment.setAttachmentFlag(attachmentFlag);
			workattachmentService.save(workattachment);
			b = true;
		}
		return b;
	}

	/**
	 * 启动流程
	 * @param
	 */
	@Transactional(readOnly = false)
	public void startProofreadProcess(WorkEngineeringProject workEngineeringProject, Map<String, Object> variables) {
		try{
			// 用来设置启动流程的人员ID，引擎会自动把用户ID保存到activiti:initiator中
			identityService.setAuthenticatedUserId(workEngineeringProject.getCurrentUser().getId());
			// 启动流程
			String businessKey = workEngineeringProject.getId().toString();
			WorkActivityMenu workActivityMenu = workActivityMenuService.findByParentAndOffice("7864872f45b84acd893010e66a3db2c8",officeService.get(workEngineeringProject.getOffice().getId()));
			// 启动流程
			StringBuffer buffer = new StringBuffer();
			StringBuffer totla = new StringBuffer();
			String processType = workActivityMenu.getProcessType();
			WorkProjectNotify workProjectNotify = new WorkProjectNotify();
			workProjectNotify.setTitle("工程咨询-三级校审审批申请");
			workProjectNotify.setNotifyId(workEngineeringProject.getId());
			workProjectNotify.setCompanyId(workEngineeringProject.getCompanyId());
			workProjectNotify.setContent(UserUtils.get(workEngineeringProject.getCreateBy().getId()).getName()+"发起工程咨询-三级校审申请,请审批");
			workProjectNotify.setType("3");
			workProjectNotify.setStatus("0");
			workProjectNotify.setRemarks("待审批");
			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;
					}
				}
				buffer.append(activity.getRole().getEnname());
				variables.put("type", workActivityMenu.getProcessType());
				if(workActivityMenu!=null&&StringUtils.isNotBlank(workActivityMenu.getId())&&StringUtils.isNotBlank(activity.getId())){
					//角色审批
					if(StringUtils.isNotBlank(activity.getRole().getEnname())){
						workProjectNotify.setNotifyRole(buffer.toString());
					}
					//人员审批
					if(StringUtils.isNotBlank(activity.getUser().getId())){
						if (activity.getUser().getId().equals("1")){
							workProjectNotify.setUser(UserUtils.getUser());
						}else {
							workProjectNotify.setUser(new User(activity.getUser().getId()));
						}
					}
				}else {
					workProjectNotify.setNotifyRole(buffer.toString());
				}
				workProjectNotify.setId("");
				workProjectNotifyService.save(workProjectNotify);
			}else {
				processType = "threeexamination";
				variables.put("type", processType);
				List<Role> roles = UserUtils.getSelectRole();
				buffer = DateUtils.getByEnnme(roles.get(0).getEnname());
				totla = DateUtils.getByEnnme(roles.get(0).getEnname());
				buffer.append("bmzr");
				variables.put("bmzr", buffer.toString());
				totla.append("zg");
				variables.put("total", totla.toString());
				List<String> assigneeList=new ArrayList<String>(); //分配任务的人员
				String approverId = workEngineeringProject.getHostOfficeMaster();
				if(approverId!=null && !approverId.equals("")) {
					String[] approverIds = approverId.split(",");
					for (int i =0 ;i<approverIds.length;i++){
						assigneeList.add(approverIds[i]);
						workProjectNotify.setUser(new User(approverIds[i]));
						workProjectNotify.setId("");
						workProjectNotifyService.save(workProjectNotify);
					}
				}
				variables.put("assigneeList", assigneeList);
				variables.put("count",assigneeList.size());
			}


			variables.put("busId", businessKey);
			variables.put("title", workEngineeringProject.getRemarks());//设置标题；
			ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processType, businessKey, variables);
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			workEngineeringProject.setProcessInstance(processInstance);
			// 更新流程实例ID
			workEngineeringProject.setProcessInstanceProofreadId(processInstance.getId());
			workEngineeringProject.setProofreadMaster(workEngineeringProject.getHostOfficeMaster());
			//workEngineeringProject.setProofreadTotal(buffer.toString());
			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("4e62d343e9444a55b5544839eedc34t"));
				workActivityProcessService.save(workActivityProcess);
				workActivityProcess.setCount(2);
				workActivityProcess.setActivity(new Activity("4e62d343e9444a55b5544839eedc2f4t"));
				workActivityProcess.setId("");
				workActivityProcessService.save(workActivityProcess);
			}
			dao.update(workEngineeringProject);
			dao.updateProcessInstanceProofreadId(workEngineeringProject);
		}catch (Exception e){
			logger.error("Exception e:"+e);
		}


	}

	/**
	 * 获取流程详细信息
	 * @param processInstanceId
	 */
	@SuppressWarnings("unchecked")
	public WorkEngineeringProject getByProcessInstanceId(String processInstanceId) {
		WorkEngineeringProject workEngineeringProject = dao.getByProcessInstanceId(processInstanceId);
		return workEngineeringProject;
	}
	/**
	 * 获取流程详细信息
	 * @param processInstanceProofreadId
	 */
	@SuppressWarnings("unchecked")
	public WorkEngineeringProject getByProcessInstanceProofreadId(String processInstanceProofreadId) {
		WorkEngineeringProject workEngineeringProject = dao.getByProcessInstanceProofreadId(processInstanceProofreadId);
		return workEngineeringProject;
	}

	public Page<WorkEngineeringProject> findPageByproject(Page<WorkEngineeringProject> page, WorkEngineeringProject workEngineeringProject) {
		workEngineeringProject.setPage(page);
		page.setList(dao.findListByprojectt(workEngineeringProject));
		return page;
	}

	public List<WorkEngineeringProject> findByList(WorkEngineeringProject workEngineeringProject) {
		return dao.findByList(workEngineeringProject);
	}
}