LogEventByStationSaveAction.java

package com.mycim.webapp.actions.logevent;

import com.fa.sesa.exception.Assert;
import com.fa.sesa.exception.Errors;
import com.fa.sesa.threadlocal.LocalContext;
import com.mycim.framework.utils.lang.StringUtils;
import com.mycim.framework.utils.lang.time.DateUtils;
import com.mycim.valueobject.MessageIdList;
import com.mycim.valueobject.ObjectList;
import com.mycim.valueobject.alm.EenAction;
import com.mycim.valueobject.alm.EenMessage;
import com.mycim.valueobject.bas.RelationEventModle;
import com.mycim.valueobject.consts.EenActionType;
import com.mycim.valueobject.consts.SessionNames;
import com.mycim.valueobject.ems.Entity;
import com.mycim.valueobject.ems.EntityStatus;
import com.mycim.valueobject.ems.Event;
import com.mycim.valueobject.ems.EventModel;
import com.mycim.valueobject.prp.ContextValue;
import com.mycim.valueobject.security.Station;
import com.mycim.valueobject.security.User;
import com.mycim.valueobject.sys.ReferenceFileDetail;
import com.mycim.webapp.Constants;
import com.mycim.webapp.WebUtils;
import com.mycim.webapp.actions.EmsSetupAction;
import com.mycim.webapp.forms.LogEventInfoForm;
import org.apache.commons.beanutils.PropertyUtils;
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.util.*;

/**
 * 按工作站变更设备状态
 *
 * @author weike.li
 * @date 2019/8/23
 * @since 1.8
 **/
public class LogEventByStationSaveAction extends EmsSetupAction {

    public static final String DUMMY_FLAG = "dummyFlag";

    public static final String LOT_STATUS = "lotStatus";

    public static final String LOG_EVENT_KEY = "LOG_EVENT";

    public static final String MAINT_TO_QC = "DD.MAINT_TO_QC";

    public static final String NUM_ONE = "1";

    private static final String NUM_TWO = "2";

    private static final String WORKFLOW = "workflow";

    private static final String SUCESS = "sucess";

    private static final String LOGEQPTEVENT = "logeqptevent";

    @Override
    public ActionForward init(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                              HttpServletResponse response) throws Exception {
        LogEventInfoForm theform = (LogEventInfoForm) form;
        return query(mapping, theform, request);
    }

