StationDetailSaveAction.java

/*
 *        @ Copyright 2001 FA Software;
 *        All right reserved. No part of this program may be reproduced or
 *        transmitted in any form or by any means, electronic or
 *        mechanical, including photocopying, recording, or by any
 *        information storage or retrieval system without written
 *        permission from FA Software, except for inclusion of brief
 *        quotations in a review.
 */
package com.mycim.webapp.actions.setting.security.station;

import com.fa.sesa.exception.Assert;
import com.fa.sesa.exception.Errors;
import com.fa.sesa.threadlocal.LocalContext;
import com.mycim.framework.jdbc.Page;
import com.mycim.framework.utils.beans.BeanUtils;
import com.mycim.framework.utils.lang.StringUtils;
import com.mycim.valueobject.MessageIdList;
import com.mycim.valueobject.ObjectList;
import com.mycim.valueobject.bas.Relation;
import com.mycim.valueobject.consts.AttributeDataEnum;
import com.mycim.valueobject.consts.LinkTypeList;
import com.mycim.valueobject.consts.SessionNames;
import com.mycim.valueobject.consts.TransactionNames;
import com.mycim.valueobject.ems.Entity;
import com.mycim.valueobject.security.Station;
import com.mycim.webapp.Constants;
import com.mycim.webapp.actions.CimSetupAction;
import com.mycim.webapp.forms.security.StationInfoForm;
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.List;

/**
 * 机台控制权限组定义 详细信息页面
 *
 * @author weike.li
 * @date 2019/8/20
 * @since 1.8
 **/
public class StationDetailSaveAction extends CimSetupAction {
    private static final String DELETE_EQPT = "deleteeqpt";

    private static final String DELETE_OPER = "deleteoper";

    private static final String DELETE_USER = "deleteuser";

    private static final String EQUIPMENT = "equipment";

    private static final String OPERATION = "operation";

    private static final String USER = "user";

    private static final String UNDERLINE = "_";

    private static final int NUM_TWO = 2;

    @Override
    public ActionForward init(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                              HttpServletResponse response) throws Exception {

        StationInfoForm theform = (StationInfoForm) form;

        Station station = new Station(theform.getInstanceId(), theform.getNamedSpace(), ObjectList.STATION_KEY);
        station = (Station) getInstance(station);

        BeanUtils.copyProperties(theform, station);

        Relation relation = new Relation();
        relation.setFromRrn(station.getInstanceRrn());
        relation.setTransPerformedby(LocalContext.getUserId());

        String initPage = request.getParameter("initPage");
        if (StringUtils.isNotEmpty(initPage)) {
            theform.setThisPage(1L);
        }

        processItem(request, theform, station);

        theform.setUserId("");
        theform.setOperationId("");

        request.setAttribute(SessionNames.STATION_KEY, station);
        return mapping.findForward(Constants.MODIFY_KEY);
    }

    @Override
    public ActionForward cancel(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                                HttpServletResponse response) {
        StationInfoForm theform = (StationInfoForm) form;

        Station station = new Station(theform.getInstanceId(), theform.getNamedSpace(), ObjectList.STATION_KEY);
        station = (Station) getInstance(station);

        theform.setInstanceId("");
        request.setAttribute(SessionNames.STATION_KEY, station);
        return mapping.findForward(Constants.SETUP_KEY);
    }

    private void processItem(HttpServletRequest request, StationInfoForm theform, Station station) {
        String type = request.getParameter(Constants.TYPE_KEY);
        if (type != null) {
            //processItemAction(request, theform);
            Page page = new Page();
            if (type.equals("operation")) {
                type = request.getParameter("transId");
            }

            if (StringUtils.equals(type, Constants.MAINTAINEQPT4S_KEY)) {
                theform.setTransId(Constants.MAINTAINEQPT4S_KEY);
                page = getRelationOfStation(theform, LinkTypeList.STATION_EQPT_KEY, station.getInstanceRrn());
                station.setEquipments((List) page.getResults());
            } else if (StringUtils.equals(type, Constants.MAINTAINOPER4S_KEY)) {
                theform.setTransId(Constants.MAINTAINOPER4S_KEY);
                page = getRelationOfStation(theform, LinkTypeList.STATION_OPER_KEY, station.getInstanceRrn());
                station.setOperations((List<Relation>) page.getResults());
            } else if (StringUtils.equals(type, Constants.MAINTAINUSER4S_KEY)) {
                theform.setTransId(Constants.MAINTAINUSER4S_KEY);
                page = getRelationOfStation(theform, LinkTypeList.STATION_USER_KEY, station.getInstanceRrn());
                station.setUsers((List<Relation>) page.getResults());
            }

            theform.setThisPage(page.getPageNo());
            theform.setLastPageSize(page.getTotalItems() % page.getPageSize());
            theform.setPageSize(page.getPageSize());
            theform.setMaxPage(page.getTotalItems() % page.getPageSize() == 0 ?
                                       page.getTotalItems() / page.getPageSize() :
                                       (page.getTotalItems() / page.getPageSize()) + 1);

            theform.setInstanceId(station.getInstanceId());
            theform.setNamedSpace(station.getNamedSpace());
            theform.setInstanceDesc(station.getInstanceDesc());
            theform.setUsers(station.getUsers());
        }
    }

