EquipmentPmScheduleSaveAction.java

package com.mycim.webapp.actions.equipmentpm;

import com.fa.sesa.exception.Assert;
import com.fa.sesa.exception.Errors;
import com.fa.sesa.threadlocal.LocalContext;
import com.mycim.framework.utils.MiscUtils;
import com.mycim.framework.utils.beans.PropertyUtils;
import com.mycim.framework.utils.lang.StringUtils;
import com.mycim.framework.utils.lang.collections.CollectionUtils;
import com.mycim.framework.utils.lang.time.DateUtils;
import com.mycim.valueobject.MessageIdList;
import com.mycim.valueobject.ObjectList;
import com.mycim.valueobject.alm.Alarm;
import com.mycim.valueobject.consts.AlarmType;
import com.mycim.valueobject.consts.SessionNames;
import com.mycim.valueobject.consts.TransactionNames;
import com.mycim.valueobject.ems.Checklist;
import com.mycim.valueobject.ems.ChecklistJob;
import com.mycim.valueobject.ems.Entity;
import com.mycim.valueobject.ems.PmSchedule;
import com.mycim.webapp.Constants;
import com.mycim.webapp.WebUtils;
import com.mycim.webapp.actions.EmsSetupAction;
import com.mycim.webapp.forms.EntityPmScheduleForm;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * EQP PM Schedule Setup
 *
 * @author pinyan.song
 * @version 6.0.0
 * @date 2019-11-4 14:18
 **/
public class EquipmentPmScheduleSaveAction extends EmsSetupAction {

    private static final String DELAY_KEY = "delay";

    @Override
    public ActionForward init(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                              HttpServletResponse response) {
        EntityPmScheduleForm theform = (EntityPmScheduleForm) form;
        toUpCase(theform);
        String id = StringUtils.isEmpty(theform.getInstanceId()) ? theform.getEquipmentId() : theform.getInstanceId();
        Entity entity = getEntityInfo(id);
        request.setAttribute(SessionNames.ENTITY_KEY, entity);
        setForm(theform, entity);
        theform.setTransId(Constants.MAINTAINPMSCHEDULE4R_KEY);

        processItemAction(request, theform);

        return mapping.getInputForward();
    }

    public ActionForward modify(ActionMapping mapping, EntityPmScheduleForm theform, HttpServletRequest request,
                                HttpServletResponse response) {
        toUpCase(theform);

        String id = theform.getInstanceId();
        Entity entity = getEntityInfo(id);
        validateTheform(theform, entity);
        setForm(theform, entity);

        PmSchedule pmSchedule = getPmSechedule(theform);
        emsService.updatePmSchedule(pmSchedule);

        entity = getEntityInfo(id);

        ChecklistJob checklistJob = getCheckJob(theform, pmSchedule, entity);

        deleteSchedule(pmSchedule, entity);
        addSchedule(pmSchedule, entity, checklistJob);

        WebUtils.setSuccessMsg(request);
        return init(mapping, theform, request, response);
    }

    public ActionForward delete(ActionMapping mapping, EntityPmScheduleForm theform, HttpServletRequest request,
                                HttpServletResponse response) {

        String id = theform.getInstanceId();
        Entity entity = getEntityInfo(id);
        setForm(theform, entity);
        PmSchedule pmSchedule = getPmSechedule(theform);

        emsService.deletePmSchedule(pmSchedule);
        deleteSchedule(pmSchedule, entity);

        WebUtils.setSuccessMsg(request);
        return init(mapping, theform, request, response);
    }