    public ActionForward query(ActionMapping mapping, LogEventInfoForm theform,
                               HttpServletRequest request) throws Exception {
        Long facilityRrn = LocalContext.getFacilityRrn();
        Event event = new Event();
        Station station = new Station();
        String stationId = WebUtils.getParameterUpperCase("stationId", request);
        request.setAttribute("entityId", stationId);
        String fmbFlag = request.getParameter("fmbFlag");
        request.setAttribute("fmbFlag", fmbFlag);
        String eventId = theform.getEventId().trim().toUpperCase();
        station = new Station(stationId, getNamedSpace(ObjectList.STATION_KEY, facilityRrn), ObjectList.STATION_KEY);
        event = new Event(eventId, getNamedSpace(ObjectList.EVENT_KEY, facilityRrn), ObjectList.EVENT_KEY);
        station = securityService.getStation(station);
        Long eventRrn = null;

        eventRrn = new Long(
                getInstanceRrn(eventId, getNamedSpace(ObjectList.EVENT_KEY, facilityRrn), ObjectList.EVENT_KEY));
        event.setInstanceRrn(eventRrn.longValue());


        List events = new ArrayList();
        if (event.getInstanceRrn() == 0) {
            theform.setTransId(Constants.CREATE_KEY);
        } else {
            events = baseService.getEvents(event.getInstanceRrn());

            if (events.size() < 1) {
            } else {
                event = (Event) events.iterator().next();
                PropertyUtils.copyProperties(theform, event);
            }
        }

        if (station == null) {
            station = new Station();
            station.setInstanceRrn(0);
        }
        List<RelationEventModle> equipments = securityService
                .getEquipmentOfStation(station.getInstanceRrn(), eventRrn.longValue());
        station.setEquipments(equipments);
        station.setOperations(securityService.getOperationOfStation(station.getInstanceRrn()));
        station.setUsers(securityService.getUserOfStation(station.getInstanceRrn()));

        theform.setEntityNamedSpace(station.getNamedSpace());

        theform.setEntityDesc(station.getInstanceDesc());

        request.setAttribute(SessionNames.STATION_KEY, station);
        request.setAttribute(SessionNames.EVENT_KEY, event);
        theform.setEventNamedSpace(event.getNamedSpace());
        theform.setEventId(event.getInstanceId());
        theform.setEventRrn(event.getInstanceRrn());
        theform.setEventDesc(event.getInstanceDesc());
        theform.setStatusEndTime(DateUtils.formatDate(new Date(), DateUtils.DATE_FORMAT));
        theform.setValidAvailability(event.getValidAvailability());
        theform.setValidAvailabilityHidden(sysService.referenceDetailExchangeNull("$$VALID_AVAILABILITY",
                                                                                  event.getValidAvailability(),
                                                                                  "data_1_value"));

        theform.setTargetAvailabilityHidden(
                (event.getTargetAvailability() == null) ? "0" : event.getTargetAvailability());

        if (NUM_TWO.equalsIgnoreCase(theform.getTargetAvailabilityHidden())) {
            theform.setTargetAvailabilityHidden(theform.getAvailabilityHidden());
        } else {
            theform.setTargetAvailabilityHidden(sysService.referenceDetailExchangeNull("$$TARGET_AVAILABILITY",
                                                                                       theform.getTargetAvailabilityHidden(),
                                                                                       "data_1_value"));
        }
        request.setAttribute("entityType", request.getParameter("entityType"));

        return mapping.findForward(Constants.MODIFY_KEY);

    }

