ReworkLotAction.java

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

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.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.valueobject.MessageIdList;
import com.mycim.valueobject.consts.ReworkConst;
import com.mycim.valueobject.consts.SessionNames;
import com.mycim.valueobject.prp.ContextValue;
import com.mycim.valueobject.prp.ReworkRouteContextValue;
import com.mycim.valueobject.wip.Lot;
import com.mycim.valueobject.wip.LotStatus;
import com.mycim.webapp.Constants;
import com.mycim.webapp.WebUtils;
import com.mycim.webapp.actions.WipSetupAction;
import com.mycim.webapp.forms.lot.LotInfoForm;
import com.mycim.webapp.forms.lot.ReworkLotInfoForm;
import org.apache.commons.compress.utils.Sets;
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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author shijie.deng
 * @version 6.0.0
 * @date 2019/10/8
 **/
public class ReworkLotAction extends WipSetupAction {

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

        Lot lot = initLotBaseInfoForJsp(request, true, null, null);
        Assert.isTrue(LotStatus.HOLD.equals(lot.getLotStatus()),
                      Errors.create().key(MessageIdList.SCRAPLOT_STATUS_NOT_ALLOW).content("Lot status must be Hold!")
                            .build());
        wipQueryService.checkActiveInlineOcapId(lot.getLotRrn());
        super.checkCstRemoved(Sets.newHashSet(lot.getLotRrn()));
        ReworkLotInfoForm theform = (ReworkLotInfoForm) form;
        Map reworkTransInfo = lotQueryService.getLotReworkInfo(lot);
        theform.setReworkRouteId(getInstanceId(((Long) reworkTransInfo.get("reworkWflRrn")).longValue()));
        theform.setReworkOperationId((String) reworkTransInfo.get("operationId"));
        theform.setReturnRouteId((String) reworkTransInfo.get("RETURN_ROUTE_NEW_ID"));
        theform.setReturnOperationId((String) reworkTransInfo.get("RETURN_OPERATION_NEW_ID"));
        this.setTheFormSession(theform, request, null, theform.getLotInfo(), null);
        return mapping.findForward(Constants.INIT_KEY);
    }

    public ActionForward reworkLot(ActionMapping mapping, ReworkLotInfoForm theform, HttpServletRequest request) {
        String userId = LocalContext.getUserId();
        Lot lot = lotQueryService.getLot(theform.getLotId(), LocalContext.getFacilityRrn());
        Map reworkTransInfo = lotQueryService.getLotReworkInfo(lot);

        reworkTransInfo.put("transPerformedBy", userId);

        //卡控post future hold被hold住的lot
        checkPostFutureHold(lot.getLotRrn());

        Assert.isTrue(LotStatus.HOLD.equals(lot.getLotStatus()),
                      Errors.create().key(MessageIdList.SCRAPLOT_STATUS_NOT_ALLOW).content("Lot status must be Hold!")
                            .build());

        Assert.isFalse(theform.getReworkCode() == null || theform.getReworkCode().trim().length() == 0,
                       Errors.create().content("Please choose rework " + "code!").build());
        reworkTransInfo.put("reasonCode", theform.getReworkCode().trim().toUpperCase());
        String reason = "[" + theform.getReworkCode().trim().toUpperCase() + "]" + sysService
                .referenceDetailExchangeNull("$$REWORK_CODE", theform.getDepartment().trim().toUpperCase(),
                                             theform.getReworkCode().trim().toUpperCase(), "data_1_value");
        reworkTransInfo.put("reason", reason);
        reworkTransInfo.put("transComments", theform.getLotComments());
        reworkTransInfo.put("CHANGE_LOT_STATUS", false + "");
        reworkTransInfo.put("reworkWflStepPath", lot.getWflStepPath());
        reworkTransInfo.put("reworkOperationRrn", lot.getOperationRrn() + "");
        reworkTransInfo.put("reworkProcessStepIdVersion", lot.getProcessStepIdVersion());
        reworkTransInfo.put("reworkProcessStepVersion", lot.getProcessStepVersion());
        // List<Lot> lockLots = new ArrayList<>();
        // lockLots.add(lot);
        // checkAndCreateLotsTransLock(LocalContext.getUserRrn(), TransactionNames.LOCK_REWORK, lockLots,
        //                             "Rework lot in ReworkLotAction by: " + userId);
        lotService.reworkLot(reworkTransInfo);
        theform.setLotId("");
        //            handlePreFutureHold(lot, facilityRrn);

        // check 是否覆盖极限,如果勾选了覆盖机限,插入情境值LOT_SPECIAL_EQUIP_CONTEXT
        //            Map tempInfo = getTempMap(lot, theform.isTargetCheckEquipConstrain(), userRrn,
        //                                      theform.getReworkRouteId(), theform.getReworkOperationId());
        return new ActionForward("/lotLocation4CSECAction.do?action=lotLocation&lotId=" + lot.getLotId());

    }

    public ActionForward showReworkInfo(ActionMapping mapping, ReworkLotInfoForm theform, HttpServletRequest request) {
        Long facilityRrn = LocalContext.getFacilityRrn();
        String lotId = theform.getLotId();
        Lot lot = lotQueryService.getLot(lotId, LocalContext.getFacilityRrn());
        request.setAttribute("inReworkFlag", lot.getReworkTransRrn() != null && lot.getReworkTransRrn() > 0);
        return mapping.findForward("lotReworkHistory");
    }

    public Map queryLotReworkInfo(Map param) {
        Map result = new HashMap();
        List dataList = new ArrayList();
        Long facilityRrn = LocalContext.getFacilityRrn();
        String lotId = MapUtils.getString(param, "lotId");
        Lot lot = lotQueryService.getLot(lotId, LocalContext.getFacilityRrn());
        if (lot == null || lot.getLotRrn() <= 0 || lot.getInt_qty1() <= 0) {
            return result;
        }
        Long reworkTransRrn = lot.getReworkTransRrn();
        if (reworkTransRrn != null && reworkTransRrn > 0) {
            //批次当前是返工状态
            Map condition = new HashMap();
            condition.put("lotRrn", lot.getLotRrn());
            condition.put("transRrn", lot.getReworkTransRrn());
            condition.put("facilityRrn", facilityRrn);
            Map<String, Object> lotCurrentReworkInfoList = lotQueryService.getLotCurrentReworkInfo(condition);
            dataList.add(lotCurrentReworkInfoList);
            result.put("dataList", dataList);
            return result;
        } else {
            //批次没有进入返工状态
            ReworkRouteContextValue contextValue = ctxExecService.buildNewReworkRouteContextValue();
            contextValue.setProcessRrn(lot.getProcessRrn());
            contextValue.setRouteRrn(lot.getRouteRrn());
            contextValue.setOperationRrn(lot.getOperationRrn());
            contextValue.setProcessVersion(lot.getProcessVersion());

            ContextValue cxt = ctxService.simulateContextValue(contextValue);
            if (cxt != null) {
                Map processInfo = new HashMap();
                processInfo.put("processRrn", lot.getProcessRrn());
                processInfo.put("processVersion", lot.getProcessVersion());
                processInfo.put("routeRrn", lot.getRouteRrn());
                processInfo.put("operationRrn", lot.getOperationRrn());
                Map showInfo = new HashMap();
                showInfo.put("routeId", lot.getRouteId());
                showInfo.put("operationId", lot.getOperationId());
                showInfo.put("routeVersion", cxt.getResultValue5());
                showInfo.put("flowSeq", ctxExecService.getFlowSeqByProcessInfo(processInfo));

                showInfo.put("reworkRouteId", getInstanceId(NumberUtils.toLong(cxt.getResultValue1())));
                showInfo.put("returnRouteId", getInstanceId(NumberUtils.toLong(cxt.getResultValue2())));
                showInfo.put("returnOperationId", getInstanceId(NumberUtils.toLong(cxt.getResultValue3())));
                showInfo.put("sumReworkCount", cxt.getResultValue4());
                showInfo.put("countWay", cxt.getResultValue6());

                String processStepVersion = lot.getProcessStepVersion();
                if (ReworkConst.CountWay.BY_ROUTE.getWay().equalsIgnoreCase(cxt.getResultValue6())) {
                    processStepVersion = processStepVersion.substring(0, processStepVersion.lastIndexOf("|"));
                }
                long reworkCount = lotQueryService.getReworkCount(lot.getLotRrn(), processStepVersion);
                long reworkCountOfUnit = lotQueryService.getMaxReworkCountByUnit(lot.getLotRrn(), processStepVersion);
                showInfo.put("reworkCount", reworkCount);
                showInfo.put("reworkCountOfUnit", reworkCountOfUnit);
                showInfo.put("reworkProcessStepVersion", processStepVersion);

                processInfo.put("routeRrn", new Long(cxt.getResultValue2()));
                processInfo.put("operationRrn", new Long(cxt.getResultValue3()));
                String returnFlowSeq = ctxExecService.getFlowSeqByProcessInfo(processInfo);
                showInfo.put("returnFlowSeq", returnFlowSeq);
                showInfo.put("lotRrn", lot.getLotRrn());
                dataList.add(showInfo);
                result.put("dataList", dataList);
                return result;
            }
        }
        return result;
    }

    public Map queryLotReworkHistoryInfo(Map param) {
        Map result = new HashMap();
        Long facilityRrn = LocalContext.getFacilityRrn();
        String lotId = MapUtils.getString(param, "lotId");
        Lot lot = lotQueryService.getLot(lotId, LocalContext.getFacilityRrn());
        int pageNo = MapUtils.getIntValue(param, "page", 1);
        int pageSize = MapUtils.getIntValue(param, "limit", 20);

        Page page = new Page();
        page.setPageSize(pageSize);
        page.setPageNo(pageNo);
        //查询返工历史
        Map hisCondition = new HashMap();
        hisCondition.put("facilityRrn", facilityRrn);
        hisCondition.put("lotRrn", lot.getLotRrn());
        page = lotQueryService.getLotReworkHistoryInfoList(page, hisCondition);
        if (page.getResults() != null && page.getResults().size() > 0) {
            result.put("dataList", page.getResults());
            result.put("totalItems", page.getTotalItems());
        }
        return result;
    }

    public Map queryUnitReworkInfo(Map param) {
        Map result = new HashMap();
        Long lotRrn = MapUtils.getLongValue(param, "lotRrn");
        Lot lot = lotQueryService.getLot(lotRrn);
        if (lot == null || lot.getLotRrn() <= 0 || lot.getInt_qty1() <= 0) {
            return result;
        }
        boolean isParentLot = lot.getLotRrn() == lot.getBasedLotRrn();
        String reworkProcessStepVersion = MapUtils.getString(param, "reworkProcessStepVersion");
        List<Map> unitReworkInfos = lotQueryService.queryUnitReworkInfo(lotRrn, reworkProcessStepVersion);
        if (CollectionUtils.isEmpty(unitReworkInfos)) {
            unitReworkInfos = wipQueryService.getUnitsByParentLotRrn(lotRrn);
        }
        unitReworkInfos = buildUnitReworkInfo(rePositionUnitList(unitReworkInfos), param, isParentLot);
        result.put("dataList", unitReworkInfos);
        return result;
    }

    private List<Map> buildUnitReworkInfo(List<Map> unitList, Map param, boolean isParentLot) {
        return unitList.stream().map(unit -> {
            String reworkCount = MapUtils.getString(unit, "reworkCount");
            if (StringUtils.isNotBlank(MapUtils.getString(unit, "unitId")) || isParentLot) {
                unit.putAll(param);
            }
            if (StringUtils.isBlank(reworkCount) && StringUtils.isNotBlank(MapUtils.getString(unit, "unitId"))) {
                unit.put("reworkCount", 0);
            } else if (StringUtils.isNotBlank(reworkCount)) {
                unit.put("reworkCount", reworkCount);
            }
            return unit;
        }).collect(Collectors.toList());
    }

    private void setTheFormSession(ReworkLotInfoForm theform, HttpServletRequest request, Lot lot, LotInfoForm lotInfo,
                                   Map<String, Object> cachePageInfo) {
        if (lot == null) {
            theform.setCacheLot(theform.getCacheLot());
            request.setAttribute(SessionNames.LOT_KEY, WebUtils.getCacheString2Obj(theform.getCacheLot()));
        } else {
            theform.setCacheLot(WebUtils.getCacheObj2String(lot));
            request.setAttribute(SessionNames.LOT_KEY, lot);
        }

        if (lotInfo == null) {
            theform.setCacheLotInfo(theform.getCacheLotInfo());
            request.setAttribute(SessionNames.LOT_INFO_FORM_KEY,
                                 WebUtils.getCacheString2Obj(theform.getCacheLotInfo()));
        } else {
            request.setAttribute(SessionNames.LOT_INFO_FORM_KEY, lotInfo);
            theform.setCacheLotInfo(WebUtils.getCacheObj2String(lotInfo));
        }

        if (cachePageInfo == null) {
            cachePageInfo = (Map<String, Object>) WebUtils.getCacheString2Obj(theform.getCachePageInfo());
        }
        if (cachePageInfo == null) {
            cachePageInfo = new HashMap<String, Object>();
        }
        theform.setCachePageInfo(WebUtils.getCacheObj2String(cachePageInfo));
        for (String key : cachePageInfo.keySet()) {
            request.setAttribute(key, MapUtils.getObject(cachePageInfo, key));
        }
    }

}