    public ActionForward members(ActionMapping mapping, StationInfoForm theform, HttpServletRequest request) {
        Station station = new Station(theform.getInstanceId(), theform.getNamedSpace(), ObjectList.STATION_KEY);
        station = (Station) getInstance(station);

        BeanUtils.copyProperties(theform, station);

        Relation relation = new Relation();
        relation.setFromRrn(station.getInstanceRrn());
        relation.setTransPerformedby(LocalContext.getUserId());

        String dest = "modify";

        station.setEquipments(getEquipments(station));
        station.setOperations(getOperations(station));
        station.setUsers(getUsers(station));

        if ((request.getParameter(Constants.MEMBERS_KEY) != null) &&
                (request.getParameter(Constants.ITEM_KEY) != null)) {
            Long objectNum = new Long(request.getParameter(Constants.ITEM_KEY));
            relation.setToRrn(objectNum);

            if ((Constants.MODIFY_KEY).equalsIgnoreCase(request.getParameter(Constants.MEMBERS_KEY))) {
                List<Relation> equipments = station.getEquipments();
                for (Relation equipment : equipments) {
                    if (equipment.getToRrn().equals(objectNum)) {
                        relation = equipment;
                        break;
                    }
                }

                theform.setEquipmentId(relation.getInstanceId());
                theform.setPositionX(relation.getAttributedata1());
                theform.setPositionY(relation.getAttributedata2());
                theform.setEquipmentDesc(relation.getInstanceDesc());
                theform.setTransId("modify");

                dest = "members";
            } else if (DELETE_EQPT.equalsIgnoreCase(request.getParameter(Constants.MEMBERS_KEY))) {
                relation.setTransId(Constants.DELETE_KEY);
                deleteRelation(relation, "equipment");
                theform.setTransId(Constants.MAINTAINEQPT4S_KEY);
            } else if (DELETE_OPER.equalsIgnoreCase(request.getParameter(Constants.MEMBERS_KEY))) {
                relation.setTransId(Constants.DELETE_KEY);
                deleteRelation(relation, "operation");
                theform.setTransId(Constants.MAINTAINOPER4S_KEY);
            } else if (DELETE_USER.equalsIgnoreCase(request.getParameter(Constants.MEMBERS_KEY))) {
                relation.setTransId(Constants.DELETE_KEY);
                deleteRelation(relation, "user");
                theform.setTransId(Constants.MAINTAINUSER4S_KEY);
            }
        }
        processItem(request, theform, station);

        theform.setUserId("");
        theform.setOperationId("");

        request.setAttribute(SessionNames.STATION_KEY, station);
        return mapping.findForward(dest);
    }

    private void deleteRelation(Relation relation, String type) {
        if (EQUIPMENT.equalsIgnoreCase(type)) {
            securityService.removeEquipmentFromStation(relation);
            List<Entity> chambers = emsService.getChildChamberEquip(relation.getToRrn());
            for (int i = 0; i < chambers.size(); i++) {
                Entity entity = chambers.get(i);
                relation.setToRrn(entity.getInstanceRrn());
                if (isDuplicateEqp(relation.getFromRrn().longValue(), relation.getToRrn().longValue())) {
                    securityService.removeEquipmentFromStation(relation);
                }
            }
        } else if (OPERATION.equalsIgnoreCase(type)) {
            securityService.removeOperationFromStation(relation);
        } else if (USER.equalsIgnoreCase(type)) {
            securityService.removeUserFromStation(relation);
        }
    }