    public ActionForward modify(ActionMapping mapping, LogEventInfoForm theform,
                                HttpServletRequest request) throws Exception {
        String user = LocalContext.getUserId();
        Long userRrn = LocalContext.getUserRrn();
        long facilityRrn = LocalContext.getFacilityRrn();
        String stationId = request.getParameter("stationId");
        Entity entity = null;
        Station station = new Station(stationId, getNamedSpace(ObjectList.STATION_KEY, facilityRrn),
                                      ObjectList.STATION_KEY);
        station = securityService.getStation(station);
        if (station == null) {
            station = new Station();
            station.setInstanceRrn(0);
        }

        String eventNamedSpace = baseService.getNamedSpace(facilityRrn, ObjectList.EVENT_KEY);
        Event oldEvent = new Event(theform.getEventId(), eventNamedSpace, ObjectList.EVENT_KEY);
        Event event = baseService.getEvent(oldEvent);
        List<RelationEventModle> equipments = securityService
                .getEquipmentOfStation(station.getInstanceRrn(), event.getInstanceRrn());
        station.setEquipments(equipments);
        station.setOperations(securityService.getOperationOfStation(station.getInstanceRrn()));
        station.setUsers(securityService.getUserOfStation(station.getInstanceRrn()));
        if (event == null) {
            return mapping.findForward(Constants.LOGIN_KEY);
        }

        String comment = theform.getComment();
        String comment1 = theform.getComment1();
        String comment2 = theform.getComment2();
        String eventId = theform.getEventId();

        if (MAINT_TO_QC.equals(eventId)) {
            Assert.isFalse("".equalsIgnoreCase(comment) || comment == null || "".equalsIgnoreCase(comment1) ||
                                   comment1 == null || "".equalsIgnoreCase(comment2) || comment2 == null,
                           Errors.create().key(MessageIdList.EQUIPMENT_MEASURES_MUST_BE_ENTERED)
                                 .content("维修人员,故障现象,处置措施 必须填写!").build());
        }

        Assert.isFalse("".equalsIgnoreCase(comment) || comment == null,
                       Errors.create().key(MessageIdList.EQUIPMENT_MISSING_COMMENT).content("备注不能为空").build());

        for (int i = 1; i < station.getEquipments().size(); i++) {
            if (request.getParameter("checkbox" + i) != null) {
                String oldEntityId = request.getParameter("entityId" + i);
                entity = new Entity(oldEntityId, getNamedSpace(ObjectList.ENTITY_KEY, facilityRrn),
                                    ObjectList.ENTITY_KEY);
                entity = emsService.getEntity(entity);
                if ("initialize".equalsIgnoreCase(eventId.trim()) || "init_rtl".equalsIgnoreCase(eventId.trim()) ||
                        "init".equalsIgnoreCase(eventId.trim())) {
                    myprocess(new Long(entity.getInstanceRrn()), entity.getObjectType(),
                              new Long(event.getInstanceRrn()), user);

                    if ("transaction".equals(theform.getTransId())) {
                        HashMap parameters = (HashMap) request.getAttribute(SessionNames.PARAMETERSINFO_KEY);

                        Assert.isFalse(parameters == null,
                                       Errors.create().key(MessageIdList.EQUIPMENT_MISSING_PARAMETER).content("缺少参数")
                                             .build());

                        parameters.put(SessionNames.RUNSTEP_FLAG, "0");

                        return mapping.findForward(WORKFLOW);
                    } else {
                    }
                }
                List<EventModel> eventStatus = baseService
                        .getEventModels(event.getInstanceRrn(), entity.getInstanceRrn());
                for (EventModel object : eventStatus) {
                    List list = new ArrayList();
                    object.setTargetStatusList(list);
                }

                event.setEventModels(eventStatus);

                Collection eventModels = event.getEventModels();

                Iterator it = eventModels.iterator();
                int j = 0;
                List entityStatuss = new ArrayList();
                while (it.hasNext()) {
                    EventModel instance = (EventModel) it.next();
                    EntityStatus entityStatus = new EntityStatus();
                    entityStatus.setStatusGroupId(instance.getStatusGroupId());
                    entityStatus.setCurrentStatus(theform.getTargetStatus()[j++]);
                    entityStatus.setStatusBefore(instance.getCurrentStatus());
                    entityStatus.setEntityRrn(entity.getInstanceRrn());
                    entityStatuss.add(entityStatus);
                }

                Assert.isFalse(entityStatuss.size() < 1,
                               Errors.create().key(MessageIdList.EQUIPMENT_MISSING_EVENT_MODEL).content("未定义事件模型")
                                     .build());

                String validAvailability = theform.getAvailability();

                String validAvailabilityHidden = theform.getAvailabilityHidden();

                if (validAvailability != null && !"2".equalsIgnoreCase(validAvailability)) {

                    Collection cascadingEvent = (Collection) request.getAttribute("cascadingEvent");

                    if (cascadingEvent != null && cascadingEvent.size() > 0) {
                        Iterator cascading = cascadingEvent.iterator();
                        while (cascading.hasNext()) {
                            HashMap map = (HashMap) cascading.next();

                            String temp = (String) map.get("availability");
                            Assert.isFalse(temp != null && !temp.equalsIgnoreCase(validAvailabilityHidden),
                                           Errors.create().key(MessageIdList.EQUIPMENT_CHECK_STATUS).content("请检查{}的状态")
                                                 .build());
                        }
                    }
                }

                if (entity != null) {

                    if ("REGULAR PROD".equalsIgnoreCase(eventId)) {
                        if (checkRunningJobByEqpt(entity.getInstanceRrn()) &&
                                ("1").equalsIgnoreCase(entity.getAvailability())) {
                            // "1"-->"REGULAR PROD" target availability
                        } else {
                            myProcess(entityStatuss, user, event, theform.getComment(), theform.getComment1(),
                                      theform.getComment2(), theform.getStatusEndTime(), entity);
                        }
                    } else if ("END PROD".equalsIgnoreCase(eventId)) {
                        if ("4".equalsIgnoreCase(entity.getAvailability()) ||
                                checkRunningJobByEqpt(entity.getInstanceRrn())) {
                            // "4"-->"END PROD" target availability
                        } else {
                            myProcess(entityStatuss, user, event, theform.getComment(), theform.getComment1(),
                                      theform.getComment2(), theform.getStatusEndTime(), entity);
                        }
                    } else {
                        myProcess(entityStatuss, user, event, theform.getComment(), theform.getComment1(),
                                  theform.getComment2(), theform.getStatusEndTime(), entity);
                    }
                }

                String message = updateWorkStream(entity, event, facilityRrn, user);

                Assert.isFalse(message != null, Errors.create().content(message).build());

                handleFutureAction4Eqpt(entity, event, "LOGEVENT", facilityRrn, userRrn, theform);

                if ("transaction".equals(theform.getTransId())) {
                    HashMap parameters = (HashMap) request.getAttribute(SessionNames.PARAMETERSINFO_KEY);


                    Assert.isFalse(parameters == null,
                                   Errors.create().key(MessageIdList.EQUIPMENT_MISSING_PARAMETER).content("缺少参数")
                                         .build());

                    parameters.put(SessionNames.RUNSTEP_FLAG, "0");

                    return mapping.findForward(WORKFLOW);
                } else {
                    theform.setEntityId("");
                    theform.setEventId("");
                    String availability = "";
                    List entityStatus = emsService.getEntityStatuss(entity.getInstanceRrn());
                    availability = emsService.getEntityAvailability(entity.getInstanceRrn());
                    request.setAttribute("availability", availability);
                    // 设备组内设备down,系统自动hold lot
                    EntityStatus es = (EntityStatus) entityStatus.iterator().next();
                    entity.setCurrentStatus(es.getCurrentStatus());
                    List<ReferenceFileDetail> eqptHoldInfos = sysService
                            .getRefFileValues("$$EQUP_LOT_HOLD_STATUS", facilityRrn);
                    for (ReferenceFileDetail eqptHoldInfo : eqptHoldInfos) {
                        if (StringUtils.equals(entity.getCurrentStatus(), eqptHoldInfo.getKey1Value())) {
                            String holdReason = eqptHoldInfo.getData2Value();
                            String holdReasonCode = eqptHoldInfo.getData1Value();
                            if (StringUtils.isBlank(holdReasonCode)) {
                                holdReasonCode = "EQPTDOWNHOLD";
                                eqptHoldInfo.setData1Value(holdReasonCode);
                            }
                            if (StringUtils.isBlank(holdReason)) {
                                holdReason = "THE EQUIPMENTS ALL DOWN";
                                eqptHoldInfo.setData2Value(holdReason);
                            }
                            handleLotsByEqptDown(entity, eqptHoldInfo, eqptHoldInfos);
                        }
                    }

                    request.setAttribute("entitystatus", entityStatus);
                    request.removeAttribute("NEXT_KEY");
                }
            }
        }
        return mapping.findForward(SUCESS);
    }

