EquipmentPMPortalAction.java

package com.mycim.webapp.actions.equipmentpm;

import com.fa.sesa.exception.Assert;
import com.fa.sesa.exception.Errors;
import com.fa.sesa.i18n.I18nUtils;
import com.fa.sesa.threadlocal.LocalContext;
import com.mycim.framework.file.excel.im.ExcelImport;
import com.mycim.framework.file.excel.im.ExcelParser;
import com.mycim.framework.file.excel.im.ExcelRow;
import com.mycim.framework.jdbc.Page;
import com.mycim.framework.utils.beans.BeanUtils;
import com.mycim.framework.utils.lang.StringUtils;
import com.mycim.framework.utils.lang.collections.CollectionUtils;
import com.mycim.framework.utils.lang.collections.MapUtils;
import com.mycim.framework.utils.lang.math.NumberUtils;
import com.mycim.framework.utils.lang.time.DateUtils;
import com.mycim.valueobject.MessageIdList;
import com.mycim.valueobject.ObjectList;
import com.mycim.valueobject.SystemConstant;
import com.mycim.valueobject.bas.EquipmentPartRelation;
import com.mycim.valueobject.bas.Relation;
import com.mycim.valueobject.consts.LinkTypeList;
import com.mycim.valueobject.ems.*;
import com.mycim.valueobject.inv.MaterialDO;
import com.mycim.valueobject.inv.PartConsumeDO;
import com.mycim.valueobject.prp.Item;
import com.mycim.valueobject.sys.ReferenceFileDetail;
import com.mycim.webapp.Constants;
import com.mycim.webapp.TemplateLocation;
import com.mycim.webapp.WebUtils;
import com.mycim.webapp.actions.EmsSetupAction;
import com.mycim.webapp.forms.PmScheduleForm;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * Pm History Action
 *
 * @author pinyan.song
 * @version 6.0.0
 * @date 2019-11-19 17:34
 **/
public class EquipmentPMPortalAction extends EmsSetupAction {

    private static final String HISTORY = "eqptPMHist";

    private static final String CHECKLISTJOBDATAHIST = "checklistJobDataHist";

    private static final String PORTAL = "eqptPMPortal";

    private final static String PMTYPE = "WEEKLY#MONTHLY#DAYS";

    private static Pattern pattern = Pattern.compile("^[0-9]{4}/[0-9]{2}/[0-9]{2}\\s{1}[0-9]{2}:[0-9]{2}:00$");

    public void addPmSchedule(PmScheduleForm theform) {
        setTheForm(theform);
        theform.setPmId(theform.getPmId().trim());
        PmsSchedule schedule = new PmsSchedule();
        validate4AddPM(LocalContext.getFacilityRrn(), theform);
        String nextPmTimeStr = theform.getNextPmTimeStr() + " " + theform.getSubNextPmTimeStr() + ":00";
        BeanUtils.copyProperties(theform, schedule);
        Date nextPmTime = DateUtils.parse(nextPmTimeStr, DateUtils.DATE_FORMAT);
        schedule.setNextPmTime(nextPmTime);
        schedule.setObjectType("EQPT");
        schedule.setCreateUserId(LocalContext.getUserId());
        schedule.setCreateDate(new Date());
        if (StringUtils.isEmpty(schedule.getChamberId())) {
            schedule.setChamberId("#");
        }
        pmsService.addPmSchedule(schedule);
    }

    public void deletePmSchedule(PmScheduleForm theform) {
        setTheForm(theform);
        PmsSchedule schedule = new PmsSchedule();
        pmScheduleCheck(theform);
        BeanUtils.copyProperties(theform, schedule);
        pmsService.deletePmSchedule(schedule);
    }

    public void modifyPmSchedule(PmScheduleForm theform) {
        setTheForm(theform);
        theform.setPmId(theform.getPmId().trim());
        PmsSchedule schedule = new PmsSchedule();
        validate4ModifyPM(LocalContext.getFacilityRrn(), theform);
        String nextPMTimeStr = theform.getNextPmTimeStr() + " " + theform.getSubNextPmTimeStr() + ":00";
        BeanUtils.copyProperties(theform, schedule);
        if (!StringUtils.isEmpty(nextPMTimeStr)) {
            Date nextPmTime = DateUtils.parse(nextPMTimeStr, DateUtils.DATE_FORMAT);
            schedule.setNextPmTime(nextPmTime);
        }
        pmsService.modifyPmSchedule(schedule);
    }

    public void pmStart(PmScheduleForm theform) {
        setTheForm(theform);
        PmsSchedule schedule = new PmsSchedule();
        pmScheduleCheck(theform);
        BeanUtils.copyProperties(theform, schedule);
        String pmLinks = StringUtils.join(schedule.getPmLink(), ",");
        schedule.setPmLinks(pmLinks);
        // if (StringUtils.isNotBlank(pmLinks)) {
        //     PmsSchedule _pmsSchedule = new PmsSchedule();
        //     _pmsSchedule.setPmRrnStr(pmLinks);
        //     List<PmsSchedule> pmsScheduleList = pmsService.qryEqptPMInfo(_pmsSchedule);
        //     String pmlinkComments = " PM Id: " + StringUtils.join(
        //             pmsScheduleList.stream().map(PmsSchedule::getPmId).toArray(), ",");
        //     schedule.setComment(schedule.getComment() + pmlinkComments);
        // }

        pmsService.pmsPmStart(schedule);
    }

    public void pmEnd(PmScheduleForm theform) {
        pmScheduleCheck(theform);
        setTheForm(theform);
        Assert.isFalse(theform.getPmRrnStr().split(",").length > 1 && theform.getPmLink().length > 0,
                       Errors.create().key(MessageIdList.PMS_MULTIPLE_PMS)
                             .content("Cannot select multiple PMs and associated PMs at the same time!").build());

        Map<Long, List<PartConsumeDO>> partConsumeMap = this.checkPmConsumePart(theform);
        PmsSchedule qrySchedule = new PmsSchedule();
        qrySchedule.setPmRrnStr(theform.getPmRrnStr());
        List<PmsSchedule> pmsSchedules = pmsService.qryEqptPMInfo(qrySchedule);//查询出勾选的多个PM ID

        for (PmsSchedule pmsSchedule : pmsSchedules) {
            String extendCondition = "PM_RRN = '" + pmsSchedule.getPmRrn() + "'";
            List<ChecklistJob> checklistJobs = emsService.getChecklistJobs(extendCondition);//查询出此PM_RRN关联的CheckListJob
            for (ChecklistJob checklistJob : checklistJobs) {
                String state = checklistJob.getChecklistJobState();
                Assert.isFalse(StringUtils.equalsIgnoreCase(state, STARTED),
                               Errors.create().key(MessageIdList.CHECKLISTJOB_UNFINISHED)
                                     .content("Please finish {} checklist first!")
                                     .args(checklistJob.getChecklistId()).build());
            }
        }

        qrySchedule.setPmLink(theform.getPmLink());
        qrySchedule.setTargetEventId(theform.getTargetEventId());
        qrySchedule.setComment(theform.getComment());
        qrySchedule.setCreateUserId(theform.getCreateUserId());
        qrySchedule.setPartConsumeMap(partConsumeMap);
        pmsService.pmsPmEnd(qrySchedule);
    }

    public Map qryCheckList(Map params) {
        Map result = new HashMap();
        String pmRrns = MapUtils.getString(params, "pmRrns");
        PmsSchedule schedule = new PmsSchedule();
        schedule.setPmRrnStr(pmRrns);
        List<PmsSchedule> pmsSchedules = pmsService.qryEqptPMInfo(schedule);
        pmsSchedules = pmsSchedules.stream().filter(pmsSchedule -> {
            Long checkListRrn = pmsSchedule.getChecklistRrn();
            if (checkListRrn == null || checkListRrn == 0L) {
                return false;
            } else {
                return true;
            }
        }).collect(Collectors.toList());
        List<ChecklistJob> checklistJobs = new ArrayList();
        for (PmsSchedule pmsSchedule : pmsSchedules) {
            String extendCondition = "PM_RRN = '" + pmsSchedule.getPmRrn() + "'";
            List<ChecklistJob> _checklistJobs = emsService.getChecklistJobs(extendCondition);
            //            _checklistJobs = _checklistJobs.stream().filter(checklistJob -> {
            //                return StringUtils.equalsIgnoreCase(checklistJob.getChecklistJobState(),
            //                "STARTED");
            //            }).collect(Collectors.toList());
            checklistJobs.addAll(_checklistJobs);
        }
        List<ChecklistJobData> checklistJobDatas = emsService.getChecklistJobDatas(checklistJobs);
        result.put("results", checklistJobDatas);
        return result;
    }