    public ActionForward create(ActionMapping mapping, EntityPmScheduleForm theform, HttpServletRequest request,
                                HttpServletResponse response) {
        toUpCase(theform);
        String id = theform.getInstanceId();
        Entity entity = getEntityInfo(id);
        validateTheform(theform, entity);
        setForm(theform, entity);

        String newId = theform.getScheduleId();
        Assert.isFalse(StringUtils.isEmpty(newId),
                       Errors.create().key(MessageIdList.ENTITYPM_SCHEDULEID_MISSING).content("ScheduleId is Request")
                             .build());

        List<PmSchedule> pmschedules = (List<PmSchedule>) entity.getPmschedules();
        Assert.isFalse(CollectionUtils.exists(pmschedules, p -> ((PmSchedule) p).getScheduleId().equals(newId)),
                       Errors.create().key(MessageIdList.ENTITYPM_SCHEDULEID_IS_EXIST).content("Schedule Id Exist")
                             .build());

        PmSchedule pmSchedule = getPmSechedule(theform);

        emsService.insertPmSchedule(pmSchedule);

        entity = getEntityInfo(id);
        List<PmSchedule> list = (List<PmSchedule>) entity.getPmschedules();
        pmSchedule = list.get(list.size() - 1);

        ChecklistJob checklistJob = getCheckJob(theform, pmSchedule, entity);
        addSchedule(pmSchedule, entity, checklistJob);

        WebUtils.setSuccessMsg(request);
        return init(mapping, theform, request, response);
    }

    public ActionForward deleteMember(ActionMapping mapping, EntityPmScheduleForm theform, HttpServletRequest request,
                                      HttpServletResponse response) {
        Entity entity = getEntityInfo(theform.getInstanceId());
        setForm(theform, entity);

        Long sequenceNumber = new Long(request.getParameter(Constants.ITEM_KEY));
        List<PmSchedule> pmschedules = (List<PmSchedule>) entity.getPmschedules();

        PmSchedule pmSchedule = new PmSchedule();

        for (PmSchedule p : pmschedules) {
            if (p.getSequenceNumber().equals(sequenceNumber)) {
                pmSchedule = p;
                pmSchedule.setEntityId(theform.getInstanceId());
                pmSchedule.setEntityRrn(theform.getEntityRrn());
                break;
            }
        }

        pmSchedule.setTransPerformedBy(LocalContext.getUserId());

        emsService.deletePmSchedule(pmSchedule);
        deleteSchedule(pmSchedule, entity);

        WebUtils.setSuccessMsg(request);
        return init(mapping, theform, request, response);
    }

    public ActionForward delayMember(ActionMapping mapping, EntityPmScheduleForm theform, HttpServletRequest request,
                                     HttpServletResponse response) {
        Entity entity = getEntityInfo(theform.getInstanceId());
        setForm(theform, entity);

        Long sequenceNumber = new Long(request.getParameter(Constants.ITEM_KEY));
        List<PmSchedule> pmschedules = (List<PmSchedule>) entity.getPmschedules();

        PmSchedule pmSchedule = new PmSchedule();

        for (PmSchedule p : pmschedules) {
            if (p.getSequenceNumber().equals(sequenceNumber)) {
                pmSchedule = p;
                pmSchedule.setEntityId(theform.getInstanceId());
                pmSchedule.setEntityRrn(theform.getEntityRrn());
                break;
            }
        }
        PmSchedule p = emsService.getActualEventTime(entity, sequenceNumber);
        if (p != null) {
            pmSchedule.setActualEventTime(p.getActualEventTime());
        }

        PropertyUtils.copyProperties(theform, pmSchedule);

        theform.setSequenceNumber(pmSchedule.getSequenceNumber());
        theform.setAlarmEnableFlag(MiscUtils.changeCheckBox(pmSchedule.getAlarmEnableFlag()));
        theform.setBasedOnPmFlag(MiscUtils.changeCheckBox(pmSchedule.getBasedOnPmFlag()));
        theform.setUnit(pmSchedule.getUnit());
        if (pmSchedule.getNextEventTime() != null) {
            theform.setNextEventTimeDate(getDate(pmSchedule.getNextEventTime()));
            theform.setNextEventTimeTime(getTime(pmSchedule.getNextEventTime()));
        }
        if (pmSchedule.getActualEventTime() != null) {
            theform.setActualEventTimeDate(getDate(pmSchedule.getActualEventTime()));
            theform.setActualEventTimeTime(getTime(pmSchedule.getActualEventTime()));
        }

        if (pmSchedule.getNotifyBefore() != null) {
            long c = pmSchedule.getNotifyBefore();
            long withday = c / (24 * 60 * 60);
            long withtime = c % (24 * 60 * 60);
            theform.setNotifyBeforeDay(withday);
            theform.setNotifyBeforeTime(DateUtils.formatDateForSeconds(withtime));
        }

        if (pmSchedule.getCancelWithin() != null) {
            long c = pmSchedule.getCancelWithin();
            long withday = c / (24 * 60 * 60);
            long withtime = c % (24 * 60 * 60);
            theform.setCancelWithinDay(withday);
            theform.setCancelWithinTime(DateUtils.formatDateForSeconds(withtime));
        }

        theform.setTransId(Constants.MODIFY_KEY);
        return mapping.findForward(DELAY_KEY);
    }

