SapphireBondedAction.java

package com.mycim.webapp.actions.lot.lotbondinginfo;

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.collections.MapUtils;
import com.mycim.valueobject.ObjectList;
import com.mycim.valueobject.consts.ProcessSwitchTypeNames;
import com.mycim.valueobject.consts.SessionNames;
import com.mycim.valueobject.ems.Carrier;
import com.mycim.valueobject.prp.Operation;
import com.mycim.valueobject.wip.*;
import com.mycim.webapp.Constants;
import com.mycim.webapp.WebUtils;
import com.mycim.webapp.actions.WipSetupAction;
import com.mycim.webapp.forms.LbrdLotInfoForm;
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.*;

public class SapphireBondedAction extends WipSetupAction {

    private static Integer DEFAULT_LOTS_SIZE = 5;

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

        if (StringUtils.isNotBlank(WebUtils.getParameter("next", request))) {
            return consume4targetLot(mapping, request, response, theform);// glass chip 确认了bonding 关系,需要把相关数据补充到数据库
        }
        return handleBond(mapping, request, response, theform);
    }

    public ActionForward next(ActionMapping mapping, HttpServletRequest request, HttpServletResponse response,
                              LbrdLotInfoForm theform) throws Exception {

        return consume4targetLot(mapping, request, response, theform);// glass chip 确认了bonding 关系,需要把相关数据补充到数据库
    }

    public ActionForward handleBond(ActionMapping mapping, HttpServletRequest request, HttpServletResponse response,
                                    LbrdLotInfoForm theform) throws Exception {
        Job job = (Job) request.getAttribute(SessionNames.JOB_KEY);
        if (job == null && theform.getCacheJob() != null) {
            job = (Job) WebUtils.getCacheString2Obj(theform.getCacheJob());
            request.setAttribute(SessionNames.JOB_KEY, job);
        }
        //Collection lots = (Collection) session.getAttribute(SessionNames.COLLECTION_KEY);
        Collection lots = (Collection) request.getAttribute(SessionNames.COLLECTION_KEY);
        if (lots == null && theform.getCacheCollection() != null) {
            lots = (Collection) WebUtils.getCacheString2Obj(theform.getCacheCollection());
            request.setAttribute(SessionNames.COLLECTION_KEY, lots);
        }
        HashMap parameters = (HashMap) request.getAttribute(SessionNames.PARAMETERSINFO_KEY);
        if (parameters == null && theform.getCacheParametersInfo() != null) {
            parameters = (HashMap) WebUtils.getCacheString2Obj(theform.getCacheParametersInfo());
            request.setAttribute(SessionNames.PARAMETERSINFO_KEY, parameters);
        }
        if (wipService.isConsume((List<Map>) lots)) {
            return handleConsume(mapping, request, response, theform);
        } else {
            return bondedCreate4Sapphire(mapping, request, response);
        }

    }

    @Override
    public void setCache4WFL(HttpServletRequest request, ActionForm form) {
        LbrdLotInfoForm theform = (LbrdLotInfoForm) form;
        theform.setCacheJob(WebUtils.getCacheObj2String(request.getAttribute(SessionNames.JOB_KEY)));
        theform.setCacheParametersInfo(
                WebUtils.getCacheObj2String(request.getAttribute(SessionNames.PARAMETERSINFO_KEY)));
        theform.setCacheCollection(WebUtils.getCacheObj2String(request.getAttribute(SessionNames.COLLECTION_KEY)));
    }

    private ActionForward handleConsume(ActionMapping mapping, HttpServletRequest request, HttpServletResponse response,
                                        LbrdLotInfoForm theform) throws Exception {
        //HashMap parameters = (HashMap) session.getAttribute(SessionNames.PARAMETERSINFO_KEY);
        HashMap parameters = (HashMap) request.getAttribute(SessionNames.PARAMETERSINFO_KEY);
        long eqtpRrn = MapUtils.getLongValue(parameters, "eqptRrn");
        // Collection lots = (Collection) session.getAttribute(SessionNames.COLLECTION_KEY);// size 必定是1
        Collection lots = (Collection) request.getAttribute(SessionNames.COLLECTION_KEY);

        Collection currentLots = lotQueryService.getLotListAtEqpt(eqtpRrn);// 当前设备上的可用批次

        Assert.isFalse(currentLots != null && currentLots.size() > 2,
                       Errors.create().content("Lot size in this eqpt is larger " + "than 2!").build());

        //lotBondingService.isNewLotAvailable(lots, language);
        for (Iterator it = lots.iterator(); it.hasNext(); ) {
            Map lotMap = (Map) it.next();
            Long lotRrn = MapUtils.getLongValue(lotMap, "lotRrn");

            Lot lot = lotQueryService.getLot(lotRrn);
            if (lotService.isTargetLot4Consume(lot)) {
                return buildLotsInfo4Target(mapping, request, theform);
            }
        }
        return consume4SourceLot(mapping, request, response);
    }

    private ActionForward consume4SourceLot(ActionMapping mapping, HttpServletRequest request,
                                            HttpServletResponse response) throws Exception {
        Long facilityRrn = LocalContext.getFacilityRrn();
        String user = LocalContext.getUserId();
        Long userRrn = LocalContext.getUserRrn();
        //Collection lots = (Collection) session.getAttribute(SessionNames.COLLECTION_KEY);
        Collection lots = (Collection) request.getAttribute(SessionNames.COLLECTION_KEY);
        //HashMap parameters = (HashMap) session.getAttribute(SessionNames.PARAMETERSINFO_KEY);
        HashMap parameters = (HashMap) request.getAttribute(SessionNames.PARAMETERSINFO_KEY);
        Long eqtpRrn = MapUtils.getLongValue(parameters, "eqptRrn");

        Map map = new HashMap();
        map.put("userId", user);
        map.put("userRrn", userRrn);
        map.put("facilityRrn", facilityRrn);
        map.put("eqtpRrn", eqtpRrn);
        wipService.consumeAndBond((List<Map>) lots, null, map);

        rebuildLots4Session(new Lot(), request, response);
        parameters.put(SessionNames.RUNSTEP_FLAG, "0");
        request.getRequestDispatcher(mapping.findForward("workflow").getPath() + "?action=init")
               .forward(request, response);
        return null;
        //return mapping.findForward("workflow");
    }

    private void rebuildLots4Session(Lot targetLot, HttpServletRequest request, HttpServletResponse response) {
        //Job job = (Job) session.getAttribute(SessionNames.JOB_KEY);
        Job job = (Job) request.getAttribute(SessionNames.JOB_KEY);

        Collection currentLots = wipQueryService.getJobList(job.getJobRrn(), ObjectList.JOB_KEY);
        //Collection handleLotInfos = (Collection) session.getAttribute(SessionNames.HANDLE_LOT_INFO_KEY);
        Collection handleLotInfos = (Collection) request.getAttribute(SessionNames.HANDLE_LOT_INFO_KEY);
        //Collection lots = (Collection) session.getAttribute(SessionNames.COLLECTION_KEY);
        Collection lots = (Collection) request.getAttribute(SessionNames.COLLECTION_KEY);

        //session.removeAttribute(SessionNames.NEW_LOT_INFO_KEY);
        request.removeAttribute(SessionNames.NEW_LOT_INFO_KEY);
        if (handleLotInfos == null) {
            handleLotInfos = new ArrayList();
        }
        boolean isExist;
        Map lotTmpMap = null;
        // 首先处理session 不正确的错误
        for (Iterator it = handleLotInfos.iterator(); it.hasNext(); ) {
            isExist = false;
            Map handleLotInfo = (Map) it.next();
            Lot lot = (Lot) handleLotInfo.get("Lot");
            for (Iterator it2 = lots.iterator(); it2.hasNext(); ) {
                lotTmpMap = (Map) it2.next();
                if (lot.getLotRrn() == MapUtils.getLongValue(lotTmpMap, "lotRrn")) {
                    isExist = true;
                    break;
                }
            }
            if (!isExist) {
                it.remove();
            }
        }

        Map lotMap = new HashMap();
        // 将 new lot加到session
        for (Iterator it = currentLots.iterator(); it.hasNext(); ) {
            isExist = false;
            lotMap = (Map) it.next();
            for (Iterator it2 = lots.iterator(); it2.hasNext(); ) {
                lotTmpMap = (Map) it2.next();
                if (MapUtils.getLongValue(lotMap, "lotRrn") == MapUtils.getLongValue(lotTmpMap, "lotRrn")) {
                    isExist = true;
                    break;
                }
            }
            if (!isExist) {
                lots.add(lotMap);
            }
        }

        // 重构出站信息
        Map handleLotInfo;
        StringBuilder sb = new StringBuilder();
        for (Iterator it = lots.iterator(); it.hasNext(); ) {
            isExist = false;
            lotTmpMap = (Map) it.next();
            Lot temp = lotQueryService.getLot(MapUtils.getLongValue(lotTmpMap, "lotRrn"));

            Operation operation = new Operation(temp.getOperationRrn());
            operation = getOperation(operation);
            // 当前工步生成的new Lot 才需要弹出
            if (StringUtils.equalsIgnoreCase("MOVEOUT_AUTOBONDED_STD", operation.getMvouWflId()) &&
                    lotService.isNewLotNeededByTargetLot(targetLot) &&
                    StringUtils.equalsIgnoreCase(temp.getLotPlanType(), BondAndConsumeEnum.NEWLOT.getValue()) &&
                    wipService.isConsumeLot(temp)) {
                sb.append("New Lot: " + temp.getLotId() + " has been started! ");
            }
            for (Iterator it2 = handleLotInfos.iterator(); it2.hasNext(); ) {
                handleLotInfo = (Map) it2.next();
                Lot lot = (Lot) handleLotInfo.get("Lot");
                if (lot.getLotRrn() == MapUtils.getLongValue(lotTmpMap, "lotRrn")) {
                    isExist = true;
                    break;
                }
            }
            if (!isExist) {
                Lot _lot = lotQueryService.getLot(MapUtils.getLongValue(lotTmpMap, "lotRrn"));
                Map _handleLotInfo = new HashMap();
                _handleLotInfo.put("Lot", _lot);
                _handleLotInfo.put("processFlag", ProcessSwitchTypeNames.PROCESS_MOVE_NEXT);
                _handleLotInfo.put("handleInfo", new HashMap<>());
                handleLotInfos.add(_handleLotInfo);
            }
        }

        if (sb.length() > 0) {// 出站界面弹出new lot 信息
            //session.setAttribute(SessionNames.NEW_LOT_INFO_KEY, sb.toString());
            request.setAttribute(SessionNames.NEW_LOT_INFO_KEY, sb.toString());
        }
        //session.setAttribute(SessionNames.COLLECTION_KEY, lots);
        request.setAttribute(SessionNames.COLLECTION_KEY, lots);
        //session.setAttribute(SessionNames.HANDLE_LOT_INFO_KEY, handleLotInfos);
        request.setAttribute(SessionNames.HANDLE_LOT_INFO_KEY, handleLotInfos);
    }

    private ActionForward buildLotsInfo4Target(ActionMapping mapping, HttpServletRequest request,
                                               LbrdLotInfoForm theform) {
        //HashMap parameters = (HashMap) session.getAttribute(SessionNames.PARAMETERSINFO_KEY);
        HashMap parameters = (HashMap) request.getAttribute(SessionNames.PARAMETERSINFO_KEY);
        long eqtpRrn = MapUtils.getLongValue(parameters, "eqptRrn");

        //Collection lots = (Collection) session.getAttribute(SessionNames.COLLECTION_KEY);
        Collection lots = (Collection) request.getAttribute(SessionNames.COLLECTION_KEY);
        Collection currentLots = lotQueryService.getLotListAtEqpt(eqtpRrn);

        List mainUnits = new ArrayList();
        Map<String, Object> comsumedLots = null;
        for (Iterator it = lots.iterator(); it.hasNext(); ) {
            Map lotMap = (Map) it.next();
            Long lotRrn = MapUtils.getLongValue(lotMap, "lotRrn");
            Lot lot = lotQueryService.getLot(lotRrn);

            comsumedLots = lotQueryService.getComsumeLotsByEqpt(lot, DEFAULT_LOTS_SIZE);
            for (Iterator it2 = currentLots.iterator(); it2.hasNext(); ) {
                Map lotMap2 = (Map) it2.next();
                Lot lotTemp = lotQueryService.getLot(MapUtils.getLongValue(lotMap2, "lotRrn"));
                if (lot.getLotRrn() != lotTemp.getLotRrn()) {
                    if (StringUtils.isEmpty(MapUtils.getString(comsumedLots, "lotIds", StringUtils.EMPTY))) {
                        comsumedLots.put("LOTIDS", lotTemp.getLotId());
                        comsumedLots.put("LOTRRNS", lotTemp.getLotRrn());

                    } else {
                        comsumedLots.put("LOTIDS", MapUtils.getString(comsumedLots, "LOTIDS", StringUtils.EMPTY) + "," +
                                lotTemp.getLotId());
                        comsumedLots.put("LOTRRNS",
                                         MapUtils.getString(comsumedLots, "LOTRRNS", StringUtils.EMPTY) + "," +
                                                 lotTemp.getLotRrn());

                    }

                }

            }

            Assert.isFalse(StringUtils.isEmpty(MapUtils.getString(comsumedLots, "LOTIDS", StringUtils.EMPTY)),
                           Errors.create().content("No consum lots for current EQP at current step!").build());
            mainUnits.addAll(wipQueryService.getUnitListByLot(lot.getLotRrn()));
        }
        request.setAttribute("comsumedLots", comsumedLots);
        request.setAttribute("maimUnits", mainUnits);
        setCache4WFL(request, theform);
        return mapping.findForward("bondMapping");
    }

    private ActionForward bondedCreate4Sapphire(ActionMapping mapping, HttpServletRequest request,
                                                HttpServletResponse response) throws Exception {
        Long facilityRrn = LocalContext.getFacilityRrn();
        String user = LocalContext.getUserId();
        //Collection lots = (Collection) session.getAttribute(SessionNames.COLLECTION_KEY);
        Collection lots = (Collection) request.getAttribute(SessionNames.COLLECTION_KEY);
        //HashMap parameters = (HashMap) session.getAttribute(SessionNames.PARAMETERSINFO_KEY);
        HashMap parameters = (HashMap) request.getAttribute(SessionNames.PARAMETERSINFO_KEY);
        List sourceUnits = new ArrayList();
        List targetUnits = new ArrayList();
        String targetCarrierId = (String) request.getAttribute("targetCarrierId");

        Long targetProductRrn = 0L;
        Long sourceProductRrn = 0L;
        Long operationRrn = 0L;
        Bonding bonding = new Bonding();
        if (StringUtils.isNotBlank(targetCarrierId)) {
            Carrier carrier = carrierService.getCarrier(LocalContext.getFacilityRrn(), targetCarrierId);
            if (carrier != null) {
                bonding.setTargetCarrierRrn(carrier.getInstanceRrn());
            }
        }
        for (Iterator it = lots.iterator(); it.hasNext(); ) {
            HashMap _lot = (HashMap) it.next();
            Lot lot = lotQueryService.getLot(MapUtils.getLongValue(_lot, "lotRrn"));
            Collection unitsList = wipQueryService.getUnitListByCarrier(lot.getCarrierRrn().longValue());
            if (lotService.isTargetLot4Bond(lot)) {
                targetUnits.addAll(unitsList);
                bonding.setTargetLotId(lot.getLotId());
                bonding.setTargetPlanType(lot.getLotPlanType());
                bonding.setTargetHandleFlag(buildHandleFlag(lot));
                bonding.setTargetLotRrn(lot.getLotRrn());
                bonding.setStepSequence(lot.getStepSequence());
                targetProductRrn = lot.getProductRrn();
                operationRrn = lot.getOperationRrn();
            } else {
                sourceUnits.addAll(unitsList);
                bonding.setSourceLotId(lot.getLotId());
                bonding.setSourcePlanType(lot.getLotPlanType());
                bonding.setSourceHandleFlag(buildHandleFlag(lot));
                bonding.setSourceLotRrn(lot.getLotRrn());
                sourceProductRrn = lot.getProductRrn();
            }
        }
        List<BondingMapping> bondingMappings = new ArrayList<BondingMapping>();
        for (Iterator itT = targetUnits.iterator(); itT.hasNext(); ) {
            BondingMapping bondingMapping = new BondingMapping();
            Map targetUnit = (Map) itT.next();
            bondingMapping.setTargetLotRrn(MapUtils.getLongValue(targetUnit, "lotRrn"));
            bondingMapping.setTargetHandleFlag(bonding.getTargetHandleFlag());
            bondingMapping.setSourceHandleFlag(bonding.getSourceHandleFlag());
            bondingMapping.setTargetUnitRrn(MapUtils.getLongValue(targetUnit, "unitRrn"));
            bondingMapping.setSourceUnitRrn(getSourceUnitRrn(bondingMapping.getTargetUnitRrn()));
            boolean haveMapping = false;
            if (bondingMapping.getSourceUnitRrn() > 0) {
                for (Iterator itS = sourceUnits.iterator(); itS.hasNext(); ) {
                    Map sourceUnit = (Map) itS.next();
                    if (bondingMapping.getSourceUnitRrn() == MapUtils.getLongValue(sourceUnit, "unitRrn")) {
                        bondingMapping.setSourceLotRrn(MapUtils.getLongValue(sourceUnit, "lotRrn"));
                        haveMapping = true;
                        itS.remove();
                        break;
                    }
                }
            }
            Assert.isTrue(haveMapping, Errors.create().content("Please rebuild the bonding mapping").build());
            bondingMappings.add(bondingMapping);
        }

        bonding.setBondingMapping(bondingMappings);

        String bondingTag = lotQueryService.getSourceLotBondingTag(targetProductRrn, sourceProductRrn, operationRrn);
        if (StringUtils.equalsIgnoreCase(Constants.BONDING_TAG_TYPE.TOP, bondingTag)) {
            bonding.setTargetBondingTag(Constants.BONDING_TAG_TYPE.BOTTOM);
            bonding.setSourceBondingTag(Constants.BONDING_TAG_TYPE.TOP);
        } else {
            bonding.setTargetBondingTag(Constants.BONDING_TAG_TYPE.TOP);
            bonding.setSourceBondingTag(Constants.BONDING_TAG_TYPE.BOTTOM);
        }
        wipService.createBatchBonded(bonding, user, facilityRrn);

        parameters.put(SessionNames.RUNSTEP_FLAG, "0");
        request.getRequestDispatcher(mapping.findForward("workflow").getPath() + "?action=init")
               .forward(request, response);
        return null;
        //return mapping.findForward("workflow");
    }

    private ActionForward consume4targetLot(ActionMapping mapping, HttpServletRequest request,
                                            HttpServletResponse response, LbrdLotInfoForm theform) throws Exception {
        Long facilityRrn = LocalContext.getFacilityRrn();
        String user = LocalContext.getUserId();
        Long userRrn = LocalContext.getUserRrn();
        Job job = (Job) request.getAttribute(SessionNames.JOB_KEY);
        if (job == null && theform.getCacheJob() != null) {
            job = (Job) WebUtils.getCacheString2Obj(theform.getCacheJob());
            request.setAttribute(SessionNames.JOB_KEY, job);
        }
        //Collection lots = (Collection) session.getAttribute(SessionNames.COLLECTION_KEY);
        Collection lots = (Collection) request.getAttribute(SessionNames.COLLECTION_KEY);
        if (lots == null && theform.getCacheCollection() != null) {
            lots = (Collection) WebUtils.getCacheString2Obj(theform.getCacheCollection());
            request.setAttribute(SessionNames.COLLECTION_KEY, lots);
        }
        // HashMap parameters = (HashMap) session.getAttribute(SessionNames.PARAMETERSINFO_KEY);
        HashMap parameters = (HashMap) request.getAttribute(SessionNames.PARAMETERSINFO_KEY);
        if (parameters == null && theform.getCacheParametersInfo() != null) {
            parameters = (HashMap) WebUtils.getCacheString2Obj(theform.getCacheParametersInfo());
            request.setAttribute(SessionNames.PARAMETERSINFO_KEY, parameters);
        }
        Long eqtpRrn = MapUtils.getLongValue(parameters, "eqptRrn");

        //lotBondingService.isNewLotAvailable(lots, language);

        List consumeList = validateAndBuildConsume(request);
        Lot lot = null;
        for (Iterator it = lots.iterator(); it.hasNext(); ) {
            Map lotMap = (Map) it.next();
            Long lotRrn = MapUtils.getLongValue(lotMap, "lotRrn");
            lot = lotQueryService.getLot(lotRrn);
            break;
        }

        Map map = new HashMap();
        map.put("userId", user);
        map.put("userRrn", userRrn);
        map.put("facilityRrn", facilityRrn);
        map.put("eqtpRrn", eqtpRrn);

        wipService.consumeAndBond((List<Map>) lots, consumeList, map);

        rebuildLots4Session(lot, request, response);

        parameters.put(SessionNames.RUNSTEP_FLAG, "0");
        request.getRequestDispatcher(mapping.findForward("workflow").getPath() + "?action=init")
               .forward(request, response);
        return null;
        //return mapping.findForward("workflow");
    }

    private List validateAndBuildConsume(HttpServletRequest request) throws Exception {
        Long facilityRrn = LocalContext.getFacilityRrn();
        String tlotId = request.getParameter("targetLotId0");
        Lot tlot = lotQueryService.getLot(lotQueryService.getLotRrn(tlotId));
        String tlotHandleFlag = buildHandleFlag(tlot);
        List consumeList = new ArrayList();
        for (int i = 0; i < tlot.getQty1(); i++) {
            String targetLotId = WebUtils.getParameterUpperCase("targetLotId" + i, request);
            String targetUnitId = WebUtils.getParameterUpperCase("targetUnitId" + i, request);
            String targetUnitRrn = WebUtils.getParameterUpperCase("targetUnitRrn" + i, request);
            String sourceLotId = WebUtils.getParameterUpperCase("sourceLotId" + i, request);
            String sourceUnitId = WebUtils.getParameterUpperCase("sourceUnitId" + i, request);
            String sourceUnitRrn = WebUtils.getParameterUpperCase("sourceUnitRrn" + i, request);
            if (sourceUnitRrn != null && sourceUnitRrn.trim().length() > 0) {
                String[] units = sourceUnitRrn.split(",");
                if (targetLotId.length() > 0 && targetUnitRrn.length() > 0 && units.length > 0) {
                    for (int j = 0; j < units.length; j++) {
                        BondingConsume consume = new BondingConsume();
                        consume.setRelationType("G2C");
                        consume.setTargetUnitRrn(Long.parseLong(targetUnitRrn));
                        consume.setConsumeUnitRrn(Long.parseLong(units[j]));
                        consume.setDataFrom("MES");

                        Unit sourceUnit = wipQueryService
                                .getUnit(facilityRrn, wipQueryService.getUnitIdByRrn(Long.parseLong(units[j])));
                        long lotRrn = sourceUnit.getLotRrn();
                        Lot slot = lotQueryService.getLot(lotRrn);

                        consume.setConsumePlanType(slot.getLotPlanType());
                        consume.setConsumeHandleFlag(buildHandleFlag(slot));
                        consume.setTargetPlanType(tlot.getLotPlanType());
                        consume.setTargetHandleFlag(tlotHandleFlag);
                        consume.setStepSequence(tlot.getStepSequence());
                        consumeList.add(consume);
                    }
                }
            }
        }

        Assert.isFalse(consumeList.isEmpty(), Errors.create().content("Please add consumption info!").build());

        return consumeList;

    }

    private String buildHandleFlag(Lot slot) {
        String flag = StringUtils.EMPTY;
        flag += (slot.getProcessId() + "#" + slot.getProcessRrn() + "#" + slot.getProcessVersion() + "/");
        flag += (slot.getOperationId() + "#" + slot.getOperationRrn());
        return flag;
    }

}