    private boolean isDuplicateEqp(long fromRrn, long toRrn) {
        return baseService.isExistedRelation(fromRrn, toRrn);
    }

    public ActionForward maintainEqpt(ActionMapping mapping, StationInfoForm theform, HttpServletRequest request) {
        Station station = new Station(theform.getInstanceId(), theform.getNamedSpace(), ObjectList.STATION_KEY);

        station = (Station) getInstance(station);

        BeanUtils.copyProperties(theform, station);

        Relation relation = new Relation();
        relation.setFromRrn(station.getInstanceRrn());
        relation.setTransPerformedby(LocalContext.getUserId());
        String eqptId = theform.getEquipmentId().trim().toUpperCase();
        Assert.isFalse(StringUtils.isBlank(eqptId),
                       Errors.create().key(MessageIdList.EQUIPMENT_ID_CANNOT_EMPTY).content("请先输入设备号").build());
        Assert.isFalse(StringUtils.equals(UNDERLINE, eqptId.substring(eqptId.length() - NUM_TWO, eqptId.length() - 1)),
                       Errors.create().key(MessageIdList.STATION_NOT_MAIN_TOOL).content("{}不是主要工具").args(eqptId)
                             .build());
        long eqptRrn = getInstanceRrn(theform.getEquipmentId().trim(),
                                      getNamedSpace(ObjectList.ENTITY_KEY, LocalContext.getFacilityRrn()),
                                      ObjectList.ENTITY_KEY, ObjectList.EQUIPMENT_KEY);
        Assert.isFalse(eqptRrn <= 0, Errors.create().key(MessageIdList.SYSTEM_INSTANCE_NOT_FOUND).content("{} 没有找到对象!")
                                           .args("equipment.").build());
        relation.setToRrn(eqptRrn);
        addObjects(relation, "equipment");
        station.setEquipments(getEquipments(station));
        theform.setTransId(Constants.MAINTAINEQPT4S_KEY);
        processItem(request, theform, station);
        theform.setUserId("");
        theform.setEquipmentId("");
        request.setAttribute(SessionNames.STATION_KEY, station);
        return mapping.findForward(Constants.MODIFY_KEY);
    }

    public ActionForward maintainOper(ActionMapping mapping, StationInfoForm theform, HttpServletRequest request) {
        Station station = new Station(theform.getInstanceId(), theform.getNamedSpace(), ObjectList.STATION_KEY);
        station = (Station) getInstance(station);

        BeanUtils.copyProperties(theform, station);

        Relation relation = new Relation();
        relation.setFromRrn(station.getInstanceRrn());
        relation.setTransPerformedby(LocalContext.getUserId());

        String dest = "modify";


        theform.setOperationId(theform.getOperationId().trim().toUpperCase());

        long operationRrn = getInstanceRrn(theform.getOperationId(),
                                           getNamedSpace(ObjectList.OPERATION_KEY, LocalContext.getFacilityRrn()),
                                           ObjectList.OPERATION_KEY);

        Assert.isFalse(operationRrn <= 0,
                       Errors.create().key(MessageIdList.SYSTEM_INSTANCE_NOT_FOUND).content("{} 没有找到对象!")
                             .args("operation").build());

        relation.setToRrn(operationRrn);
        addObjects(relation, "operation");
        station.setOperations(getOperations(station));

        theform.setTransId(Constants.MAINTAINOPER4S_KEY);

        processItem(request, theform, station);

        theform.setUserId("");
        theform.setOperationId("");

        request.setAttribute(SessionNames.STATION_KEY, station);
        return mapping.findForward(dest);
    }

    private void addObjects(Relation relation, String type) {
        relation.setTransId(TransactionNames.CREATE_KEY);

        if (OPERATION.equalsIgnoreCase(type)) {
            relation.setLinkType(LinkTypeList.STATION_OPER_KEY);
            if (baseService.getRelation(relation) == null) {
                securityService.addOperationToStation(relation);
            }
        } else if (USER.equalsIgnoreCase(type)) {
            relation.setLinkType(LinkTypeList.STATION_USER_KEY);
            if (baseService.getRelation(relation) == null) {
                securityService.addUserToStation(relation);
            }
        } else if (EQUIPMENT.equalsIgnoreCase(type)) {
            relation.setLinkType(LinkTypeList.STATION_EQPT_KEY);
            Assert.isFalse(isDuplicateEqp(relation.getFromRrn(), relation.getToRrn()),
                           Errors.create().key(MessageIdList.STATION_RECORDS_DUPLICATE).content("不能添加重复记录!").build());
            securityService.addEquipmentToStation(relation);
            List<Entity> chambers = emsService.getChildChamberEquipByFormat(relation.getToRrn());
            for (Entity entity : chambers) {
                relation.setToRrn(entity.getInstanceRrn());
                if (!isDuplicateEqp(relation.getFromRrn(), relation.getToRrn())) {
                    securityService.addEquipmentToStation(relation);
                }
            }
        }
    }