    public ActionForward delay(ActionMapping mapping, EntityPmScheduleForm theform, HttpServletRequest request,
                               HttpServletResponse response) {
        toUpCase(theform);

        String id = theform.getInstanceId();
        Entity entity = getEntityInfo(id);
        validateTheform(theform, entity);
        setForm(theform, entity);

        Assert.isFalse(theform.getActualEventTimeDate() == null || theform.getActualEventTimeDate().equals(""),
                       Errors.create().key(MessageIdList.ENTITYPM_PM_TIME_MISSING)
                             .content("Please input " + "delay " + "PM time.").build());
        if ((!theform.getActualEventTimeDate().trim().equals("")) &&
                (theform.getActualEventTimeTime().trim().equals(""))) {
            theform.setActualEventTime(theform.getActualEventTimeDate());
        } else {
            theform.setActualEventTime(
                    theform.getActualEventTimeDate().trim() + " " + theform.getActualEventTimeTime().trim());
        }
        theform.setNextEventTime(theform.getNextEventTimeDate().trim() + " " + theform.getNextEventTimeTime().trim());
        Timestamp nextEventTime = DateUtils.stringToTimestamp(theform.getNextEventTime());
        Timestamp actualEventTime = DateUtils.stringToTimestamp(theform.getActualEventTime());
        Assert.isFalse(actualEventTime.getTime() < System.currentTimeMillis(),
                       Errors.create().key(MessageIdList.ENTITYPM_DELAY_NO_LESS_CURRENT)
                             .content("Delay PM time " + "cannot be less " + "than current " + "time.").build());

        Assert.isFalse(actualEventTime.getTime() < nextEventTime.getTime(),
                       Errors.create().key(MessageIdList.ENTITYPM_DELAY_NO_LESS_NEXT)
                             .content("Delay PM time cannot" + " " + "be less than the " + "next PM time.").build());

        PmSchedule pmSchedule = getPmSechedule(theform);

        ChecklistJob checklistJob = getCheckJob(theform, pmSchedule, entity);

        delaySchedule(pmSchedule, entity, checklistJob);

        WebUtils.setSuccessMsg(request);
        return init(mapping, theform, request, response);
    }

    public ActionForward member(ActionMapping mapping, EntityPmScheduleForm theform, HttpServletRequest request,
                                HttpServletResponse response) {
        Entity entity = getEntityInfo(theform.getInstanceId());
        setForm(theform, entity);

        Long sequenceNumber = new Long(request.getParameter(Constants.ITEM_KEY));
        List<PmSchedule> pmschedules = (List<PmSchedule>) entity.getPmschedules();

        PmSchedule pmSchedule = new PmSchedule();

        for (PmSchedule p : pmschedules) {
            if (p.getSequenceNumber().equals(sequenceNumber)) {
                pmSchedule = p;
                pmSchedule.setEntityId(theform.getInstanceId());
                pmSchedule.setEntityRrn(theform.getEntityRrn());
                break;
            }
        }

        PmSchedule p = emsService.getActualEventTime(entity, sequenceNumber);
        if (p != null) {
            pmSchedule.setActualEventTime(p.getActualEventTime());
        }

        PropertyUtils.copyProperties(theform, pmSchedule);
        theform.setSequenceNumber(pmSchedule.getSequenceNumber());
        theform.setAlarmEnableFlag(MiscUtils.changeCheckBox(pmSchedule.getAlarmEnableFlag()));
        theform.setBasedOnPmFlag(MiscUtils.changeCheckBox(pmSchedule.getBasedOnPmFlag()));
        theform.setActionFlag1(MiscUtils.changeCheckBox(pmSchedule.getActionFlag1()));
        theform.setActionFlag2(MiscUtils.changeCheckBox(pmSchedule.getActionFlag2()));
        theform.setUnit(pmSchedule.getUnit());
        if (pmSchedule.getNextEventTime() != null) {
            theform.setNextEventTimeDate(getDate(pmSchedule.getNextEventTime()));
            theform.setNextEventTimeTime(getTime(pmSchedule.getNextEventTime()));
        }

        if (pmSchedule.getNotifyBefore() != null) {
            long c = pmSchedule.getNotifyBefore();
            long withday = c / (24 * 60 * 60);
            long withtime = c % (24 * 60 * 60);
            theform.setNotifyBeforeDay(withday);
            theform.setNotifyBeforeTime(DateUtils.formatDateForSeconds(withtime));
        }

        if (pmSchedule.getCancelWithin() != null) {
            long c = pmSchedule.getCancelWithin();
            long withday = c / (24 * 60 * 60);
            long withtime = c % (24 * 60 * 60);
            theform.setCancelWithinDay(withday);
            theform.setCancelWithinTime(DateUtils.formatDateForSeconds(withtime));
        }

        theform.setTransId(Constants.MODIFY_KEY);
        return mapping.findForward(Constants.MEMBERS_KEY);
    }

