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

import com.google.common.collect.Maps;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.service.CrudService;
import com.jeeplus.common.utils.Collections3;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.IdGen;
import com.jeeplus.common.utils.MenuStatusEnum;
import com.jeeplus.modules.act.entity.Act;
import com.jeeplus.modules.act.service.ActTaskService;
import com.jeeplus.modules.act.utils.ProcessDefCache;
import com.jeeplus.modules.projectcontentinfo.dao.ProjectReportDataDao;
import com.jeeplus.modules.projectcontentinfo.dao.ProjectcontentinfoDao;
import com.jeeplus.modules.projectcontentinfo.entity.ProjectReportData;
import com.jeeplus.modules.projectcontentinfo.entity.Projectcontentinfo;
import com.jeeplus.modules.ruralprojectrecords.dao.RuralProjectClientLinkmanDao;
import com.jeeplus.modules.ruralprojectrecords.dao.RuralProjectRecordsDao;
import com.jeeplus.modules.ruralprojectrecords.dao.RuralWorkProjectUserDao;
import com.jeeplus.modules.ruralprojectrecords.entity.RuralProjectRecords;
import com.jeeplus.modules.ruralprojectrecords.enums.ProjectStatusEnum;
import com.jeeplus.modules.serialnum.service.SerialNumTplService;
import com.jeeplus.modules.sys.entity.Office;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.service.OfficeService;
import com.jeeplus.modules.sys.utils.DictUtils;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workactivity.dao.WorkActivityProcessDao;
import com.jeeplus.modules.workactivity.entity.Activity;
import com.jeeplus.modules.workactivity.entity.WorkActivityProcess;
import com.jeeplus.modules.workactivity.service.ActivityService;
import com.jeeplus.modules.workactivity.service.WorkActivityProcessService;
import com.jeeplus.modules.workactivitymenu.entity.WorkActivityMenu;
import com.jeeplus.modules.workactivitymenu.service.WorkActivityMenuService;
import com.jeeplus.modules.workclientinfo.dao.WorkClientAttachmentDao;
import com.jeeplus.modules.workclientinfo.dao.WorkClientLinkmanDao;
import com.jeeplus.modules.workclientinfo.entity.WorkClientAttachment;
import com.jeeplus.modules.workclientinfo.entity.WorkClientInfo;
import com.jeeplus.modules.workclientinfo.entity.WorkClientLinkman;
import com.jeeplus.modules.workclientinfo.service.WorkClientInfoService;
import com.jeeplus.modules.workcontractinfo.dao.WorkContractInfoDao;
import com.jeeplus.modules.workcontractinfo.entity.WorkContractInfo;
import com.jeeplus.modules.workcontractinfo.service.WorkContractInfoService;
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.HistoryService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricTaskInstanceQuery;
import org.activiti.engine.runtime.ProcessInstance;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 项目登记Service
 * @author ppt
 * @version 2018-05-02
 */
@Service
@Transactional(readOnly = true)
public class RuralProjectRecordsService extends CrudService<RuralProjectRecordsDao, RuralProjectRecords> {

	@Autowired
	private RuralWorkProjectUserDao workProjectUserDao;
	@Autowired
	private RuralProjectClientLinkmanDao clientLinkmanDao;
	@Autowired
	private WorkClientLinkmanDao workClientLinkmanDao;
	@Autowired
	private IdentityService identityService;
	@Autowired
	private OfficeService officeService;
	@Autowired
	private ActTaskService actTaskService;
	@Autowired
	private WorkActivityMenuService workActivityMenuService;
	@Autowired
	private RuntimeService runtimeService;
	@Autowired
	private WorkActivityProcessService workActivityProcessService;
	@Autowired
	private WorkProjectNotifyService workProjectNotifyService;
	@Autowired
	private ActivityService activityService;
    @Autowired
    protected HistoryService historyService;
	@Autowired
	private WorkContractInfoService contractInfoService;
	@Autowired
	private WorkContractInfoDao workContractInfoDao;
	@Autowired
	private WorkClientAttachmentDao workClientAttachmentDao;
	@Autowired
	private WorkClientInfoService workClientInfoService;
	@Autowired
	private SerialNumTplService serialNumTplService;
	@Autowired
	private ProjectcontentinfoDao projectcontentinfoDao;
    @Autowired
    private WorkActivityProcessDao workActivityProcessDao;
    @Autowired
	private ProjectReportDataDao projectReportDataDao;

	public RuralProjectRecords get(String id) {
		return super.get(id);
	}
	public RuralProjectRecords getQueryProjectUsers(String id) {
		RuralProjectRecords projectRecords = super.get(id);
		List<User> users = workProjectUserDao.queryProjectUsers(projectRecords.getId(), "1");
		projectRecords.setLeaderNameStr(Collections3.extractToString(users, "name", ","));
		if (StringUtils.isNotBlank(projectRecords.getWorkContractInfo().getId())) {
			WorkContractInfo workContractInfo = contractInfoService.get(projectRecords.getWorkContractInfo().getId());
//			workContractInfo.setConstructionProjectTypeStr(DictUtils.getDictLabel(String.valueOf(workContractInfo.getConstructionProjectType()), "construction_project_type", ""));
			projectRecords.setWorkContractInfo(workContractInfo);
		}
		return projectRecords;
	}
	public RuralProjectRecords getQueryProjectMasters(RuralProjectRecords projectRecords) {
		List<User> users = workProjectUserDao.queryProjectUsers(projectRecords.getId(), "1");
		projectRecords.setLeaderNameStr(Collections3.extractToString(users, "name", ","));
		return projectRecords;
	}
	public String getMasterStr(String id) {
		RuralProjectRecords projectRecords = super.get(id);
		List<User> users = workProjectUserDao.queryProjectUsers(projectRecords.getId(), "1");
		return Collections3.extractToString(users, "name", ",");
	}
	public RuralProjectRecords getMasters(String id) {
		RuralProjectRecords projectRecords = super.get(id);
		List<User> users = workProjectUserDao.queryProjectUsers(projectRecords.getId(), "1");
		projectRecords.setProjectLeaders(users);
		return projectRecords;
	}
	public Boolean getByUsers(RuralProjectRecords projectRecords) {
		List<User> users = workProjectUserDao.queryAllProjectUsers(projectRecords.getId());
		User user = UserUtils.getUser();
		if (user!=null && users.size()!=0) {
			for (User u : users) {
				if (user.getId().equals(u.getId())) {
					return true;
				}
			}
		}
		return false;
	}
	//开票用
	public RuralProjectRecords getInfo(String id) {
		RuralProjectRecords projectRecords = super.get(id);
		if(projectRecords!=null){
			String cid = projectRecords.getWorkContractInfo().getId();
			WorkContractInfo workContractInfo = contractInfoService.get(cid);
			WorkClientInfo workClientInfo = workClientInfoService.get(workContractInfo.getClient().getId());
			workContractInfo.setClient(workClientInfo);
			projectRecords.setWorkContractInfo(workContractInfo);
		}
		return projectRecords;
	}
	public List<RuralProjectRecords> findList(RuralProjectRecords projectRecords) {
		return super.findList(projectRecords);
	}
	public List<RuralProjectRecords> findListByStatus(RuralProjectRecords projectRecords) {
		return dao.findListByStatus(projectRecords);
	}