    public Map checkPmEndConfirmMessage(Map params) {
        Map result = new HashMap();
        String pmRrns = MapUtils.getString(params, "pmRrnStr");
        PmsSchedule schedule = new PmsSchedule();
        schedule.setPmRrnStr(pmRrns);
        List<PmsSchedule> pmsSchedules = pmsService.qryEqptPMInfo(schedule);

        StringBuilder str = new StringBuilder();
        for (PmsSchedule ps : pmsSchedules) {
            if (PmControlTypeEnum.PM_TRIGGER_READING.name().equalsIgnoreCase(ps.getControlType()) && ps.getToleranceStatus() == 3){
                str.append(",").append(ps.getPmId());
            }
        }

        result.put("message", str.length()>0?str.substring(1):StringUtils.EMPTY);
        return result;
    }

    public Map updateCheckListData(Map params) {
        Map resultMap = new HashMap();
        Map<Long, ChecklistJob> checklistJobMap = new HashMap<>();
        List<Map> checkListDataList = (List) MapUtils.getObject(params, "checkListDataList");
        for (Map map : checkListDataList) {
            int seq = MapUtils.getIntValue(map, "checklistItemSequence");
            long entityRrn = MapUtils.getLongValue(map, "entityRrn");
            long checklistJobRrn = MapUtils.getLongValue(map, "checklistJobRrn");
            String dataValue = MapUtils.getString(map, "dataValue");
            String standard = MapUtils.getString(map, "standard");
            String comments = MapUtils.getString(map, "comments");
            ChecklistJob checklistJob = new ChecklistJob();
            checklistJob.setChecklistJobRrn(checklistJobRrn);
            checklistJob = emsService.getChecklistJob(checklistJob);
            checklistJob.setTriggerPerformedBy(LocalContext.getUserId());
            checklistJob.setTriggerTimestamp(new Timestamp(System.currentTimeMillis()));

            ChecklistJobData checklistJobData = new ChecklistJobData();
            List<ChecklistJobData> checklistJobDatas = (List<ChecklistJobData>) checklistJob.getChecklistJobDatas();
            for (ChecklistJobData _checklistJobData : checklistJobDatas) {
                if (_checklistJobData.getChecklistItemSequence() == seq) {
                    _checklistJobData.setChecklistItemSequence(seq);
                    _checklistJobData.setOperatorRrn(LocalContext.getUserRrn());
                    _checklistJobData.setChecklistJobRrn(checklistJob.getChecklistJobRrn());
                    checklistJobData = _checklistJobData;
                    break;
                }
            }
            int colNum = checklistJobData.getColNum();
            checklistJobData.setDataValue(dataValue);
            checklistJobData.setStandard(standard);
            checklistJobData.setComments(comments);

            this.doChecklistItem(checklistJobData);

            checklistJob.setChecklistJobDatas(emsService.getChecklistJobDatas(checklistJob));

            Entity entity = emsService.getEntity(entityRrn);
            entity.setPmschedules(emsService.getPmSchedulesOfEntity(entity.getInstanceRrn()));
            checklistJob.setComments(comments);
            completeChecklistJob(checklistJob, entity, checklistJobMap);
            updatePmNextTriggerTime(checklistJob, entity);
        }
        if (checklistJobMap.size() > 0) {
            StringBuilder str = new StringBuilder();
            for(Map.Entry<Long, ChecklistJob> entry : checklistJobMap.entrySet()) {
                if (entry.getValue().getSaveFlag()) {
                    entry.getValue().setChecklistJobDatas(emsService.getChecklistJobDatas(entry.getValue()));
                    entry.getValue().setTransId(Constants.ERR_SAVE_KEY);
                    emsService.saveErrChecklistJobH(entry.getValue(), LocalContext.getUserRrn());
                }
                str.append(entry.getValue().getErrMsg());
            }
            if (str.length() > 0) {
                Assert.isFalse(true, Errors.create().content(str.toString()).build());
            }
        }

        return resultMap;
    }

    public void onOffChange(PmScheduleForm theform) {
        setTheForm(theform);
        PmsSchedule schedule = new PmsSchedule();
        String pmRrns = theform.getPmRrnStr();
        Assert.isFalse(StringUtils.isEmpty(pmRrns), Errors.create().key(MessageIdList.ENTITYPM_PLEASE_SELECT_ITEM)
                                                          .content("Please select one or more item for operation.")
                                                          .build());

        pmScheduleCheck(theform);
        BeanUtils.copyProperties(theform, schedule);
        pmsService.onOffChange(schedule);
    }

    @Override
    public ActionForward init(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                              HttpServletResponse response) throws Exception {
        String op = WebUtils.getParameter("op", request);

        if (StringUtils.equalsIgnoreCase(op, "pmsHistInit")) {
            // history
            return history(mapping, form, request, response);
        } else if (StringUtils.equalsIgnoreCase(op, "index")) {
            // portal
            return portal(mapping, form, request, response);
        } else if (StringUtils.equalsIgnoreCase(op, "viewChecklistJobData")) {
            return viewChecklistJobData(mapping, form, request, response);
        } else {
            return super.init(mapping, form, request, response);
        }
    }

    public ActionForward export(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String checklistJobRrn = WebUtils.getParameter("checklistJobRrn", request);
        List<Map> jobDataList = pmsService.qryChecklistJobDataHist(Long.parseLong(checklistJobRrn));
        int i =1;
        for (Map map :  jobDataList) {
            map.put("seq", i++);
        }
        String pmId = (String) ((Map)jobDataList.get(0)).get("pmId");
        Map<String, Object> titles = WebUtils.getExportTitles(request);
        titles.put("title", "Checklist Job Data History");
        String exportDateTime = DateUtils.getNowTime(DateUtils.DATE_FORMAT4NOSPLICING);
        String fileName = pmId +"_"+ exportDateTime + ".xlsx";
        WebUtils.exportExcel(fileName, titles, jobDataList, TemplateLocation.PM_CHECKLIST_HIST, response);
        return WebUtils.NULLActionForward;
    }

    public List<PmsSchedule> queryPmsList(PmScheduleForm theform) {
        setTheForm(theform);
        PmsSchedule schedule = new PmsSchedule();
        BeanUtils.copyProperties(theform, schedule);
        return pmsService.qryEqptPMInfo(schedule);
    }

    public ActionForward queryPmsHist(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                                      HttpServletResponse response) {
        String startDateStr = WebUtils.getParameter("startDate", request);
        String endDateStr = WebUtils.getParameter("endDate", request);
        String eqptId = WebUtils.getParameterUpperCase("eqptId", request);
        String chamberId = WebUtils.getParameterUpperCase("chamberId", request);
        String pmType = WebUtils.getParameterUpperCase("pmType", request);

        Map<String, Object> condition = new HashMap<>();
        condition.put("eqptId", eqptId);
        condition.put("chamberId", chamberId);
        condition.put("pmType", pmType);

        Timestamp startDate = DateUtils.stringToTimestamp(startDateStr + SystemConstant.Str.TIME_START);
        Timestamp endDate = DateUtils.stringToTimestamp(endDateStr + SystemConstant.Str.TIME_END);

        Assert.isFalse(startDate == null || endDate == null,
                       Errors.create().key(MessageIdList.DATE_DATE_FORMAT_INCORRECT).content("Date format is wrong!")
                             .build());

        condition.put("startDate", startDateStr);
        condition.put("endDate", endDateStr);

        int thisPage = WebUtils.getThisPage(request);
        int pageSize = WebUtils.getPageSize(request);
        Page page = new Page();
        page.setPageNo(thisPage);
        page.setPageSize(pageSize);

        if (StringUtils.isNotBlank(WebUtils.getParameter("showAll", request))) {
            page.setPageNo(1);
            page.setPageSize(Integer.MAX_VALUE);
        }
        page = pmsService.qryPmsEqptHist(condition, page);

        request.setAttribute("eqptId", eqptId);
        request.setAttribute("chamberId", chamberId);
        request.setAttribute("pmType", pmType);
        request.setAttribute("pageSize", 20);
        request.setAttribute("lastPageSize", 20);
        request.setAttribute("thisPage", page.getPageNo());
        request.setAttribute("maxPage", page.getTotalPages());
        request.setAttribute("pmHist", page.getResults());
        request.setAttribute("startDate", startDateStr);
        request.setAttribute("endDate", endDateStr);

        return mapping.findForward(HISTORY);
    }

