EquipmentSaveAction.java

package com.mycim.webapp.actions.equipment;

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.BooleanUtils;
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.time.DateUtils;
import com.mycim.valueobject.MessageIdList;
import com.mycim.valueobject.ObjectList;
import com.mycim.valueobject.SystemConstant;
import com.mycim.valueobject.bas.Relation;
import com.mycim.valueobject.consts.EventName;
import com.mycim.valueobject.consts.LinkTypeList;
import com.mycim.valueobject.consts.ReferenceDetailNames;
import com.mycim.valueobject.consts.SessionNames;
import com.mycim.valueobject.ems.EmployeeCertification;
import com.mycim.valueobject.ems.Entity;
import com.mycim.valueobject.ems.EntityGroup;
import com.mycim.valueobject.ems.Equipment;
import com.mycim.valueobject.prp.EquipmentConstrainInfo;
import com.mycim.webapp.Constants;
import com.mycim.webapp.WebUtils;
import com.mycim.webapp.actions.EmsSetupAction;
import com.mycim.webapp.forms.EntityInfoForm;
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.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 设备定义 -> saveAction
 *
 * @author pinyan song
 * @version 6.0.0
 * @date 2019-8-29
 **/
public class EquipmentSaveAction extends EmsSetupAction {
    private static final String CHAMBER_FLAG = "_";

    @Override
    public ActionForward init(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                              HttpServletResponse response) throws Exception {
        EntityInfoForm theForm = (EntityInfoForm) form;
        theForm.setInstanceId(StringUtils.trim(theForm.getInstanceId()));

        if (StringUtils.isEmpty(theForm.getInstanceId())) {
            request.setAttribute("childChambers", new ArrayList<Entity>());
            theForm.setTransId(Constants.INIT_KEY);
            return new ActionForward(mapping.getInputForward());
        }

        Entity entity = getEntityInfo(theForm);
        if (StringUtils.isNotEmpty((String) entity.getPollutionLevel())) {
            theForm.setIsPlOpen(MiscUtils.changeCheckBox("1"));
        }
        PropertyUtils.copyProperties(theForm, entity);
        if (entity.getInstanceRrn() == 0) {
            // 创建
            theForm.setTransId(Constants.CREATE_KEY);

            verifyId(entity.getInstanceId());

            // 设置默认选中事件集
            setAllowableEventsId(theForm);

            String id = entity.getInstanceId();

            // 根据id判断是否存在父类 例子:test_1->test
            isExistParentAndProcess(theForm, id);
        } else {
            // 修改
            theForm.setTransId(Constants.MODIFY_KEY);

            setEquipmentExt(theForm, entity, false);

            Assert.isTrue(StringUtils.isEqual(entity.getObjectType(), ObjectList.EQUIPMENT_KEY),
                          Errors.create().key(MessageIdList.EQUIPMENT_NOT_EQUIPMENT).content("It is not equipment!")
                                .build());
        }

        refreshData(theForm, entity, request);

        return mapping.findForward(Constants.MODIFY_KEY);
    }

    /**
     * 删除设备组
     */
    public ActionForward deleteEqptGroup(ActionMapping mapping, ActionForm form, HttpServletRequest request) {
        EntityInfoForm theForm = (EntityInfoForm) form;
        Entity entity = getEntityInfo(theForm);
        EntityGroup entityGroup = new EntityGroup();

        entityGroup.setInstanceRrn(WebUtils.getParameterInt("itemRrn", request));
        entityGroup = (EntityGroup) getInstance(entityGroup);

        emsService.removeEntityFromGroup(entityGroup.getInstanceRrn(), entity.getInstanceRrn());
        // 刷新数据
        entity = getEntityInfo(theForm);
        theForm.setTransId(Constants.MODIFY_KEY);
        refreshData(theForm, entity, request);
        WebUtils.setSuccessMsg(request);
        return new ActionForward(mapping.getInputForward());
    }

    public ActionForward eqptwheretouse(ActionMapping mapping, ActionForm form, HttpServletRequest request) {
        EntityInfoForm theform = (EntityInfoForm) form;
        Entity entity = getEntityInfo(theform);

        PropertyUtils.copyProperties(theform, entity);

        if (StringUtils.isNotBlank(request.getParameter("equipmentReadOnlyFlag"))) {
            request.setAttribute("equipmentReadOnlyFlag", 1);
        }

        request.setAttribute("eqptGroupLists", entity.getEntitieGroups());
        return mapping.findForward("eqptwheretouse");
    }

