AutoMonitorLotAction.java

package com.mycim.webapp.actions;

import com.fa.sesa.exception.Assert;
import com.fa.sesa.exception.Errors;
import com.fa.sesa.exception.SystemIllegalArgumentException;
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.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.msg.JsonUtils;
import com.mycim.utils.WipUtils;
import com.mycim.valueobject.MessageIdList;
import com.mycim.valueobject.ObjectList;
import com.mycim.valueobject.automonitor.dto.LotAutoMonitorQueryDTO;
import com.mycim.valueobject.automonitor.dto.ReadingPromptDTO;
import com.mycim.valueobject.automonitor.entity.AutoMonitorItemStepEdcInfo;
import com.mycim.valueobject.automonitor.entity.LotAutoMonitorInfo;
import com.mycim.valueobject.automonitor.util.AutoMonitorOperationConstants;
import com.mycim.valueobject.automonitor.util.AutoMonitorUtils;
import com.mycim.valueobject.bas.InputObject;
import com.mycim.valueobject.bas.Relation;
import com.mycim.valueobject.consts.ActionPointList;
import com.mycim.valueobject.consts.ReferenceFileConst;
import com.mycim.valueobject.consts.TransactionNames;
import com.mycim.valueobject.ems.Entity;
import com.mycim.valueobject.ems.Equipment;
import com.mycim.valueobject.prp.Recipe;
import com.mycim.valueobject.prp.RecipeVersion;
import com.mycim.valueobject.wip.Lot;
import com.mycim.valueobject.wip.LotStatus;
import com.mycim.valueobject.wip.TransReason;
import com.mycim.valueobject.wip.Unit;
import com.mycim.valueobject.wip.dto.*;
import com.mycim.webapp.Constants;
import com.mycim.webapp.WebUtils;
import com.mycim.webapp.forms.LotInfoFormAutoMonitor;
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.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

public class AutoMonitorLotAction extends AutoMonitorAction {

