ViewUnitOfLotHistoryAction.java

package com.mycim.webapp.actions.unit.viewunitoflothistory;

import com.fa.sesa.exception.Assert;
import com.fa.sesa.exception.Errors;
import com.fa.sesa.i18n.I18nUtils;
import com.fa.sesa.threadlocal.LocalContext;
import com.mycim.framework.utils.lang.StringUtils;
import com.mycim.framework.utils.lang.collections.MapUtils;
import com.mycim.framework.utils.lang.time.DateUtils;
import com.mycim.framework.utils.msg.JsonUtils;
import com.mycim.valueobject.MessageIdList;
import com.mycim.valueobject.ObjectList;
import com.mycim.valueobject.consts.TransactionNames;
import com.mycim.valueobject.prp.Operation;
import com.mycim.valueobject.wip.Unit;
import com.mycim.webapp.TemplateLocation;
import com.mycim.webapp.WebUtils;
import com.mycim.webapp.actions.WipSetupAction;
import org.apache.commons.lang3.math.NumberUtils;
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.*;

/**
 * 查看晶圆片加工流程历史信息
 *
 * @author weike.li
 * @version 6.0.0
 * @date 2019/9/23
 **/
public class ViewUnitOfLotHistoryAction extends WipSetupAction {
    private static final String CN = "CN";

    @Override
    public ActionForward init(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                              HttpServletResponse response) {
        Long facility = LocalContext.getFacilityRrn();
        String unitId = request.getParameter("unitId");
        Unit unit = null;
        if (StringUtils.isNotEmpty(unitId)) {
            unit = wipQueryService.getUnit(facility, unitId);
        }
        if (unit == null) {
            return mapping.findForward("init");
        }
        return mapping.findForward("lothistorybyunit");
    }