    /**
     * 删除设备
     *
     * @param mapping mapping
     * @param form    form
     * @return ActionForward
     */
    public ActionForward delete(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                                HttpServletResponse response) throws Exception {
        EntityInfoForm theForm = (EntityInfoForm) form;
        verifyId(theForm.getInstanceId());

        Entity entity = getEntityInfo(theForm);

        Assert.isFalse(entity.getInstanceRrn() == 0,
                       Errors.create().key(MessageIdList.EQUIPMENT_MISSING).content("equipment not exist").build());

        entity.setTransId(Constants.DELETE_KEY);

        verifyEntityIsExit(entity);

        Equipment equipment = new Equipment();
        PropertyUtils.copyProperties(equipment, entity);
        equipment.setObjectType(ObjectList.EQUIPMENT_KEY);
        equipment.setTransId(Constants.DELETE_KEY);

        boolean isChamberEquipment =
                BooleanUtils.toBoolean(equipment.getIsChamberEquip()) || equipment.getParentEntityRrn() == null ||
                        equipment.getParentEntityRrn() == 0;

        Long deleteEntityRrn = isChamberEquipment ? equipment.getInstanceRrn() : equipment.getParentEntityRrn();

        emsService.deleteChamberEquipmentRelation(isChamberEquipment, deleteEntityRrn, equipment.getChamberType());
        process(equipment);

        entity = new Entity();
        theForm = new EntityInfoForm();
        theForm.setTransId(Constants.CREATE_KEY);
        request.setAttribute(mapping.getAttribute(), theForm);
        WebUtils.setSuccessMsg(request);
        return init(mapping, theForm, request, response);
    }