    public ActionForward addMember(ActionMapping mapping, EntityPmScheduleForm theform, HttpServletRequest request,
                                   HttpServletResponse response) {
        toUpCase(theform);
        String id = theform.getInstanceId();
        Entity entity = getEntityInfo(id);
        setForm(theform, entity);

        theform.setTransId(Constants.CREATE_KEY);
        return mapping.findForward(Constants.MEMBERS_KEY);
    }

    private void delaySchedule(PmSchedule instance, Entity entity, ChecklistJob checklistJob) {
        String[] id = getScheduleJobIdGroupId(instance, entity);
        long startTime = DateUtils.stringToTimestamp(instance.getActualEventTime()).getTime();
        long repeatStartTime = this.getNextTime(DateUtils.stringToTimestamp(instance.getActualEventTime()).getTime(),
                                                instance.getRepeatInFrequence().intValue(), instance.getRepeatInUnit());

        emsService.delaySchedule(instance, LocalContext.getUserRrn(), id[0], id[1], "R" + id[0], "R" + id[1], startTime,
                                 repeatStartTime);
        this.deleteRepeatSchedule(instance, entity);
        this.addDelayRepeatSchedule(instance, entity);
    }


    /**
     * @param startDate :开始时间
     * @param f:频率
     */
    private String getcronExpression(Date startDate, String f) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(startDate);

        int ss = cal.get(Calendar.SECOND);
        int mm = cal.get(Calendar.MINUTE);
        int hh = cal.get(Calendar.HOUR);
        int day = cal.get(Calendar.DATE);
        int month = cal.get(Calendar.MONTH);