    public ActionForward cancel(ActionMapping mapping, HttpServletRequest request) {

        request.removeAttribute(SessionNames.ENTITY_KEY);
        request.removeAttribute(SessionNames.EVENT_KEY);
        request.removeAttribute(SessionNames.OPTIONS_KEY);
        request.removeAttribute(SessionNames.ENTITY_KEY);

        return mapping.findForward(LOGEQPTEVENT);
    }

    private String updateWorkStream(Entity entity, Event event, Long facility, String user) {
        String message = "";

        HashMap map = new HashMap(10);

        List status = new ArrayList();

        map.put("status", status);

        entity.setAvailability("");

        map.put("entity", entity);
        map.put("event", event);
        map.put("wsname", "logEvent");
        message = connectMesSystem(map, facility.longValue(), user);

        return message;
    }

    private void myProcess(List entityStatuss, String user, Event event, String comments, String comments1,
                           String comments2, String statusEndTime, Entity entity) {
        if (statusService.checkEnableLogEvent(event.getInstanceRrn(), entity.getInstanceRrn())) {
            HashMap map = new HashMap(15);
            map.put("event", event);
            map.put("user", user);
            map.put("comments", comments);
            map.put("comments1", comments1);
            map.put("comments2", comments2);
            map.put("statusEndTime", statusEndTime);
            map.put("entityrrn", new Long(entity.getInstanceRrn()));
            statusService.updateEntityStatus(entityStatuss, map);
            if (entity.getParentEntityRrn() != null && entity.getParentEntityRrn().intValue() > 0) {
                Iterator it = entityStatuss.iterator();
                entityStatuss = new ArrayList();
                while (it.hasNext()) {
                    EntityStatus entityStatus = (EntityStatus) it.next();
                    entityStatus.setEntityRrn(entity.getParentEntityRrn().longValue());
                    entityStatuss.add(entityStatus);
                }
                map.put("entityrrn", new Long(entity.getParentEntityRrn().longValue()));
                statusService.updateEntityStatus(entityStatuss, map);

            }
        }

    }