    public List<Map<String, Object>> getCycleType(Map params, HttpServletRequest request) {
        List<Map<String, Object>> datas = new ArrayList<>();
        List<ReferenceFileDetail> cycleTime = new ArrayList<>();
        List<ReferenceFileDetail> countType = new ArrayList<>();
        List<ReferenceFileDetail> triggerType = new ArrayList<>();

        String flag = MapUtils.getString(params, "type");
        if (StringUtils.equalsIgnoreCase("PM_ALL", flag) || StringUtils.equalsIgnoreCase("PM_TIME", flag)) {
            cycleTime = sysService.getRefFileValues("$$PMS_CYCLE_TIME", LocalContext.getFacilityRrn());
        }

        if (StringUtils.equalsIgnoreCase("PM_ALL", flag) || StringUtils.equalsIgnoreCase("PM_COUNT", flag)) {
            countType = sysService
                    .getRefFileValues("$$PM_CONTROL_TYPE", LocalContext.getFacilityRrn());
        }

        if (StringUtils.equalsIgnoreCase("PM_ALL", flag) || StringUtils.equalsIgnoreCase("PM_TRIGGER", flag)) {
            triggerType = sysService
                    .getRefFileValues("$$PM_TRIGGER_TYPE", LocalContext.getFacilityRrn());
        }


        String windowFlag = request.getParameter("windowFlag");

        if (StringUtils.isNotBlank(windowFlag)) {
            Map map = new HashMap();
            map.put("key", "");
            map.put("data1", "ALL");
            map.put("data2", "");
            datas.add(map);
        }

        for (ReferenceFileDetail r : countType) {
            Map<String, Object> data = new HashMap<>();
            data.put("key", r.getKey1Value());
            data.put("data1", r.getData1Value());
            data.put("data2", r.getData2Value());
            datas.add(data);
        }

        for (ReferenceFileDetail r : cycleTime) {
            Map<String, Object> data = new HashMap<>();
            data.put("key", r.getKey1Value());
            data.put("data1", r.getData1Value());
            data.put("data2", r.getData2Value());
            datas.add(data);
        }

        for (ReferenceFileDetail type : triggerType) {
            Map<String, Object> data = new HashMap<>();
            data.put("key", type.getKey1Value());
            data.put("data1", type.getData1Value());
            data.put("data2", type.getData2Value());
            datas.add(data);
        }

        return datas;
    }

    public List<Map<String, Object>> getLinkPms(Map params) {
        List<Map<String, Object>> datas = new ArrayList<>();
        String pmRrns = MapUtils.getString(params, "pmRrns");
        List pmRrnList = Arrays.asList(pmRrns.split(","));
        boolean startOrEndFlag = MapUtils.getBooleanValue(params, "startOrEndFlag");
        PmsSchedule schedule = new PmsSchedule();
        schedule.setPmRrnStr(pmRrns);
        List<PmsSchedule> allPmsSchedules = new ArrayList<>();
        List<PmsSchedule> pmsSchedules = pmsService.qryEqptPMInfo(schedule);
        if (startOrEndFlag) {
            //start 查询可以绑定的
            for (PmsSchedule pms : pmsSchedules) {
                schedule = new PmsSchedule();
                schedule.setObjectRrn(pms.getObjectRrn());
                List<PmsSchedule> _pmsSchedulesByEqpt = pmsService.qryEqptPMInfo(schedule);
                _pmsSchedulesByEqpt = _pmsSchedulesByEqpt.stream().filter(pmsScheduleByEqpt -> {
                    //过滤掉自己
                    return !pms.getPmRrn().equals(pmsScheduleByEqpt.getPmRrn());
                }).collect(Collectors.toList());
                allPmsSchedules.addAll(_pmsSchedulesByEqpt);
            }
        } else {
            //end 查询绑定在pm上的
            for (PmsSchedule pms : pmsSchedules) {
                String pmLinks = pms.getPmLinks() == null ? "" : pms.getPmLinks();
                String[] pmRrn = pmLinks.split(",");
                for (String rrn : pmRrn) {
                    if (StringUtils.isNotBlank(rrn)) {
                        PmsSchedule _schedule = pmsService.qryEqptPMInfo(Long.parseLong(rrn));
                        allPmsSchedules.add(_schedule);
                    }
                }
            }
        }
        allPmsSchedules = allPmsSchedules.stream().filter(pmsSchedule -> {
            if (pmsSchedule == null) {
                return false;
            }
            return !pmRrnList.contains(pmsSchedule.getPmRrn().toString());
        }).collect(Collectors.toList());

        HashSet<Long> pmRrnsSet = new HashSet<>(allPmsSchedules.size());//仅用于去重
        for (PmsSchedule _pms : allPmsSchedules) {
            if (pmRrnsSet.add(_pms.getPmRrn())) {
                Map map = new HashMap();
                map.put("key", _pms.getPmRrn());
                map.put("value", _pms.getPmId() + ", (" + _pms.getPmType() + ")");
                datas.add(map);
            }
        }
        return datas;
    }

    public List<Map<String, Object>> getLinkPart(Map params) {
        List<Map<String, Object>> datas = new ArrayList<>();
        String eqptId = MapUtils.getString(params, "eqptId");
        boolean startOrEndFlag = MapUtils.getBooleanValue(params, "startOrEndFlag");

        if (startOrEndFlag){
            return datas;
        }

        Entity entity = new Entity(eqptId, getNamedSpace(ObjectList.ENTITY_KEY, LocalContext.getFacilityRrn()),
                                   ObjectList.ENTITY_KEY);
        entity = (Entity) getInstance(entity);
        Assert.isFalse(entity == null || entity.getInstanceRrn() <=0,
                       Errors.create().key(MessageIdList.EQUIPMENT_MISSING_ID).build());

        List<EquipmentPartRelation> linkList = emsService.getFullRelationForPart(entity.getInstanceRrn(), LinkTypeList.ENTITY_TO_PART);
        for (EquipmentPartRelation r : linkList) {
            Map map = new HashMap();
            map.put("key", r.getToId());
            map.put("value", r.getToId());
            datas.add(map);
        }
        return datas;
    }

    public Page getPmList(PmScheduleForm theform, Map params) {
        setTheForm(theform);

        PmsSchedule schedule = new PmsSchedule();
        int startRow = MapUtils.getIntValue(params, "start");
        int pageSize = MapUtils.getIntValue(params, "limit");
        int thisPage = (startRow / pageSize) + 1;
        Page page = new Page();
        page.setPageNo(thisPage);
        page.setPageSize(pageSize);

        String area = theform.getArea();
        BeanUtils.copyProperties(theform, schedule);
        schedule.setEquipmentLocation(area);
        page = pmsService.qryEqptPMInfo(schedule, page);
        return page;
    }

    //未发现有何意义??
    public List<Map<String, Object>> getPMControlTypes(Map params) {
        String type = MapUtils.getString(params, "type");
        List<Map<String, Object>> datas = new ArrayList<>();
        List<ReferenceFileDetail> c;
        c = sysService.getRefFileValues("$$PM_CONTROL_TYPE", LocalContext.getFacilityRrn());
        for (ReferenceFileDetail r : c) {
            Map<String, Object> data = new HashMap<>();
            data.put("key", r.getKey1Value());
            data.put("value", r.getData1Value());

            if (StringUtils.equalsIgnoreCase(type, "PM_TIME") &&
                    PmControlTypeEnum.PM_TIME.getControlType().equalsIgnoreCase(r.getKey1Value())) {
                //只查PM_TIME
                datas.add(data);
            } else if (StringUtils.equalsIgnoreCase(type, "PM_COUNT") &&
                    PmControlTypeEnum.PM_COUNT.getControlType().equalsIgnoreCase(r.getKey1Value())) {
                //只查PMCOUNT
                datas.add(data);
            } else if (StringUtils.equalsIgnoreCase(type, "ALL")) {
                datas.add(data);
            }
        }
        return datas;
    }