    @Override
    public ActionForward init(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                              HttpServletResponse response) {
        LotInfoFormAutoMonitor theform = (LotInfoFormAutoMonitor) form;
        String lotId = StringUtils.trimToUpperCase(WebUtils.getParameter("lotId", request));
        if ("operate_panel".equals(request.getParameter("operate_panel"))) {
            request.setAttribute("operate_panel", "operate_panel");
        }
        theform.setTransId(Constants.INIT_KEY);

        Lot lot = lotInqService.getLot(lotId);
        LotAutoMonitorInfo monitorLotInfo = lotAutoMonitorInqService.getLotAutoMonitorInfo(lot.getLotRrn());
        Assert.state(monitorLotInfo != null, Errors.create().content("Monitor lot not exist!").build());

        Map<String, Object> lotMapInfo = builidlotMapInfo(lot, monitorLotInfo);
        if (LotStatus.isCanHold(lot.getLotStatus())) {
            List<Long> eqptRrns = new ArrayList<Long>();
            if (monitorLotInfo.getEqptRrn() != null && monitorLotInfo.getEqptRrn().longValue() > 0) {
                eqptRrns.add(monitorLotInfo.getEqptRrn());
            } else {
                long eqptGroupRrn = monitorLotInfo.getEqptGroupRrn();
                List<Entity> eqptList = emsService.getEntitiesFromEntityToEntityGroup(eqptGroupRrn);
                for (Object obj : eqptList) {
                    Entity entity = (Entity) obj;
                    eqptRrns.add(entity.getInstanceRrn());
                }
            }

            List<Map<String, Object>> availableEquipmentInfos = new ArrayList<>();
            for (Long eqptRrn : eqptRrns) {
                Entity entity = emsService.getEntity(new Entity(eqptRrn));
                String eqptId = entity.getInstanceId();
                String eqptDesc = entity.getInstanceDesc();

                Equipment eqpt = new Equipment();
                eqpt.setInstanceId(eqptId);
                eqpt.setInstanceRrn(eqptRrn);
                eqpt = emsService.getEquipment(eqpt);

                Map<String, Object> equipmentInfo = MapUtils.newHashMap();
                equipmentInfo.put("equipmentId", eqptId);
                equipmentInfo.put("equipmentDesc", eqptDesc);
                equipmentInfo.put("equipmentRrn", eqptRrn);

                String eqptStatus = emsService.getEntityCurrentStatus(eqptRrn);
                equipmentInfo.put("equipmentStatus", eqptStatus);

                if (wipCheckService.checkEqptStatusByMoveIn(lot, eqpt)) {
                    equipmentInfo.put("equipmentAvailable", "AVAILABLE");
                } else {
                    equipmentInfo.put("equipmentAvailable", "NOT_AVAILABLE");
                }

                equipmentInfo.put("equipmentConstrain", StringUtils.EMPTY);
                availableEquipmentInfos.add(equipmentInfo);
            }
            request.setAttribute("availableEquipmentInfos", availableEquipmentInfos);
        } else if (lot.getEqptRrn() != null && lot.getEqptRrn().longValue() > 0) {
            lotMapInfo.put("recipeId", lot.getRecipePhysicalId());

            List<Map<String, Object>> availableEquipmentInfos = new ArrayList<>();
            Long eqptRrn = lot.getEqptRrn();
            Entity entity = emsService.getEntity(new Entity(eqptRrn));
            String eqptId = entity.getInstanceId();
            String eqptDesc = entity.getInstanceDesc();

            Equipment eqpt = new Equipment();
            eqpt.setInstanceId(eqptId);
            eqpt.setInstanceRrn(eqptRrn);
            eqpt = emsService.getEquipment(eqpt);

            Map<String, Object> equipmentInfo = new HashMap<String, Object>();
            equipmentInfo.put("equipmentId", eqptId);
            equipmentInfo.put("equipmentDesc", eqptDesc);
            equipmentInfo.put("equipmentRrn", eqptRrn);

            String eqptStatus = emsService.getEntityCurrentStatus(eqptRrn);
            equipmentInfo.put("equipmentStatus", eqptStatus);

            equipmentInfo.put("equipmentAvailable", "AVAILABLE");

            // start: 检查批次在当前设备是否有constrain
            equipmentInfo.put("equipmentConstrain", StringUtils.EMPTY);

            availableEquipmentInfos.add(equipmentInfo);
            request.setAttribute("availableEquipmentInfos", availableEquipmentInfos);

            if (lot.getReticleRrn() != null && lot.getReticleRrn() > 0) {
                List<Map<String, Object>> inuseReticleInfoList = wipService
                        .buildInuseReticleInfoList(lot.getReticleRrn());
                if (CollectionUtils.isNotEmpty(inuseReticleInfoList)) {
                    request.setAttribute("availableReticleInfos", inuseReticleInfoList);
                }
            }
        }

        if (StringUtils.equalsIgnoreCase(LotStatus.HOLD, lot.getLotStatus()) ||
                StringUtils.equalsIgnoreCase(LotStatus.RUNNINGHOLD, lot.getLotStatus())) {
            List holdReasons = wipQueryService.getHoldReasons(lot.getLotRrn());
            request.setAttribute("holdReasons", holdReasons);
        }
        request.setAttribute("lotInfo", lotMapInfo);
        request.setAttribute("cacheLot", WebUtils.getCacheObj2String(lot));
        request.setAttribute("ocapIdList", wipQueryService.getActiveOfflineOcapListByLot(lot.getLotRrn()));

        theform.setReason("");
        return mapping.findForward(Constants.INIT_KEY);
    }