    public Map query(Map map) {

        String language = I18nUtils.getCurrentLanguage().toString();

        String unitId = StringUtils.trim((String) map.get("unitId"));
        List<Map<String,Long>>lotInfo = null;

        if (StringUtils.isNotEmpty(unitId)) {
            lotInfo = wipQueryService.getLotRrnFromUnitStepRangeHistory(StringUtils.trim(unitId).toUpperCase());
        }
        Map condition = new HashMap();
        List lotHistory = null;
        Map returnResult = new HashMap();
        Map result;
        List resultArray = new ArrayList();

        int i = 1;
        for (Map<String,Long> obj : lotInfo) {
            Long lotRrn =obj.get("LOT_RRN");
            condition.put("lotRrn", lotRrn);
            lotHistory = lotQueryService.qryLotHistoryExp(lotRrn);

            for (Object listHis : lotHistory) {
                Map object = (Map) listHis;
                List operationList = (List) object.get(object.get("operationRrn"));
                result = new HashMap();
                StringBuffer transId = new StringBuffer();
                StringBuffer holdReason = new StringBuffer();
                StringBuffer trackInTime = new StringBuffer();
                StringBuffer trackInUser = new StringBuffer();
                String lastTrackInTime = null;
                StringBuffer trackOutTime = new StringBuffer();
                StringBuffer trackOutUser = new StringBuffer();
                String lastTrackOutTime = null;
                StringBuffer holdComments = new StringBuffer();
                StringBuffer holdUsers = new StringBuffer();
                StringBuffer releaseComments = new StringBuffer();
                StringBuffer splitLots = new StringBuffer();
                StringBuffer mergeLots = new StringBuffer();
                StringBuffer reworkFlag = new StringBuffer();
                StringBuffer scrapFlag = new StringBuffer();
                StringBuffer action = new StringBuffer();
                StringBuffer reticleId = new StringBuffer();
                StringBuffer stepComments = new StringBuffer();
                String parameterData = "";
                StringBuffer operationParameters = new StringBuffer();
                StringBuffer spcJob = new StringBuffer();

                boolean firstFlag = true;
                int holdCount = 0;
                for (Object operationLis : operationList) {
                    result.put("stepSeq", new Integer(i));
                    Map lotTransmap = (Map) operationLis;
                    String tempTransId = (String) lotTransmap.get("trans_id");
                    transId.append(tempTransId).append(" ");

                    if (firstFlag) {
                        result.put("lotId", lotTransmap.get("lot_id"));
                        result.put("productId", object.get("product_id"));
                        result.put("processId", object.get("technology_id"));
                        result.put("equipId", object.get("equipment_id"));
                        result.put("stageId", lotTransmap.get("stageId"));
                        result.put("routeId", lotTransmap.get("route_id"));
                        result.put("routeDesc", getInstanceDesc(
                                getInstanceRrn(String.valueOf(lotTransmap.get("route_id")), "MYCIM2",
                                               ObjectList.WFL_KEY)));

                        addOperation(result, lotTransmap);

                        result.put("recipeId", lotTransmap.get("recipePhysicalId"));

                        result.put("recipeParam", lotTransmap.get("recipeParam"));

                        result.put("quantity", lotTransmap.get("qty_1"));
                        result.put("lotPollutionLevel", lotTransmap.get("lotPollutionLevel"));
                        result.put("lotPollutionLevelAfter", "");
                        result.put("operationSeq", lotTransmap.get("operationSeq"));
                        result.put("routeSeq", lotTransmap.get("routeSeq"));
                        result.put("hotFlag", lotTransmap.get("hotFlag"));
                        result.put("priority", lotTransmap.get("priority"));
                        result.put("createCategory", lotTransmap.get("createCategory"));
                        condition.put("lotRrn", lotRrn.toString());
                        condition.put("stepSequence", lotTransmap.get("step_sequence"));
                        result.put("operationDesc", lotTransmap.get("operationDesc"));
                        result.put("processStepIdVersion", MapUtils.getString(lotTransmap, "processStepIdVersion"));

                        List comments = lotQueryService.qryLotStepHistoryComment(lotRrn, NumberUtils
                                .toLong((String) lotTransmap.get("step_sequence")), 1, 1000);
                        for (Object commentLis : comments) {
                            Map comment = (Map) commentLis;
                            stepComments.append("(").append(comment.get("commentSequence")).append(")")
                                        .append(comment.get("stepComment")).append(";");

                        }

                        firstFlag = false;
                    }
                    if (lotTransmap.get("reticleId") != null &&
                            !(reticleId.indexOf((String) lotTransmap.get("reticleId")) > 0)) {
                        reticleId.append(lotTransmap.get("reticleId")).append(" ");
                    }
                    result.put("reticleId", lotTransmap.get("reticleId"));
                    if (TransactionNames.HOLD_KEY.equals(tempTransId)) {
                        holdReason.append(lotTransmap.get("reason")).append(" ");
                        holdComments.append(lotTransmap.get("comments")).append(" ");
                        holdUsers.append(lotTransmap.get("trans_performed_by")).append(" ");
                        holdCount++;
                    }
                    if (TransactionNames.RELEASE_KEY.equals(tempTransId)) {
                        releaseComments.append(lotTransmap.get("reason")).append(" ");
                    }

                    if (TransactionNames.MOVEIN_KEY.equals(tempTransId)) {
                        trackInTime.append(lotTransmap.get("trans_start_timestamp")).append(" ");
                        trackInUser.append(lotTransmap.get("trans_performed_by")).append(" ");
                        lastTrackInTime = (String) lotTransmap.get("trans_start_timestamp");
                    }
                    if (TransactionNames.MOVEOUT_KEY.equals(tempTransId)) {
                        trackOutTime.append(lotTransmap.get("trans_start_timestamp")).append(" ");
                        trackOutUser.append(lotTransmap.get("trans_performed_by")).append(" ");
                        lastTrackOutTime = (String) lotTransmap.get("trans_start_timestamp");
                    }

                    if (TransactionNames.SPLIT_KEY.equals(tempTransId)) {
                        splitLots.append(lotTransmap.get("to_lot_id")).append(" ");
                    }
                    if (TransactionNames.MERGE_KEY.equals(tempTransId)) {
                        mergeLots.append(lotTransmap.get("to_lot_id")).append(" ");
                    }

                    if (TransactionNames.EXTERNALREWORK_KEY.equals(tempTransId) ||
                            TransactionNames.INTERNALREWORK_KEY.equals(tempTransId)) {
                        reworkFlag.append("rework").append(" ");
                    }

                    if (TransactionNames.SCRAP_KEY.equals(tempTransId)) {
                        scrapFlag.append(lotTransmap.get("lotId")).append(" ");
                    }
                    if ((!TransactionNames.MOVEIN_KEY.equals(tempTransId)) &&
                            (!TransactionNames.MOVEOUT_KEY.equals(tempTransId)) &&
                            (!TransactionNames.DISPATCH_KEY.equals(tempTransId)) &&
                            (!TransactionNames.MOVENEXT_KEY.equals(tempTransId)) &&
                            (!TransactionNames.CREATE_KEY.equals(tempTransId))
                            // && (!TransactionNames.START_KEY.equals(tempTransId))
                            && (!TransactionNames.SPLIT_HOLD_KEY.equals(tempTransId)) &&
                            (!TransactionNames.SPLIT_RELEASE_KEY.equals(tempTransId)) &&
                            (!TransactionNames.LBRD_KEY.equals(tempTransId))

                    ) {
                        // 结尾使用<br>,以便前台显示时能够换行
                        if (StringUtils.equalsIgnoreCase("CN", language)) {
                            action.append(tempTransId).append(": ").append(lotTransmap.get("trans_start_timestamp"))
                                  .append(" 操作者: ").append(lotTransmap.get("trans_performed_by")).append(" 原因: ")
                                  .append(convertNull2Blank(lotTransmap.get("reason"))).append(" 备注: ")
                                  .append(convertNull2Blank(lotTransmap.get("comments"))).append("<br>");
                        } else {
                            action.append(tempTransId).append(": ").append(lotTransmap.get("trans_start_timestamp"))
                                  .append(" Operator: ").append(lotTransmap.get("trans_performed_by"))
                                  .append(" Reason: ").append(convertNull2Blank(lotTransmap.get("reason")))
                                  .append(" Remarks: ").append(convertNull2Blank(lotTransmap.get("comments")))
                                  .append("<br>");
                        }
                    }
                }
                result.put("transId", transId.toString());
                result.put("trackInTime", trackInTime.toString().trim());
                result.put("trackInUser", trackInUser.toString().trim());
                result.put("trackOutTime", trackOutTime.toString().trim());
                result.put("trackOutUser", trackOutUser.toString().trim());
                String processTime = "";
                if (lastTrackInTime != null && lastTrackOutTime != null) {
                    Date lastTrackInDate = DateUtils.stringToTimestamp(lastTrackInTime);
                    Date lastTrackOutDate = DateUtils.stringToTimestamp(lastTrackOutTime);
                    if (lastTrackOutDate.getTime() > lastTrackInDate.getTime()) {
                        processTime = DateUtils
                                .formatDateForSeconds((lastTrackOutDate.getTime() - lastTrackInDate.getTime()) / 1000);
                    }
                }
                result.put("processTime", processTime);

                result.put("holdReson", holdReason.toString());
                result.put("holdComment", holdComments.toString());
                result.put("holdUser", holdUsers.toString());
                result.put("releaseComment", releaseComments.toString());
                if (holdCount > 0) {
                    result.put("holdFlag", holdCount + "");
                }

                result.put("splitLots", splitLots.toString());
                result.put("mergeLots", mergeLots.toString());

                result.put("reworkFlag", reworkFlag.toString().trim());

                result.put("scrapFlag", scrapFlag.toString());
                // 去除action中的最后一个<br>
                String actionStr = action.toString().trim();
                if (actionStr.length() > 0) {
                    if (actionStr.substring(actionStr.length() - 4).equals("<br>")) {
                        actionStr = actionStr.substring(0, actionStr.length() - 4);
                    }
                }
                result.put("action", actionStr);
                result.put("stepComment", stepComments.toString());

                parameterData = wipQueryService.getParamCon(lotRrn, condition.get("stepSequence").toString());
                if (StringUtils.isNotEmpty(parameterData)) {
                    if (parameterData.substring(parameterData.length() - 4).equals("<br>")) {
                        parameterData = parameterData.substring(0, parameterData.length() - 4);
                    }
                }
                result.put("edcParameter", parameterData);

                Long stepSequence = MapUtils.getLong(result, "stepSequence");
                List operationParameterList = prpService.getOperationParameters(lotRrn, stepSequence);

                for (Iterator iterator2 = operationParameterList.iterator(); iterator2.hasNext(); ) {
                    Map operationParameter = (Map) iterator2.next();
                    String operationParameterId = MapUtils.getString(operationParameter, "operationParameterId");
                    String operationParameterDesc = sysService
                            .referenceDetailExchangeNull("$$OPERATION_PARAMETER", operationParameterId, "DATA_1_VALUE");
                    operationParameters.append(operationParameterDesc);
                    operationParameters.append(":");
                    operationParameters.append(MapUtils.getString(operationParameter, "operationParameterValue"));
                    if (iterator2.hasNext()) {
                        operationParameters.append("<br>");
                    }
                }
                result.put("operationParameters", operationParameters.toString());
                //TODO:spc的东西可能不用了
                    /*if (StringUtils.isNotEmptyTrim(parameterData)) {
                        int  k              = 1;
                        List spcJobInfoList = getSpcJobInfo(lotRrn,stepSequence);
                        if (spcJobInfoList.size() > 0) {
                            for (Iterator iterator2 = spcJobInfoList.iterator(); iterator2.hasNext(); ) {
                                Map    spcJobInfo = (Map) iterator2.next();
                                String reasonCode = MapUtils.getString(spcJobInfo, "reasonCode");
                                if (StringUtils.isNotEmpty(reasonCode)) {
                                    spcJob.append(k++);
                                    spcJob.append(":");
                                    spcJob.append(reasonCode);
                                    if (iterator2.hasNext()) {
                                        spcJob.append("<br>");
                                    }
                                }
                            }
                        }
                        result.put("spcJobInfo", spcJob.toString());
                    }*/
                resultArray.add(result);
                i++;
            }
        }
        returnResult.put("rows", resultArray);
        returnResult.put("success", "true");
        return returnResult;
    }