    private ActionForward viewChecklistJobData(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                                               HttpServletResponse response) {
        String checklistJobRrn = request.getParameter("checklistJobRrn");
        List jobDataList = pmsService.qryChecklistJobDataHist(Long.parseLong(checklistJobRrn));
        request.setAttribute("checklistJobRrn", checklistJobRrn);
        request.setAttribute("jobDataListHist", jobDataList);
        return mapping.findForward(CHECKLISTJOBDATAHIST);
    }

    private void setTheForm(PmScheduleForm theform) {
        theform.setObjectId(StringUtils.trimToUpperCase(theform.getObjectId()));
        theform.setCreateUserId(LocalContext.getUserId());
        theform.setCreateUserRrn(LocalContext.getUserRrn());
        theform.setLanguage(I18nUtils.getCurrentLanguage().toString());
    }

    private void modifyPmScheduleCheck(PmScheduleForm theform) {
        double cycleTime = theform.getCycleTime();
        Assert.isFalse(cycleTime <= 0.0D,
                       Errors.create().key(MessageIdList.ENTITYPM_CYCLETIME_ERROR).content("Cycle Time error.")
                             .build());

        double cycleHour = cycleTime * 24;
        double tolerance = theform.getToleranceTime();
        Assert.isFalse(tolerance <= 0.0D,
                       Errors.create().key(MessageIdList.ENTITYPM_TOLERANCE_ERROR).content("Tolerance Time error.")
                             .build());

        Assert.isFalse(cycleHour < tolerance, Errors.create().key(MessageIdList.ENTITYPM_TOLERANCE_LESS_CYCLE)
                                                    .content("Tolerance Time must be less than Cycle Time.").build());

        double duration = theform.getDurationTime();
        Assert.isFalse(duration <= 0.0D,
                       Errors.create().key(MessageIdList.ENTITYPM_DURATION_TIME_ERROR).content("Duration Time error.")
                             .build());

        Assert.isFalse(cycleHour < duration, Errors.create().key(MessageIdList.ENTITYPM_DURATION_LESS_CYCLE)
                                                   .content("Duration Time must be less than Cycle Time.").build());

        String nextPmTimeStr = theform.getNextPmTimeStr();
        String subNextPmTimeStr = theform.getSubNextPmTimeStr();
        Assert.isFalse(StringUtils.isEmpty(nextPmTimeStr) || StringUtils.isEmpty(subNextPmTimeStr),
                       Errors.create().key(MessageIdList.ENTITYPM_NEXT_TIME_MISSING)
                             .content("Next PM Time cannot empty.").build());

        String nextPmTime = nextPmTimeStr + " " + subNextPmTimeStr + ":00";
        Assert.isTrue(pattern.matcher(nextPmTime).matches(),
                      Errors.create().key(MessageIdList.ENTITYPM_NEXT_TIME_FORMAT_ERROR)
                            .content("Next PM Time format error.").build());

        Date nextPmDate = DateUtils.parse(nextPmTime, DateUtils.DATE_FORMAT);
        Assert.isFalse(nextPmDate.getTime() <= System.currentTimeMillis(),
                       Errors.create().key(MessageIdList.ENTITYPM_NEXT_TIME_MORE_CURRENT)
                             .content("Next PM Time must more than the current time.").build());

        pmScheduleCheck(theform);
    }

    private void pmScheduleCheck(PmScheduleForm theform) {
        String comments = theform.getComment();
        Assert.isFalse(comments.length() > 120, Errors.create().key(MessageIdList.ENTITYPM_COMMENTS_LENGTH_MORE_120)
                                                      .content("Comments length  cannot more Than 120.").build());
    }

    private Map<Long, List<PartConsumeDO>> checkPmConsumePart(PmScheduleForm theForm) {
        List<Map> selectPartList = theForm.getPartList();
        Map<Long, List<PartConsumeDO>> consumePartMap = new HashMap<>();
        Map<String, Integer> tempMap = new HashMap<>();

        if (CollectionUtils.isNotEmpty(selectPartList)){
            for (Map m: selectPartList) {
                long pmRrn = MapUtils.getLong(m, "pmRrn", 0L);
                if (pmRrn <=0 ) continue;
                List<PartConsumeDO> pcdl = consumePartMap.getOrDefault(pmRrn, new ArrayList<>());
                PartConsumeDO pc = new PartConsumeDO(pmRrn, MapUtils.getString(m, "pmId"),
                                                     MapUtils.getString(m, "selectPartId"), MapUtils.getInteger(m, "selectPartQty"));
                pcdl.add(pc);
                consumePartMap.put(pc.getConsumePmRrn(), pcdl);
                tempMap.put(pc.getConsumePartId(), tempMap.getOrDefault(pc.getConsumePartId(), 0) + pc.getConsumePartQty());
            }

            for (Map.Entry<String, Integer> part :tempMap.entrySet()){
                MaterialDO material = asmService.getMaterial(LocalContext.getFacilityRrn(), part.getKey());
                Assert.isFalse(material==null || material.getInstanceRrn() <= 0,
                               Errors.create().key(MessageIdList.PART_ID_NOT_EXIST).content("Part ID not exist!").build());
                Integer qty = part.getValue();
                Assert.isFalse(qty == null || qty <= 0, Errors.create().key(MessageIdList.CONSUME_QTY_NOT_EMPTY).content("Please enter the consumption quantity!").build());
                int totalQuantity = asmService.getMaterialTotalQuantity(material.getInstanceRrn());
                int remainQty = totalQuantity - qty ;
                Assert.isFalse(remainQty < 0, Errors.create().key(MessageIdList.PART_INVENTORY_NOT_ENOUGH).content("Insufficient parts inventory, only {} left!").
                        args(material.getInstanceId() + ":" + remainQty).build());
            }
        }
        return consumePartMap;
    }

    private ActionForward history(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                                  HttpServletResponse response) {
        Date startDate = new Date();
        Date endDate = new Date(DateUtils.addTimeByUnit(startDate.getTime(), DateUtils.UNIT_DAY, 1));
        String startDateStr = DateUtils.formatDate(startDate, DateUtils.DATE_FORMAT4DAY);
        String endDateStr = DateUtils.formatDate(endDate, DateUtils.DATE_FORMAT4DAY);

        request.setAttribute("startDate", startDateStr);
        request.setAttribute("endDate", endDateStr);
        request.setAttribute("thisPage", 1);
        request.setAttribute("maxPage", 1);
        request.setAttribute("pageSize", 20);
        request.setAttribute("lastPageSize", 20);
        request.setAttribute("reticleFamilyHist", new ArrayList());
        return mapping.findForward(HISTORY);
    }

    private ActionForward portal(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                                 HttpServletResponse response) {
        return mapping.findForward(PORTAL);
    }

    private void validate4AddPM(Long facilityRrn, PmScheduleForm theform) {
        validateBaseInfo(facilityRrn, theform);
        initScheduleInfo4Add(theform);
        if (PmControlTypeEnum.PM_TIME.name().equalsIgnoreCase(theform.getControlType())) {
            validate4AddPMTime(facilityRrn, theform);
        } else if (PmControlTypeEnum.PM_COUNT.name().equalsIgnoreCase(theform.getControlType())) {
            validate4AddCount(facilityRrn, theform);
        } else if (PmControlTypeEnum.PM_TRIGGER_READING.name().equalsIgnoreCase(theform.getControlType())){
            Assert.isFalse(isExistedPm(theform),
                           Errors.create().key(MessageIdList.ENTITYPM_ITEM_IS_EXISTED).content("PM Item has existed.").build());
            validate4TriggerReading(theform);
        }
    }