	public Page<RuralProjectRecords> findPage(Page<RuralProjectRecords> page, RuralProjectRecords projectRecords) {
		//设置数据权限
        if(!UserUtils.getUser().isAdmin()) {
            String dataScopeSql = dataScopeFilterOR(projectRecords.getCurrentUser(), "o", "u", "s", MenuStatusEnum.WORK_RECORDS.getValue());
            projectRecords.getSqlMap().put("dsf", dataScopeSql);
        }
        int count = dao.queryCount(projectRecords);
        page.setCount(count);
        page.setCountFlag(false);
        projectRecords.setPage(page);
		List<RuralProjectRecords> recordsList = findList(projectRecords);
		//查询负责人信息
		for (RuralProjectRecords records : recordsList) {
			this.queryContractInfos(records);
			List<User> users = workProjectUserDao.queryProjectUsers(records.getId(), "1");
			records.setProjectLeaders(users);
			records.setLeaderNameStr(Collections3.extractToString(users, "name", ","));
			records.setLeaderIds(Collections3.extractToString(users, "id", ","));
		}
		page.setList(recordsList);
		return page;
	}
	public Page<RuralProjectRecords> findPageByStatus(Page<RuralProjectRecords> page, RuralProjectRecords projectRecords) {
		//设置数据权限
		if(!UserUtils.getUser().isAdmin()) {
			String dataScopeSql = dataScopeFilterOR(projectRecords.getCurrentUser(), "o", "u", "s", MenuStatusEnum.WORK_RECORDS.getValue());
			projectRecords.getSqlMap().put("dsf", dataScopeSql);
		}
        int count = dao.queryCountByStatus(projectRecords);
        page.setCount(count);
        page.setCountFlag(false);
		projectRecords.setPage(page);
		List<RuralProjectRecords> recordsList = findListByStatus(projectRecords);
		//查询负责人信息
		for (RuralProjectRecords records : recordsList) {
			List<User> users = workProjectUserDao.queryProjectUsers(records.getId(), "1");
			records.setProjectLeaders(users);
			records.setLeaderNameStr(Collections3.extractToString(users, "name", ","));
		}
		for (RuralProjectRecords records : recordsList) {
			List<User> users = workProjectUserDao.projectUsers(records.getId());
			records.setMembercount(users.size());
		}
		page.setList(recordsList);
		return page;
	}
	public Page<RuralProjectRecords> findPageByRe(Page<RuralProjectRecords> page, RuralProjectRecords projectRecords, String userId) {
		projectRecords.setPage(page);
		projectRecords.setUserId(userId);
		List<RuralProjectRecords> recordsList = dao.findPageByRe(projectRecords);
		page.setList(recordsList);
		return page;
	}
	@Transactional(readOnly = false)
	public void saveProject(RuralProjectRecords projectRecords, ProjectStatusEnum projectStatus) throws Exception {
		long t1 = System.currentTimeMillis();

		WorkContractInfo workContractInfo = null;
		WorkClientInfo workClientInfo = new WorkClientInfo();
		Office company= new Office();
		Office office =  new Office();
        if(StringUtils.isNotBlank((projectRecords.getWorkContractInfo().getId()))){
            //有合同状态
			workContractInfo = workContractInfoDao.get(projectRecords.getWorkContractInfo().getId());
			company.setId(workContractInfo.getCompanyId());
//			office.setId(workContractInfo.getChargeCompany());
			office.setId(UserUtils.getUser().getOffice().getId());
        }else{
        	//无合同
			company.setId(UserUtils.getUser().getCompany().getId());
			office.setId(UserUtils.getUser().getOffice().getId());
		}
		projectRecords.setCompany(company);
		projectRecords.setOffice(office);

		Integer oldStatus = projectRecords.getProjectStatus();
        projectRecords.setProjectStatus(projectStatus.getValue());
        User createBy = projectRecords.getCreateBy();
		if(createBy != null){
			createBy = UserUtils.get(createBy.getId());
		}else {
		    createBy = UserUtils.getUser();
        }

		if(StringUtils.isBlank(projectRecords.getProjectId())){
            projectRecords.setProjectId(serialNumTplService.genSerialNum(createBy.getCompany(), RuralProjectRecords.SERIAL_BIZCODE));
        }
        if(projectRecords.getProjectStatus()== ProjectStatusEnum.INVALID.getValue()){
            projectRecords.setId(IdGen.uuid());
            dao.insert(projectRecords);
        }else {
            super.save(projectRecords);
        }
		//保存项目负责人
		List<User> leaders = projectRecords.getProjectLeaders();
		this.saveProjectUsers(projectRecords.getId(), leaders, true);
		//保存委托方联系人
		List<WorkClientLinkman> workClientLinkmanList = projectRecords.getWorkClientLinkmanList();
		this.saveLinkmanInfos(projectRecords.getId(), workClientLinkmanList, true);
		//保存施工方联系信息
		List<WorkClientLinkman> constructionLinkmanList = projectRecords.getWorkConstructionLinkmanList();
		this.saveLinkmanInfos(projectRecords.getId(), constructionLinkmanList, false);
        long t4 = System.currentTimeMillis();
		//保存项目计划附件信息
		if (projectRecords.getProjectStatus()== ProjectStatusEnum.INVALID.getValue()) {
			this.copyAttachments(projectRecords);
		}else {
            this.saveAttachments(projectRecords);
        }
		//启动审批流程
		if (projectRecords.getProjectStatus()== ProjectStatusEnum.IN_APRL.getValue()&&(oldStatus==null|| ProjectStatusEnum.REJECTED.getValue()!=oldStatus)) {
			this.startAudit(projectRecords,projectRecords.getProcessInstanceId());
		}
		logger.info("保存项目耗时：{}ms;启动流程耗时：{}ms",t4-t1,System.currentTimeMillis()-t4);
	}