    public ActionForward maintainUser(ActionMapping mapping, StationInfoForm theform, HttpServletRequest request) {
        Station station = new Station(theform.getInstanceId(), theform.getNamedSpace(), ObjectList.STATION_KEY);
        station = (Station) getInstance(station);

        BeanUtils.copyProperties(theform, station);

        Relation relation = new Relation();
        relation.setFromRrn(station.getInstanceRrn());
        relation.setTransPerformedby(LocalContext.getUserId());

        String dest = "modify";

        long userGroupRrn = getInstanceRrn(theform.getUserId(),
                                           getNamedSpace(ObjectList.USERGROUP_KEY, LocalContext.getFacilityRrn()),
                                           ObjectList.USERGROUP_KEY);

        Assert.isFalse(userGroupRrn <= 0,
                       Errors.create().key(MessageIdList.SYSTEM_INSTANCE_NOT_FOUND).content("{} 没有找到对象!")
                             .args("User Group").build());

        relation.setToRrn(userGroupRrn);
        relation.setAttributedata3("1");
        addObjects(relation, "user");
        station.setUsers(getUsers(station));

        theform.setTransId(Constants.MAINTAINUSER4S_KEY);

        processItem(request, theform, station);

        theform.setUserId("");
        theform.setOperationId("");

        request.setAttribute(SessionNames.STATION_KEY, station);
        return mapping.findForward(dest);
    }

    public ActionForward modify(ActionMapping mapping, StationInfoForm theform, HttpServletRequest request) {
        Station station = new Station(theform.getInstanceId(), theform.getNamedSpace(), ObjectList.STATION_KEY);
        station = (Station) getInstance(station);

        BeanUtils.copyProperties(theform, station);

        Relation relation = new Relation();
        relation.setFromRrn(station.getInstanceRrn());
        relation.setTransPerformedby(LocalContext.getUserId());

        String dest = "modify";

        List<Relation> userGroups = station.getUsers();
        int userNumber = 0;
        for (Relation userGroup : userGroups) {
            String moveInFlag = request.getParameter("moveInFlag" + userNumber++);
            userGroup.setAttributedata3(moveInFlag);
            baseService.updateRelationAttribute(AttributeDataEnum.ATTRIBUTE_DATA_3.toString(), moveInFlag,
                                                userGroup.getFromRrn(), userGroup.getToRrn(), LocalContext.getUserId());
        }
        theform.setTransId(Constants.MAINTAINUSER4S_KEY);

        processItem(request, theform, station);

        theform.setUserId("");
        theform.setOperationId("");

        request.setAttribute(SessionNames.STATION_KEY, station);
        return mapping.findForward(dest);
    }

    public Page getRelationOfStation(StationInfoForm form, String linkType, long stationRrn) {
        Page page = new Page();
        page.setPageNo(form.getThisPage());
        page.setPageSize(form.getPageSize());
        return securityService.getRelationOfStation(page, linkType, stationRrn);
    }

    protected void processItemAction(HttpServletRequest request, StationInfoForm theForm) {
        if (theForm.getThisPage() == null) {
            theForm.setThisPage(1L);
        }

        if (request.getParameter(Constants.FIRST_KEY) != null) {
            theForm.setThisPage(1L);
        } else if (request.getParameter(Constants.PREV_KEY) != null) {
            theForm.setThisPage(theForm.getThisPage() - 1);
        } else if (request.getParameter(Constants.NEXT_KEY) != null) {
            theForm.setThisPage(theForm.getThisPage() + 1);
        } else if (request.getParameter(Constants.LAST_KEY) != null) {
            theForm.setThisPage(-1L);
        } else {
            theForm.setThisPage(1L);
        }

    }

}