    public ActionForward cancelMoveInInit(ActionMapping mapping, LotInfoFormAutoMonitor theform,
                                          HttpServletRequest request, HttpServletResponse response) throws Exception {

        request.setAttribute("_scancelMoveIn", new Boolean(true));
        String lotId = WebUtils.getParameterUpperCase("lotId", request);
        Assert.state(StringUtils.isNotBlank(lotId), Errors.create().content("No such Lot exist!").build());

        Lot lot = lotInqService.getLot(lotId);
        Assert.state(lot != null, Errors.create().content("No such Lot exist!").build());

        LotAutoMonitorInfo lotMonitorInfo = lotAutoMonitorInqService.getLotActiveAutoMonitorInfo(lot.getLotRrn());
        request.setAttribute("lotInfo", builidlotMapInfo(lot, lotMonitorInfo));

        String equipmentRrns = request.getParameter("avaliableEqtRrn");
        request.setAttribute("equipmentRrns", equipmentRrns);

        Long lotRrn = lot.getLotRrn();
        Lot curLot = lotInqService.getLot(lotRrn.longValue());

        String lotStatus = lotQueryService.getLotStatus(lotRrn.longValue());
        Long jobRrn = wipQueryService.getJobRrn(lotRrn.longValue());
        Assert.state(LotStatus.isCanCancelMoveIn(lotStatus) && jobRrn != null,
                     Errors.create().key(MessageIdList.LOT_STATUS_MUST_RUNNING_OR_DISPATCH)
                           .content("批次的状态必须是Running或者Dispatch!").build());
        BeanUtils.copyProperties(lot, theform);
        theform.setLot_rrn(lotRrn);
        theform.setJobRrn(jobRrn);
        theform.setWflStepPath(curLot.getWflStepPath());
        theform.setOperationSeq(lot.getOperationSeq());
        request.setAttribute("dueDate", lot.getDueDate());

        return mapping.findForward("cancelMoveInInit");
    }

    public Map checkEqptAvailable(Map map) {
        String result = StringUtils.EMPTY;
        String constrainResult = StringUtils.EMPTY;
        Long equipmenRrn = MapUtils.getLong(map, "eqptRrn");
        String recipeId = MapUtils.getString(map, "recipeId");
        Lot lot = (Lot) WebUtils.getCacheString2Obj(MapUtils.getString(map, "cacheLot"));

        Map<String, Object> resultMap = MapUtils.newHashMap();

        LotAutoMonitorInfo monitorInfo = lotAutoMonitorInqService.getLotActiveAutoMonitorInfo(lot.getLotRrn());
        Assert.state(monitorInfo != null, Errors.create().content("Monitor lot not exist!").build());
        lot.setRecipeId(recipeId);

        result = wipCheckService.checkAvailableEquipmentByAutoMonitor(lot, equipmenRrn, LocalContext.getUserId());

        if (LotStatus.isMoveInCheckStatus(lot.getLotStatus())) {
            String recipeCheckResult = StringUtils.EMPTY;
            if (AutoMonitorUtils.checkStepIsMainProcessStep(monitorInfo.getEqptType())) {
                recipeCheckResult = wipCheckService
                        .checkHasAvailableDispatchRecipeByAutoMonitor(lot, equipmenRrn, recipeId);
            } else {
                recipeCheckResult = wipCheckService
                        .checkHasAvailableDispatchRecipe(lot, equipmenRrn, recipeId, lot.getInt_qty1().doubleValue());
            }
            result += recipeCheckResult;
            // result += wipCheckService.checkHasAvailableDispatchRecipeByAutoMonitor(lot, equipmenRrn, recipeId);
        }

        // constrainResult = buildEqptConstrain(facilityRrn, lot, equipmenRrn);
        resultMap.put("availableMsg", result);
        resultMap.put("constrainMsg", constrainResult);
        map.put("success", true);
        map.put("msg", resultMap);
        return map;
    }