    private void copyAttachments(RuralProjectRecords projectRecords) {
        if (projectRecords==null||projectRecords.getWorkAttachments()==null||projectRecords.getWorkAttachments().isEmpty()){
            return;
        }
        for (WorkClientAttachment workClientAttachment : projectRecords.getWorkAttachments()) {
            workClientAttachment.setAttachmentId(projectRecords.getId());
            workClientAttachment.setId(null);
            workClientAttachment.setIsNewRecord(false);
            workClientAttachment.preInsert();
            workClientAttachmentDao.insert(workClientAttachment);
        }
    }

    /**
	 * 保存委托方和施工方联系人信息
	 *
	 * @param projectId
	 * @param linkmanList
	 * @param isEntrust   是否委托方,1委托方，0施工方
	 */
	private void saveLinkmanInfos(String projectId, List<WorkClientLinkman> linkmanList, boolean isEntrust) {
		assert (projectId != null);
		if(linkmanList == null || linkmanList.isEmpty()){
		    return;
        }
		HashMap<String, Object> map = new HashMap<>(5);
		map.put("projectId", projectId);
		map.put("linkmanList", linkmanList);
		int entrust = 0;
		if (isEntrust) {
			entrust = 1;
		}
		clientLinkmanDao.deleteProjectLinkmans(projectId, entrust);
		map.put("isEntrust", entrust);
		clientLinkmanDao.batchInsert(map);
	}

	/**
	 * 保存项目组成员信息
	 *
	 * @param projectId
	 * @param users
	 * @param isMaster
	 */
	private void saveProjectUsers(String projectId, List<User> users, boolean isMaster) {
		assert (projectId != null);
		assert (users != null && !users.isEmpty());
		HashMap<String, Object> map = new HashMap<>(5);
		List<String> memberIds = new ArrayList<>(users.size());
		for (User user : users) {
			memberIds.add(user.getId());
		}
		map.put("memberIds", memberIds);
		map.put("projectId", projectId);
		String master = null;
		if (isMaster) {
			master = "1";
            workProjectUserDao.deleteProjectMasterMembers(map);
            /*map.put("isMaster", "0");
            workProjectUserDao.batchInsert(map);*/
		} else {
			master = "0";
		}
		workProjectUserDao.deleteProjectMembers(projectId, master);
		map.put("isMaster", master);
		workProjectUserDao.batchInsert(map);
	}

	@Transactional(readOnly = false)
	public void delete(RuralProjectRecords projectRecords) {
		//删除项目负责人
		workProjectUserDao.deleteProjectMembers(projectRecords.getId(), "1");
		//删除项目组成员
		workProjectUserDao.deleteProjectMembers(projectRecords.getId(), "0");
		//删除委托方联系人
		clientLinkmanDao.deleteProjectLinkmans(projectRecords.getId(), 1);
		//删除施工方联系人
		clientLinkmanDao.deleteProjectLinkmans(projectRecords.getId(), 0);
		super.delete(projectRecords);
        WorkProjectNotify notify = new WorkProjectNotify();
        notify.setNotifyId(projectRecords.getId());
        List<User> users = workProjectNotifyService.readByNotifyId(notify);
        if (users!=null && users.size()!=0){
            for (User user:users){
                UserUtils.pushMeIm(user.getId());
            }
        }
	}

	/**
	 * 设置项目组成员信息
	 *
	 * @param records
	 */
	public void queryUserNames(RuralProjectRecords records) {
		//查询负责人信息
		List<User> users = workProjectUserDao.queryProjectUsers(records.getId(), "1");
		records.setProjectLeaders(users);
		records.setLeaderNameStr(Collections3.extractToString(users, "name", ","));
		records.setLeaderIds(Collections3.extractToString(users, "id", ","));

		//查询项目组成员信息
		List<User> members = workProjectUserDao.isDelFalg(records.getId(), "");
		records.setProjectMembers(members);
		records.setMemberNameStr(Collections3.extractToString(members, "name", ","));
		records.setMemberIds(Collections3.extractToString(members, "id", ","));
	}

	/**
	 * 设置联系人信息
	 *
	 * @param projectRecords
	 */
	public void queryLinkmanInfos(RuralProjectRecords projectRecords) {
		List<WorkClientLinkman> clientLinkmanList = workClientLinkmanDao.queryProjectLinkmans(projectRecords.getId(), 1);
		for(WorkClientLinkman linkman :clientLinkmanList){
			WorkClientInfo clientInfo = workClientInfoService.get(linkman.getClientId().getId());
			linkman.setClientId(clientInfo);
		}
		projectRecords.setWorkClientLinkmanList(clientLinkmanList);
		List<WorkClientLinkman> constructionLinkmanList = workClientLinkmanDao.queryProjectLinkmans(projectRecords.getId(), 0);
		projectRecords.setWorkConstructionLinkmanList(constructionLinkmanList);
	}

