# Edc2MyspcManagerImpl.java

    package com.mycim.server.edcmyspc.manager.impl;

    import com.fa.sesa.exception.Assert;
    import com.fa.sesa.exception.Errors;
    import com.fa.sesa.exception.SystemIllegalException;
    import com.fa.sesa.threadlocal.LocalContext;
    import com.mycim.framework.logging.Logger;
    import com.mycim.framework.logging.LoggerFactory;
    import com.mycim.framework.utils.exception.ExceptionUtils;
    import com.mycim.framework.utils.lang.BooleanUtils;
    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.msg.JsonUtils;
    import com.mycim.server.base.manager.NamedObjectManager;
    import com.mycim.server.base.manager.TransactionLogManager;
    import com.mycim.server.ctx.exec.manager.ReworkRouteContextValueManager;
    import com.mycim.server.edc.manager.ParameterManager;
    import com.mycim.server.edc.manager.ParameterSetManager;
    import com.mycim.server.edcmyspc.manager.Edc2MyspcManager;
    import com.mycim.server.ems.manager.EquipmentManager;
    import com.mycim.server.prp.manager.OperationManager;
    import com.mycim.server.security.manager.UserManager;
    import com.mycim.server.spc.manager.SpcManager;
    import com.mycim.server.wip.manager.*;
    import com.mycim.utils.ChartNamingRule;
    import com.mycim.valueobject.LotConstants;
    import com.mycim.valueobject.MessageIdList;
    import com.mycim.valueobject.bas.TransactionLog;
    import com.mycim.valueobject.consts.*;
    import com.mycim.valueobject.edcspc.DataCollection;
    import com.mycim.valueobject.edcspc.Parameter;
    import com.mycim.valueobject.edcspc.Reading;
    import com.mycim.valueobject.edcspc.Sample;
    import com.mycim.valueobject.edcspc.dto.*;
    import com.mycim.valueobject.ems.Equipment;
    import com.mycim.valueobject.prp.ContextValue;
    import com.mycim.valueobject.runcard.util.RunCardUtils;
    import com.mycim.valueobject.security.User;
    import com.mycim.valueobject.spc.SpcResult;
    import com.mycim.valueobject.wip.*;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;

    import javax.print.DocFlavor;
    import java.util.*;
    import java.util.stream.Collectors;

    /**
     * @author Luopeng.Wang
     * @version 6.0.0
     * @date 2019/11/11
     **/
    @Service
    @Transactional
    public class Edc2MyspcManagerImpl implements Edc2MyspcManager {
        public static final String HOLD_GROUP = "SPC";

        public static final String HOLD_USER = "SPC";

        public static final String HOLD_CODE = "SPCHOLD";

        private static final String CHAMBER_ID_FLAG = "-";

        private final Logger logger = LoggerFactory.getLogger(Edc2MyspcManagerImpl.class);

        @Autowired
        private NamedObjectManager namedObjectManager;

        @Autowired
        private LotQueryManager lotQueryManager;

        @Autowired
        private LotInqManager lotInqManager;

        @Autowired
        private UnitQueryManager unitQueryManager;

        @Autowired
        private ParameterSetManager parameterSetManager;

        @Autowired
        private ParameterManager parameterManager;

        @Autowired
        private TransactionLogManager transactionLogManager;

        @Autowired
        private SpcManager spcManager;

        @Autowired
        private UserManager userManager;

        @Autowired
        private OperationManager operationManager;

        @Autowired
        private ReworkRouteContextValueManager reworkRouteContextValueManager;

        @Autowired
        private DiffBatchQueryManager diffBatchQueryManager;

        @Autowired
        private ElogSheetQueryManager elogSheetQueryManager;

        @Autowired
        private EquipmentManager equipmentManager;

        @Override
        public List<SpcDataCollectionDto> buildRTSpcDataForMeasure(List<Map> dcolStepInfos) {
            List<SpcDataCollectionDto> dataCollectionList = new ArrayList<>();

            Boolean batchFlag = false;
            for (Map dcolStepInfo : dcolStepInfos) {
                List<DataCollection> dataCollections = (List<DataCollection>) MapUtils
                        .getObject(dcolStepInfo, "datacollections");

                long lotRrn = dataCollections.get(0).getLotRrn();
                Lot lot = lotQueryManager.getLot(lotRrn);
                batchFlag = diffBatchQueryManager.checkLotInBatch(lotRrn);

                SpcProcessDataInfoDto[] processDataInfos = buildProcessDataInfo(lot, batchFlag);

                SpcDataCollectionDto spcDataCollection = new SpcDataCollectionDto();

                Calendar nowTime = Calendar.getInstance();
                nowTime.setTime(new Date());

                spcDataCollection.setFabID(namedObjectManager.getInstanceId(LocalContext.getFacilityRrn()));
                spcDataCollection.setOperatorID(LocalContext.getUserId());
                spcDataCollection.setEquipmentId(namedObjectManager.getInstanceId(lot.getEqptRrn()));
                spcDataCollection.setLotId(lot.getLotId());
                spcDataCollection.setLotType(lot.getLotType());
                spcDataCollection.setProductId(lot.getProductId());
                spcDataCollection.setOperationNumber(
                        (StringUtils.isNotEmpty(lot.getRouteSeq()) ? lot.getRouteSeq() : "*") + "#$#" +
                                lot.getOperationId());
                spcDataCollection.setRouteSeq(lot.getRouteSeq());
                spcDataCollection.setRouteID(lot.getRouteId());
                spcDataCollection.setOperationSeq(lot.getOperationSeq());
                spcDataCollection.setFlowSeq(lot.getFlowSeq());
                spcDataCollection.setRecipeID(lot.getRecipeId());
                spcDataCollection.setCustomer(lot.getCustomerId());
                spcDataCollection.setCustomerLot(lot.getCustomerLotId());

                spcDataCollection.setProd_1(lot.getRecipeId());
                spcDataCollection.setProd_2(lot.getProcessId());
                spcDataCollection.setProd_3(lot.getProductId());
                spcDataCollection.setProd_6(lot.getStepSequence() + "");

                //发送p站点的eqpId,TrackOutTime
                LotProcessStepInfo lotProcessStepInfo = lotQueryManager
                        .getLotProcessStepInfo(lot.getLotRrn(), StepTypeConst.PROCESSING_STEP_TYPE);

                ContextValue actionCondition = reworkRouteContextValueManager.getReworkRouteContextValueByLot(lot);
                String processStepVersion = lot.getProcessStepVersion();
                if (actionCondition != null) {
                    String countWay = actionCondition.getResultValue6();
                    if (ReworkConst.CountWay.BY_ROUTE.getWay().equalsIgnoreCase(countWay)) {
                        processStepVersion = processStepVersion.substring(0, processStepVersion.lastIndexOf("|"));
                    }
                }

                //返工次数
                List<Map<String, Long>> reworkUnitSeqs = unitQueryManager
                        .getReworkUnitSeq(lot.getLotRrn(), processStepVersion);
                List<Long> reworkCounts = reworkUnitSeqs.stream()
                                                        .map(reworkUnitSeq -> MapUtils.getLongValue(reworkUnitSeq, "num"))
                                                        .sorted(Comparator.reverseOrder()).collect(Collectors.toList());
                int reworkCount = CollectionUtils.isNotEmpty(reworkCounts) ? Math.toIntExact(reworkCounts.get(0)) : 0;
                spcDataCollection.setReworkCount(reworkCount);
                if (processDataInfos.length > 1) {
                    spcDataCollection.setProcessDataInfos(processDataInfos);
                    spcDataCollection.setBatchFlag("Y");
                } else {
                    spcDataCollection.setProcessDataInfos(new SpcProcessDataInfoDto[0]);
                    spcDataCollection.setBatchFlag("N");
                }

                if (batchFlag) {
                    spcDataCollection.setDcItems(buildDiffBatchDCitems(dataCollections));
                } else {
                    spcDataCollection.setDcItems(buildDCitems(dataCollections));
                }

                DataCollection mesDataCollection = dataCollections.get(0);
                spcDataCollection.setUsl(mesDataCollection.getUpperSpecificationLimit() != null ? mesDataCollection
                        .getUpperSpecificationLimit().doubleValue() : Double.NaN);
                spcDataCollection.setLsl(mesDataCollection.getLowerSpecificationLimit() != null ? mesDataCollection
                        .getLowerSpecificationLimit().doubleValue() : Double.NaN);
                spcDataCollection.setTartget(mesDataCollection.getTargetValue() != null ? mesDataCollection.getTargetValue()
                                                                                                           .doubleValue() : Double.NaN);

                spcDataCollection.setJobNames(
                        buildSpcJobs(mesDataCollection.getParameterSetRrn(), mesDataCollection.getParameterSetVersion()));

                spcDataCollection.setCompletionDate(nowTime);
                spcDataCollection.setReceiveTime(nowTime);
                if (lotProcessStepInfo != null) {
                    List<PInfosDto> p_infos = new ArrayList<PInfosDto>();
                    PInfosDto pInfosDto = new PInfosDto();
                    pInfosDto.setEquipment(lotProcessStepInfo.getProcessEqpId());
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(lotProcessStepInfo.getTrackOutTime());
                    pInfosDto.setpTime(calendar);
                    p_infos.add(pInfosDto);
                    spcDataCollection.setP_Infos(p_infos);
                    //判断是否是chamber设备，如果是将chamberId传给spc
                    buildChamberId(spcDataCollection,lotProcessStepInfo.getProcessEqpId());
                }

                dataCollectionList.add(spcDataCollection);
            }

            if (batchFlag) {
                return rebuildBatchDataCollection(dataCollectionList);
            } else {
                return dataCollectionList;
            }
        }

        @Override
        public List<SpcDataCollectionDto> buildSpcDataForProcess(List<Lot> lots) {
            List<SpcDataCollectionDto> dataCollectionList = new ArrayList<>();
            for (Lot lot : lots) {
                if (lot != null && lot.getLotRrn() > 0) {
                    lot = lotQueryManager.getLot(lot.getLotRrn());

                    //                Operation operation = operationManager.getOperation(lot.getOperationRrn());
                    //                if (!StringUtils.equalsIgnoreCase("on", operation.getUseSpcFlag())) {
                    //                    continue;
                    //                }

                    SpcProcessDataInfoDto[] processDataInfos = buildProcessDataInfo(lot, false);

                    SpcDataCollectionDto spcDataCollection = new SpcDataCollectionDto();

                    Calendar nowTime = Calendar.getInstance();
                    nowTime.setTime(new Date());

                    spcDataCollection.setFabID(namedObjectManager.getInstanceId(LocalContext.getFacilityRrn()));
                    spcDataCollection.setOperatorID(LocalContext.getUserId());
                    spcDataCollection.setEquipmentId(namedObjectManager.getInstanceId(lot.getEqptRrn()));
                    spcDataCollection.setFlowSeq(lot.getFlowSeq());
                    spcDataCollection.setLotId(lot.getLotId());
                    spcDataCollection.setLotType(lot.getLotType());
                    spcDataCollection.setProductId(lot.getProductId());
                    spcDataCollection.setOperationNumber(
                            (StringUtils.isNotEmpty(lot.getRouteSeq()) ? lot.getRouteSeq() : "*") + "#$#" +
                                    lot.getOperationId());
                    spcDataCollection.setRouteSeq(lot.getRouteSeq());
                    spcDataCollection.setRouteID(lot.getRouteId());
                    spcDataCollection.setOperationSeq(lot.getOperationSeq());
                    spcDataCollection.setRecipeID(lot.getRecipeId());
                    spcDataCollection.setCustomer(lot.getCustomerId());
                    spcDataCollection.setCustomerLot(lot.getCustomerLotId());

                    spcDataCollection.setProd_1(lot.getRecipeId());
                    spcDataCollection.setProd_2(lot.getProcessId());
                    spcDataCollection.setProd_3(lot.getProductId());
                    spcDataCollection.setProd_6(lot.getStepSequence() + "");

                    spcDataCollection.setDcItems(new SpcDCItemDto[0]);
                    spcDataCollection.setBatchFlag("N");
                    spcDataCollection.setProcessDataInfos(processDataInfos);

                    ContextValue actionCondition = reworkRouteContextValueManager.getReworkRouteContextValueByLot(lot);
                    String processStepVersion = lot.getProcessStepVersion();
                    if (actionCondition != null) {
                        String countWay = actionCondition.getResultValue6();
                        if (ReworkConst.CountWay.BY_ROUTE.getWay().equalsIgnoreCase(countWay)) {
                            processStepVersion = processStepVersion.substring(0, processStepVersion.lastIndexOf("|"));
                        }
                    }

                    //返工次数
                    List<Map<String, Long>> reworkUnitSeqs = unitQueryManager
                            .getReworkUnitSeq(lot.getLotRrn(), processStepVersion);
                    List<Long> reworkCounts = reworkUnitSeqs.stream().map(reworkUnitSeq -> MapUtils
                            .getLongValue(reworkUnitSeq, "num")).sorted(Comparator.reverseOrder())
                                                            .collect(Collectors.toList());
                    int reworkCount = CollectionUtils.isNotEmpty(reworkCounts) ? Math.toIntExact(reworkCounts.get(0)) : 0;
                    spcDataCollection.setReworkCount(reworkCount);

                    //                spcDataCollection.setJobNames(buildSpcJobs(mesDataCollection
                    //                .getParameterSetRrn(),
                    //                                                           mesDataCollection
                    //                                                           .getParameterSetVersion()));

                    spcDataCollection.setCompletionDate(nowTime);
                    spcDataCollection.setReceiveTime(nowTime);

                    dataCollectionList.add(spcDataCollection);
                }
            }

            return dataCollectionList;
        }

        @Override
        public void handleSpcCheckResults(String responseMsg, String requestMsg, Boolean rtFlag, Boolean processFlag,
                                          Boolean isOcapSend) {
            TransactionLog transactionLog = transactionLogManager.startTransactionLog(HOLD_USER, "EDC2SPC");
            transactionLogManager.markTransactionLog(transactionLog);
            long transRrn = transactionLog.getTransRrn();
            String excuteResult = "Sucess";
            String errorCode = StringUtils.EMPTY;
            String errorMsg = StringUtils.EMPTY;

            try {
                Assert.isFalse(StringUtils.isEmpty(responseMsg),
                               Errors.create().key(MessageIdList.ERROR_SPC_RESPONSEMSG_EMPTY).content("SPC 返回信息为空!")
                                     .build());

                SpcCheckResultDto[] spcResults = JsonUtils.toObject(responseMsg, SpcCheckResultDto[].class);
                List<SpcCheckResultDto> spcResultList = Arrays.asList(spcResults);

                List<String> holdLotIds = new ArrayList<>();

                String edcType = StringUtils.EMPTY;
                if (processFlag) {
                    edcType = "PROCESS";
                    return;
                } else {
                    edcType = rtFlag ? "RT" : "NORT";
                }

                for (SpcCheckResultDto spcCheckResult : spcResultList) {
                    if (spcCheckResult.isLotHold() && !isOcapSend) {
                        holdLotForSpc(transactionLog, spcCheckResult, edcType);
                    } else {
                        spcManager.recordSpcResult(transactionLog, spcCheckResult, edcType);
                    }
                }

            } catch (Exception e) {
                logger.error(e);
                SystemIllegalException systemIllegalException = ExceptionUtils.findSystemException(e);
                excuteResult = "Fail";
                errorCode = systemIllegalException.getCode().getErrCode();
                errorMsg = systemIllegalException.getMessage();
                throw e;
            } finally {
                //记录request 和response消息
                spcManager.insertSpcMessageLog(requestMsg, responseMsg, transRrn, excuteResult, errorCode, errorMsg);
            }

        }

        @Override
        public void holdEquipmentForMyspc(SpcHoldEquipmentRequestDto spcHoldEquipmentRequestDto) {
            TransactionLog transactionLog = transactionLogManager.startTransactionLog(HOLD_USER, "EDC2SPC");
            transactionLogManager.markTransactionLog(transactionLog);
            long transRrn = transactionLog.getTransRrn();
            String excuteResult = "Sucess";
            String errorCode = StringUtils.EMPTY;
            String errorMsg = StringUtils.EMPTY;

            int seq = 1;
            try {
                List<SpcHoldEquipmentInfoDto> holdEquipmentInfos = spcHoldEquipmentRequestDto.getHoldEquipmentInfos();
                for (SpcHoldEquipmentInfoDto holdEquipmentDto : holdEquipmentInfos) {
                    if (holdEquipmentDto.isEquipmentHold()) {
                        String equipmentId = holdEquipmentDto.getEquipmentId();
                        String holdType = holdEquipmentDto.getHoldType();
                        String reason = holdEquipmentDto.getReason();
                        String holdReasons = holdEquipmentDto.getReasonCode();
                        String alarmID = holdEquipmentDto.getAlarmID();
                        String spcErrorCode = holdEquipmentDto.getErrorCode();
                        String spcErrorMessage = holdEquipmentDto.getErrorMessage();
                        List<String> releaseEuipments = holdEquipmentDto.getReleaseEuipments();
                        spcManager.holdEquipmentForSpc("", equipmentId, HOLD_USER, HOLD_GROUP, HOLD_CODE, holdReasons, "",
                                                       holdType, alarmID, spcErrorCode, spcErrorMessage, transRrn, seq++);
                    }
                }
            } catch (Exception e) {
                logger.error(e);
                SystemIllegalException systemIllegalException = ExceptionUtils.findSystemException(e);
                excuteResult = "Fail";
                errorCode = systemIllegalException.getCode().getErrCode();
                // errorMsg = systemIllegalException.getMessage(msg -> I18nUtils.getMessage(msg));
                errorMsg = systemIllegalException.getMessage();
                throw e;
            } finally {
                //2.记录request 和response消息
                spcManager.insertSpcMessageLog(JsonUtils.toString(spcHoldEquipmentRequestDto), StringUtils.EMPTY, transRrn,
                                               excuteResult, errorCode, errorMsg);
            }
        }

        private void holdLotForSpc(TransactionLog transactionLog, SpcCheckResultDto spcCheckResultDto, String edcType) {
            String holdUser = HOLD_USER;
            String holdGroup = HOLD_GROUP;
            String holdCode = HOLD_CODE;

            String holdDesp = spcCheckResultDto.getHoldDesp();
            List<String> holdRoles = new ArrayList<String>();
            holdRoles.add(holdDesp);
            holdRoles.add(LotStatus.ALL);
            List<Map> holdReasonCodes = lotQueryManager
                    .getHoldReasonCodes(holdDesp, holdRoles, ReferenceDetailNames.HOLD_CODE);
            for (Map map : holdReasonCodes) {
                if (MapUtils.getString(map, LotHoldConts.MapKey.KEY_HOLD_CODE).contains(HoldCodeNames.SPC_HOLD_CODE)) {
                    holdGroup = StringUtils.isNotBlank(holdDesp)?holdDesp:holdGroup;
                    holdCode = MapUtils.getString(map, LotHoldConts.MapKey.KEY_HOLD_CODE);
                    break;
                }
            }
            spcManager.holdLotForSpc(transactionLog,spcCheckResultDto,edcType,holdUser,holdGroup,holdCode);
        }

        private SpcDCItemDto[] buildDCitems(List<DataCollection> dataCollections) {
            List<SpcDCItemDto> dcItemList = new ArrayList<SpcDCItemDto>();

            for (DataCollection mesDataCollection : dataCollections) {
                Long parameterRrn = mesDataCollection.getParameterRrn();

                Parameter parameter = new Parameter();
                parameter.setInstanceRrn(parameterRrn);
                parameter = parameterManager.getParameter(parameter);

                // 根据SampleID对SampleList分组
                if (parameter != null) {
                    List<Sample> samples = (List<Sample>) mesDataCollection.getSamples();

                    for (Sample sample : samples) {
                        List<Reading> readings = (List<Reading>) sample.getReadings();
                        Unit unit = unitQueryManager.getUnit(LocalContext.getFacilityRrn(), sample.getSampleId());
                        for (Reading reading : readings) {
                            SpcDCItemDto item = new SpcDCItemDto();
                            item.setDataCollectionItemName(parameter.getInstanceId());
                            item.setWaferId(sample.getSampleId());
                            item.setWaferPosition(String.valueOf(unit.getPositionInCarrier()));
                            item.setSiteID(reading.getReadingId());
                            item.setSitePosition(String.valueOf(reading.getReadingSequence()));
                            item.setBumpPosition("");
                            item.setBumpID("");
                            item.setDataValue(String.valueOf(reading.getDataValue()));

                            dcItemList.add(item);
                        }
                    }
                }

            }
            SpcDCItemDto[] dcItems = new SpcDCItemDto[dcItemList.size()];
            return orderByWaferId(dcItemList).toArray(dcItems);
        }

        private SpcDCItemDto[] buildDiffBatchDCitems(List<DataCollection> dataCollections) {
            List<SpcDCItemDto> dcItemList = new ArrayList<SpcDCItemDto>();

            for (DataCollection mesDataCollection : dataCollections) {
                Long parameterRrn = mesDataCollection.getParameterRrn();
                String lotId = lotInqManager.getLotId(mesDataCollection.getLotRrn());

                Parameter parameter = new Parameter();
                parameter.setInstanceRrn(parameterRrn);
                parameter = parameterManager.getParameter(parameter);

                // 根据SampleID对SampleList分组
                if (parameter != null) {
                    List<Sample> samples = (List<Sample>) mesDataCollection.getSamples();

                    for (Sample sample : samples) {
                        List<Reading> readings = (List<Reading>) sample.getReadings();
                        for (Reading reading : readings) {
                            SpcDCItemDto item = new SpcDCItemDto();
                            item.setLotId(lotId);
                            item.setDataCollectionItemName(parameter.getInstanceId());
                            item.setWaferId(sample.getSampleId());
                            item.setWaferPosition(StringUtils.toString(sample.getSampleSequence()));
                            item.setSiteID(reading.getReadingId());
                            item.setSitePosition(String.valueOf(reading.getReadingSequence()));
                            item.setBumpPosition("");
                            item.setBumpID("");
                            item.setDataValue(String.valueOf(reading.getDataValue()));

                            dcItemList.add(item);
                        }
                    }
                }

            }
            SpcDCItemDto[] dcItems = new SpcDCItemDto[dcItemList.size()];
            return orderByWaferId(dcItemList).toArray(dcItems);
        }
        //需求40969  数据按照waferid从大到小的顺序排序
        private List<SpcDCItemDto> orderByWaferId(List<SpcDCItemDto> dcItemList){
            Collections.sort(dcItemList, new Comparator<SpcDCItemDto>() {
                @Override
                public int compare(SpcDCItemDto o1, SpcDCItemDto o2) {
                   String[]o1Arr=  o1.getWaferId().split("#");
                   String[]o2Arr= o2.getWaferId().split("#");
                   return Integer.compare(Integer.parseInt(o1Arr.length>=2?o1Arr[1]:"0"),Integer.parseInt(o2Arr.length>=2?o2Arr[1]:"0"));
                }
            });
            return dcItemList;
        }
        private SpcProcessDataInfoDto[] buildProcessDataInfo(Lot lot, Boolean batchFlag) {
            List<SpcProcessDataInfoDto> processDataInfoList = new ArrayList();

            if (batchFlag) {
                List<BatchLotStore> lotBatchList = diffBatchQueryManager.getBatchStoreListByLot(lot.getLotRrn());
                for (int i = 0; i < lotBatchList.size(); i++) {
                    Lot batchLot = lotQueryManager.getLot(lotBatchList.get(i).getLotRrn());

                    if(!RunCardUtils.checkLotIdIsRunCardLot(batchLot.getLotId())) {
                        SpcProcessDataInfoDto processDataInfo = new SpcProcessDataInfoDto();
                        processDataInfo.setProcessLotId(batchLot.getLotId());
                        processDataInfo.setProcessLotType(batchLot.getLotType());
                        processDataInfo.setProcessOperationNumber(batchLot.getOperationId());
                        processDataInfo.setProcessSubLotType(batchLot.getLotType());
                        processDataInfo.setProcessRecipeId(batchLot.getRecipePhysicalId());
                        processDataInfo.setProcessProductId(batchLot.getProductId());

                        processDataInfoList.add(processDataInfo);
                        break;
                    }
                }
            } else {
                SpcProcessDataInfoDto processDataInfo = new SpcProcessDataInfoDto();

                processDataInfo.setProcessLotId(lot.getLotId());
                processDataInfo.setProcessLotType(lot.getLotType());
                processDataInfo.setProcessOperationNumber(lot.getOperationId());
                processDataInfo.setProcessSubLotType(lot.getLotType());
                processDataInfo.setProcessRecipeId(lot.getRecipePhysicalId());
                processDataInfo.setProcessProductId(lot.getProductId());

                processDataInfoList.add(processDataInfo);
            }

            SpcProcessDataInfoDto[] processDataInfos = new SpcProcessDataInfoDto[processDataInfoList.size()];
            return processDataInfoList.toArray(processDataInfos);
        }

        private String handleSpcEmptyValue(String source) {
            return StringUtils.isEmpty(source) ? "" : source;
        }

        private String[] buildSpcJobs(long parameterSetRrn, int parameterSetVersion) {
            List parameters = parameterSetManager.getParameters(parameterSetRrn, parameterSetVersion);

            if (parameters != null && !parameters.isEmpty()) {
                String[] spcJob = new String[parameters.size()];
                for (int i = 0; i < parameters.size(); i++) {
                    Map parameter = (Map) parameters.get(i);
                    String parameterId = MapUtils.getString(parameter, "parameterId", StringUtils.EMPTY);
                    // TODO: 2021/4/29 临时解决北京项目jobName，后期需要去掉 start
                    if (StringUtils.isNotEmpty(parameterId) && parameterId.length() > 2) {
                        Integer mIndex = StringUtils.indexOf(parameterId, "M");
                        if (mIndex == 1) {
                            parameterId = new StringBuilder(parameterId).replace(1, 2, "").toString();
                        }
                    }
                    // 2021/4/29 临时解决北京项目jobName，后期需要去掉 end
                    spcJob[i] = parameterId;
                }
                return spcJob;
            }
            return null;
        }

        private List<SpcDataCollectionDto> rebuildBatchDataCollection(List<SpcDataCollectionDto> baseDtoList) {

            if (baseDtoList.size() > 1) {
                SpcDataCollectionDto baseDataCollectionDto = baseDtoList.get(0);

                String lotId = baseDataCollectionDto.getLotId();
                List<BatchLotStore> batchLotStoreList = diffBatchQueryManager
                        .getBatchStoreListByLot(lotQueryManager.getLotRrn(lotId));
                setBatchDataCollectionBaseInfo(baseDataCollectionDto, batchLotStoreList);
                setBatchDataCollectionDcItemAndJobNames(baseDtoList, baseDataCollectionDto);

                List<SpcDataCollectionDto> targetDcList = new ArrayList<SpcDataCollectionDto>();
                targetDcList.add(baseDataCollectionDto);
                return targetDcList;
            }
            return baseDtoList;
        }

        private void setBatchDataCollectionBaseInfo(SpcDataCollectionDto baseDataCollectionDto,
                                                    List<BatchLotStore> batchLotStoreList) {
            String batchLotIds = StringUtils.EMPTY;
            String batchProductIds = StringUtils.EMPTY;
            String batchId = StringUtils.EMPTY;
            for (BatchLotStore batchLotStore : batchLotStoreList) {
                Lot batchLot = lotQueryManager.getLot(batchLotStore.getLotRrn());
                batchId = batchLotStore.getBatchId();
                batchLotIds += batchLot.getLotId() + LotConstants.DEFAULY_SEPARATOR;
                batchProductIds += batchLot.getProductId() + LotConstants.DEFAULY_SEPARATOR;
            }

            baseDataCollectionDto.setBatchInfo(batchId);
            baseDataCollectionDto.setBatchLot(StringUtils.substringBeforeLast(batchLotIds, LotConstants.DEFAULY_SEPARATOR));
            baseDataCollectionDto
                    .setBatchProductID(StringUtils.substringBeforeLast(batchProductIds, LotConstants.DEFAULY_SEPARATOR));
            baseDataCollectionDto.setBatchSize(batchLotStoreList.size());
        }

        private void setBatchDataCollectionDcItemAndJobNames(List<SpcDataCollectionDto> baseDtoList,
                                                             SpcDataCollectionDto baseDataCollectionDto) {
            List<String> jobNames = new ArrayList<>();
            List<SpcDCItemDto> dcItemDtoList = new ArrayList<>();
            dcItemDtoList.addAll(Arrays.asList(baseDataCollectionDto.getDcItems()));
            for (SpcDCItemDto baseDcItemDto : dcItemDtoList) {
                String jobName = ChartNamingRule.getChartNameByParameterId(baseDcItemDto.getDataCollectionItemName());
                if (!jobNames.contains(jobName)) {
                    jobNames.add(jobName);
                }
            }
            for (SpcDataCollectionDto dataCollection : baseDtoList) {
                for (SpcDCItemDto dcItemDto : dataCollection.getDcItems()) {
                    String itemName = dcItemDto.getDataCollectionItemName();
                    if (!jobNames.contains(ChartNamingRule.getChartNameByParameterId(itemName))) {
                        dcItemDtoList.add(dcItemDto);
                    }
                }
            }
            for (SpcDCItemDto baseDcItemDto : dcItemDtoList) {
                String jobName = ChartNamingRule.getChartNameByParameterId(baseDcItemDto.getDataCollectionItemName());
                if (!jobNames.contains(jobName)) {
                    jobNames.add(jobName);
                }
            }
            baseDataCollectionDto.setJobNames(jobNames.toArray(new String[jobNames.size()]));
            baseDataCollectionDto.setDcItems(dcItemDtoList.toArray(new SpcDCItemDto[dcItemDtoList.size()]));
        }

        private void buildChamberId(SpcDataCollectionDto spcDataCollection,String equipmentId){

            boolean isChamberEquipment = false;
            String lotId = spcDataCollection.getLotId();
            if (StringUtils.isNotBlank(equipmentId)) {
                Equipment equipment = equipmentManager.getEquipment(equipmentId, LocalContext.getFacilityRrn());

                isChamberEquipment = BooleanUtils.toBoolean(equipment.getIsChamberEquip());
            }
            if (isChamberEquipment) {
                List<Map<String, Object>> elogChamberSheets = elogSheetQueryManager.getElogChamberSheet(lotId, equipmentId);
                HashMap<String, String> chamMap = MapUtils.newHashMap();

                for (Map<String, Object> elogSheet : elogChamberSheets) {
                    String unitId = MapUtils.getString(elogSheet, "unitId");
                    String eqptId = MapUtils.getString(elogSheet, "eqptId");
                    String chamberType = MapUtils.getString(elogSheet, "chamberType");
                    chamMap.put(unitId, eqptId + CHAMBER_ID_FLAG + chamberType);
                }

               SpcDCItemDto[] dcItems = spcDataCollection.getDcItems();
               for (SpcDCItemDto dcItem : dcItems) {
                   String chamberId = chamMap.get(dcItem.getWaferId());
                   if (StringUtils.isNotBlank(chamberId)) {
                       dcItem.setChamberID(chamberId);
                   }else {
                       dcItem.setChamberID(StringUtils.EMPTY);
                   }

               }
            }
        }

    }