    private void validate4TriggerReading(PmScheduleForm theform) {
        String triggerCode = theform.getTriggerCode();
        String triggerCodeSpec = theform.getTriggerCodeSpec();
        String toleranceTrigger = theform.getToleranceOther();
        Assert.isFalse(StringUtils.isEmpty(triggerCode),
                       Errors.create().key(MessageIdList.CAN_NOT_EMPTY).content("{} cannot be empty!").args("TriggerCode").build());
        Assert.isFalse(StringUtils.isEmpty(triggerCodeSpec),
                       Errors.create().key(MessageIdList.CAN_NOT_EMPTY).content("{} cannot be empty!").args("TriggerCodeSpec").build());
        Assert.isFalse(StringUtils.isNotBlank(toleranceTrigger) && !NumberUtils.isNumber(toleranceTrigger),
                       Errors.create().key(MessageIdList.NOT_NUMBER).content("The {} is not number!").args("tolerance trigger").build());
    }

    private void validate4ModifyPM(Long facilityRrn, PmScheduleForm theform) {
        validateBaseInfo(facilityRrn, theform);
        initScheduleInfo4Modify(theform);
        if (PmControlTypeEnum.PM_TIME.name().equalsIgnoreCase(theform.getControlType())) {
            validate4ModifyPMTime(facilityRrn, theform);
        } else if (PmControlTypeEnum.PM_COUNT.name().equalsIgnoreCase(theform.getControlType())){
            validate4ModifyCount(facilityRrn, theform);
        } else if (PmControlTypeEnum.PM_TRIGGER_READING.name().equalsIgnoreCase(theform.getControlType())){
            validate4TriggerReading(theform);
        }
    }

    private void validate4ModifyCount(Long facilityRrn, PmScheduleForm theform) {
        //表中PmType不能为空,赋值ControlType给它
        //theform.setPmType(theform.getControlType());
        /*
        if(isExistedPm(theform)){
            throw new WebException("entitypm.itemId_is_existed", "PM Id has existed.");
        }
        */
        validate4Count(facilityRrn, theform);
    }

    private void validate4ModifyPMTime(Long facilityRrn, PmScheduleForm theform) {
        /*
        if(isExistedPm(theform)){
            throw new WebException("entitypm.itemId_is_existed", "PM Id has existed.");
        }
        */
        validate4PMTime(facilityRrn, theform);
    }

    private void initScheduleInfo4Modify(PmScheduleForm theform) {
        if (StringUtils.isBlank(theform.getNextPmTimeStr())) {
            theform.setNextPmTimeStr("9999/12/12");
            theform.setSubNextPmTimeStr("00:00");
        }
        if (StringUtils.isBlank(theform.getControlType())) {
            theform.setControlType(PmControlTypeEnum.PM_TIME.getControlType());
        }
    }

    private void validate4AddPMTime(Long facilityRrn, PmScheduleForm theform) {
        Assert.isFalse(isExistedPm(theform),
                       Errors.create().key(MessageIdList.ENTITYPM_ITEM_IS_EXISTED).content("PM Item has existed.")
                             .build());
        validate4PMTime(facilityRrn, theform);
    }

    private void validate4PMTime(Long facilityRrn, PmScheduleForm theform) {
        String pmType = theform.getPmType();
        String timeType = theform.getPmTimeType();
        Assert.isFalse(StringUtils.isEmpty(pmType),
                       Errors.create().key(MessageIdList.ENTITYPM_PMTYPE_MISSING).content("PM Type error.").build());

        Assert.isFalse(StringUtils.isEmpty(timeType),
                       Errors.create().key(MessageIdList.ENTITYPM_TIMETYPE_MISSING).content("PM Time Type error.")
                             .build());

        modifyPmScheduleCheck(theform);
    }

    private void validate4AddCount(Long facilityRrn, PmScheduleForm theform) {
        Assert.isFalse(isExistedPm(theform),
                       Errors.create().key(MessageIdList.ENTITYPM_ITEM_IS_EXISTED).content("PM Item has existed.")
                             .build());
        validate4Count(facilityRrn, theform);
    }

    private void validateBaseInfo(Long facilityRrn, PmScheduleForm theform) {
        String objectId = StringUtils.upperCase(StringUtils.trim(theform.getObjectId()));
        theform.setObjectId(objectId);
        long entityRrn = 0L;
        if (StringUtils.isNotEmpty(objectId)) {
            entityRrn = this.getInstanceRrn(objectId, baseService.getNamedSpace(facilityRrn, ObjectList.ENTITY_KEY),
                                            ObjectList.ENTITY_KEY);
        }
        Assert.isFalse(entityRrn <= 0,
                       Errors.create().key(MessageIdList.EQUIPMENT_MISSING).content("equipment not exist").build());

        theform.setObjectRrn(entityRrn);
        Collection status = emsService.getEntityStatuss(entityRrn);
        Assert.isFalse(status.isEmpty(),
                       Errors.create().key(MessageIdList.ENTITYPM_PLEASE_INIT_ENTITY).content("Please Init EQP: {}")
                             .args(objectId).build());

        Assert.isFalse(StringUtils.isBlank(theform.getPmId()),
                       Errors.create().key(MessageIdList.ENTITYPM_PLEASE_INIT_PMID).content("Please Init Pm Id")
                             .build());

        String chamberId = theform.getChamberId();
        if (!StringUtils.equalsIgnoreCase("#", chamberId) && !StringUtils.isEmpty(chamberId)) {
            long chamberRrn = this
                    .getInstanceRrn(chamberId, baseService.getNamedSpace(facilityRrn, ObjectList.ENTITY_KEY),
                                    ObjectList.ENTITY_KEY);
            Assert.isFalse(chamberRrn <= 0,
                           Errors.create().key(MessageIdList.CHAMBER_MISSING).content("CHAMBER not exist").build());
            theform.setChamberRrn(chamberRrn);
            status = emsService.getEntityStatuss(chamberRrn);
            Assert.isFalse(status.isEmpty(),
                           Errors.create().key(MessageIdList.ENTITYPM_PLEASE_INIT_ENTITY).content("Please Init EQP: {}")
                                 .args(objectId).build());
        }

        //判断是否有检查单
        String checklistId = StringUtils.trimToUpperCase(theform.getChecklistId());
        if (StringUtils.isNotEmpty(checklistId)) {
            long checklistRrn = this
                    .getInstanceRrn(checklistId, baseService.getNamedSpace(facilityRrn, ObjectList.CHECKLIST_KEY),
                                    ObjectList.CHECKLIST_KEY);
            Assert.isFalse(checklistRrn < 1,
                           Errors.create().key(MessageIdList.ENTITYPM_INVALID_CHECKLIST).content("无效检查单ID").build());

            theform.setChecklistId(checklistId);
            theform.setChecklistRrn(checklistRrn);//checklistRrn插入db
        }
        //check comments
        pmScheduleCheck(theform);
    }

    private boolean isExistedPm(PmScheduleForm theform) {
        PmsSchedule schedule = new PmsSchedule();
        schedule.setPmId(theform.getPmId());
        List<PmsSchedule> list = pmsService.qryEqptPMInfo(schedule);
        return CollectionUtils.isNotEmpty(list);
    }

    private void initScheduleInfo4Add(PmScheduleForm theform) {
        if (StringUtils.isBlank(theform.getNextPmTimeStr())) {
            theform.setNextPmTimeStr("9999/12/12");
            theform.setSubNextPmTimeStr("00:00");
        }
        if (StringUtils.isBlank(theform.getControlType())) {
            theform.setControlType(PmControlTypeEnum.PM_TIME.getControlType());
        }
    }

    private void validate4Count(Long facilityRrn, PmScheduleForm theform) {
        Assert.isFalse(
                theform.getAlarmCount() == null || theform.getAlarmCount() < 1 || theform.getAlarmCount() > 100000,
                Errors.create().key(MessageIdList.ENTITYPM_ALARM_COUNT_RANGE).content("The alarm count ranges from 1 to 100000!").build());

        if (theform.getTotalCount() != null && theform.getTotalCount() > 0) {
            Assert.isFalse(theform.getTotalCount() > 100000,
                           Errors.create().key(MessageIdList.ENTITYPM_TOTAL_COUNT_RANGE).content("The total count ranges from 1 to 100000!").build());

            Assert.isFalse(theform.getAlarmCount() >= theform.getTotalCount(), Errors.create().key(MessageIdList.ENTITYPM_TOTAL_GREATER_ALARM).content(
                    "The count of alarms must not exceed the count of total!").build());
        }
    }