        return ss + " " + mm + " " + hh + " " + day + " " + month + "/" + f + " ?";
    }

    private String getDate(String time) {
        return ((time.toString().length()) >= 10) ? time.toString().substring(0, 10) : time.toString();
    }

    private String getTime(String time) {

        return ((time.toString().length()) >= 10) ? time.toString().substring(11) : time.toString();
    }

    private PmSchedule getPmSechedule(EntityPmScheduleForm theform) {
        PmSchedule pmSchedule = new PmSchedule();
        PropertyUtils.copyProperties(pmSchedule, theform);

        pmSchedule.setTransPerformedBy(LocalContext.getUserId());
        pmSchedule.setAlarmEnableFlag(MiscUtils.parseCheckBox(theform.getAlarmEnableFlag()));
        pmSchedule.setBasedOnPmFlag(MiscUtils.parseCheckBox(theform.getBasedOnPmFlag()));
        pmSchedule.setActionFlag1(MiscUtils.parseCheckBox(theform.getActionFlag1()));
        pmSchedule.setActionFlag2(MiscUtils.parseCheckBox(theform.getActionFlag2()));
        return pmSchedule;
    }

    private ChecklistJob getCheckJob(EntityPmScheduleForm theform, PmSchedule pmSchedule, Entity entity) {
        String checklistId = theform.getChecklistId();
        String namedSpace = getNamedSpace(ObjectList.ALARM_KEY, LocalContext.getFacilityRrn());
        Checklist checklist = new Checklist(checklistId, namedSpace, ObjectList.CHECKLIST_KEY);

        pmSchedule.setEquipmentNamedSpace(namedSpace);
        checklist = emsService.getChecklist(checklist);
        long checklistRrn = checklist.getInstanceRrn();
        String checklistJobState = "STARTED";
        long entityRrn = entity.getInstanceRrn();
        Timestamp startTimestamp = new Timestamp(System.currentTimeMillis());

        ChecklistJob checklistJob = new ChecklistJob();

        checklistJob.setChecklistId(checklistId);
        checklistJob.setEntityRrn(entityRrn);
        checklistJob.setChecklistRrn(checklistRrn);
        checklistJob.setChecklistJobState(checklistJobState);
        checklistJob.setStartTimestamp(startTimestamp);
        checklistJob.setTransPerformedby(LocalContext.getUserId());
        checklistJob.setTransId(TransactionNames.CREATE_KEY);

        return checklistJob;
    }

    private void validateTheform(EntityPmScheduleForm theform, Entity entity) {

        String newId = theform.getScheduleId();
        Assert.isFalse(StringUtils.isEmpty(newId),
                       Errors.create().key(MessageIdList.ENTITYPM_SCHEDULEID_MISSING).content("ScheduleId is Request")
                             .build());

        if (StringUtils.equalsIgnoreCase(theform.getTransId(), Constants.CREATE_KEY)) {
            List<PmSchedule> pmschedules = (List<PmSchedule>) entity.getPmschedules();
            Assert.isFalse(CollectionUtils.exists(pmschedules, p -> ((PmSchedule) p).getScheduleId().equals(newId)),
                           Errors.create().key(MessageIdList.ENTITYPM_SCHEDULEID_IS_EXIST).content("Schedule Id Exist")
                                 .build());
        }

        Assert.isFalse(theform.getRepeatInFrequence() != null && theform.getRepeatInFrequence() < 0,
                       Errors.create().key(MessageIdList.ENTITYPM_REPEAT_MORE_ZERO)
                             .content("Repeat should be more than zero!").build());

        if (theform.getRepeatInFrequence() != null && theform.getRepeatInFrequence() > 0) {
            Assert.isFalse(isAlarmExisted(theform.getAlarmIdWhenRepeat(), AlarmType.SYSTEM_KEY),
                           Errors.create().key(MessageIdList.ENTITYPM_SEND_REPEAT_ALARM)
                                 .content("Invalid send Alarm When Repeat Alarm!").build());
        }

        Assert.isTrue(StringUtils.isNotEmpty(theform.getFrequence()),
                      Errors.create().key(MessageIdList.ENTITYPM_INVALID_FREQUENCE)
                            .content("Frequence should be more than " + "zero!").build());
        long temp = Long.parseLong(theform.getFrequence());

        Assert.isFalse(temp < 0, Errors.create().key(MessageIdList.ENTITYPM_INVALID_FREQUENCE)
                                       .content("Frequence should be more than zero!").build());

        if ((theform.getNextEventTimeDate() != null) && (theform.getNextEventTimeTime() != null)) {
            if ((theform.getNextEventTimeDate().trim().equals("")) &&
                    (theform.getNextEventTimeTime().trim().equals(""))) {
                theform.setNextEventTime(null);
            } else if ((!theform.getNextEventTimeDate().trim().equals("")) &&
                    (theform.getNextEventTimeTime().trim().equals(""))) {
                theform.setNextEventTime(theform.getNextEventTimeDate());
            } else {
                theform.setNextEventTime(
                        theform.getNextEventTimeDate().trim() + " " + theform.getNextEventTimeTime().trim());
            }

            /*
             * comment by Bright 修改触发时间的判断,触发时间=nextEventTime-offset(Day)
             */
            int offset = 0;
            if (theform.getOffset() != null && theform.getOffset() > 0) {
                offset = theform.getOffset().intValue();
            }
            Timestamp triggerTime = DateUtils.stringToTimestamp(theform.getNextEventTime());
            java.util.Calendar calendar = java.util.Calendar.getInstance();
            calendar.setTimeInMillis(triggerTime.getTime());
            // triggerTime-offset(Day)
            calendar.add(java.util.Calendar.DATE, 0 - offset);

            Assert.isFalse(calendar.getTimeInMillis() < System.currentTimeMillis(),
                           Errors.create().key(MessageIdList.ENTITYPM_NEXT_LATER_CURRENT).content(
                                   "Next Event " + "Time " + "should be " + "later " + "than" + " " + "current " +
                                           "time!").build());
        }

        if (StringUtils.isNotEmpty(theform.getEstimatedDurationTime())) {
            theform.setEstimatedDuration(new Long(theform.getEstimatedDurationTime()));
        }

        // 前端js已经注释,这段逻辑不走
        //        if ((theform.getNotifyBeforeDay() != null) && (theform.getNotifyBeforeTime() != null)) {
        //            if ((theform.getNotifyBeforeDay().equals("")) && (theform.getNotifyBeforeTime()
        //            .equals(""))) {
        //                theform.setNotifyBefore(null);
        //            } else if (!theform.getNotifyBeforeDay().equals("") && (theform.getNotifyBeforeTime()
        //            .equals(
        //                    ""))) {
        //                long c   = theform.getNotifyBeforeDay().longValue();
        //                long sec = c * 24 * 60 * 60;
        //                theform.setNotifyBefore(new Long(sec));
        //            } else {
        //                long c = theform.getNotifyBeforeDay().longValue();
        //
        //                long sec = c * 24 * 60 * 60;
        //
        //                long t = MiscUtils.timeToLongSecs(theform.getNotifyBeforeTime());
        //
        //                // Long cancelWithin = new Long(c==null);
        //                theform.setNotifyBefore(new Long(sec + t));
        //
        //            }
        //        }

        //        if ((theform.getCancelWithinDay() != null) && (theform.getCancelWithinTime() != null)) {
        //            if ((theform.getCancelWithinDay().equals("")) && (theform.getCancelWithinTime()
        //            .equals(""))) {
        //                theform.setCancelWithin(null);
        //            } else if (!theform.getCancelWithinDay().equals("") && (theform.getCancelWithinTime()
        //            .equals(
        //                    ""))) {
        //                long c   = theform.getCancelWithinDay();
        //                long sec = c * 24 * 60 * 60;
        //                theform.setCancelWithin(sec);
        //
        //            } else {
        //                long c = theform.getCancelWithinDay().longValue();
        //
        //                long sec = c * 24 * 60 * 60;
        //
        //                long t = MiscUtils.timeToLongSecs(theform.getCancelWithinTime());
        //
        //                // Long cancelWithin = new Long(c==null);
        //                theform.setCancelWithin(sec + t);
        //            }
        //        }

        if ((theform.getChecklistId() != null) && !theform.getChecklistId().trim().equals("")) {
            long checklistRrn = getInstanceRrn(theform.getChecklistId(),
                                               getNamedSpace(ObjectList.CHECKLIST_KEY, LocalContext.getFacilityRrn()),
                                               ObjectList.CHECKLIST_KEY);

            Assert.isFalse(checklistRrn <= 0,
                           Errors.create().key(MessageIdList.SYSTEM_INSTANCE_NOT_FOUND).content("{} 没有找到对象!")
                                 .args("CheckList").build());
            theform.setChecklistRrn(checklistRrn);
        }
        if ((theform.getAlarmIdWhenDue() != null) && !theform.getAlarmIdWhenDue().trim().equals("")) {

            Assert.isFalse(isAlarmExisted(theform.getAlarmIdWhenDue(), AlarmType.SYSTEM_KEY),
                           Errors.create().key(MessageIdList.ENTITYPM_SEND_ALARM_INVALID)
                                 .content("Invalid Send Alarm When Due Alarm!").build());
        }

        if ((theform.getNotifyAlarmId() != null) && !theform.getNotifyAlarmId().trim().equals("")) {

            Assert.isFalse(isAlarmExisted(theform.getNotifyAlarmId(), AlarmType.SYSTEM_KEY),
                           Errors.create().key(MessageIdList.ENTITYPM_ALARM_INVALID).content("Invalid Alarm!").build());
        }

    }

    private boolean isAlarmExisted(String alarmId, String alarmType) {
        Alarm alarm = new Alarm();
        alarm.setAlarmId(alarmId);
        alarm.setAlarmType(alarmType);
        alarm = alarmService.getAlarm(alarm);
        return alarm == null;
    }

    private void setForm(EntityPmScheduleForm theform, Entity entity) {
        theform.setInstanceId(entity.getInstanceId());
        theform.setEntityRrn(entity.getInstanceRrn());
        theform.setNamedSpace(entity.getNamedSpace());
        theform.setInstanceDesc(entity.getInstanceDesc());
    }

    private Entity getEntityInfo(String id) {
        Entity entity = new Entity(id, getNamedSpace(ObjectList.ENTITY_KEY, LocalContext.getFacilityRrn()),
                                   ObjectList.ENTITY_KEY);

        entity = (Entity) getInstance(entity);

        Assert.isFalse(entity == null,
                       Errors.create().key(MessageIdList.EQUIPMENT_ID_NOT_EXIST).content("EQP ID is not exist!")
                             .build());

        List<PmSchedule> data = emsService.getPmSchedulesOfEntity(entity.getInstanceRrn());
        entity.setPmschedules(data);

        return entity;
    }

    private void toUpCase(EntityPmScheduleForm theform) {
        if (theform.getChecklistId() != null) {
            theform.setChecklistId(theform.getChecklistId().trim().toUpperCase());
        }

        if (theform.getAlarmIdWhenDue() != null) {
            theform.setAlarmIdWhenDue(theform.getAlarmIdWhenDue().trim().toUpperCase());
        }

        if (theform.getNotifyAlarmId() != null) {
            theform.setNotifyAlarmId(theform.getNotifyAlarmId().trim().toUpperCase());
        }
    }

    /**
     * @param startDate                                            :开始时间
     * @param f:频率
     * @param unit:单位,天:D,分钟:I,月:M,周:W,年:Y
     * @param baseFlag:以完成checklistjob为标志,true表示只触发一次,false表示周期性触发
     * @return String : 返回一个cron trigger的周期字符串 通过开始时间和时间间隔返回一个cron trigger识别格式的周期字符串,用来处理年,月的周期,
     * 取代原有的月通过30天,年365天的计算方式 version 2的修改: 修改原有的bug,并且添加年的判断,年通过12个月来表示,字符串中默认年为缺省 格式:"秒 分 小时 天 月初始/月跨度
     * 星期(?表示忽略) 年(缺省表示忽略)" 由于quartz无法做到每隔n个月触发,所以返回每个月触发
     */
    private String getcronExpression(Date startDate, long f, String unit, boolean baseFlag) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(startDate);

        int ss = cal.get(Calendar.SECOND);
        int mm = cal.get(Calendar.MINUTE);
        int hh = cal.get(Calendar.HOUR);
        int day = cal.get(Calendar.DATE);
        int month = cal.get(Calendar.MONTH);
        int year = cal.get(Calendar.YEAR);

        if (baseFlag) {
            return ss + " " + mm + " " + hh + " " + day + " " + month + " ? " + year;
        } else {
            if (unit != null && unit.equalsIgnoreCase("M")) {
                return ss + " " + mm + " " + hh + " " + day + " " + "*" + " ?";
            } else if (unit != null && unit.equalsIgnoreCase("Y")) {
                return ss + " " + mm + " " + hh + " " + day + " " + "*" + " ?";
            } else {
                return ss + " " + mm + " " + hh + " " + day + " " + "*" + " ?";
            }
        }
    }

    /**
     * @param jobName   jobName
     * @param jobGroup  jobGroup
     * @param alarmInfo jobData
     * @param baseFlag  以完成checklistjob为标志,true表示只触发一次,false表示周期性触发
     * @param startDate 开始日期
     * @param frequency 频率
     * @param unit      单位
     */
    @Override
    protected void addJob(String jobName, String jobGroup, Map alarmInfo, boolean baseFlag, Date startDate, Long repeat,
                          long frequency, String unit) {
        if (StringUtils.equals("Y", unit) || StringUtils.equals("M", unit)) {
            quartzOperateService
                    .addJob(jobName, JOB_CLASS_NAME, jobGroup, getcronExpression(startDate, frequency, unit, baseFlag),
                            alarmInfo);
        } else {
            super.addJob(jobName, jobGroup, alarmInfo, baseFlag, startDate, repeat, frequency, unit);
        }
    }

}