# PmsScheduleManagerImpl.java

    package com.mycim.server.pms.manager.impl;

    import com.fa.sesa.exception.Assert;
    import com.fa.sesa.exception.Errors;
    import com.fa.sesa.threadlocal.LocalContext;
    import com.mycim.framework.jdbc.Page;
    import com.mycim.framework.utils.MiscUtils;
    import com.mycim.framework.utils.lang.StringUtils;
    import com.mycim.framework.utils.lang.collections.CollectionUtils;
    import com.mycim.framework.utils.lang.math.NumberUtils;
    import com.mycim.framework.utils.lang.time.DateUtils;
    import com.mycim.server.asm.manager.LotInventoryManager;
    import com.mycim.server.asm.manager.MaterialManager;
    import com.mycim.server.asm.manager.WarehouseManager;
    import com.mycim.server.base.manager.EventManager;
    import com.mycim.server.base.manager.NamedObjectManager;
    import com.mycim.server.base.manager.TransactionLogManager;
    import com.mycim.server.emas.manager.EmasEventManager;
    import com.mycim.server.ems.manager.CheckListJobManager;
    import com.mycim.server.ems.manager.EntityManager;
    import com.mycim.server.pilot.manager.PiLotCheckManager;
    import com.mycim.server.pms.dao.PmsScheduleDao;
    import com.mycim.server.pms.manager.CheckListManager;
    import com.mycim.server.pms.manager.PmsScheduleManager;
    import com.mycim.server.prp.manager.OperationManager;
    import com.mycim.server.status.manager.StatusManager;
    import com.mycim.valueobject.MessageIdList;
    import com.mycim.valueobject.ObjectList;
    import com.mycim.valueobject.SystemConstant;
    import com.mycim.valueobject.bas.TransactionLog;
    import com.mycim.valueobject.consts.Constants;
    import com.mycim.valueobject.consts.EventName;
    import com.mycim.valueobject.consts.TransactionNames;
    import com.mycim.valueobject.ems.*;
    import com.mycim.valueobject.inv.LotInventoryDO;
    import com.mycim.valueobject.inv.MaterialDO;
    import com.mycim.valueobject.inv.PartConsumeDO;
    import com.mycim.valueobject.inv.WarehouseTransBO;
    import com.mycim.valueobject.prp.Operation;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;

    import java.sql.Timestamp;
    import java.util.*;
    import java.util.stream.Collectors;

    @Service
    @Transactional
    public class PmsScheduleManagerImpl implements PmsScheduleManager {

        @Autowired
        PmsScheduleDao pmsScheduleDao;

        @Autowired
        NamedObjectManager namedObjectManager;

        @Autowired
        TransactionLogManager transactionLogManager;

        @Autowired
        EventManager eventManager;

        @Autowired
        StatusManager statusManager;

        @Autowired
        EntityManager entityManager;

        @Autowired
        CheckListManager checkListManager;

        @Autowired
        CheckListJobManager checkListJobManager;

        @Autowired
        EmasEventManager emasEventManager;

        @Autowired
        MaterialManager materialManager;

        @Autowired
        private LotInventoryManager lotInventoryManager;

        @Autowired
        private WarehouseManager warehouseManager;

        @Autowired
        private OperationManager operationManager;

        @Autowired
        private PiLotCheckManager piLotCheckManager;

        @Override
        public String pmsCheck(Entity entity, String type) {
            PmsSchedule pmItem = new PmsSchedule();
            pmItem.setItemStatus(SystemConstant.Str.ON);
            pmItem.setObjectRrn(entity.getInstanceRrn());
            pmItem.setObjectId(entity.getInstanceId());
            List<PmsSchedule> list = pmsScheduleDao.qryEqptPMInfo(pmItem);
            for (PmsSchedule pmsSchedule : list) {
                if (StringUtils.equalsIgnoreCase(type, Constants.PM_CHECK_TYPE.WAIT_ENT4DEADLINE)) {
                    String ControlType = pmsSchedule.getControlType();
                    if (StringUtils.equals(ControlType, PmControlTypeEnum.PM_TIME.getControlType())) {
                        //Time类型的
                        long deadLineTime = DateUtils.parse(pmsSchedule.getDeadLine()).getTime();
                        long currentTime = System.currentTimeMillis();
                        if (currentTime >= deadLineTime &&
                                StringUtils.equalsIgnoreCase(pmsSchedule.getEqptStatus(), EventName.HOLD_TO_EE)) {
                            return pmsSchedule.getObjectId() + " must PM before.</br>";
                        }
                    } else if (StringUtils.equals(ControlType, PmControlTypeEnum.PM_COUNT.getControlType())) {
                        //Count类型的
                        int runCount = pmsScheduleDao.getRunCountForPMCount(pmsSchedule);
                        if (runCount >= pmsSchedule.getTotalCount() &&
                                StringUtils.equalsIgnoreCase(pmsSchedule.getEqptStatus(), EventName.HOLD_TO_EE)) {
                            return pmsSchedule.getObjectId() + " must PM before.</br>";
                        }

                    }
                }

                if (StringUtils.equalsIgnoreCase(type, Constants.PM_CHECK_TYPE.EQPTRUN4PM)) {
                    if (StringUtils.equals(pmsSchedule.getEqptStatus(), EventName.PM)) {
                        return pmsSchedule.getObjectId() + " is under maintenance.<br>";
                    }
                    String ControlType = pmsSchedule.getControlType();
                    if (StringUtils.equals(ControlType, PmControlTypeEnum.PM_TIME.getControlType())) {
                        long nextPmTime = pmsSchedule.getNextPmTime().getTime();
                        long toleranceTime = (long) (pmsSchedule.getToleranceTime() * 24 * 60 * 60 * 1000);
                        long currentTime = System.currentTimeMillis();
                        if (currentTime > (nextPmTime + toleranceTime)) {
                            return pmsSchedule.getObjectId() + " must PM before.</br>";
                        }
                    }
                }
            }
            return StringUtils.EMPTY;
        }

        @Override
        public String pmsCheck(Entity entity) {
            PmsSchedule pmItem = new PmsSchedule();
            pmItem.setItemStatus(SystemConstant.Str.ON);
            pmItem.setObjectRrn(entity.getInstanceRrn());
            pmItem.setObjectId(entity.getInstanceId());
            List<PmsSchedule> list = pmsScheduleDao.qryEqptPMInfo(pmItem);
            StringBuilder msg = new StringBuilder();
            for (PmsSchedule pmsSchedule : list) {
                if (pmsSchedule.getToleranceStatus() == 3) {
                    msg.append("PM of ").append(entity.getInstanceId()).append(" : ").append(pmsSchedule.getPmId())
                       .append(" has expired!</br>");
                }
            }
            return msg.toString();
        }

        @Override
        public String deletePmSchedules(long instanceRrn) {
            return pmsScheduleDao.deletePmSchedules(instanceRrn);
        }

        @Override
        public List<PmSchedule> getPmSchedulesOfEntity(long entityRrn) {
            List<PmSchedule> temp = pmsScheduleDao.getPmSchedulesOfEntity(entityRrn);
            // 补充数据
            for (PmSchedule pmSchedule : temp) {
                if (MiscUtils.parseSQL(pmSchedule.getChecklistRrn()) > 0) {
                    pmSchedule.setChecklistId(
                            namedObjectManager.getInstanceId(MiscUtils.parseSQL(pmSchedule.getChecklistRrn())));
                }
            }

            return temp;
        }

        @Override
        public List<Map> getPmListByCheckList(long checklistRrn) {
            return pmsScheduleDao.getPmListByCheckList(checklistRrn);
        }

        @Override
        public void insertPmSchedule(PmSchedule pmSchedule) {
            TransactionLog transactionLog = transactionLogManager.startTransactionLog(pmSchedule.getTransPerformedBy(),
                                                                                      TransactionNames.CREATE_KEY);
            pmsScheduleDao.insertPmSchedule(pmSchedule);
            pmsScheduleDao.insertPmScheduleHistory(pmSchedule, transactionLog.getTransRrn());
            transactionLogManager.markTransactionLog(transactionLog);
        }

        @Override
        public PmSchedule getPmSchedule(PmSchedule pmSchedule) {
            pmSchedule = pmsScheduleDao.getPmSchedule(pmSchedule);
            // 补充数据
            pmSchedule.setChecklistId(namedObjectManager.getInstanceId(MiscUtils.parseSQL(pmSchedule.getChecklistRrn())));
            return pmSchedule;
        }

        @Override
        public void updatePmSchedule(PmSchedule pmSchedule) {
            TransactionLog transactionLog = transactionLogManager.startTransactionLog(pmSchedule.getTransPerformedBy(),
                                                                                      TransactionNames.MODIFY_KEY);
            pmsScheduleDao.insertPmScheduleHistory(pmSchedule, transactionLog.getTransRrn());
            pmsScheduleDao.updatePmSchedule(pmSchedule);
            transactionLogManager.markTransactionLog(transactionLog);
        }

        @Override
        public void deletePmSchedule(PmSchedule pmSchedule) {
            TransactionLog transactionLog = transactionLogManager.startTransactionLog(pmSchedule.getTransPerformedBy(),
                                                                                      TransactionNames.DELETE_KEY);
            pmsScheduleDao.insertPmScheduleHistory(pmSchedule, transactionLog.getTransRrn());
            pmsScheduleDao.deletePmSchedule(pmSchedule);
            transactionLogManager.markTransactionLog(transactionLog);
        }

        @Override
        public PmSchedule getActualEventTime(Entity entity, Long sequenceNumber) {
            return pmsScheduleDao.getActualEventTime(entity, sequenceNumber);
        }

        @Override
        public void delaySchedule(PmSchedule instance, Long userRrn, String jobName, String jobGroup, String rjobName,
                                  String rjobGroup, long startTime, long repeatStartTime) {
            pmsScheduleDao.delaySchedule(jobName, jobGroup, startTime);
            pmsScheduleDao.delaySchedule(rjobName, rjobGroup, repeatStartTime);
        }

        @Override
        public Page qryPmsEqptHist(Map<String, Object> condition, Page page) {
            return pmsScheduleDao.qryPmsEqptHist(condition, page);
        }

        @Override
        public Page qryEqptPMInfo(PmsSchedule schedule, Page page) {
            if (StringUtils.isNotBlank(schedule.getObjectId())) {
                schedule.setObjectId(StringUtils.replace(schedule.getObjectId(), "*", "%").toString());
            }
            if (StringUtils.isNotBlank(schedule.getStation())) {
                schedule.setStation(StringUtils.replace(schedule.getStation(), "*", "%").toString());
            }
            schedule.setNamedSpace(namedObjectManager.getNamedSpace(LocalContext.getFacilityRrn(), ObjectList.ENTITY_KEY));
            return pmsScheduleDao.qryEqptPMInfo(schedule, page);
        }

        @Override
        public List<PmsSchedule> qryEqptPMInfo(PmsSchedule schedule) {
            return pmsScheduleDao.qryEqptPMInfo(schedule);
        }

        @Override
        public PmsSchedule qryEqptPMInfo(long pmRrn) {
            return pmsScheduleDao.qryEqptPMInfo(pmRrn);
        }

        @Override
        public void addPmSchedule(PmsSchedule schedule) {
            TransactionLog transactionLog = transactionLogManager.startTransactionLog(schedule.getCreateUserId(),
                                                                                      TransactionNames.CREATE_KEY);
            long transRrn = transactionLog.getTransRrn();
            transactionLog.setComments(schedule.getComment());
            schedule.setPmRrn(transRrn);
            schedule.setTransRrn(transRrn);
            pmsScheduleDao.addPmSchedule(schedule);
            pmsScheduleDao.addPmScheduleH(schedule);
            String checklistId = schedule.getChecklistId();
            if (StringUtils.isNotBlank(checklistId)) {
                Checklist checklist = new Checklist(checklistId,
                                                    namedObjectManager.getNamedSpace(LocalContext.getFacilityRrn(),
                                                                                     ObjectList.CHECKLIST_KEY),
                                                    ObjectList.CHECKLIST_KEY);
                checklist = checkListManager.getCheckList(checklist);
                Assert.isFalse((checklist == null) || (checklist.getInstanceRrn() <= 0),
                               Errors.create().content("Checklist not " + "find!").build());
                ChecklistJob instance = new ChecklistJob();
                instance.setEntityRrn(schedule.getObjectRrn());
                instance.setChecklistJobId("");
                instance.setComments(schedule.getComment());
                instance.setChecklistRrn(checklist.getInstanceRrn());
                instance.setStartTimestamp(new Timestamp(System.currentTimeMillis()));
                instance.setTriggerTimestamp(new Timestamp(System.currentTimeMillis()));
                instance.setChecklistJobState("STARTED");
                instance.setTransId("create");
                instance.setTransPerformedby(LocalContext.getUserId());
                instance.setTriggerPerformedBy(LocalContext.getUserId());
                instance.setAttri1(schedule.getControlType());
                instance.setCreatePerformedBy(LocalContext.getUserId());
                instance.setPmType(schedule.getPmType());
                instance.setPmRrn(schedule.getPmRrn());
                checkListJobManager.insertChecklistJob(instance);
            }
            transactionLogManager.markTransactionLog(transactionLog);
        }

        @Override
        public void modifyPmSchedule(PmsSchedule schedule) {
            String transId = StringUtils.isEmpty(
                    schedule.getTransId()) ? TransactionNames.MODIFY_KEY : schedule.getTransId();
            TransactionLog transactionLog = transactionLogManager.startTransactionLog(schedule.getCreateUserId(), transId);
            long transRrn = transactionLog.getTransRrn();
            transactionLog.setTransPerformedBy(StringUtils.isBlank(
                    transactionLog.getTransPerformedBy()) ? LocalContext.getUserId() :
                                                       transactionLog.getTransPerformedBy());
            transactionLog.setComments(schedule.getComment());
            schedule.setTransRrn(transRrn);
            schedule.setTransPerformedby(LocalContext.getUserId());
            String[] pmRrns = schedule.getPmLink();
            Map<String, EquipmentTriggerMaintain> triggerMaintainMap = new HashMap<>();
            if (StringUtils.equalsIgnoreCase(TransactionNames.PMS_END, transId)) {
                for (String pmRrn : pmRrns) {
                    if (StringUtils.isBlank(pmRrn)) {
                        continue;
                    }
                    PmsSchedule __schedule = pmsScheduleDao.qryEqptPMInfo(Long.parseLong(pmRrn));
                    Long checkListRrn = __schedule.getChecklistRrn();
                    if (checkListRrn != null && checkListRrn > 0) {
                        List<ChecklistJob> checklistJobs = new ArrayList();
                        String extendCondition = "PM_RRN = '" + __schedule.getPmRrn() + "'";
                        List<ChecklistJob> _checklistJobs = checkListJobManager.getChecklistJobs(extendCondition);
                        for (ChecklistJob checklistJob : _checklistJobs) {
                            checklistJob.setComments("主PM完成,关联PM的checkList重置");
                            checkListJobManager.insertChecklistJobH(transRrn, checklistJob);
                            checkListJobManager.deleteChecklistJob(
                                    checklistJob.getChecklistJobRrn());//多勾选情况下，第一个循环中删除了以后，第二次在进入循环时，便查不出数据了。
                            /*
                            checklistJob.setComments(checklistJob.getComments() + " >>>System.echo: 主PM完成,
                            关联PM的checkList自动完成<<<");
                            checklistJob.setChecklistJobState("COMPLETED");
                            checklistJob.setTransPerformedby("SYSTEM");
                            checklistJob.setTriggerPerformedBy("SYSTEM");
                            checklistJob.setCompletePerformedBy("SYSTEM");
                            checklistJob.setTriggerTimestamp(new Timestamp(System.currentTimeMillis()));
                            checklistJob.setCompletedTimestamp(new Timestamp(System.currentTimeMillis()));
                            checklistJob.setTransId("COMPLETED");
                            checkListJobManager.completeChecklistJob(checklistJob);
                             */
                        }
                    }
                    PmsSchedule _schedule = buildNewPmsScheduleForSE(TransactionNames.PMS_END, __schedule);
                    _schedule.setTransRrn(transRrn);
                    _schedule.setPmLinks("");
                    //如果配置了checkList 再创建一个新的checklistJob
                    if (checkListRrn != null && checkListRrn > 0) {
                        Checklist checklist = new Checklist();
                        checklist.setInstanceRrn(checkListRrn);
                        checklist = checkListManager.getCheckList(checklist);
                        ChecklistJob instance = new ChecklistJob();
                        instance.setEntityRrn(__schedule.getObjectRrn());
                        instance.setChecklistJobId("");
                        instance.setComments(schedule.getComment());
                        instance.setChecklistRrn(checklist.getInstanceRrn());
                        instance.setStartTimestamp(new Timestamp(System.currentTimeMillis()));
                        instance.setTriggerTimestamp(new Timestamp(System.currentTimeMillis()));
                        instance.setChecklistJobState("STARTED");
                        instance.setTransId("create");
                        instance.setTransPerformedby(LocalContext.getUserId());
                        instance.setTriggerPerformedBy(LocalContext.getUserId());
                        instance.setCreatePerformedBy(LocalContext.getUserId());
                        instance.setAttri1(__schedule.getControlType());
                        instance.setPmType(__schedule.getPmType());
                        instance.setPmRrn(__schedule.getPmRrn());
                        checkListJobManager.insertChecklistJob(instance);
                    }
                    pmsScheduleDao.modifyPmSchedule(_schedule);
                    this.buildTriggerMaintain(_schedule, triggerMaintainMap);
                    pmsScheduleDao.addPmScheduleH(_schedule);
                }
                schedule.setPmLinks("");
                if (TransactionNames.PMS_END.equalsIgnoreCase(schedule.getPmEnd())) {
                    //手动点击 PM End 才消耗Part
                    this.consumeParts(schedule);
                }
            }
            pmsScheduleDao.modifyPmSchedule(schedule);
            this.buildTriggerMaintain(schedule, triggerMaintainMap);
            pmsScheduleDao.addPmScheduleH(schedule);
            //PM END后，Trigger Maintain中的reading值需要被清空
            List<EquipmentTriggerMaintain> triggerMaintainList = new ArrayList<>(triggerMaintainMap.values());
            this.batchUpdateTriggerMaintain(triggerMaintainList, transactionLog);
            transactionLogManager.markTransactionLog(transactionLog);
        }

        private void buildTriggerMaintain(PmsSchedule schedule, Map<String, EquipmentTriggerMaintain> triggerMaintainMap) {
            if (TransactionNames.PMS_END.equalsIgnoreCase(schedule.getTransId())){
                if (PmControlTypeEnum.PM_TRIGGER_READING.name().equalsIgnoreCase(schedule.getControlType())){
                    EquipmentTriggerMaintain etm = new EquipmentTriggerMaintain();
                    etm.setEquipmentRrn(schedule.getObjectRrn());
                    etm.setTriggerCode(schedule.getTriggerCode());
                    etm.setTriggerCodeSpec(schedule.getTriggerCodeSpec());
                    triggerMaintainMap.put(etm.getEquipmentRrn() + "|" +etm.getTriggerCode(), etm);
                }
            }
        }

        @Override
        public void refreshCheckList(long transRrn, List<Long> refreshCheckListPmRrn) {
            for (Long pmRrn : refreshCheckListPmRrn) {
                PmsSchedule __schedule = pmsScheduleDao.qryEqptPMInfo(pmRrn);
                Long checkListRrn = __schedule.getChecklistRrn();
                if (checkListRrn != null && checkListRrn > 0) {
                    List<ChecklistJob> checklistJobs = new ArrayList();
                    String extendCondition = "PM_RRN = '" + __schedule.getPmRrn() + "' ";
                    List<ChecklistJob> _checklistJobs = checkListJobManager.getChecklistJobs(extendCondition);
                    for (ChecklistJob checklistJob : _checklistJobs) {
                        checklistJob.setComments("主PM完成,关联PM的checkList重置");
                        checkListJobManager.insertChecklistJobH(transRrn, checklistJob);
                        checkListJobManager.deleteChecklistJob(checklistJob.getChecklistJobRrn());
                        /*
                        checklistJob.setComments(checklistJob.getComments() + " >>>System.echo: PM完成,
                        同设备的其他PM的checkList刷新<<<");
                        checklistJob.setChecklistJobState("COMPLETED");
                        checklistJob.setTransPerformedby("SYSTEM");
                        checklistJob.setTriggerPerformedBy("SYSTEM");
                        checklistJob.setCompletePerformedBy("SYSTEM");
                        checklistJob.setTriggerTimestamp(new Timestamp(System.currentTimeMillis()));
                        checklistJob.setCompletedTimestamp(new Timestamp(System.currentTimeMillis()));
                        checklistJob.setTransId("COMPLETED");
                        checkListJobManager.completeChecklistJob(checklistJob);
                         */
                    }
                    Checklist checklist = new Checklist();
                    checklist.setInstanceRrn(checkListRrn);
                    checklist = checkListManager.getCheckList(checklist);
                    ChecklistJob instance = new ChecklistJob();
                    instance.setEntityRrn(__schedule.getObjectRrn());
                    instance.setChecklistJobId("");
                    instance.setComments("该设备有PM完成，同设备的其他PM刷新。");
                    instance.setChecklistRrn(checklist.getInstanceRrn());
                    instance.setStartTimestamp(new Timestamp(System.currentTimeMillis()));
                    instance.setTriggerTimestamp(new Timestamp(System.currentTimeMillis()));
                    instance.setChecklistJobState("STARTED");
                    instance.setTransId("create");
                    instance.setTransPerformedby(LocalContext.getUserId());
                    instance.setTriggerPerformedBy(LocalContext.getUserId());
                    instance.setCreatePerformedBy(LocalContext.getUserId());
                    instance.setAttri1(__schedule.getControlType());
                    instance.setPmType(__schedule.getPmType());
                    instance.setPmRrn(__schedule.getPmRrn());
                    checkListJobManager.insertChecklistJob(instance);
                }
            }
        }

        @Override
        public void pmsPmStart(PmsSchedule schedule) {
            String pmsStr = schedule.getPmRrnStr();
            String[] pmLink = schedule.getPmLink();
            String pmLinks = schedule.getPmLinks();
            String comment = schedule.getComment();
            String linkComment = comment;
            List<PmsSchedule> list = pmsScheduleDao.qryEqptPMInfo(schedule);
            List<PmsSchedule> pmsScheduleList = new ArrayList<>();
            if (StringUtils.isNotBlank(pmLinks)) {
                PmsSchedule _pmsSchedule = new PmsSchedule();
                _pmsSchedule.setPmRrnStr(pmLinks);
                pmsScheduleList = pmsScheduleDao.qryEqptPMInfo(_pmsSchedule);
                if (CollectionUtils.isNotEmpty(pmsScheduleList)){
                    String pmlinkComments = ".Link PM Id: " + StringUtils.join(
                            pmsScheduleList.stream().map(PmsSchedule::getPmId).toArray(), ",");
                    linkComment += pmlinkComments;
                }
            }

            String eventId = EventName.WAIT_ENG_TO_PM;

            Event event = new Event(eventId,  namedObjectManager.getNamedSpace(LocalContext.getFacilityRrn(), ObjectList.EVENT_KEY), ObjectList.EVENT_KEY);
            event.setEntityType(ObjectList.EQUIPMENT_KEY);
            event = eventManager.getEvent(event);
            Map<Long, Long> map = new HashMap<>();
            if (CollectionUtils.isNotEmpty(list)) {
                startPm(list, pmLinks, linkComment, event, schedule, map);
            }
            if (CollectionUtils.isNotEmpty(pmsScheduleList)){
                startPm(pmsScheduleList, StringUtils.EMPTY, comment, event, schedule, map);
            }
        }

        private void startPm(List<PmsSchedule> list, String pmLinks, String comment, Event event, PmsSchedule schedule, Map<Long, Long> map) {
            long parentEqptRrn = getParentEqptFromPms(list);
            for (PmsSchedule pmsSchedule : list) {
                long entityRrn = pmsSchedule.getChamberRrn() != null &&
                        pmsSchedule.getChamberRrn() > 0 ? pmsSchedule.getChamberRrn() : pmsSchedule.getObjectRrn();
                if (map.get(entityRrn) == null) {
                    autoEvent4Entity(event, entityRrn, schedule.getCreateUserId(), schedule.getComment());
                    map.put(entityRrn, entityRrn);
                }
                Assert.isFalse(map.size() > 1 && parentEqptRrn <= 0,
                               Errors.create().content("Multiple Eqpt can`t PM start together.").build());

                PmsSchedule modifyPms = new PmsSchedule();
                modifyPms.setPmRrn(pmsSchedule.getPmRrn());
                modifyPms.setTransId(TransactionNames.PMS_START);
                modifyPms.setPmLinks(pmLinks);
                modifyPms.setComment(comment);
                modifyPmSchedule(modifyPms);
            }
        }

        @Override
        public void pmsPmEnd(PmsSchedule schedule) {
            String transId = TransactionNames.PMS_END;
            TransactionLog transactionLog = transactionLogManager.startTransactionLog(schedule.getCreateUserId(), transId);
            long transRrn = transactionLog.getTransRrn();
            transactionLog.setComments(schedule.getComment());
            Map<Long, List<PartConsumeDO>> partConsumeMap = schedule.getPartConsumeMap();
            List<PmsSchedule> list = pmsScheduleDao.qryEqptPMInfo(schedule);//根据pmRrn 和 pmRrnStr来查询
            String[] pmLink = schedule.getPmLink();
            String pmLinks = schedule.getPmLinks();
            String eventId = schedule.getTargetEventId();
            Event event = new Event(eventId,
                                    namedObjectManager.getNamedSpace(LocalContext.getFacilityRrn(), ObjectList.EVENT_KEY),
                                    ObjectList.EVENT_KEY);
            event.setEntityType(ObjectList.EQUIPMENT_KEY);
            event = eventManager.getEvent(event);
            if (list != null && !list.isEmpty()) {//可能出现1条 或者勾选的N条
                Map<Long, Long> map = new HashMap<>();
                long parentEqptRrn = getParentEqptFromPms(list);//找出N条中的主机台，也可能为0
                for (PmsSchedule pmsSchedule : list) {
                    PmsSchedule _pmsSchedule = new PmsSchedule();
                    _pmsSchedule.setObjectId(pmsSchedule.getObjectId());
                    List<PmsSchedule> allPmsList = pmsScheduleDao.qryEqptPMInfo(
                            _pmsSchedule);//主机台找主+Chamber的，Chamber机台只找Chamber的
                    List<Long> refreshCheckListPmRrns = allPmsList.stream().filter(_pms -> {
                        if (_pms.getChecklistRrn() == null && _pms.getChecklistRrn() < 1) {
                            return false;
                        }
                        Long _pmRrn = _pms.getPmRrn();
                        if (_pmRrn.equals(pmsSchedule.getPmRrn())) {
                            return false;
                        }
                        String[] _pmLink =
                                pmsSchedule.getPmLinks() == null ? new String[]{} : pmsSchedule.getPmLinks().split(",");
                        for (String _pmStr : _pmLink) {
                            if (StringUtils.equals(_pmRrn.toString(), _pmStr)) {
                                return false;
                            }
                        }
                        return true;
                    }).map(PmsSchedule::getPmRrn).collect(Collectors.toList());
                    long entityRrn = pmsSchedule.getChamberRrn() != null &&
                            pmsSchedule.getChamberRrn() > 0 ? pmsSchedule.getChamberRrn() : pmsSchedule.getObjectRrn();
                    if (map.get(entityRrn) == null) {
                        autoEvent4Entity(event, entityRrn, schedule.getCreateUserId(), schedule.getComment());
                        map.put(entityRrn, entityRrn);
                    }
                    Assert.isFalse(map.size() > 1 && parentEqptRrn <= 0,
                                   Errors.create().content("Multiple Eqpt can`t pm end " + "together.").build());

                    pmsSchedule.setCreateUserId(schedule.getCreateUserId());
                    pmsSchedule.setComment(schedule.getComment());
                    Long checklistRrn = pmsSchedule.getChecklistRrn();
                    PmsSchedule ms = buildNewPmsScheduleForSE(TransactionNames.PMS_END, pmsSchedule);
                    ms.setPmLink(pmLink);
                    ms.setPmEnd(TransactionNames.PMS_END);
                    ms.setPartConsume(partConsumeMap.get(pmsSchedule.getPmRrn()));
                    modifyPmSchedule(ms);
                    //刷新该设备的其他checkList，防止没有关联pm，但是做了checkList。
                    refreshCheckList(transRrn, refreshCheckListPmRrns);
                    //如果配置了checkList 再创建一个新的checklistJob
                    List<ChecklistJob> checklistJobs = new ArrayList<>();
                    String extendCondition = "PM_RRN = '" + pmsSchedule.getPmRrn() + "'";
                    List<ChecklistJob> _checklistJobs = checkListJobManager.getChecklistJobs(extendCondition);
                    for (ChecklistJob checklistJob : _checklistJobs) {
                        checklistJob.setComments("checkList重置");
                        checkListJobManager.insertChecklistJobH(transRrn, checklistJob);
                        checkListJobManager.deleteChecklistJob(checklistJob.getChecklistJobRrn());
                    }
                    if (checklistRrn != null && checklistRrn > 0) {
                        Checklist checklist = new Checklist();
                        checklist.setInstanceRrn(checklistRrn);
                        checklist = checkListManager.getCheckList(checklist);
                        ChecklistJob instance = new ChecklistJob();
                        instance.setEntityRrn(pmsSchedule.getObjectRrn());
                        instance.setChecklistJobId("");
                        instance.setComments(schedule.getComment());
                        instance.setChecklistRrn(checklist.getInstanceRrn());
                        instance.setStartTimestamp(new Timestamp(System.currentTimeMillis()));
                        instance.setTriggerTimestamp(new Timestamp(System.currentTimeMillis()));
                        instance.setChecklistJobState("STARTED");
                        instance.setTransId("create");
                        instance.setTransPerformedby(LocalContext.getUserId());
                        instance.setTriggerPerformedBy(LocalContext.getUserId());
                        instance.setCreatePerformedBy(LocalContext.getUserId());
                        instance.setAttri1(pmsSchedule.getControlType());
                        instance.setPmType(pmsSchedule.getPmType());
                        instance.setPmRrn(ms.getPmRrn());
                        checkListJobManager.insertChecklistJob(instance);
                    }

                    // new Emas 处理
                    emasEventManager.generateEmasEventRecord(pmsSchedule.getObjectId(), eventId);
                    piLotCheckManager.checkEquipmentPiLotByPM(pmsSchedule.getObjectId());

                }
                /*String msg = autoPmEndForChildEqpt(parentEqptRrn, event, schedule.getCreateUserId(),
                                                   schedule.getComment(), map);
                if (StringUtils.isNotBlank(msg)) {
                    throw new ManagerException("", msg + "cannot end pm, reason: status is invalid.");
                }*/
                transactionLogManager.markTransactionLog(transactionLog);
            }
        }

        @Override
        public void pmsPmEnd(List<PmsSchedule> schedules) {
            for (PmsSchedule pmsSchedule : schedules) {
                this.pmsPmEnd(pmsSchedule);
            }
        }

        @Override
        public void onOffChange(PmsSchedule schedule) {
            TransactionLog transactionLog = transactionLogManager.startTransactionLog(schedule.getCreateUserId(),
                                                                                      TransactionNames.PMS_ON_OFF);
            long transRrn = transactionLog.getTransRrn();
            transactionLog.setComments(schedule.getComment());
            PmsSchedule pm = new PmsSchedule();
            pm.setPmRrnStr(schedule.getPmRrnStr());
            pm.setTransRrn(transRrn);
            pm.setItemStatus(schedule.getItemStatus());
            pmsScheduleDao.modifyPmSchedule(pm);
            pmsScheduleDao.addPmScheduleH(pm);
            transactionLogManager.markTransactionLog(transactionLog);
        }

        @Override
        public void deletePmSchedule(PmsSchedule schedule) {
            List<PmsSchedule> scheduleList = this.qryEqptPMInfo(schedule);
            for (PmsSchedule _schedule : scheduleList) {
                Assert.isFalse(StringUtils.equals(_schedule.getTransId(), TransactionNames.PMS_START),
                               Errors.create().content("PM Item has started. delete not allowed!").build());
            }
            TransactionLog transactionLog = transactionLogManager.startTransactionLog(schedule.getCreateUserId(),
                                                                                      TransactionNames.DELETE_KEY);
            long transRrn = transactionLog.getTransRrn();
            transactionLog.setComments(schedule.getComment());
            schedule.setTransRrn(transRrn);
            pmsScheduleDao.addPmScheduleH(schedule);
            pmsScheduleDao.deletePmSchedule(schedule);
            transactionLogManager.markTransactionLog(transactionLog);
        }

        @Override
        public PmSchedule updateNextPMTime(PmSchedule pmSchedule) {
            return pmsScheduleDao.updateNextPMTime(pmSchedule);
        }

        @Override
        public Page getPmSchedulesByPageQuery(Map condition, Page page) {
            return pmsScheduleDao.getPmSchedulesByPageQuery(condition, page);
        }

        @Override
        public Map getPMScheduleByMonth(String equipmentId, int year, int month, long ownerEntityRrn) {
            return pmsScheduleDao.getPMScheduleByMonth(equipmentId, year, month, ownerEntityRrn);
        }

        @Override
        public PmSchedule selectPMScheduleDetail(long checklistRrn, long entityRrn, long sequenceNum) {
            return pmsScheduleDao.selectPMScheduleDetail(checklistRrn, entityRrn, sequenceNum);
        }

        @Override
        public void updatePmScheduleNext(PmSchedule pms) {
            pmsScheduleDao.updatePmScheduleNext(pms);
        }

        @Override
        public Map getPMScheduleByWeek(int year, int week, long ownerEntityRrn) {
            return null;
        }

        @Override
        public void pmsAutoEvent(PmsSchedule pmItem) {
            String eventId = pmItem.getTargetEventId();
            Event event = new Event(eventId,
                                    namedObjectManager.getNamedSpace(LocalContext.getFacilityRrn(), ObjectList.EVENT_KEY),
                                    ObjectList.EVENT_KEY);
            event.setEntityType(ObjectList.EQUIPMENT_KEY);
            event = eventManager.getEvent(event);
            if (event != null) {
                long entityRrn = pmItem.getChamberRrn() != null &&
                        pmItem.getChamberRrn() > 0 ? pmItem.getChamberRrn() : pmItem.getObjectRrn();
                autoEvent4Entity(event, entityRrn, pmItem.getCreateUserId(), pmItem.getComment());
            }
        }

        @Override
        public void updatePmScheduleNextTime(Map jobData) {
            pmsScheduleDao.updatePmScheduleNextTime(jobData);
        }

        @Override
        public Map<String, Object> getTrigger(String jobName, String jobGroup) {
            return pmsScheduleDao.getTrigger(jobName, jobGroup);
        }

        @Override
        public List qryChecklistJobDataHist(Long checklistJobRrn) {
            return pmsScheduleDao.qryChecklistJobDataHist(checklistJobRrn);
        }

        @Override
        public void addTriggerMaintain(EquipmentTriggerMaintainQuery maintainQuery) {
            if (getTriggerMaintain(maintainQuery) == null){
                TransactionLog tl = transactionLogManager.startTransactionLog(maintainQuery.getUserId(), TransactionNames.CREATE_KEY);
                pmsScheduleDao.addTriggerMaintain(maintainQuery, tl);
                pmsScheduleDao.addTriggerMaintainHistory(maintainQuery, tl);
                transactionLogManager.markTransactionLog(tl);
            }
        }

        @Override
        public void modifyTriggerMaintain(EquipmentTriggerMaintainQuery maintainQuery, List<PmsSchedule> list) {
            //先查询有没有被PM关联
            if (getTriggerMaintain(maintainQuery) != null){
                TransactionLog tl = transactionLogManager.startTransactionLog(maintainQuery.getUserId(), TransactionNames.MODIFY_KEY);
                pmsScheduleDao.modifyTriggerMaintain(maintainQuery, tl);
                tl.setComments(maintainQuery.getComment());
                pmsScheduleDao.addTriggerMaintainHistory(maintainQuery, tl);
                if (CollectionUtils.isNotEmpty(list)){
                    for (PmsSchedule ps:list){
                        ps.setTriggerReading(maintainQuery.getTriggerReading());
                    }
                    batchUpdateTriggerMaintain("", list, new ArrayList<>(),TransactionNames.MANUAL_TRIGGER_READING);
                }
                transactionLogManager.markTransactionLog(tl);
            }
        }

        @Override
        public void deleteTriggerMaintain(EquipmentTriggerMaintainQuery maintainQuery) {
            TransactionLog tl = transactionLogManager.startTransactionLog(maintainQuery.getUserId(), TransactionNames.DELETE_KEY);
            tl.setComments(maintainQuery.getComment());
            for (EquipmentTriggerMaintain etmq: maintainQuery.getDeleteList()){
                maintainQuery.setEquipmentRrn(etmq.getEquipmentRrn());
                maintainQuery.setTriggerCode(etmq.getTriggerCode());
                pmsScheduleDao.addTriggerMaintainHistory(maintainQuery, tl);
                pmsScheduleDao.deleteTriggerMaintain(maintainQuery);
            }
            transactionLogManager.markTransactionLog(tl);
        }

        @Override
        public List<EquipmentTriggerMaintain> queryTriggerCodeByEquipment(EquipmentTriggerMaintainQuery maintainQuery) {
            return pmsScheduleDao.queryTriggerCodeByEquipment(maintainQuery);
        }

        @Override
        public Page queryMaintainByPage(Page page, EquipmentTriggerMaintainQuery maintainQuery) {
            return pmsScheduleDao.queryMaintainByPage(page, maintainQuery);
        }

        @Override
        public Page queryMaintainHistoryByPage(Page page, EquipmentTriggerMaintainQuery maintainQuery) {
            return pmsScheduleDao.queryMaintainHistoryByPage(page, maintainQuery);
        }

        @Override
        public EquipmentTriggerMaintain getTriggerMaintain(EquipmentTriggerMaintainQuery maintainQuery) {
            return pmsScheduleDao.getTriggerMaintain(maintainQuery);
        }

        @Override
        public void batchUpdateTriggerMaintain(String equipmentId, List<PmsSchedule> maintainList, List<EquipmentTriggerMaintain> triggerMaintainList, String transId) {
            TransactionLog tl = transactionLogManager.startTransactionLog(LocalContext.getUserId(), transId);
            for (PmsSchedule ps : maintainList){
                ps.setTransRrn(tl.getTransRrn());
                pmsScheduleDao.updateTriggerReadingByPms(ps);//修改PMS中的TriggerReading
                pmsScheduleDao.addPmScheduleH(ps);//记录修改PMS中的TriggerReading的历史
                tl.setTransSequence(tl.getTransSequence() + 1);
            }
            this.batchUpdateTriggerMaintain(triggerMaintainList, tl);
            transactionLogManager.markTransactionLog(tl);
        }

        @Override
        public void batchUpdateTriggerMaintain(List<EquipmentTriggerMaintain> triggerMaintainList, TransactionLog tl) {
            if (CollectionUtils.isNotEmpty(triggerMaintainList)){
                for (EquipmentTriggerMaintain e: triggerMaintainList){
                    EquipmentTriggerMaintainQuery etmq = new EquipmentTriggerMaintainQuery();
                    etmq.setTriggerCodeSpec(e.getTriggerCodeSpec());
                    etmq.setUserRrn(LocalContext.getUserRrn());
                    etmq.setTriggerReading(e.getTriggerReading());
                    etmq.setEquipmentRrn(e.getEquipmentRrn());
                    etmq.setTriggerCode(e.getTriggerCode());
                    pmsScheduleDao.modifyTriggerMaintain(etmq, tl);
                    pmsScheduleDao.addTriggerMaintainHistory(etmq, tl);
                    tl.setTransSequence(tl.getTransSequence() + 1);
                }
            }
        }

        /**
         * 根据chamber主机台rrn，自动做chamber设备的PM start或end
         *
         * @param parentEqptRrn chamber主机台rrn
         * @param event         事件
         * @param userId        用户ID
         * @param comment       备注
         * @param changedRrnMap map<rrn, rrn>, chamber主机台下已经做过了event的chamber设备rrn
         * @param transId       事务ID
         * @return 不能做event的设备ID，多个设备以逗号分隔
         */
        public String autoChildEqptPmOfSE(long parentEqptRrn, Event event, String userId, String comment,
                                          Map<Long, Long> changedRrnMap, String transId) {
            List<Long> notWatiEngEqptRrnList = new ArrayList<Long>();
            if (parentEqptRrn > 0) {
                List<Long> childRrnList = entityManager.getChildEntityRrns(parentEqptRrn);
                if (CollectionUtils.isNotEmpty(childRrnList)) {
                    for (Long childRrn : childRrnList) {
                        if (changedRrnMap.get(childRrn) == null) {
                            Entity childEntity = new Entity();
                            childEntity.setInstanceRrn(childRrn);
                            childEntity = entityManager.getEntity(childEntity);
                            if (StringUtils.isNotBlank(childEntity.getChamberType())) {
                                // 有chamber type的才算是chamber设备
                                boolean allowLogEventFlag = false;
                                allowLogEventFlag = statusManager.checkEnableLogEvent(event.getInstanceRrn(), childRrn);
                                if (allowLogEventFlag) {
                                    autoEvent4Entity(event, childRrn, userId, comment);
                                    // 在PMS中是否设置了设备PM
                                    PmsSchedule existPms = new PmsSchedule();
                                    existPms.setObjectRrn(childRrn);
                                    List<PmsSchedule> childPmsList = pmsScheduleDao.qryEqptPMInfo(existPms);
                                    if (CollectionUtils.isNotEmpty(childPmsList)) {
                                        for (PmsSchedule childPm : childPmsList) {
                                            childPm.setCreateUserId(userId);
                                            childPm.setComment(comment);
                                            PmsSchedule ms = buildNewPmsScheduleForSE(transId, childPm);
                                            modifyPmSchedule(ms);
                                        }
                                    }
                                } else {
                                    // 设备当前状态不允许执行 PM 的 rrn 集合
                                    notWatiEngEqptRrnList.add(childRrn);
                                }
                            }
                            changedRrnMap.put(childRrn, childRrn);
                        }
                    }
                }
            }
            StringBuilder eqptIds = new StringBuilder("");
            if (CollectionUtils.isNotEmpty(notWatiEngEqptRrnList)) {
                for (Long rrn : notWatiEngEqptRrnList) {
                    eqptIds.append(namedObjectManager.getInstanceId(rrn));
                    eqptIds.append(",");
                }
            }
            return StringUtils.removeLastChar(eqptIds.toString(), ",");
        }

        private void consumeParts(PmsSchedule ms) {
            //query part
            List<PartConsumeDO> partConsumeDOList = ms.getPartConsume();
            //consume part
            if (CollectionUtils.isNotEmpty(partConsumeDOList)) {
                for (PartConsumeDO part : partConsumeDOList) {
                    String partId = part.getConsumePartId();
                    int consumeQty = part.getConsumePartQty();
                    MaterialDO material = new MaterialDO(partId,
                                                         namedObjectManager.getNamedSpace(LocalContext.getFacilityRrn(),
                                                                                          ObjectList.ITEM_KEY),
                                                         ObjectList.ITEM_KEY);
                    material = materialManager.getMaterial(material);
                    Assert.isFalse(material == null || material.getInstanceRrn() <= 0,
                                   Errors.create().key(MessageIdList.PART_ID_NOT_EXIST).content("Part ID not exist!")
                                         .build());
                    int totalQuantity = materialManager.getMaterialTotalQuantity(material.getInstanceRrn());
                    int remainQty = totalQuantity - consumeQty;
                    Assert.isFalse(remainQty < 0,
                                   Errors.create().key(MessageIdList.PART_INVENTORY_NOT_ENOUGH).args(remainQty).build());
                    //inventory maintain
                    consumeMaterialFromWarehouseForPms(material, consumeQty, part.getConsumePmId());

                }
            }

        }

        private void consumeMaterialFromWarehouseForPms(MaterialDO material, int consumeQty, String pmId) {
            long facilityRrn = LocalContext.getFacilityRrn();
            WarehouseTransBO warehouseTrans;
            LotInventoryDO lotInventory;
            Operation warehouse = operationManager.getOperation(SystemConstant.PmSchedule.PARTS_BANK, facilityRrn);
            List<WarehouseTransBO> convertTrans = new ArrayList<>();
            //找到需要消耗的物料的批次
            List<LotInventoryDO> lids = lotInventoryManager.getAvailableLotInventory(material.getInstanceRrn(),
                                                                                     warehouse.getInstanceRrn(), null);
            Assert.isFalse(lids == null || lids.isEmpty(),
                           Errors.create().key(MessageIdList.NO_HAVE_PART_LOT).content("No material lot available")
                                 .build());
            String lotNumber = "";
            int remainQty = consumeQty;
            int consume;
            for (LotInventoryDO lid : lids) {
                //多个LotNumber消耗
                if (lid.getTotalQuantity() <= 0) {
                    continue;
                }
                if (remainQty <= 0) {
                    break;
                }
                if (lid.getTotalQuantity() > remainQty) {
                    consume = remainQty;
                    remainQty = remainQty - consumeQty;
                } else {
                    consume = lid.getTotalQuantity().intValue();
                    remainQty = remainQty - consume;
                }
                lotNumber = lid.getLotNumber();
                Double qty = NumberUtils.toDouble(Integer.toString(consume));
                lotInventory = lotInventoryManager.getLotInventory(lotNumber, material.getInstanceRrn(),
                                                                   warehouse.getInstanceRrn());
                lotInventory.setReceiptQty(0D);
                lotInventory.setAdjustQty(0D);
                lotInventory.setIssueQty(qty);

                warehouseTrans = new WarehouseTransBO(lotInventory);
                warehouseTrans.setTransComments(SystemConstant.PmSchedule.PM_END_CONSUME + pmId);
                warehouseTrans.setTransQty(qty);
                convertTrans.add(warehouseTrans);
            }

            warehouseManager.consumeMaterialFromWarehouse4Pms(facilityRrn, LocalContext.getUserId(), convertTrans);

        }

        /**
         * pm start的时候，如果选中有chamber主机台设备，则同时操作所有chamber设备
         *
         * @param parentEqptRrn chamber主机台设备rrn
         * @param event         logevent 事件对象
         * @param changedRrnMap chamber设备已经做过的设备rrn map<rrn, rrn>
         * @return 不能执行PM的chamber设备id，多个id用逗号分隔
         */
        private String autoPmStartForChildEqpt(long parentEqptRrn, Event event, String userId, String comment,
                                               Map<Long, Long> changedRrnMap) {
            return autoChildEqptPmOfSE(parentEqptRrn, event, userId, comment, changedRrnMap, TransactionNames.PMS_START);
        }

        /**
         * pm end的时候，如果选中有chamber主机台设备，则同时操作所有chamber设备
         *
         * @param parentEqptRrn chamber主机台设备rrn
         * @param event         logevent 事件对象
         * @param changedRrnMap chamber设备已经做过的设备rrn map<rrn, rrn>
         * @return 不能执行PM的chamber设备id，多个id用逗号分隔
         */
        private String autoPmEndForChildEqpt(long parentEqptRrn, Event event, String userId, String comment,
                                             Map<Long, Long> changedRrnMap) {
            return autoChildEqptPmOfSE(parentEqptRrn, event, userId, comment, changedRrnMap, TransactionNames.PMS_END);
        }

        /**
         * 构建一个新的修改后的的PM对象
         *
         * @param transId
         * @param oldPms  原PM对象
         * @return 新new的一个PmsSchedule对象，对象中的数据是修改后的信息
         */
        private PmsSchedule buildNewPmsScheduleForSE(String transId, PmsSchedule oldPms) {
            PmsSchedule ms = new PmsSchedule();
            if (StringUtils.equals(TransactionNames.PMS_END, transId)) {
                ms.setTriggerReading(StringUtils.UPDATE_COLUMN_NULL_FLAG);
                if (PmControlTypeEnum.PM_COUNT.name().equalsIgnoreCase(oldPms.getControlType())
                        || PmControlTypeEnum.PM_TRIGGER_READING.name().equalsIgnoreCase(oldPms.getControlType())) {
                    ms.setCreateDate(new Date());
                } else {
                    // PM END 操作重新计算next pm time
                    if (StringUtils.equalsIgnoreCase(oldPms.getPmTimeType(), "static")) {
                        Date nextPmBaseDate = oldPms.getNextPmTime();
                        long cycleTimes = (long) (oldPms.getCycleTime() * 24 * 60 * 60 * 1000);
                        ms.setNextPmTime(new Date(nextPmBaseDate.getTime() + cycleTimes));
                    } else {
                        String setPmTimeStr = DateUtils.formatDate(oldPms.getNextPmTime());
                        String setTime = setPmTimeStr.split(" ")[1];
                        String newDay = DateUtils.formatDate(new Date(), DateUtils.DATE_FORMAT4DAY);
                        setPmTimeStr = newDay + " " + setTime;
                        Date nextPmBaseDate = DateUtils.parse(setPmTimeStr, DateUtils.DATE_FORMAT);
                        long cycleTimes = (long) (oldPms.getCycleTime() * 24 * 60 * 60 * 1000);
                        //long toleranceTime = (long) (oldPms.getToleranceTime() * 24 * 60 * 60 * 1000);
                        ms.setNextPmTime(new Date(nextPmBaseDate.getTime() + cycleTimes));
                    }
                }
                //PM END 的时候需要重置TriggerMaintain里的TriggerReading
                ms.setObjectRrn(oldPms.getObjectRrn());
                ms.setTriggerCode(oldPms.getTriggerCode());
                ms.setTriggerCodeSpec(oldPms.getTriggerCodeSpec());
                ms.setControlType(oldPms.getControlType());
            }

            ms.setPmRrn(oldPms.getPmRrn());
            ms.setComment(oldPms.getComment());
            ms.setCreateUserId(oldPms.getCreateUserId());
            ms.setPmId(oldPms.getPmId());
            ms.setObjectId(oldPms.getObjectId());
            ms.setPmType(oldPms.getPmType());
            ms.setPmItemDesc(oldPms.getPmItemDesc());
            ms.setTransId(transId);
            return ms;
        }

        private void autoEvent4Entity(Event event, Long entityRrn, String userId, String comments) {
            List<EventModel> eventModels = eventManager.getEventModels(event.getInstanceRrn(), entityRrn);
            List<EntityStatus> entityStatuss = new ArrayList<>();
            for (EventModel instance : eventModels) {
                EntityStatus entityStatus = new EntityStatus();
                entityStatus.setCurrentStatus(instance.getTargetStatus());
                entityStatus.setStatusGroupId(instance.getStatusGroupId());
                entityStatus.setStatusBefore(instance.getCurrentStatus());
                entityStatus.setEntityRrn(entityRrn);
                entityStatuss.add(entityStatus);
            }
            boolean boo = statusManager.checkEnableLogEvent(event.getInstanceRrn(), entityRrn);
            if (boo) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("event", event);
                map.put("user", userId);
                map.put("comments", comments);
                map.put("comments1", "");
                map.put("comments2", "");
                map.put("statusEndTime", DateUtils.getNowTime());
                map.put("entityrrn", entityRrn);
                statusManager.updateEntityStatus(entityStatuss, map);//操作chamber 设备
                //如果为down 或者 wait_eng 集联更新
                statusManager.updateParentEntityByChamberAllInSameState(entityStatuss, map,
                                                                        Arrays.asList(EventName.WAIT_ENG, EventName.DOWN));
            }
        }

        /**
         * pms的目标设备中是否含有chamber主机台设备
         *
         * @param list pm的设备集合
         * @return 返回chamber主机台设备rrn；返回 0 表示没有chamber主机台设备
         */
        private long getParentEqptFromPms(List<PmsSchedule> list) {
            if (CollectionUtils.isNotEmpty(list)) {
                for (PmsSchedule pmsSchedule : list) {
                    long entityRrn = pmsSchedule.getChamberRrn() != null &&
                            pmsSchedule.getChamberRrn() > 0 ? pmsSchedule.getChamberRrn() : pmsSchedule.getObjectRrn();
                    if (pmsScheduleDao.checkIsParentEqpt(entityRrn)) {
                        return entityRrn;
                    }
                }
            }
            return 0;
        }

    }