    private void completeChecklistJob(ChecklistJob checklistJob, Entity entity, Map<Long, ChecklistJob> checklistJobMap) {
        boolean updateFlag = true;
        boolean saveFlag = false;
        StringBuilder errMsg = new StringBuilder();
        List<ChecklistJobData> checklistJobDatas = (List<ChecklistJobData>) checklistJob.getChecklistJobDatas();
        for (ChecklistJobData checklistJobData : checklistJobDatas) {
            String dataValue = checklistJobData.getDataValue();
            if (StringUtils.isBlank(dataValue)) {
                updateFlag = false;
            }
            if (StringUtils.equalsIgnoreCase(checklistJobData.getDataType(), Constants.NUMBER_KEY)) {
                if (checklistJobData.getUpperLimit() < NumberUtils.toDouble(dataValue) ||
                        checklistJobData.getLowerLimit() > NumberUtils.toDouble(dataValue)) {
                    errMsg.append(checklistJob.getChecklistId()+"."+checklistJobData.getChecklistItemId() + " out of range;<br/>");
                    saveFlag = true;
                }
            }
            if (StringUtils.equalsIgnoreCase(checklistJobData.getDataType(), Constants.BOOLEAN_KEY)) {
                if (!StringUtils.equalsIgnoreCase(dataValue, checklistJobData.getBool())) {
                    errMsg.append(checklistJob.getChecklistId()+"."+checklistJobData.getChecklistItemId() + " should take the opposite value;<br/>");
                    saveFlag = true;
                }
            }
        }

        checklistJob.setCompletedTimestamp(new Timestamp(System.currentTimeMillis()));
        checklistJob.setTransPerformedby(LocalContext.getUserId());
        checklistJob.setCompletePerformedBy(LocalContext.getUserId());

        if (!saveFlag && updateFlag && !StringUtils.equalsIgnoreCase(checklistJob.getChecklistJobState(), "COMPLETED")) {
            checklistJob.setChecklistJobState(COMPLETED);
            checklistJob.setTransId(Constants.COMPLETED_KEY);
            emsService.completeChecklistJob(checklistJob, LocalContext.getUserRrn());
        }
        checklistJob.setSaveFlag(saveFlag);
        checklistJob.setErrMsg(errMsg.toString());
        checklistJobMap.put(checklistJob.getChecklistJobRrn(), checklistJob);
    }

    private void updatePmNextTriggerTime(ChecklistJob checklistJob, Entity entity) {
        if (checklistJob.getSequenceNumber() != null && checklistJob.getSequenceNumber() > 0) {
            boolean exist = false;
            List<PmSchedule> pmSchedules = (List<PmSchedule>) entity.getPmschedules();
            PmSchedule pmSchedule = new PmSchedule();
            for (PmSchedule p : pmSchedules) {
                if (p.getSequenceNumber().equals(checklistJob.getSequenceNumber())) {
                    pmSchedule = p;
                    pmSchedule.setEntityRrn(entity.getInstanceRrn());
                    exist = true;
                    break;
                }
            }
            if (exist) {
                if ("1".equalsIgnoreCase(pmSchedule.getBasedOnPmFlag()) ||
                        "Y".equalsIgnoreCase(pmSchedule.getBasedOnPmFlag())) {
                    // to update next pm time
                    pmSchedule = emsService.updateNextPMTime(pmSchedule);
                    checklistJob.setChecklistJobState(STARTED);
                    // to update quartz
                    this.deleteSchedule(pmSchedule, entity);
                    this.addSchedule(pmSchedule, entity, checklistJob);
                } else {
                    // to update repeatquartz
                    if ("0".equals(pmSchedule.getFrequence())) {// 如果频率为0,无下次repeat
                        this.deleteRepeatSchedule(pmSchedule, entity);
                    } else {
                        this.deleteRepeatSchedule(pmSchedule, entity);
                        this.addRepeatSchedule(pmSchedule, entity);
                    }
                }
            }
        }
    }

    public void downloadTemplate(HttpServletRequest request, HttpServletResponse response) throws Exception {

        String type = request.getParameter(Constants.TYPE_KEY);
        if (StringUtils.equalsIgnoreCase(type, Constants.BY_TIME_KEY)) {
            String fileName = "pm_time_template-version.xlsx";
            WebUtils.exportExcel(fileName, new HashMap<>(), new ArrayList<>(), TemplateLocation.PM_TIME_IMPORT_TEMPLATE, 1, 1,
                                 response);
        }
        if (StringUtils.equalsIgnoreCase(type, Constants.BY_COUNT_KEY)){
            String fileName = "pm_count_template-version.xlsx";
            WebUtils.exportExcel(fileName, new HashMap<>(), new ArrayList<>(), TemplateLocation.PM_COUNT_IMPORT_TEMPLATE, 1, 1,
                                 response);
        }
    }

    public ActionForward exportQuery(PmScheduleForm theform, HttpServletRequest request, HttpServletResponse response) throws Exception{
        setTheForm(theform);
        PmsSchedule schedule = new PmsSchedule();
        Page page = new Page();
        page.setPageNo(1);
        page.setPageSize(9999);

        String area = theform.getArea();
        BeanUtils.copyProperties(theform, schedule);
        schedule.setEquipmentLocation(area);
        page = pmsService.qryEqptPMInfo(schedule, page);
        List<PmsSchedule> list = (ArrayList)page.getResults();
        long i = 1;
        for (PmsSchedule pmsSchedule : list) {
            pmsSchedule.setSeq(i++);
            pmsSchedule.setNextPmTimeStr(DateUtils.formatDate(pmsSchedule.getNextPmTime()));
        }
        Map<String, Object> titles = WebUtils.getExportTitles(request);
        titles.put("title","Pm Info");
        String fileName = "Pm_Info_" +DateUtils.getNowTime(DateUtils.DATE_FORMAT4NOSPLICING)+ ".xlsx";
        WebUtils.exportExcel(fileName, titles, list, TemplateLocation.PM_INFO, response);
        return WebUtils.NULLActionForward;
    }