	/**
	 * 启动审批流程
	 *
	 * @param projectRecords
	 */
    private void startAudit(RuralProjectRecords projectRecords, String processInstanceId) throws Exception {
        try{
            Map<String, Object> variables = new HashMap<String, Object>();
            identityService.setAuthenticatedUserId(projectRecords.getCurrentUser().getId());
            Office office = projectRecords.getOffice();
            office = officeService.get(office.getId());
            projectRecords.setOffice(office);
            String contentStr = "项目编号："+projectRecords.getProjectId()+"，项目名称："+ projectRecords.getProjectName()+"，创建人："+projectRecords.getCreateBy().getName()+"，所属部门："+projectRecords.getOffice().getName();
            String titleStr = "项目名称："+ projectRecords.getProjectName();

            String businessKey = projectRecords.getId();

            WorkActivityMenu workActivityMenu = workActivityMenuService.findByParentAndOffice("7854872f45b84acd893010e66a3db2c8", office);
            // 启动流程
            String processType = workActivityMenu.getProcessType();
            StringBuffer buffer = new StringBuffer();
            Activity activity = new Activity();
            WorkProjectNotify workProjectNotify = UtilNotify
                    .saveNotify(projectRecords.getId(),
                            null,
                            projectRecords.getCompany().getId(),
                            titleStr,
                            contentStr,
                            "39",
                            "0",
                            "待审批",
                            ""
                    );

            List<User> users = new ArrayList<>();
			List<User> bmzrs = UserUtils.getByRoleActivityEnname("bmzr",2,office.getId(),"4",projectRecords.getCreateBy());

			if (StringUtils.isNotBlank(workActivityMenu.getId())) {
                processType = workActivityMenu.getProcessType();
                workActivityMenu = workActivityMenuService.get(workActivityMenu.getId());
                List<Activity> activities = workActivityMenu.getActivities();
                for (Activity a : activities) {
                    String encount = a.getEncount();
                    String enlist = a.getEnlist();
                    if (a.getRole()!=null && StringUtils.isNotBlank(a.getRole().getEnname())){
                        List enusers = UserUtils.getByRoleActivityEnnames(a.getRole().getEnname(),office.getId(),"8",projectRecords.getCreateBy());
                        if (enusers.size()==0){
                            /*this.delete(projectRecords);
                            for (WorkClientAttachment workClientAttachment : projectRecords.getWorkAttachments()) {
                                workClientAttachmentDao.delete(workClientAttachment);
                            }*/
                            throw new Exception("流程审批人不能为空,角色"+a.getRole().getName()+"下无用户,请联系管理员！");
                        }
                        variables.put(enlist, enusers);
                        variables.put(encount, enusers.size());
                    }
                    if (a.getDelFlag().equals("0") && a.getCount() == 1) {
                        activity = a;
                    }
                }
                buffer.append(activity.getRole().getEnname());
                if (activity != null && StringUtils.isNotBlank(activity.getId())) {
                    //角色审批
                    if (StringUtils.isNotBlank(activity.getRole().getEnname())) {
                        users = UserUtils.getByRoleActivityEnnames(activity.getRole().getEnname(),office.getId(),"4",projectRecords.getCreateBy());
                    }
                    //人员审批
                    if (StringUtils.isNotBlank(activity.getUser().getId())) {
                        users.add(activity.getUser());
                    }
                }
                workProjectNotify.setId("");
            } else {
                 if (bmzrs==null||bmzrs.size()==0){
                    /*this.delete(projectRecords);
                    if (projectRecords.getWorkAttachments()!=null) {
                        for (WorkClientAttachment workClientAttachment : projectRecords.getWorkAttachments()) {
                            workClientAttachmentDao.delete(workClientAttachment);
                        }
                    }*/
                    throw new Exception("流程审批人不能为空,角色部门负责人下无用户,请联系管理员！");
                }
                processType = "projectAudit";
                variables.put("applyUserId", projectRecords.getCreateBy().getId());
                variables.put("bmzrCount",bmzrs.size());
                variables.put("bmzrList",bmzrs);
                users.addAll(bmzrs);
            }
            List<String> userIds = new ArrayList<>(users.size());
            for (User u : users){
                userIds.add(u.getId());
                workProjectNotify.setUser(u);
                workProjectNotify.setId("");
                workProjectNotify.setNotifyRole("部门负责人审批");
                workProjectNotifyService.save(workProjectNotify);
                Map<String,Object> extras = new HashMap<>();
                extras.put("type","7003");
                extras.put("procDefKey","39");
                extras.put("id",workProjectNotify.getId());
                UserUtils.pushInfoToApp(titleStr,contentStr,extras,u.getId());
            }

            long t1 = System.currentTimeMillis();
            UserUtils.pushIm(userIds,contentStr);
            logger.info("推送消息耗时：{}ms",System.currentTimeMillis()-t1);
            variables.put("busId", businessKey);
            variables.put("type", processType);
            variables.put("title", "审批单：" + projectRecords.getProjectName());//设置标题；

            ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processType, businessKey, variables);
            //        projectRecords.setProcessInstance(processInstance);
            if (StringUtils.isNotBlank(processInstanceId)) {
                workActivityProcessService.updateProcessInstanceId(processInstance.getId(),processInstanceId);
                workActivityProcessService.deleteProcessInstanceId(processInstanceId);
				workActivityProcessService.deleteProcessIdAuditUsers(processInstanceId);
            }
            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");
                workActivityProcessService.save(workActivityProcess);
				workActivityProcessService.insertAuditsByType(bmzrs,processInstance.getId(),1,1);
            }
            projectRecords.setProcessInstanceId(processInstance.getId());
            projectRecords.setProjectStatus(ProjectStatusEnum.IN_APRL.getValue());
            dao.updateProcessIdAndStatus(projectRecords);
        }catch (Exception e){
            logger.error("启动审批流程异常：",e);
            throw e;
        }
    }

	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	public void updateSelectiveById(RuralProjectRecords projectRecords) {
		dao.updateSelectiveById(projectRecords);
	}

	public RuralProjectRecords getByProcessInstanceId(String procInsId) {
		RuralProjectRecords records = dao.findUniqueByProperty("process_instance_id", procInsId);
		if(records!=null) {
            List<User> users = workProjectUserDao.queryProjectUsers(records.getId(), "1");
            records.setProjectLeaders(users);
        }
		return records;
	}

    @Transactional(readOnly = false)
    public String auditSave(RuralProjectRecords projectRecords, List<User> auditUsers) throws Exception {
		int projectStatus = projectRecords.getProjectStatus();
		String taskDefKey = projectRecords.getAct().getTaskDefKey();
		if (!"modifyApply".equals(taskDefKey) && !taskDefKey.contains("audit") ) {
			actTaskService.claim(projectRecords.getAct().getTaskId(), UserUtils.getUser().getId());
            List<User> leaders = projectRecords.getProjectLeaders();
            this.saveProjectUsers(projectRecords.getId(), leaders, true);
		}else {
			projectRecords.getAct().setFlag("yes");
			saveProject(projectRecords, ProjectStatusEnum.IN_APRL);
		}

		String comment = "";
		if ( projectStatus == ProjectStatusEnum.REJECTED.getValue()) {
			comment = ("yes".equals(projectRecords.getAct().getFlag())?"[重新申请] ":"[已撤销] ");
		}else {
			comment = ("yes".equals(projectRecords.getAct().getFlag())?"[同意] ":"[驳回] ")+projectRecords.getAct().getComment();
		}

		if (!"yes".equals(projectRecords.getAct().getFlag())) {
			projectRecords.setProjectStatus(ProjectStatusEnum.REJECTED.getValue());
		}

		User createUser = UserUtils.get(projectRecords.getCreateBy().getId());

		Map<String, Object> vars = Maps.newHashMap();
		String notifyRole = "";
		//业务逻辑对应的条件表达式
		User user = null;
		List<Activity> activitieList = activityService.getByProcessInstanceId(projectRecords.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(projectRecords.getProcessInstanceId());
		List<WorkActivityProcess> workActivityProcesses = workActivityProcessService.findList(selectProcess);
		List<Activity> activities = workActivityMenu.getActivities();
		String  taskCount = "1";
		String enname = "";
        Office office = projectRecords.getOffice();
        office = officeService.get(office.getId());
        projectRecords.setOffice(office);
		String notifyStr = "项目编号："+projectRecords.getProjectId()+"，项目名称："+ projectRecords.getProjectName();
		String str = notifyStr+"，创建人："+projectRecords.getCreateBy().getName()+"，所属部门："+projectRecords.getOffice().getName();
		String titleStr = "项目名称："+ projectRecords.getProjectName();
		int key = 0;
		if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("projectAudit")) {
			key = 1;
			for (int i = 0; i < workActivityProcesses.size(); i++) {
				WorkActivityProcess activityProcess = workActivityProcesses.get(i);
				if (taskDefKey.equals("modifyApply")) {
					taskCount = "0";
					workActivityProcess.setId("");
					workActivityProcess.setCount(0);
					if (!"yes".equals(projectRecords.getAct().getFlag())) {
						projectRecords.setProjectStatus(ProjectStatusEnum.RECALL.getValue());
						workActivityProcess.setIsApproval("2");
						vars.put("pass", false);
					} else {
						vars.put("pass", true);
						workActivityProcess.setIsApproval("1");
					}
					break;
				} else {
					taskCount = activityProcess.getCount()+"";
					workActivityProcess = activityProcess;
					if (!workActivityProcess.getIsApproval().equals("0")) {
						workActivityProcess.setId("");
					}
					for (Activity activity : activities) {
						if (activity.getCount() == activityProcess.getCount()) {
							notifyRole = activity.getName();
							break;
						}
					}
					if (!"yes".equals(projectRecords.getAct().getFlag())) {
						notifyRole = "调整项目";
						projectRecords.setProjectStatus(ProjectStatusEnum.REJECTED.getValue());
						workActivityProcess.setIsApproval("2");
						String returnBack = "-1";
						for (Activity activity : activities) {
							if (activity.getCount() == activityProcess.getCount()) {
								returnBack = activity.getReturnBack();
								break;
							}
						}
						if (returnBack.equals("0")) {
							workActivityProcess.setId("");
						}
						vars.put("pass", false);
					} else {
						workActivityProcess.setIsApproval("1");
						vars.put("pass", true);
					}
					break;
				}
			}
		}else {
			workActivityMenu.setProcessType("projectAudit");
			for (int i = 0; i < workActivityProcesses.size(); i++) {
				WorkActivityProcess activityProcess = workActivityProcesses.get(i);
				String count = String.valueOf(activityProcess.getCount());
				workActivityProcess = activityProcess;
				if (!workActivityProcess.getIsApproval().equals("0")) {
					workActivityProcess.setId("");
				}
				// 审核环节
				if ("bmzr".equals(taskDefKey) && "1".equals(count)) {
					taskCount = count;
					if ("yes".equals(projectRecords.getAct().getFlag())) {
						workActivityProcess.setIsApproval("1");
						vars.put("pass", true);
						notifyRole = "审批通过";
					} else {
						workActivityProcess.setIsApproval("2");
						vars.put("pass", false);
						user = createUser;
						notifyRole = "调整项目";
					}
					break;
				} else if ("modifyApply".equals(taskDefKey) && "0".equals(count)) {
					notifyRole = "部门负责人审批";
					taskCount = "0";
					enname = "bmzr";
					workActivityProcess.setCount(0);
					if("yes".equals(projectRecords.getAct().getFlag())){
						workActivityProcess.setIsApproval("1");
						vars.put("pass",true);
					}else{
						workActivityProcess.setIsApproval("2");
						projectRecords.setProjectStatus(ProjectStatusEnum.RECALL.getValue());
						vars.put("pass",false);
					}
					break;
				}
			}
		}
		workActivityProcessService.updateProcess(workActivityProcess,workActivityMenu,key,taskCount,projectRecords.getProcessInstanceId(),taskDefKey,"modifyApply",projectRecords.getAct().getFlag(),comment, activities);
		// 设置意见
		projectRecords.getAct().setComment(comment);
		projectRecords.preUpdate();
		// 提交流程任务
		actTaskService.complete(projectRecords.getAct().getTaskId(), projectRecords.getAct().getProcInsId(), projectRecords.getAct().getComment(), vars);
		boolean state = actTaskService.isProcessEnd(projectRecords.getAct().getProcInsId());
		List<User> users = new ArrayList<>();
		List<User> userList = new ArrayList<>();
		if(!state) {
			users.add(projectRecords.getCreateBy());
			if ("yes".equals(projectRecords.getAct().getFlag())) {
				projectRecords.setProjectStatus(ProjectStatusEnum.SIGNED.getValue());
				WorkProjectNotify notify = new WorkProjectNotify();
				notify.setNotifyId(projectRecords.getId());
				userList = workProjectNotifyService.readByNotifyId(notify);
				users.add(projectRecords.getCreateBy());
				workProjectNotifyService
						.save(UtilNotify
								.saveNotify(projectRecords.getId(),
										projectRecords.getCreateBy(),
										projectRecords.getCompany().getId(),
										titleStr,
										notifyStr,
										"39",
										"0",
										"待通知",
										notifyRole));
			} else {
				WorkProjectNotify notify = new WorkProjectNotify();
				notify.setNotifyId(projectRecords.getId());
				userList = workProjectNotifyService.readByNotifyId(notify);
				users.add(projectRecords.getCreateBy());
				if (projectRecords.getProjectStatus()!= ProjectStatusEnum.RECALL.getValue()){
					projectRecords.setProjectStatus(ProjectStatusEnum.REJECTED.getValue());
					workProjectNotifyService
							.save(UtilNotify
									.saveNotify(projectRecords.getId(),
											projectRecords.getCreateBy(),
											projectRecords.getCompany().getId(),
											titleStr,
											notifyStr,
											"39",
											"0",
											"待通知",
											notifyRole));
				}
			}
			workActivityProcessService.deleteProcessIdAuditUsers(projectRecords.getProcessInstanceId());

		}else{
			if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("projectAudit")) {
				WorkProjectNotify notify = new WorkProjectNotify();
				notify.setNotifyId(projectRecords.getId());
				userList = workProjectNotifyService.readByNotifyId(notify);
				WorkProjectNotify workProjectNotify = UtilNotify
						.saveNotify(projectRecords.getId(),
								new User(),
								projectRecords.getCompany().getId(),
								titleStr,
								str,
								"39",
								"0",
								"待审批",
								notifyRole);
				String count = taskDefKey.replace("audit","").replace("task","");
				List<WorkProjectNotify> workProjectNotifys = activityService.getByFlagAndTaskDefKeyList(
						activities,
						workProjectNotify,
						taskDefKey,
						projectRecords.getAct().getFlag(),
						count,
						projectRecords.getCreateBy(),
						projectRecords.getOffice().getId(),
						"4");
				for (WorkProjectNotify workProjectNotify1:workProjectNotifys){
					users.add(workProjectNotify1.getUser());
					workProjectNotify1.setId("");
					workProjectNotify1.setIsNewRecord(false);
					workProjectNotifyService.save(workProjectNotify1);
				}
			}else {
				if (!"yes".equals(projectRecords.getAct().getFlag())) {
					WorkProjectNotify notify = new WorkProjectNotify();
					notify.setNotifyId(projectRecords.getId());
					userList = workProjectNotifyService.readByNotifyId(notify);
					users.add(user);
					WorkProjectNotify workProjectNotify = UtilNotify
							.saveNotify(projectRecords.getId(),
									user,
									projectRecords.getCompany().getId(),
									titleStr,
									str,
									"39",
									"0",
									"重新申请",
									notifyRole);
					workProjectNotifyService.save(workProjectNotify);
				} else {
					if (StringUtils.isNotBlank(enname)) {
						WorkProjectNotify notify = new WorkProjectNotify();
						notify.setNotifyId(projectRecords.getId());
						userList = workProjectNotifyService.readByNotifyId(notify);
						WorkProjectNotify workProjectNotify = UtilNotify
								.saveNotify(projectRecords.getId(),
										new User(),
										projectRecords.getCompany().getId(),
										titleStr,
										str,
										"39",
										"0",
										"待审批",
										notifyRole);
						for (User user1:auditUsers){
							users.add(user1);
							workProjectNotify.setUser(user1);
							workProjectNotify.setId("");
							workProjectNotify.setIsNewRecord(false);
							workProjectNotifyService.save(workProjectNotify);
							Map<String,Object> extras = new HashMap<>();
							extras.put("type","7003");
							extras.put("procDefKey","39");
							extras.put("id",workProjectNotify.getId());
							UserUtils.pushInfoToApp(titleStr,str,extras,user1.getId());
						}
					}else {
						WorkProjectNotify notify = new WorkProjectNotify();
						notify.setNotifyId(projectRecords.getId());
						userList = workProjectNotifyService.readByNotifyId(notify);
						users.add(projectRecords.getCreateBy());
						workProjectNotifyService
								.save(UtilNotify
										.saveNotify(projectRecords.getId(),
												projectRecords.getCreateBy(),
												projectRecords.getCompany().getId(),
												titleStr,
												str,
												"39",
												"0",
												"重新申请",
												notifyRole));
					}
				}
			}
		}

		if (users!=null && users.size()!=0) {
			List<String> userIds = new ArrayList<>(users.size());
			for (User u : users) {
				userIds.add(u.getId());
			}
			UserUtils.pushIm(userIds,titleStr);
		}
		if (userList!=null && userList.size()!=0) {
			for (User u : userList) {
				UserUtils.pushMeIm(u.getId());
			}
		}
		if(ProjectStatusEnum.SIGNED.getValue()==projectRecords.getProjectStatus()){
			Projectcontentinfo projectcontentinfo = new Projectcontentinfo();
//			projectcontentinfo.setProject(projectRecords);
			projectcontentinfo.setCompanyId(projectRecords.getCompany().getId());
			projectcontentinfo.setOfficeId(projectRecords.getOffice().getId());
			projectcontentinfo.setSort(30);
			projectcontentinfo.setParentIds("0,");
			projectcontentinfo.setParent(new Projectcontentinfo("0"));
			projectcontentinfo.setName(projectRecords.getProjectId());
			projectcontentinfo.preInsert();
			projectcontentinfoDao.insert(projectcontentinfo);
		}
		dao.updateSelectiveById(projectRecords);
		return "保存审核意见成功！";
    }

    /**
     * 获取已办任务
     * @return
     */
    public List<RuralProjectRecords> historicList(Act act){
        String userId = UserUtils.getUser().getId();
        HistoricTaskInstanceQuery query = historyService.createHistoricTaskInstanceQuery().finished().taskAssignee(userId);
        // 设置查询条件
        if (StringUtils.isNotBlank(act.getProcDefKey())){
            query.processDefinitionKey(act.getProcDefKey());
        }
        if (act.getBeginDate() != null){
            query.taskCompletedAfter(act.getBeginDate());
        }
        if (act.getEndDate() != null){
            query.taskCompletedBefore(act.getEndDate());
        }
        // 查询总数
        List<HistoricTaskInstance> list = query.list();
        List<RuralProjectRecords> list1 = new ArrayList<RuralProjectRecords>();
        Office office = UserUtils.getSelectCompany();
        String companyId = office==null?"":office.getId();
        for (HistoricTaskInstance histTask : list) {
            RuralProjectRecords projectRecords = this.getByProcessInstanceId(histTask.getProcessInstanceId());
            if (projectRecords != null && projectRecords.getCompany().getId().equals(companyId)) {
                projectRecords.setCreateBy(UserUtils.get(projectRecords.getCreateBy().getId()));
                historyService.getHistoricIdentityLinksForProcessInstance(histTask.getProcessInstanceId());
                act.setHistTask(histTask);
                act.setVars(histTask.getProcessVariables());
                act.setProcDef(ProcessDefCache.get(histTask.getProcessDefinitionId()));
                act.setStatus("finish");
                projectRecords.setAct(act);
                List<User> users = workProjectUserDao.queryProjectUsers(projectRecords.getId(), "1");
                projectRecords.setProjectLeaders(users);
				WorkContractInfo workContractInfo = contractInfoService.get(projectRecords.getWorkContractInfo().getId());
				workContractInfo.setConstructionProjectTypeStr(DictUtils.getDictLabel(String.valueOf(workContractInfo.getConstructionProjectType()), "construction_project_type", ""));
				projectRecords.setWorkContractInfo(workContractInfo);
                list1.add(projectRecords);
            }
        }
//        workReimbursement.setPage(page);
        return list1;
    }

    public RuralProjectRecords getByAlterProcessInstanceId(String alterProcessId) {
		RuralProjectRecords projectRecords = dao.findUniqueByProperty("alter_process_id", alterProcessId);
		if(projectRecords!=null) {
			List<User> users = workProjectUserDao.queryProjectUsers(projectRecords.getId(), "1");
			projectRecords.setProjectLeaders(users);
		}
		return  projectRecords;
	}

	public List<RuralProjectRecords> historicAlterList(Act act) {
		String userId = UserUtils.getUser().getId();
		HistoricTaskInstanceQuery query = historyService.createHistoricTaskInstanceQuery().finished().taskAssignee(userId);
		// 设置查询条件
		if (StringUtils.isNotBlank(act.getProcDefKey())){
			query.processDefinitionKey(act.getProcDefKey());
		}
		if (act.getBeginDate() != null){
			query.taskCompletedAfter(act.getBeginDate());
		}
		if (act.getEndDate() != null){
			query.taskCompletedBefore(act.getEndDate());
		}
		// 查询总数
		List<HistoricTaskInstance> list = query.list();
		List<RuralProjectRecords> list1 = new ArrayList<RuralProjectRecords>();
		Office office = UserUtils.getSelectCompany();
		String companyId = office==null?"":office.getId();
		for (HistoricTaskInstance histTask : list) {
			RuralProjectRecords projectRecords = this.getByAlterProcessInstanceId(histTask.getProcessInstanceId());
			if (projectRecords != null && projectRecords.getCompany().getId().equals(companyId)) {
				projectRecords.setCreateBy(UserUtils.get(projectRecords.getCreateBy().getId()));
				historyService.getHistoricIdentityLinksForProcessInstance(histTask.getProcessInstanceId());
				act.setHistTask(histTask);
				act.setVars(histTask.getProcessVariables());
				act.setProcDef(ProcessDefCache.get(histTask.getProcessDefinitionId()));
				act.setStatus("finish");
				projectRecords.setAct(act);
				List<User> users = workProjectUserDao.queryProjectUsers(projectRecords.getId(), "1");
				projectRecords.setProjectLeaders(users);
				WorkContractInfo workContractInfo = contractInfoService.get(projectRecords.getWorkContractInfo().getId());
				workContractInfo.setConstructionProjectTypeStr(DictUtils.getDictLabel(String.valueOf(workContractInfo.getConstructionProjectType()), "construction_project_type", ""));
				projectRecords.setWorkContractInfo(workContractInfo);
				list1.add(projectRecords);
			}
		}
//        workReimbursement.setPage(page);
		return list1;
	}

	public void updateSelectiveByProjectId(RuralProjectRecords records) {
    	dao.updateSelectiveByProjectId(records);
	}

	public void queryWorkAttachment(RuralProjectRecords projectRecords) {
		WorkClientAttachment attchment = new WorkClientAttachment();
		attchment.setAttachmentId(projectRecords.getId());
		List<WorkClientAttachment> attachments = workClientAttachmentDao.findList(attchment);
		projectRecords.setWorkAttachments(attachments);
	}

	public void queryReportData(RuralProjectRecords projectRecords){
       String projectId = projectRecords.getId();
       List<ProjectReportData> byProjectId = projectReportDataDao.findByProjectId(projectId);
       projectRecords.setProjectReportData(byProjectId);

	}

	private void saveAttachments(RuralProjectRecords projectRecords) {
		if (projectRecords.getWorkAttachments()!=null && !projectRecords.getWorkAttachments().isEmpty()) {
			//保存附件信息
			for (WorkClientAttachment workClientAttachment : projectRecords.getWorkAttachments()) {
				if (StringUtils.isBlank(workClientAttachment.getId())&&StringUtils.isNotBlank(workClientAttachment.getAttachmentId())) {
					continue;
				}
				if (StringUtils.isBlank(workClientAttachment.getId())&&StringUtils.isBlank(workClientAttachment.getUrl())) {
					continue;
				}
				if (WorkClientAttachment.DEL_FLAG_NORMAL.equals(workClientAttachment.getDelFlag())) {
					workClientAttachment.setAttachmentId(projectRecords.getId());
					workClientAttachment.setAttachmentFlag("82");
					workClientAttachment.setAttachmentUser(UserUtils.getUser().getId());
					if (StringUtils.isBlank(workClientAttachment.getId()) || "null".equals(workClientAttachment.getId())) {
						workClientAttachment.preInsert();
						workClientAttachmentDao.insert(workClientAttachment);
					} else {
						workClientAttachment.preUpdate();
						workClientAttachmentDao.update(workClientAttachment);
					}
				} else {
					workClientAttachmentDao.delete(workClientAttachment);
				}
			}
		}
	}

	/**
	 * 查询合同信息
	 * @param projectRecords
	 */
	public void queryContractInfos(RuralProjectRecords projectRecords) {
		WorkContractInfo workContractInfo = contractInfoService.get(projectRecords.getWorkContractInfo().getId());
		if(workContractInfo!=null){
			workContractInfo.setConstructionProjectTypeStr(DictUtils.getMainDictLabel(String.valueOf(workContractInfo.getContractType()), "contract_type", ""));
			if(workContractInfo.getWorkClientInfoList()!=null&&!workContractInfo.getWorkClientInfoList().isEmpty()){
				StringBuilder workClinetInfoIds = new StringBuilder();
				for (WorkClientInfo workClientInfo : workContractInfo.getWorkClientInfoList()) {
					workClinetInfoIds.append(workClientInfo.getId()).append(",");
				}
				workClinetInfoIds.deleteCharAt(workClinetInfoIds.length()-1);
				workContractInfo.setWorkClinetInfoIds(workClinetInfoIds.toString());
			}
		}
		projectRecords.setWorkContractInfo(workContractInfo);
	}

    public RuralProjectRecords findUseableByProjectId(String projectId) {
	    return  dao.findUseableByProjectId(projectId);
    }

    public void queryProjectDetail(RuralProjectRecords projectRecords) {
        this.queryContractInfos(projectRecords);
        //设置项目组成员
        this.queryUserNames(projectRecords);
        //设置委托方联系人信息
        this.queryLinkmanInfos(projectRecords);
        //设置附件信息
        this.queryWorkAttachment(projectRecords);
        //设置报告
        this.queryReportData(projectRecords);
    }

    public Page<RuralProjectRecords> findPageDetail(Page<RuralProjectRecords> page, RuralProjectRecords projectRecords) {
	    boolean dateflag = false;
	    if(projectRecords.getBeginDate()==null){
	        projectRecords.setBeginDate(DateUtils.addYears(new Date(),-1));
	        dateflag = true;
        }
        page.setOrderBy("createDate desc");

        Page<RuralProjectRecords> recordsPage = this.findPage(page, projectRecords);
	    if (dateflag){
	        projectRecords.setBeginDate(null);
        }
        return recordsPage;
    }

    @Transactional(readOnly = false)
    public void cancelProcess(RuralProjectRecords projectRecords) throws Exception {
        WorkActivityProcess process = new WorkActivityProcess();
        process.setProcessInstanceId(projectRecords.getProcessInstanceId());
        process.setIsApproval("0");
        //List<WorkActivityProcess> processList1 = workActivityProcessService.findByProcInsId(process);
        WorkActivityProcess workActivityProcess = new WorkActivityProcess();
        workActivityProcess.setProcessInstanceId(projectRecords.getProcessInstanceId());
        List<WorkActivityProcess> processList = workActivityProcessService.findList(workActivityProcess);
        WorkProjectNotify notify = new WorkProjectNotify();
        notify.setNotifyId(projectRecords.getId());
        List<User> userList = workProjectNotifyService.readByNotifyId(notify);
        if (userList!=null && userList.size()!=0) {
            for (User u : userList) {
                User user = UserUtils.get(u.getId());
                /*List<WebSocket> toUserConns = ChatServerPool.getWebSocketByUser(u.getId());
                for (WebSocket toUserConn : toUserConns) {
                    String message = "{\"to\":\""+u.getId()+"\"," +
                            "\"msg\":\"审批信息 申请人:"+ user.getName()+",项目登记审批:"+projectRecords.getProjectName() +" 强制撤销!\"," +
                            "\"useType\":\"sys\"}";
                    ChatServerPool.sendMessageToUser(toUserConn, message);//同时向本人发送消息
                    //ChatServerPool.sendMessageToUser(toUserConn, u.getId() + "_sys_审批信息 " + "报销人:" + user.getName() + ",报销编号:" + workReimbursement.getNumber() + " 强制撤销!");//同时向本人发送消息
                }*/
				UserUtils.pushIm(u.getId(),"申请人 "+user.getName() +",项目登记审批:"+projectRecords.getProjectName() +" 强制撤销!");
			}
        }
        if(processList!=null && processList.size()>0) {
            for (int i = 0; i < processList.size(); i++) {
                WorkActivityProcess p = processList.get(i);
                if (StringUtils.isNotBlank(p.getIsApproval()) && "0".equals(p.getIsApproval())) {
                    p.setIsApproval("-1");
                    p.setDelFlag("1");
                    workActivityProcessDao.updateDelFlagAndIsApproval(p);
                }
            }
            WorkActivityProcess pro = new WorkActivityProcess();
            pro.setId("");
            pro.setDelFlag("0");
            pro.preInsert();
            pro.setRemarks("[强制撤销]");
            pro.setProcessKey(processList.get(0).getProcessKey());
            pro.setIsApproval("1");
            pro.setProcessInstanceId(processList.get(0).getProcessInstanceId());
            pro.setCount(0);
            workActivityProcessDao.insert(pro);

            //结束该流程,设为"撤销"状态月
            RuralProjectRecords newRecords = new RuralProjectRecords();
            newRecords.setId(projectRecords.getId());
            newRecords.setProjectStatus(ProjectStatusEnum.RECALL.getValue());
            newRecords.preUpdate();
            this.updateSelectiveById(newRecords);
            actTaskService.endProcessInstance(projectRecords.getProcessInstanceId(), "项目登记-撤回");
        }
    }

    public WorkClientLinkman getLinkMan(WorkClientLinkman workClientLinkman){
		return clientLinkmanDao.getLinkManByNameAndOffice(workClientLinkman);
	}


}