    public ActionForward cancelmovein(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                                      HttpServletResponse response) throws Exception {
        String user = LocalContext.getUserId();
        Long facilityRrn = LocalContext.getFacilityRrn();
        LotInfoFormAutoMonitor theform = (LotInfoFormAutoMonitor) form;

        Long lotRrn = theform.getLot_rrn();
        Long jobRrn = theform.getJobRrn();
        String comments = theform.getLotComments();

        String userRRN = StringUtils.trimToUpperCase(theform.getUserId());
        Assert.isFalse(StringUtils.isEmpty(theform.getUserId()),
                       Errors.create().content("Responsibility cannot be empty! ").build());

        String userName = securityService.getUser(Long.parseLong(userRRN)).getUserName();
        Assert.isFalse(comments != null && comments.getBytes("UTF-8").length > 128,
                       Errors.create().content("The input content " + "exceeds " + "the length" + " limit!").build());

        String reason =
                theform.getReasonCode() + " " + theform.getDeptExt().trim().toUpperCase() + " " + userName + " " +
                        theform.getReason();

        Assert.isFalse(reason != null && reason.getBytes("UTF-8").length > 1024,
                       Errors.create().content("The input content " + "exceeds the " + "length limit!").build());

        List<Lot> lotList = new ArrayList<>();

        List<Lot> batchLotList = diffBatchQueryService.getBatchLotList(lotRrn);
        if(CollectionUtils.isNotEmpty(batchLotList)) {
            lotList.addAll(batchLotList);
        } else {
            lotList.add(lotInqService.getLot(lotRrn));
        }

        //TODO 循环RPC
        List<Map> transInfo = new ArrayList<Map>();
        List<String> lotRrns = new ArrayList<>();
        for (Lot _lot : lotList) {
            _lot = lotInqService.getLot(_lot.getLotRrn());
            //涉及数据权限问题,有些功能比如RRC的cancleMovein的job为0,会查出其它没有权限的批次,导致getLot的结果为空
            if (_lot == null || _lot.getLotRrn() <= 0L) {
                continue;
            }
            TransReason transReason = new TransReason();
            transReason.setReasonCode(theform.getReasonCode());
            transReason.setReason(reason);
            transReason.setResponsibility(user);
            transReason.setTransQty1(_lot.getQty1());
            transReason.setTransQty2(_lot.getQty2());

            Map<String, Object> tranMap = new HashMap<String, Object>();

            if (!StringUtils.equalsIgnoreCase(_lot.getLotStatus(), LotStatus.WAITING) && _lot.getJobRrn() != null &&
                    _lot.getJobRrn() > 0) {
                tranMap.put("lot", _lot);
                tranMap.put("user", user);
                tranMap.put("comments", comments);
                tranMap.put("transReason", transReason);
                tranMap.put("facilityRrn", facilityRrn);
                transInfo.add(tranMap);
                lotRrns.add(StringUtils.toString(_lot.getLotRrn()));
            }
        }
        lotService.cancelMoveIn(transInfo,lotRrns);
        cancelMoveInReturn(theform, request, response);
        return WebUtils.NULLActionForward;
    }

    public ActionForward cancelMoveInReturn(LotInfoFormAutoMonitor theform, HttpServletRequest request,
                                            HttpServletResponse response) throws Exception {
        request.getRequestDispatcher("automonitorlot.do?action=init&lotId=" + theform.getLotId())
               .forward(request, response);
        return null;
    }

    public ActionForward historyPage(ActionMapping mapping, HttpServletRequest request, HttpServletResponse response) {
        int thisPage = NumberUtils.toInt(WebUtils.getParameter("thisPage", request));
        int pageSize = NumberUtils.toInt(WebUtils.getParameter("pageSize", request));

        if (thisPage == 0) {
            thisPage = 1;
        }
        if (pageSize == 0) {
            pageSize = 10;
        }

        String lotId = WebUtils.getParameter("lotId", request);
        Lot lot = lotInqService.getLot(lotId);

        Page page = new Page(thisPage, pageSize);
        Map<String, Object> condition = new HashMap<>();
        condition.put("lotRrn", lot.getLotRrn());

        int rowCount = lotQueryService.qryLotTransHistoryCount(lot.getLotRrn());
        List list = lotQueryService.qryLotTransHistory(condition, thisPage, pageSize);
        for (Object obj : list) {
            Map<String, Object> transHistorMap = (Map<String, Object>) obj;
            String transModule = MapUtils.getString(transHistorMap, "transModule");
            if (StringUtils.isNotBlank(transModule) && WipUtils.AUTO.equals(transModule)) {
                String performedBy = MapUtils.getString(transHistorMap, "trans_performed_by") + "(" + transModule + ")";
                transHistorMap.put("trans_performed_by", performedBy);
            }
        }

        request.setAttribute("transHistoryList", list);
        request.setAttribute("thisPage", thisPage);
        request.setAttribute("maxPage", getTotalPages(rowCount,pageSize));
        request.setAttribute("lotInfo", lot);
        request.setAttribute("fromUrlFlag", "1");

        return mapping.findForward("historyPage");
    }

    /**
     * 根据pageSize与totalItems计算总页数, 默认值为-1.
     */
    private long getTotalPages(int totalItems,int pageSize) {
        if (totalItems < 0) {
            return -1;
        }

        long count = totalItems / pageSize;
        if (totalItems % pageSize > 0) {
            count++;
        }
        return count;
    }

}