    /**
     * 保存设备
     *
     * @param mapping mapping
     * @param form    form
     * @param request request
     * @return action
     */
    public ActionForward modify(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                                HttpServletResponse response) throws Exception {
        EntityInfoForm theform = (EntityInfoForm) form;
        verifyId(theform.getInstanceId());
        Entity entity = getEntityInfo(theform);
        //检查描述字符的长度是否超过数据库对应字段的长度
        Assert.isTrue(
                new String(theform.getInstanceDesc().getBytes(StandardCharsets.UTF_8), "ISO8859_1").length() <= 128,
                Errors.create().key(MessageIdList.EQUIPMENT_DESC_LONGER).content("Description should smaller than 128!")
                      .build());

        Assert.isFalse(entity.getInstanceRrn() == 0,
                       Errors.create().key(MessageIdList.EQUIPMENT_MISSING).content("equipment not exist").build());
        // modify之前的chamber mode
        String chamberMode = entity.getChamberMode();
        // Chamber Mode为OFF状态,chamberMode:"",""字符串添加到oracle数据库,再取出来,将为null
        if (StringUtils.isBlank(chamberMode)) {
            chamberMode = "";
        }
        theform.setInstanceStatus(entity.getInstanceStatus());
        if (StringUtils.isNotEmpty((String) entity.getPollutionLevel())) {
            theform.setIsPlOpen(MiscUtils.changeCheckBox("1"));
        }
        PropertyUtils.copyProperties(entity, theform);

        setEntityProperty(entity, theform);

        entity.setEntitystatuss(emsService.getEntityStatuss(entity.getInstanceRrn()));


        boolean isChamberEquipment = BooleanUtils.toBoolean(entity.getIsChamberEquip());
        boolean isChangeMode =
                isChamberEquipment && !StringUtils.equalsIgnoreCase(chamberMode, entity.getChamberMode());

        if (isChangeMode) {
            // 修改chamber mode需要校验
            isAllowChangeChamberMode(entity.getInstanceRrn(), entity.getInstanceId());
        }

        List<Entity> childs = emsService.getChildChamberEquip(entity.getInstanceRrn());
        for (Entity chamber : childs) {
            chamber.setParentEntityRrn(entity.getInstanceRrn());
            List<String> values = sysService.getRefFileKey(ReferenceDetailNames.CHAMBER_TYPE,
                                                           chamber.getChamberType().trim());
            String chamberkey = values.get(0);
            emsService.updateParentEntity(entity.getInstanceRrn(), chamber.getInstanceRrn());
            emsService.updateChamberType(chamber.getInstanceRrn(), chamberkey);
        }

        List<Entity> childChambers = emsService.getChildChamberEquipByFormat(entity.getInstanceRrn());
        for (Entity chamber : childChambers) {
            chamber.setTransId(Constants.MODIFY_KEY);
            chamber.setTransPerformedby(LocalContext.getUserId());
            emsService.chamberExtendFileFromPentity(chamber, entity);
        }

        // checkEntityLocation实体位置检查
        long entityRRN = emsService.checkEntityLocation(theform.getEntityLocation());
        long checkEntityRRN = entity.getInstanceRrn();
        Assert.isFalse(entityRRN != checkEntityRRN && entityRRN != 0,
                       Errors.create().key(MessageIdList.LOCALTION_IS_USED).content("The selected location is in use!")
                             .build());

        entity.setTransId(Constants.MODIFY_KEY);
        entity.setTransPerformedby(LocalContext.getUserId());

        Equipment equipment = emsService.getEquipment(entity.getInstanceRrn());
        PropertyUtils.copyProperties(equipment, entity);
        equipment.setObjectType(ObjectList.EQUIPMENT_KEY);
        equipment.setTransId(Constants.MODIFY_KEY);
        String equipmentLocation = theform.getEquipmentLocation();
        String equipmentOwner = theform.getEquipmentOwner();
        String QCEngineerId = theform.getQCEngineerId();
        String PMEngineerId = theform.getPMEngineerId();
        String equipmentWph = theform.getEquipmentWph();
        String equipmentModel = theform.getEquipmentModel();
        String pollutionLevel = theform.getPollutionLevel();
        equipment.setEquipmentLocation(equipmentLocation);
        equipment.setEquipmentOwner(equipmentOwner);
        equipment.setEquipmentWph(equipmentWph);
        equipment.setEquipmentModel(equipmentModel);
        equipment.setPMEngineerId(PMEngineerId);
        equipment.setQCEngineerId(QCEngineerId);
        equipment.setPollutionLevel(pollutionLevel);
        equipment.setNeedReticleFlag(MiscUtils.parseCheckBox(theform.getNeedReticleFlag()));
        equipment.setSorterFlag(MiscUtils.parseCheckBox(theform.getSorterFlag()));
        equipment.setWetFlag(MiscUtils.parseCheckBox(theform.getWetBatchFlag()));
        process(equipment);

        saveDefaultEquipmentConstrain(entity);

        updateChamberAndParentEquipmentInfo(chamberMode, equipment);

        emsService.updateEquipmentDiffFlag(entity.getInstanceRrn(), MiscUtils.parseCheckBox(theform.getDiffFlag()));

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

    /**
     * 添加 设备组
     */
    public ActionForward addEqptGroup(ActionMapping mapping, ActionForm form, HttpServletRequest request) {
        EntityInfoForm theForm = (EntityInfoForm) form;
        Entity entity = getEntityInfo(theForm);
        String groupId = theForm.getEntityGroupId();

        Assert.isFalse(StringUtils.isEmpty(groupId),
                       Errors.create().key(MessageIdList.ENTITY_MISSING_ENGINEER_ID).content("Missing EQP group id!")
                             .build());

        EntityGroup entityGroup = new EntityGroup(groupId, getNamedSpace(ObjectList.ENTITYGROUP_KEY,
                                                                         LocalContext.getFacilityRrn()),
                                                  ObjectList.ENTITYGROUP_KEY);

        entityGroup = (EntityGroup) getInstance(entityGroup);
        Assert.isFalse(null == entityGroup,
                       Errors.create().key(MessageIdList.ENTITYGROUP_INVALID_ID).content("Invalid EQP group id!")
                             .build());

        List<Relation> entities = emsService.getAllEntities(entityGroup.getInstanceRrn());

        Relation parentRelation = null;
        if (CollectionUtils.isNotEmpty(entities)) {
            parentRelation = checkAndQueryParentEntity(entities, entity, theForm, entityGroup);
        } else {
            parentRelation = getParentRelation(entity, entityGroup);
        }
        emsService.addEntityToEntityGroup(entityGroup.getInstanceRrn(), entity.getInstanceRrn());

        if (parentRelation != null) {
            Relation tmp = baseService.getRelation(parentRelation);
            if (tmp == null || tmp.getFromRrn() <= 0) {
                emsService.addEntityToEntityGroup(parentRelation.getToRrn(), parentRelation.getFromRrn());
            }
        }

        // 刷新数据并返回
        entity = getEntityInfo(theForm);
        theForm.setTransId(Constants.MODIFY_KEY);
        refreshData(theForm, entity, request);
        theForm.setEntityGroupId(StringUtils.EMPTY);

        WebUtils.setSuccessMsg(request);
        return new ActionForward(mapping.getInputForward());
    }

    public ActionForward create(ActionMapping mapping, ActionForm form, HttpServletRequest request) throws Exception {
        String user = LocalContext.getUserId();
        EntityInfoForm theForm = (EntityInfoForm) form;
        verifyId(theForm.getInstanceId());
        Assert.isTrue(
                new String(theForm.getInstanceDesc().getBytes(StandardCharsets.UTF_8), "ISO8859_1").length() <= 128,
                Errors.create().key(MessageIdList.EQUIPMENT_DESC_LONGER).content("Description should smaller than 128!")
                      .build());
        Entity entity = getEntityInfo(theForm);

        PropertyUtils.copyProperties(entity, theForm);

        setEntityProperty(entity, theForm);

        entity.setTransId(Constants.CREATE_KEY);

        Equipment equipment = new Equipment();
        PropertyUtils.copyProperties(equipment, entity);
        equipment.setObjectType(ObjectList.EQUIPMENT_KEY);
        equipment.setCreatedUserId(user);
        String _eqptId = entity.getInstanceId();
        if (StringUtils.equals(CHAMBER_FLAG, _eqptId.substring(_eqptId.length() - 2, _eqptId.length() - 1))) {
            String peqptId = _eqptId.substring(0, _eqptId.length() - 2);
            long _pentityRrn = this.getInstanceRrn(peqptId,
                                                   getNamedSpace(ObjectList.ENTITY_KEY, LocalContext.getFacilityRrn()),
                                                   ObjectList.ENTITY_KEY);
            Assert.isFalse(_pentityRrn <= 0, Errors.create().key(MessageIdList.EQUIPMENT_MISSING_PARENT)
                                                   .content("Please add maintool {} first!").args(peqptId).build());

            equipment.setParentEntityRrn(_pentityRrn);
            equipment.setParentEntityId(peqptId);
        }

        setEquipmentProperty(equipment, theForm);

        process(equipment);

        boolean isChamberEquipment = BooleanUtils.toBoolean(equipment.getIsChamberEquip());

        emsService.addChamberEquipmentRelation(isChamberEquipment, equipment.getInstanceId(),
                                               equipment.getInstanceRrn());
        Long copyEntityRrn = theForm.getCopyInstanceRrn();
        if (copyEntityRrn != null && copyEntityRrn > 0) {
            addRecipeFromCopyEquipment(equipment.getInstanceRrn(), copyEntityRrn,theForm.getReason());
        }
        saveDefaultEquipmentConstrain(entity);

        entity = getEntityInfo(theForm);
        carrySationInfoFromParentEqpt(entity);

        emsService.updateEquipmentDiffFlag(entity.getInstanceRrn(), MiscUtils.parseCheckBox(theForm.getDiffFlag()));

        refreshData(theForm, entity, request);
        theForm.setTransId(Constants.MODIFY_KEY);

        WebUtils.setSuccessMsg(request);
        return mapping.findForward(Constants.MODIFY_KEY);
    }

    public ActionForward copy(ActionMapping mapping, ActionForm form, HttpServletRequest request) throws Exception {
        EntityInfoForm theForm = (EntityInfoForm) form;
        verifyId(theForm.getInstanceId());

        Entity entity = getEntityInfo(theForm);

        String id = request.getParameter(Constants.COPY_KEY);

        Entity copyEntity = new Entity(id, getNamedSpace(ObjectList.ENTITY_KEY, LocalContext.getFacilityRrn()),
                                       ObjectList.ENTITY_KEY);
        copyEntity = (Entity) getInstance(copyEntity);

        doCopy(theForm, copyEntity);

        setEquipmentExt(theForm, copyEntity, true);

        theForm.setTransId(Constants.CREATE_KEY);
        refreshData(theForm, entity, request);
        return (mapping.findForward(Constants.MODIFY_KEY));
    }

    private void updateChamberAndParentEquipmentInfo(String chamberMode, Equipment equipment) {
        boolean isChamberEquipment = BooleanUtils.toBoolean(equipment.getIsChamberEquip());

        emsService.addChamberEquipmentRelation(isChamberEquipment, equipment.getInstanceId(),
                                               equipment.getInstanceRrn());

        boolean isChangeMode =
                isChamberEquipment && !StringUtils.equalsIgnoreCase(chamberMode, equipment.getChamberMode());
        if (isChangeMode) {
            emsService.deleteRelationAllWhenModifyChamberMode(equipment.getInstanceRrn());
        }
    }

    private void isAllowChangeChamberMode(long entityRrn, String entityId) {
        Assert.isTrue(securityService.isHasBtnPermission(LocalContext.getUserRrn(),
                                                         com.mycim.valueobject.consts.Constants.BUTTON_ID.CHANGE_CHAMBER_MODE_BTN),
                      Errors.create().key(MessageIdList.EQUIPMENT_USER_NOT_HAVE_PERMISSIONS)
                            .content("Cannot modify chamber mode, the current user has no permissions!").build());

        Assert.isFalse(StringUtils.isEqual(emsService.getEntityCurrentStatus(entityRrn), EventName.RUN),
                       Errors.create().key(MessageIdList.EQUIPMENT_NOT_MODIFY_BECAUSE)
                             .content("Cannot modify chamber mode, the EQP status is {}").args(EventName.RUN).build());

        Assert.isFalse(CollectionUtils.isNotEmpty(emsService.getRunLotByEqpt(entityRrn)),
                       Errors.create().key(MessageIdList.EQUIPMENT_NOT_MODIFY_BECAUSE)
                             .content("Cannot modify chamber mode, the EQP status is {}").args(EventName.RUN).build());
    }

    private void setEquipmentProperty(Equipment equipment, EntityInfoForm theForm) {
        String equipmentLocation = theForm.getEquipmentLocation();
        String equipmentOwner = theForm.getEquipmentOwner();
        String PMEngineerId = theForm.getPMEngineerId();
        String QCEngineerId = theForm.getQCEngineerId();
        String equipmentWph = theForm.getEquipmentWph();
        String equipmentModel = theForm.getEquipmentModel();
        String pollutionLevel = theForm.getPollutionLevel();

        equipment.setEquipmentLocation(equipmentLocation);
        equipment.setEquipmentOwner(equipmentOwner);
        equipment.setPMEngineerId(PMEngineerId);
        equipment.setQCEngineerId(QCEngineerId);
        equipment.setEquipmentWph(equipmentWph);
        equipment.setProcessingBatchType("L");
        equipment.setProcessingBatchSizeMin(1L);
        equipment.setProcessingBatchSizeMax(99L);
        equipment.setProcessingBatchSizeAvg(1L);
        equipment.setConcurrentJobSize(99L);
        equipment.setEquipmentModel(equipmentModel);
        equipment.setPollutionLevel(pollutionLevel);
        equipment.setNeedReticleFlag(MiscUtils.parseCheckBox(theForm.getNeedReticleFlag()));
        equipment.setSorterFlag(MiscUtils.parseCheckBox(theForm.getSorterFlag()));
        equipment.setWetFlag(MiscUtils.parseCheckBox(theForm.getWetBatchFlag()));
    }

    private void setEntityProperty(Entity entity, EntityInfoForm theForm) {
        if (StringUtils.isNotEmpty(theForm.getRoleId())) {
            entity.setRoleRrn(baseService.getNamedObjectRrn(theForm.getRoleId(), getNamedSpace(ObjectList.ROLE_KEY,
                                                                                               LocalContext.getFacilityRrn()),
                                                            ObjectList.ROLE_KEY));
        }

        // 事件集合
        if (StringUtils.isNotEmpty(theForm.getAllowableEventsId())) {
            entity.setAllowableEventsRrn(baseService.getNamedObjectRrn(theForm.getAllowableEventsId(),
                                                                       getNamedSpace(ObjectList.ALLOWABLEEVENTSET_KEY,
                                                                                     LocalContext.getFacilityRrn()),
                                                                       ObjectList.ALLOWABLEEVENTSET_KEY));
        }
        // 工程师组
        if (StringUtils.isNotEmpty(theForm.getMaintenanceEngineerId())) {
            entity.setMaintenanceEngineerRrn(baseService.getNamedObjectRrn(theForm.getMaintenanceEngineerId(),
                                                                           getNamedSpace(ObjectList.USERGROUP_KEY,
                                                                                         LocalContext.getFacilityRrn()),
                                                                           ObjectList.USERGROUP_KEY));
        }
        // 父设备
        if (StringUtils.isNotEmpty(theForm.getParentEntityId())) {
            entity.setParentEntityRrn(baseService.getNamedObjectRrn(theForm.getParentEntityId(),
                                                                    getNamedSpace(ObjectList.ENTITY_KEY,
                                                                                  LocalContext.getFacilityRrn()),
                                                                    ObjectList.ENTITY_KEY, ObjectList.EQUIPMENT_KEY));
        }
    }

    /**
     * 判断是否存在父类,并处理
     *
     * @param id 设备ID
     */
    private void isExistParentAndProcess(EntityInfoForm theForm, String id) {
        if (StringUtils.equals(CHAMBER_FLAG, id.substring(id.length() - 2, id.length() - 1))) {
            String parentId = id.substring(0, id.length() - 2);

            Entity parentEntity = new Entity(parentId,
                                             getNamedSpace(ObjectList.ENTITY_KEY, LocalContext.getFacilityRrn()),
                                             ObjectList.ENTITY_KEY);

            parentEntity = (Entity) getInstance(parentEntity);

            Assert.isFalse(parentEntity == null, Errors.create().key(MessageIdList.EQUIPMENT_MISSING_PARENT)
                                                       .content("Please add maintool {} first!").args(parentId)
                                                       .build());
            theForm.setObjectSubtype(parentEntity.getObjectSubtype());
            theForm.setParentEntityId(parentId);
            theForm.setEquipmentLocation(
                    MapUtils.getString(emsService.getEquipmentExtMap(parentEntity.getInstanceRrn()),
                                       "equipmentLocation"));
            theForm.setMaintenanceEngineerId(parentEntity.getMaintenanceEngineerId());
        }
    }

    /**
     * 设置默认允许事件集
     */
    private void setAllowableEventsId(EntityInfoForm theForm) {
        Map objectInfo = baseService.getObjectInfoMap(
                getNamedSpace(ObjectList.ALLOWABLEEVENTSET_KEY, LocalContext.getFacilityRrn()),
                ObjectList.MAIN_ALLOWABLE_EVENTS, ObjectList.ALLOWABLEEVENTSET_KEY, ObjectList.EQUIPMENT_KEY);
        if (MapUtils.isNotEmpty(objectInfo)) {
            theForm.setAllowableEventsId(MapUtils.getString(objectInfo, "INSTANCEID"));
        }
    }

    private void refreshData(EntityInfoForm theForm, Entity entity, HttpServletRequest request) {
        request.setAttribute(SessionNames.ENTITY_KEY, entity);

        List childs = emsService.getChildChamberEquip(entity.getInstanceRrn());
        if (CollectionUtils.isEmpty(childs)) {
            childs = new ArrayList();
        }
        request.setAttribute("childChambers", childs);

        if (StringUtils.isNotBlank(request.getParameter("equipmentReadOnlyFlag"))) {
            request.setAttribute("equipmentReadOnlyFlag", 1);
        }

        if (entity.getParentEntityRrn() != null && entity.getParentEntityRrn() != 0) {
            theForm.setParentEntityId(getInstanceId(entity.getParentEntityRrn()));
        }
    }

    Entity getEntityInfo(EntityInfoForm form) {
        Entity entity = new Entity(form.getInstanceId(),
                                   getNamedSpace(ObjectList.ENTITY_KEY, LocalContext.getFacilityRrn()),
                                   ObjectList.ENTITY_KEY);

        Entity result = (Entity) getInstance(entity);

        if (result == null) {
            entity.setTransPerformedby(LocalContext.getUserId());
            return entity;
        } else {
            result.setTransPerformedby(LocalContext.getUserId());
            result.setDefaultEquipConstrain(qryDefaultEquipmentConstrain(result));
            result.setEntitieGroups(emsService.getEqptGroupLists(result.getInstanceRrn()));
            return result;
        }

    }

    /**
     * 查询缺省机限 - 目前前端已经隐藏
     */
    private String qryDefaultEquipmentConstrain(Entity entity) {
        String defaultEquipConstrain = "";
        EquipmentConstrainInfo equipmentConstrainInfo = buildDefaultEquipmentConstrain(entity);
        equipmentConstrainInfo = constrainService.getEquipmentConstrainInfo(equipmentConstrainInfo, false);
        if (equipmentConstrainInfo != null &&
                StringUtils.equals(equipmentConstrainInfo.getConstrainStatus(), EquipmentConstrainInfo.ENABLE)) {
            defaultEquipConstrain = equipmentConstrainInfo.getConstrainAction();
        }
        return defaultEquipConstrain;
    }

    private EquipmentConstrainInfo buildDefaultEquipmentConstrain(Entity entity) {
        EquipmentConstrainInfo equipmentConstrainInfo = new EquipmentConstrainInfo();
        equipmentConstrainInfo.setEquipmentId(entity.getInstanceId());
        equipmentConstrainInfo.setCreateBy(LocalContext.getUserId());
        equipmentConstrainInfo.setFacilityRrn(LocalContext.getFacilityRrn());
        equipmentConstrainInfo.setConstrainType("0");
        equipmentConstrainInfo.setConstrainRule(EquipmentConstrainInfo.EQUIPMENT_RULE);
        equipmentConstrainInfo.setConstrainSeq("-100");
        equipmentConstrainInfo.setConstrainStatus(EquipmentConstrainInfo.ENABLE);
        equipmentConstrainInfo.setConstrainAction(entity.getDefaultEquipConstrain());
        equipmentConstrainInfo.setATTRIBUTE_DATA1("SYSTEM SET UP");
        equipmentConstrainInfo.setRemark("System set the default constrain.");
        return equipmentConstrainInfo;
    }

    private void verifyEntityIsExit(Entity entity) {
        List<Relation> exitedEntityGroup = emsService.getEqptGroupLists(entity.getInstanceRrn());
        Assert.isFalse(CollectionUtils.isNotEmpty(exitedEntityGroup),
                       Errors.create().key(MessageIdList.EQUIPMENT_HAS_ENTITYGROUP).content(
                                     "Can not delete! Because " + "this equipment exists " + "in" + " Equipment Group.")
                             .build());

        List<Relation> exitedStation = emsService.getEquipmentOfStation(entity.getInstanceRrn());
        Assert.isFalse(CollectionUtils.isNotEmpty(exitedEntityGroup),
                       Errors.create().key(MessageIdList.EQUIPMENT_EXISTS_IN_STATION)
                             .content("Can not delete! Because " + "this equipment exists " + "in" + " Station.")
                             .build());

        List<EmployeeCertification> exitedEmployeeCertification = emsService.getEmployeeCertifications(
                LocalContext.getUserRrn(), entity.getMaintenanceEngineerId(), null, entity.getInstanceId());
        Assert.isFalse(CollectionUtils.isNotEmpty(exitedEmployeeCertification),
                       Errors.create().key(MessageIdList.EQUIPMENT_EXISTS_IN_OPERATOR).content(
                               "Can not delete! " + "Because this " + "equipment " + "exists in " + "operator " +
                                       "license.").build());

        Assert.isFalse(emsService.isEqptInJob(entity.getInstanceId()),
                       Errors.create().key(MessageIdList.EQUIPMENT_EXISTS_IN_JOB)
                             .content("Can not delete! Because " + "this equipment exists " + "in Job.").build());

        if (!StringUtils.equals(CHAMBER_FLAG, entity.getInstanceId().substring(entity.getInstanceId().length() - 2,
                                                                               entity.getInstanceId().length() - 1))) {
            List chamber = emsService.getChildChamberEquip(entity.getInstanceRrn());
            Assert.isFalse(chamber != null && chamber.size() > 0,
                           Errors.create().key(MessageIdList.EQUIPMENT_HAS_CHAMBERS).content(
                                   "Can not delete! Because this " + "equipment has chamber " +
                                           "equipment,Please delete " + "chamber " + "first!").build());
        }

    }

    /**
     * 校验 ID
     *
     * @param id 设备ID
     */
    private void verifyId(String id) {
        Assert.isFalse(StringUtils.isNotEmpty(id) && id.length() <= 1,
                       Errors.create().key(MessageIdList.EQUIPMENT_ID_LENGTH_MUST_GREATER_1)
                             .content("The length of the EQP id " + "must be greater than 1!").build());

        Assert.isFalse(StringUtils.isEmpty(id), Errors.create().key(MessageIdList.EQUIPMENT_ENTER_THE_EQP_ID)
                                                      .content("Please enter or confirm the current EQP id!").build());

        Assert.isFalse(id.length() > 64, Errors.create().key(MessageIdList.EQUIPMENT_ID_LENGTH_EXCEED_64)
                                               .content("EQP ID length cannot exceed 64!").build());
    }

    private Relation checkAndQueryParentEntity(List<Relation> entities, Entity entity, EntityInfoForm theForm,
                                               EntityGroup entityGroup) {
        boolean grpIsChamgberGrp = false;
        for (Relation r : entities) {
            Map grpEntityExtMap = emsService.getEquipmentExtMap(r.getInstanceRrn());
            if (StringUtils.equalsIgnoreCase("on", MapUtils.getString(grpEntityExtMap, "isChamberEquip"))) {
                grpIsChamgberGrp = true;
                break;
            }
        }

        boolean isChamberEquip = false;
        Map thisEntityExtMap = emsService.getEquipmentExtMap(entity.getInstanceRrn());
        if (StringUtils.equalsIgnoreCase(StringUtils.STRING_ON,
                                         MapUtils.getString(thisEntityExtMap, "isChamberEquip")) ||
                StringUtils.equalsIgnoreCase(StringUtils.STRING_ON, theForm.getIsChamberEquip())) {
            isChamberEquip = true;
        }

        Relation parentRelation = getParentRelation(entity, entityGroup);
        if (parentRelation != null) {
            isChamberEquip = true;
        }

        Assert.isFalse(isChamberEquip && !grpIsChamgberGrp,
                       Errors.create().key(MessageIdList.CHAMBER_FORBID_PUT_GRP).content("chamber不能放进此设备组").build());

        Assert.isFalse(!isChamberEquip && grpIsChamgberGrp,
                       Errors.create().key(MessageIdList.ENTITYGROUP_PUT_CHAMBER_EQP).content("此设备组应该放进chamber中")
                             .build());
        return parentRelation;
    }

    private Relation getParentRelation(Entity entity, EntityGroup entityGroup) {
        Relation parentRelation = null;
        Map thisEntityExtMap = emsService.getEquipmentExtMap(entity.getInstanceRrn());
        if (MapUtils.getLongValue(thisEntityExtMap, "parentEqptRrn") > 0) {
            Map parentEquipMap = emsService.getEquipmentExtMap(
                    MapUtils.getLongValue(thisEntityExtMap, "parentEqptRrn"));
            if (StringUtils.equalsIgnoreCase(StringUtils.STRING_ON,
                                             MapUtils.getString(parentEquipMap, "isChamberEquip"))) {
                parentRelation = new Relation();
                parentRelation.setFromRrn(MapUtils.getLong(thisEntityExtMap, "parentEqptRrn"));
                parentRelation.setToRrn(entityGroup.getInstanceRrn());
                parentRelation.setLinkType(LinkTypeList.ENTITY_ENTITYROUP_KEY);
            }
        }
        return parentRelation;
    }

    private void carrySationInfoFromParentEqpt(Entity entity) {
        String eqptId = entity.getInstanceId();
        if (StringUtils.equals(CHAMBER_FLAG, eqptId.substring(eqptId.length() - 2, eqptId.length() - 1))) {
            String peqptId = eqptId.substring(0, eqptId.length() - 2);
            long pentityRrn = getInstanceRrn(peqptId,
                                             getNamedSpace(ObjectList.ENTITY_KEY, LocalContext.getFacilityRrn()),
                                             ObjectList.ENTITY_KEY);

            List<Relation> prelations = baseService.getRelationsUseToRrn(pentityRrn, LinkTypeList.STATION_EQPT_KEY);
            List<Relation> relations = baseService.getRelationsUseToRrn(entity.getInstanceRrn(),
                                                                        LinkTypeList.STATION_EQPT_KEY);
            for (Relation relation : relations) {

                securityService.removeEquipmentFromStation(relation);
            }
            for (Relation relation : prelations) {
                relation.setToRrn(entity.getInstanceRrn());
                relation.setTransPerformedby(entity.getTransPerformedby());

                securityService.removeEquipmentFromStation(relation);
            }
        }

    }

    private void addRecipeFromCopyEquipment(long instanceRrn, Long copyEntityRrn,String comments) {
        List<Map> recipes = baseService.getRelationForRecipe(copyEntityRrn, LinkTypeList.ENTITY_TO_RECIPE);
        if (recipes != null && recipes.size() > 0) {
            for (Map recipe : recipes) {
                if (recipe != null) {
                    String recipeId = (String) recipe.get("recipeId");
                    Relation relation = new Relation();
                    relation.setFromRrn(instanceRrn);
                    relation.setLinkType(LinkTypeList.ENTITY_TO_RECIPE);
                    relation.setAttributedata1(SystemConstant.Str.ON);
                    relation.setAttributedata2(String.valueOf(LocalContext.getUserRrn()));
                    relation.setAttributedata3(DateUtils.formatDate(new Date()));
                    Long recipeRrn = getInstanceRrn(recipeId, LocalContext.getFacilityRrn(), ObjectList.RECIPE_KEY);
                    relation.setToRrn(recipeRrn);
                    relation.setTransPerformedby(LocalContext.getUserId());
                    relation.setTransId(Constants.ADD_KEY);
                    emsService.insertRelation4RecipeToEntity(relation,comments);
                }
            }
        }
    }

    private void saveDefaultEquipmentConstrain(Entity entity) {
        String defaultEquipConstrain = entity.getDefaultEquipConstrain();
        if (StringUtils.isEmpty(defaultEquipConstrain)) {
            return;
        }
        EquipmentConstrainInfo equipmentConstrainInfo = buildDefaultEquipmentConstrain(entity);

        EquipmentConstrainInfo oldEquipmentConstrainInfo = constrainService.getEquipmentConstrainInfo(
                equipmentConstrainInfo, false);
        if (oldEquipmentConstrainInfo != null && oldEquipmentConstrainInfo.getConstrainRrn() > 0) {
            equipmentConstrainInfo.setConstrainRrn(oldEquipmentConstrainInfo.getConstrainRrn());
            equipmentConstrainInfo.setModifyBy(LocalContext.getUserId());
            constrainService.modifyEquipmentConstrainInfo(equipmentConstrainInfo);
        } else {
            constrainService.insertEquipmentConstrainInfo(equipmentConstrainInfo);
        }
    }

    private void setEquipmentExt(EntityInfoForm theForm, Entity entity, Boolean isCopy) {
        Map entityExtMap = emsService.getEquipmentExtMap(entity.getInstanceRrn());
        if (MapUtils.isNotEmpty(entityExtMap)) {
            theForm.setEquipmentLocation((String) entityExtMap.get("equipmentLocation"));
            theForm.setEquipmentOwner((String) entityExtMap.get("equipmentOwner"));
            theForm.setPollutionLevel((String) entityExtMap.get("pollutionLevel"));
            if (StringUtils.isNotEmpty((String) entityExtMap.get("pollutionLevel"))) {
                theForm.setIsPlOpen(MiscUtils.changeCheckBox("1"));
            }
            theForm.setIsChamberEquip(MapUtils.getString(entityExtMap, "isChamberEquip"));
            theForm.setChamberMode(MapUtils.getString(entityExtMap, "chamberMode"));
            theForm.setDiffFlag(MiscUtils.changeCheckBox(MapUtils.getString(entityExtMap, "diffFlag")));
            theForm.setEquipmentCapability((String) entityExtMap.get("equipmentCapability"));
            if (isCopy) {
                theForm.setCopyInstanceRrn(entity.getInstanceRrn());
            }
            Equipment equipment = emsService.getEquipment(entity.getInstanceRrn());
            theForm.setNeedReticleFlag(MiscUtils.changeCheckBox(equipment.getNeedReticleFlag()));
            theForm.setSorterFlag(MiscUtils.changeCheckBox(equipment.getSorterFlag()));
            theForm.setWetBatchFlag(MiscUtils.changeCheckBox(equipment.getWetFlag()));
        }
    }

}