    private void handleFutureAction4Eqpt(Entity entity, Event event, String actionPoint, long facilityRrn, Long userRrn,
                                         LogEventInfoForm theform) throws Exception {
        if (StringUtils.equals(event.getNoticeLotEngineer(), NUM_ONE)) {
            User user = new User();
            user.setInstanceRrn(userRrn.longValue());
            //todo email重做
            //            EmailMessage emailMessage = buildEmail(entity, securityService.getUser(user),
            //            theform, event);
            //            alarmService.insertAlarmEmailMessag(emailMessage);
        }
        ContextValue actionCondition = new ContextValue();
        actionCondition.setContextRrn(
                getInstanceRrn("EEN_CONTEXT_EQPT", getNamedSpace(ObjectList.CONTEXT_KEY, new Long(facilityRrn)),
                               ObjectList.CONTEXT_KEY));

        actionCondition.setContextKey1(entity.getInstanceId());
        actionCondition.setContextKey2(event.getInstanceId());
        actionCondition.setContextKey3(actionPoint);

        List<EenAction> actions = wipQueryService.getFutureActions(actionCondition, facilityRrn);

        for (EenAction eenAction : actions) {
            if (eenAction.getActionType() == null) {
                continue;
            }

            if (EenActionType.SEND_EMAIL_KEY.equals(eenAction.getActionType())) {

                Map fromUserInfo = securityService.getUserInfo4Alarm(userRrn.longValue());

                Map toUserInfo = new HashMap(20);

                if (!"Current Operator".equals(eenAction.getParameterValue1())) {
                    toUserInfo = securityService
                            .getUserInfo4Alarm(new Long(eenAction.getParameterValue1()).longValue());
                    if (toUserInfo == null) {
                        toUserInfo = securityService
                                .getUserInfo4AlarmByUserGroup(new Long(eenAction.getParameterValue1()).longValue());
                    }

                } else {
                    toUserInfo = fromUserInfo;
                }

                String subject = "";
                String content = "";

                if (eenAction.getParameterValue2() != null) {
                    long msg = new Long(eenAction.getParameterValue2()).longValue();
                    EenMessage e = alarmService.getEenMessage(new EenMessage(msg));
                    subject = entity.getInstanceId() + e.getMessageSubject();
                    content = e.getMessageText();
                }

                HashMap values = new HashMap(10);

                values.put("from", fromUserInfo.get("emailAddress"));
                values.put("to", toUserInfo.get("emailAddress"));
                values.put("subject", subject);
                values.put("content", content);

                //todo email重做
                //sysService.sendMail(values);
            }

        }
    }

    private boolean checkRunningJobByEqpt(long eqptRrn) {
        return emsService.checkRunningJobByEqpt(eqptRrn);
    }

    protected void myprocess(Long entityRrn, String entityType, Long eventRrn, String user) {

        emsService.initializeEntityStatus(entityRrn, entityType, eventRrn, user, new HashMap(15));

    }

}