    public ActionForward importPm(PmScheduleForm theform, HttpServletRequest request, HttpServletResponse response) throws IOException {
        FormFile formFile = theform.getFormFile();
        String type = theform.getType();
        Assert.isFalse(!StringUtils.endsWith(formFile.getFileName(), ".xlsx") || formFile.getFileSize() < 1,
                       Errors.create().key(MessageIdList.IMPORT_ERROR_NAME).content("Only import .xlsx files!").build());
        List<PmScheduleForm> list = new ArrayList<>();
        if (StringUtils.equalsIgnoreCase(type, Constants.BY_TIME_KEY)) {
            Assert.isFalse(!StringUtils.startsWith(formFile.getFileName(), PmControlTypeEnum.PM_TIME.getControlType().toLowerCase()) ,
                           Errors.create().key(MessageIdList.IMPORT_ERROE_TYPE).content("Please select the template type to import!").build());
            list = this.setPmTimeExcelData(formFile);

        }

        if (StringUtils.equalsIgnoreCase(type, Constants.BY_COUNT_KEY)) {
            Assert.isFalse(!StringUtils.startsWith(formFile.getFileName(), PmControlTypeEnum.PM_COUNT.getControlType().toLowerCase()) ,
                           Errors.create().key(MessageIdList.IMPORT_ERROE_TYPE).content("Please select the template type to import!").build());
            list = this.setPmCountExcelData(formFile);
        }
        Set<String> set = new HashSet<>();
        Boolean saveFlag = true;
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0 ; i < list.size() ; i++) {
            set.add(list.get(i).getPmId());
            Integer rowNum = i + 1;
            if (!list.get(i).getErrMsg().isEmpty()){
                saveFlag = false;
                stringBuilder.append("Row Num "+rowNum+": </br>").append(list.get(i).getErrMsg());
            }
        }
        if (set.size() < list.size() && list.size() > 0) {
            saveFlag = false;
            stringBuilder.append(StringUtils.equalsIgnoreCase(list.get(0).getLanguage(), "EN") ?
                                         "Import PM Item must not be repeated!<br/>" : "Import PM Item 不能重复!<br/>");
        }
        if (saveFlag) {
            for (PmScheduleForm pmScheduleForm : list) {
                PmsSchedule schedule = new PmsSchedule();
                String nextPmTimeStr = pmScheduleForm.getNextPmTimeStr()+ " " + pmScheduleForm.getSubNextPmTimeStr() + ":00";
                BeanUtils.copyProperties(pmScheduleForm, schedule);
                Date nextPmTime = DateUtils.parse(nextPmTimeStr, DateUtils.DATE_FORMAT);
                schedule.setNextPmTime(nextPmTime);
                schedule.setObjectType("EQPT");
                schedule.setCreateUserId(LocalContext.getUserId());
                schedule.setCreateDate(new Date());
                if (StringUtils.isEmpty(schedule.getChamberId())) {
                    schedule.setChamberId("#");
                }
                pmsService.addPmSchedule(schedule);//TODO
            }
        } else {
            Assert.isFalse(true , Errors.create().content(stringBuilder.toString()).build());
        }
        return WebUtils.NULLActionForward;
    }

    private List<PmScheduleForm> setPmTimeExcelData(FormFile formFile) throws IOException {
        List<PmScheduleForm> results = new ExcelImport().attributeFrom(0).attributeTo(0).tableFrom(1).mapper(new ExcelParser<Object, PmScheduleForm>() {
            @Override
            public Object attributeMapper(List<ExcelRow> attributeRows, int attributeFrom, int attributeTo) {
                return null;
            }

            @Override
            public PmScheduleForm tableRowMapper(ExcelRow excelRow, int rowNum, Object attributeDatas) {
                if (StringUtils.isNotBlank(excelRow.getString(0))) {
                    PmScheduleForm pmScheduleForm = new PmScheduleForm();
                    pmScheduleForm.setPmId(excelRow.getString(0));
                    pmScheduleForm.setObjectId(excelRow.getString(1));
                    pmScheduleForm.setPmType(excelRow.getString(2));
                    pmScheduleForm.setCycleTime(NumberUtils.toDouble(excelRow.getString(3)));
                    pmScheduleForm.setPmItemDesc(excelRow.getString(4));
                    pmScheduleForm.setChecklistId(excelRow.getString(5));
                    pmScheduleForm.setToleranceTime(NumberUtils.toDouble(excelRow.getString(6)));
                    pmScheduleForm.setDurationTime(NumberUtils.toDouble(excelRow.getString(7)));
                    pmScheduleForm.setNextPmTimeStr(excelRow.getString(8));
                    pmScheduleForm.setSubNextPmTimeStr(excelRow.getString(9));
                    pmScheduleForm.setPmTimeType(excelRow.getString(10));
                    pmScheduleForm.setItemStatus(excelRow.getString(11));
                    pmScheduleForm.setAutoEqpStatus(excelRow.getString(12));
                    pmScheduleForm.setComment(excelRow.getString(13));
                    pmScheduleForm.setControlType(PmControlTypeEnum.PM_TIME.getControlType());
                    setTheForm(pmScheduleForm);
                    pmScheduleForm.setPmId(pmScheduleForm.getPmId().trim());
                    validateImp4PmTimeOrPmCount(LocalContext.getFacilityRrn(), pmScheduleForm);
                    return pmScheduleForm;
                } else {
                    return null;
                }

            }



        }).file(formFile.getInputStream()).getTableDataList();
        return results;
    }

    private List<PmScheduleForm> setPmCountExcelData(FormFile formFile) throws IOException {
        List<PmScheduleForm> results = new ExcelImport().attributeFrom(0).attributeTo(0).tableFrom(1).mapper(new ExcelParser<Object, PmScheduleForm>() {
            @Override
            public Object attributeMapper(List<ExcelRow> attributeRows, int attributeFrom, int attributeTo) {
                return null;
            }

            @Override
            public PmScheduleForm tableRowMapper(ExcelRow excelRow, int rowNum, Object attributeDatas) {
                if (StringUtils.isNotBlank(excelRow.getString(0))) {
                    PmScheduleForm pmScheduleForm = new PmScheduleForm();
                    pmScheduleForm.setPmId(excelRow.getString(0));
                    pmScheduleForm.setObjectId(excelRow.getString(1));
                    pmScheduleForm.setPmType(excelRow.getString(2));
                    pmScheduleForm.setPmItemDesc(excelRow.getString(3));
                    pmScheduleForm.setChecklistId(excelRow.getString(4));
                    pmScheduleForm.setTotalCount(Double.valueOf(excelRow.getString(5)).intValue());
                    pmScheduleForm.setAlarmCount(Double.valueOf(excelRow.getString(6)).intValue());
                    pmScheduleForm.setItemStatus(excelRow.getString(7));
                    pmScheduleForm.setAutoEqpStatus(excelRow.getString(8));
                    pmScheduleForm.setComment(excelRow.getString(9));
                    pmScheduleForm.setControlType(PmControlTypeEnum.PM_COUNT.getControlType());
                    setTheForm(pmScheduleForm);
                    pmScheduleForm.setPmId(pmScheduleForm.getPmId().trim());
                    validateImp4PmTimeOrPmCount(LocalContext.getFacilityRrn(), pmScheduleForm);
                    return pmScheduleForm;
                }else {
                    return null;
                }
            }

        }).file(formFile.getInputStream()).getTableDataList();
        return results;
    }

    private void validateImpBaseInfo(Long facilityRrn, PmScheduleForm pmScheduleForm, StringBuilder stringBuilder) {
        String objectId = StringUtils.upperCase(StringUtils.trim(pmScheduleForm.getObjectId()));
        pmScheduleForm.setObjectId(objectId);
        long entityRrn = 0L;
        if (StringUtils.isNotEmpty(objectId)) {
            entityRrn = this.getInstanceRrn(objectId, baseService.getNamedSpace(facilityRrn, ObjectList.ENTITY_KEY),
                                            ObjectList.ENTITY_KEY);
        }
        if(entityRrn <= 0) {
            stringBuilder.append(I18nUtils.getMessage(MessageIdList.EQUIPMENT_MISSING,"equipment not exist!"));
            stringBuilder.append("<br/>");
        }

        pmScheduleForm.setObjectRrn(entityRrn);
        Collection status = emsService.getEntityStatuss(entityRrn);

        if (status.isEmpty() && entityRrn>1) {
            stringBuilder.append(I18nUtils.getMessage(MessageIdList.ENTITYPM_PLEASE_INIT_ENTITY,"Please Init EQP: {}!",objectId));
            stringBuilder.append("<br/>");
        }
        if (StringUtils.isBlank(pmScheduleForm.getPmId())) {
            stringBuilder.append(I18nUtils.getMessage(MessageIdList.ENTITYPM_PLEASE_INIT_PMID,"Please Init Pm Id!"));
            stringBuilder.append("<br/>");
        }
        String chamberId = pmScheduleForm.getChamberId();
        if (!StringUtils.equalsIgnoreCase("#", chamberId) && !StringUtils.isEmpty(chamberId)) {
            long chamberRrn = this
                    .getInstanceRrn(chamberId, baseService.getNamedSpace(facilityRrn, ObjectList.ENTITY_KEY),
                                    ObjectList.ENTITY_KEY);
            if (chamberRrn <= 0) {
                stringBuilder.append(I18nUtils.getMessage(MessageIdList.CHAMBER_MISSING,"CHAMBER not exist!"));
                stringBuilder.append("<br/>");
            }
            pmScheduleForm.setChamberRrn(chamberRrn);
            status = emsService.getEntityStatuss(chamberRrn);
            if (status.isEmpty()) {
                stringBuilder.append(I18nUtils.getMessage(MessageIdList.ENTITYPM_PLEASE_INIT_ENTITY,"Please Init EQP: {}!",objectId));
                stringBuilder.append("<br/>");
            }
        }

        //判断是否有检查单
        String checklistId = StringUtils.trimToUpperCase(pmScheduleForm.getChecklistId());
        if (StringUtils.isNotEmpty(checklistId)) {
            long checklistRrn = this
                    .getInstanceRrn(checklistId, baseService.getNamedSpace(facilityRrn, ObjectList.CHECKLIST_KEY),
                                    ObjectList.CHECKLIST_KEY);

            if (checklistRrn < 1) {
                stringBuilder.append(I18nUtils.getMessage(MessageIdList.ENTITYPM_INVALID_CHECKLIST,"Invalid checklist ID!"));
                stringBuilder.append("<br/>");
            }

            pmScheduleForm.setChecklistId(checklistId);
            pmScheduleForm.setChecklistRrn(checklistRrn);//checklistRrn插入db
        }
        //check comments
        String comments = pmScheduleForm.getComment();
        if (comments.length() > 120) {
            stringBuilder.append(I18nUtils.getMessage(MessageIdList.ENTITYPM_COMMENTS_LENGTH_MORE_120,"Comments length cannot more than 120."));
            stringBuilder.append("<br/>");
        }
    }

    private void validateImp4PmTimeOrPmCount(Long facilityRrn, PmScheduleForm pmScheduleForm) {
        StringBuilder stringBuilder = new StringBuilder();
        validateImpBaseInfo(facilityRrn,pmScheduleForm, stringBuilder);
        initScheduleInfo4Add(pmScheduleForm);
        if (isExistedPm(pmScheduleForm)) {
            stringBuilder.append(I18nUtils.getMessage(MessageIdList.ENTITYPM_ITEM_IS_EXISTED,"PM Item has existed."));
            stringBuilder.append("<br/>");
        }

        if (StringUtils.equalsIgnoreCase(pmScheduleForm.getControlType(), PmControlTypeEnum.PM_TIME.getControlType())) {
            if (pmScheduleForm.getPmType().isEmpty()) {
                stringBuilder.append(I18nUtils.getMessage(MessageIdList.ENTITYPM_PMTYPE_MISSING,"PM Type error."));
                stringBuilder.append("<br/>");
            }
            if(pmScheduleForm.getPmTimeType().isEmpty()) {
                stringBuilder.append(I18nUtils.getMessage(MessageIdList.ENTITYPM_TIMETYPE_MISSING,"PM Time Type error."));
                stringBuilder.append("<br/>");
            }

            String nextPmTimeStr = pmScheduleForm.getNextPmTimeStr();
            double cycleTime = pmScheduleForm.getCycleTime();
            String pmType = pmScheduleForm.getPmType();
            if (StringUtils.equalsIgnoreCase(pmType, Constants.DAYS_KEY)) {
                pmScheduleForm.setCycleTime(cycleTime);
            }
            if (StringUtils.equalsIgnoreCase(pmType, Constants.WEEKLY_KEY)) {
                pmScheduleForm.setCycleTime(7D);
            }
            if (StringUtils.equalsIgnoreCase(pmType, Constants.QUARTERLY_KEY)) {
                pmScheduleForm.setCycleTime(90D);
            }
            if (StringUtils.equalsIgnoreCase(pmType, Constants.SEMIANNUAL_KEY)) {
                pmScheduleForm.setCycleTime(180D);
            }
            if (StringUtils.equalsIgnoreCase(pmType, Constants.ANNUAL_KEY)) {
                pmScheduleForm.setCycleTime(365D);
            }

            if (StringUtils.equalsIgnoreCase(pmType, Constants.MONTHLY_KEY)) {
                String month = nextPmTimeStr.substring(5,7);
                long year = NumberUtils.toLong(nextPmTimeStr.substring(0,4));
                String[] arr = new String[]{"01", "03", "05", "07", "08", "10", "12"};
                if (Arrays.asList(arr).contains(month)) {
                    pmScheduleForm.setCycleTime(31D);
                } else if(StringUtils.equalsIgnoreCase(month, "02")){
                    if((year % 4 == 0 && year % 100!=0) || year % 400 == 0) {
                        pmScheduleForm.setCycleTime(29D);
                    } else {
                        pmScheduleForm.setCycleTime(28D);
                    }
                } else {
                    pmScheduleForm.setCycleTime(30D);
                }
            }
            if (pmScheduleForm.getCycleTime() <= 0.0D) {
                stringBuilder.append(I18nUtils.getMessage(MessageIdList.ENTITYPM_CYCLETIME_ERROR,"Cycle Time error."));
                stringBuilder.append("<br/>");
            }

            double cycleHour = pmScheduleForm.getCycleTime()  * 24;
            double tolerance = pmScheduleForm.getToleranceTime();
            if (tolerance <= 0.0D) {
                stringBuilder.append(I18nUtils.getMessage(MessageIdList.ENTITYPM_TOLERANCE_ERROR,"Tolerance Time error."));
                stringBuilder.append("<br/>");
            }
            if (cycleHour < tolerance) {
                stringBuilder.append(I18nUtils.getMessage(MessageIdList.ENTITYPM_TOLERANCE_LESS_CYCLE,"Tolerance Time must be less than Cycle Time."));
                stringBuilder.append("<br/>");
            }

            double duration = pmScheduleForm.getDurationTime();
            if (duration <= 0.0D) {
                stringBuilder.append(I18nUtils.getMessage(MessageIdList.ENTITYPM_DURATION_TIME_ERROR,"Duration Time error."));
                stringBuilder.append("<br/>");
            }
            if (cycleHour < duration) {
                stringBuilder.append(I18nUtils.getMessage(MessageIdList.ENTITYPM_DURATION_LESS_CYCLE,"Duration Time must be less than Cycle Time."));
                stringBuilder.append("<br/>");
            }

            String subNextPmTimeStr = pmScheduleForm.getSubNextPmTimeStr();
            if (StringUtils.isEmpty(nextPmTimeStr) || StringUtils.isEmpty(subNextPmTimeStr)) {
                stringBuilder.append(I18nUtils.getMessage(MessageIdList.ENTITYPM_NEXT_TIME_MISSING,"Next PM Time cannot empty."));
                stringBuilder.append("<br/>");
            }
            String nextPmTime = nextPmTimeStr + " " + subNextPmTimeStr + ":00";
            if (!pattern.matcher(nextPmTime).matches()) {
                stringBuilder.append(I18nUtils.getMessage(MessageIdList.ENTITYPM_NEXT_TIME_FORMAT_ERROR,"Next PM Time format error."));
                stringBuilder.append("<br/>");
            }
            Date nextPmDate = DateUtils.parse(nextPmTime, DateUtils.DATE_FORMAT);
            if (nextPmDate.getTime() <= System.currentTimeMillis()) {
                stringBuilder.append(I18nUtils.getMessage(MessageIdList.ENTITYPM_NEXT_TIME_MORE_CURRENT,"Next PM Time must be greater than or equal to the current time."));
                stringBuilder.append("<br/>");
            }

        }

        if (StringUtils.equalsIgnoreCase(pmScheduleForm.getControlType(), PmControlTypeEnum.PM_COUNT.getControlType())) {

            if (pmScheduleForm.getAlarmCount() == null || pmScheduleForm.getAlarmCount() < 1
                    || pmScheduleForm.getAlarmCount() > 100000) {
                stringBuilder.append(I18nUtils.getMessage(MessageIdList.ENTITYPM_TOTAL_COUNT_RANGE,"The alarm count ranges from 1 to 100000!"));
                stringBuilder.append("<br/>");
            }

            if (pmScheduleForm.getTotalCount() != null && pmScheduleForm.getTotalCount() > 0) {

                if (pmScheduleForm.getTotalCount() > 100000) {
                    stringBuilder.append(I18nUtils.getMessage(MessageIdList.ENTITYPM_ALARM_COUNT_RANGE ,"The total count ranges from 1 to 100000!"));
                    stringBuilder.append("<br/>");
                }
                if (pmScheduleForm.getAlarmCount() >= pmScheduleForm.getTotalCount()) {
                    stringBuilder.append(I18nUtils.getMessage(MessageIdList.ENTITYPM_TOTAL_GREATER_ALARM ,"The count of alarms must not exceed the count of total!"));
                    stringBuilder.append("<br/>");
                }

            }
        }
        pmScheduleForm.setErrMsg(stringBuilder.toString());
    }

}