    public ActionForward validLotHistory(ActionMapping mapping, HttpServletRequest request) {
        Long facility = LocalContext.getFacilityRrn();
        String unitId = StringUtils.trim(request.getParameter("unitId"));

        Unit unit = null;
        if (unitId != null && !unitId.trim().equals("")) {
            unit = wipQueryService.getUnit(facility, unitId);
        }
        Assert.notNull(unit, Errors.create().key(MessageIdList.UNIT_MISSING_ID).content("No such unit exist!").build());

        Map lotBaseInfo = new HashMap();
        lotBaseInfo.put("unitId", unit.getUnitId());
        lotBaseInfo.put("unitRrn", unit.getUnitRrn());
        lotBaseInfo.put("unitStatus", unit.getUnitStatus());

        String resultLotBaseInfo = JsonUtils.toString(lotBaseInfo);
        request.setAttribute("lot_base_info", resultLotBaseInfo);
        request.setAttribute("from", request.getParameter("from"));
        request.setAttribute("unit_id", unitId);

        return mapping.findForward("lothistorybyunit");
    }

    public ActionForward export(HttpServletRequest request, HttpServletResponse response) throws Exception {

        Long facility = LocalContext.getFacilityRrn();

        String unitId = request.getParameter("unitId");

        Unit unit = null;
        if (unitId != null && !unitId.trim().equals("")) {
            unit = wipQueryService.getUnit(facility, unitId);
        }
        Map map = new HashMap();
        map.put("unitId", request.getParameter("unitId"));
        List<Map> unitOfLotHistory = (List<Map>) query(map).get("rows");

        Map<String, Object> titles = WebUtils.getExportTitles(request);
        if (CN.equals(I18nUtils.getCurrentLanguage())) {
            titles.put("stepSeq", "序号");
            titles.put("title", "批次工步历史信息");
            titles.put("titleWaferId", "片号:" + unitId);
            titles.put("titleWaferStatus", "状态:" + unit.getUnitStatus());
        } else {
            titles.put("stepSeq", "No.");
            titles.put("title", "Lot history information");
            titles.put("titleWaferId", "Wafer Id:" + unitId);
            titles.put("titleWaferStatus", "Status:" + unit.getUnitStatus());
        }

        String exportDateTime = DateUtils.getNowTime(DateUtils.DATE_FORMAT4NOSPLICING);
        String fileName = "lot_" + exportDateTime + ".xlsx";

        WebUtils.exportExcel(fileName, titles, unitOfLotHistory, TemplateLocation.UNIT_OF_LOT_HISTORY, response);
        return WebUtils.NULLActionForward;
    }

    private void addOperation(Map result, Map object) {
        if (NumberUtils.isCreatable((String) object.get("operation_rrn"))) {
            Operation operation = prpService.getOperation(NumberUtils.toLong((String) object.get("operation_rrn")));
            if (operation != null) {
                result.put("operationDesc", operation.getInstanceDesc());
                result.put("operationId", operation.getInstanceId());

                String operationType = sysService
                        .referenceDetailExchangeNull("$OPERATION_TYPE", operation.getObjectType(), "DATA_1_VALUE");
                result.put("operationType", operationType);

                if (operation != null && StringUtils.isNotEmpty(operation.getWorkArea())) {
                    String workArea = sysService
                            .referenceDetailExchangeNull("$$WORK_AREA", operation.getWorkArea(), "DATA_1_VALUE");
                    result.put("workArea", workArea);
                }

                result.put("edcFlag", operation.getMoveInRequired());
            }
        }
    }

    private String convertNull2Blank(Object obj) {
        String str = "";
        if (obj != null && (obj instanceof String) && !"null".equals(obj)) {
            return obj.toString();
        }
        return str;
    }

}