package com.xisc.pm.app.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.hzero.boot.platform.code.builder.CodeRuleBuilder;
import org.hzero.boot.platform.code.constant.CodeConstants;
import org.hzero.boot.platform.lov.adapter.LovAdapter;
import org.hzero.core.base.AopProxy;
import org.hzero.core.base.BaseAppService;
import org.hzero.core.base.BaseConstants;
import org.hzero.core.redis.RedisHelper;
import org.hzero.mybatis.domian.Condition;
import org.hzero.mybatis.helper.SecurityTokenHelper;
import org.hzero.mybatis.util.Sqls;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.xisc.pm.api.dto.PmCompositeSlabCalcDTO;
import com.xisc.pm.api.dto.PmProContFilterResposeDTO;
import com.xisc.pm.api.dto.PmProContYieldResposeDTO;
import com.xisc.pm.api.dto.ctevent.ProContBoardEndDTO;
import com.xisc.pm.app.service.PmAutoPdResultService;
import com.xisc.pm.app.service.autoboard.config.CalcLog;
import com.xisc.pm.app.service.autoboard.dto.PmAutoBoardExecResult;
import com.xisc.pm.app.service.autoboard.dto.PmAutoBoardPolicyGroupDTO;
import com.xisc.pm.app.service.autoboard.dto.PmAutoPdCheckDTO;
import com.xisc.pm.app.service.autoboard.dto.PmAutoPdContractSummaryDTO;
import com.xisc.pm.app.service.autoboard.dto.PmAutoPdLog;
import com.xisc.pm.app.service.autoboard.dto.PmAutoPdPublishedDTO;
import com.xisc.pm.app.service.autoboard.dto.PmAutoPdPublishedDetailDTO;
import com.xisc.pm.app.service.autoboard.dto.PmAutoPdPublishedRequestDTO;
import com.xisc.pm.app.service.autoboard.dto.PmAutoPdResultRequestDTO;
import com.xisc.pm.app.service.autoboard.dto.PmAutoPdVersionDTO;
import com.xisc.pm.app.service.autoboard.dto.PmPdResultDTO;
import com.xisc.pm.domain.entity.PmAutoPdContract;
import com.xisc.pm.domain.entity.PmAutoPdPosition;
import com.xisc.pm.domain.entity.PmAutoPdPubllished;
import com.xisc.pm.domain.entity.PmAutoPdResult;
import com.xisc.pm.domain.entity.PmContMscTech;
import com.xisc.pm.domain.entity.PmPdBlockPos;
import com.xisc.pm.domain.entity.PmPdCcSlab;
import com.xisc.pm.domain.entity.PmPdContSum;
import com.xisc.pm.domain.entity.PmPdPlateCut;
import com.xisc.pm.domain.entity.PmRequestInfo;
import com.xisc.pm.domain.entity.PmRuntimeContract;
import com.xisc.pm.domain.entity.PmSmallPltPos;
import com.xisc.pm.domain.entity.PmSteelTypeGroup;
import com.xisc.pm.domain.repository.PmAutoPdContractRepository;
import com.xisc.pm.domain.repository.PmAutoPdPositionRepository;
import com.xisc.pm.domain.repository.PmAutoPdResultRepository;
import com.xisc.pm.domain.repository.PmContMscTechRepository;
import com.xisc.pm.domain.repository.PmProContRepository;
import com.xisc.pm.domain.repository.PmRequestInfoRepository;
import com.xisc.pm.domain.repository.PmRuntimeContractRepository;
import com.xisc.pm.domain.repository.PmSteelTypeGroupRepository;
import com.xisc.pm.infra.client.EventClient;
import com.xisc.pm.infra.constant.Constants;
import com.xisc.pm.infra.constant.Constants.AutoManualFlag;
import com.xisc.pm.infra.constant.Constants.CcType;
import com.xisc.pm.infra.constant.Constants.PdStatusHp;
import com.xisc.pm.infra.constant.CtEventConstants;
import com.xisc.pm.infra.constant.PmPlateConstants;
import com.xisc.pm.infra.enums.AutoPdRequestStatus;
import com.xisc.pm.infra.enums.CutPositionType;
import com.xisc.pm.infra.enums.CutType;
import com.xisc.pm.infra.enums.PdMatType;
import com.xisc.pm.infra.enums.PdProdFlag;
import com.xisc.pm.infra.util.BatchInsertUtils;
import com.xisc.pm.infra.util.Utils;

import io.choerodon.core.domain.Page;
import io.choerodon.core.domain.PageInfo;
import io.choerodon.core.exception.CommonException;
import io.choerodon.core.oauth.DetailsHelper;
import io.choerodon.mybatis.pagehelper.PageHelper;
import io.choerodon.mybatis.pagehelper.domain.PageRequest;
import io.seata.spring.annotation.GlobalTransactional;

/**
 * 自动组板结果信息表应用服务默认实现
 *
 * @author jun.zeng 2024-11-21 11:05:36
 */
@Service
public class PmAutoPdResultServiceImpl extends BaseAppService implements PmAutoPdResultService , AopProxy<PmAutoPdResultService> {

    @Autowired
    private PmAutoPdResultRepository pmAutoPdResultRepository;

    @Autowired
    private PmAutoPdPositionRepository pmAutoPdPositionRepository;

    @Autowired
    private PmAutoPdContractRepository pmAutoPdContractRepository;

    @Autowired
    private PmRequestInfoRepository pmRequestInfoRepository;

    @Autowired
    private BatchInsertUtils batchInsertUtils;

    @Autowired
    private PmRuntimeContractRepository pmRuntimeContractRepository;
    
    @Autowired
    private PmSteelTypeGroupRepository pmSteelTypeGroupRepository;

    @Autowired
    private PmContMscTechRepository pmContMscTechRepository;
    
    @Autowired
    private PmProContRepository pmProContRepository;

    @Autowired
    private MongoTemplate mongoTemplate;
    
    @Autowired
    private CodeRuleBuilder codeRuleBuilder;
    
    @Autowired
    private EventClient eventClient;
    
    @Autowired
    private LovAdapter lovAdapter;

    private static final String SPLIT = "*";
    
    @Autowired
    private RedisHelper redisHelper;
    
    private static final String PUBLISH_LOCK = "pm:autoPd:publish:lock:key";
    
    @Override
    public Page<PmAutoPdLog> autoPdLogList(PmAutoPdResultRequestDTO pmAutoPdResultRequest, Long organizationId,
            PageRequest pageRequest) {
        Query query = new Query();
        Criteria criteriaDefinition = Criteria.where("requestId").is(pmAutoPdResultRequest.getRequestId());
        if (pmAutoPdResultRequest.getVersion() != null) {
            criteriaDefinition.and("version").is(pmAutoPdResultRequest.getVersion());
        }
        if (StringUtils.isNotBlank(pmAutoPdResultRequest.getOrderNo())) {
            criteriaDefinition.orOperator(new Criteria("axisOrderNo").regex(pmAutoPdResultRequest.getOrderNo()),
                    new Criteria("block1").regex(pmAutoPdResultRequest.getOrderNo()),
                    new Criteria("block2").regex(pmAutoPdResultRequest.getOrderNo()));
        }
        query.addCriteria(criteriaDefinition).with(Sort.by(Sort.Order.asc("version")));
        List<PmAutoPdLog> logs = mongoTemplate.find(query, PmAutoPdLog.class, CalcLog.COLLECTION_AUTO_PD_LOG);
        return new Page<>(logs, new PageInfo(pageRequest.getPage(), pageRequest.getSize()), logs.size());
    }

    @Override
    public Page<PmAutoPdResult> list(Long tenantId, PmAutoPdResult pmAutoPdResult, PageRequest pageRequest) {
        return pmAutoPdResultRepository.pageAndSort(pageRequest, pmAutoPdResult);
    }

    @Override
    public PmAutoPdResult detail(Long tenantId, Long resultId) {
        return pmAutoPdResultRepository.selectByPrimaryKey(resultId);
    }

    @Override
    public PmAutoPdResult create(Long tenantId, PmAutoPdResult pmAutoPdResult) {
        validObject(pmAutoPdResult);
        pmAutoPdResultRepository.insertSelective(pmAutoPdResult);
        return pmAutoPdResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PmAutoPdResult update(Long tenantId, PmAutoPdResult pmAutoPdResult) {
        SecurityTokenHelper.validToken(pmAutoPdResult);
        pmAutoPdResultRepository.updateByPrimaryKeySelective(pmAutoPdResult);
        return pmAutoPdResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void remove(PmAutoPdResult pmAutoPdResult) {
        SecurityTokenHelper.validToken(pmAutoPdResult);
        pmAutoPdResultRepository.deleteByPrimaryKey(pmAutoPdResult);
    }

    @Override
    public List<PmAutoPdVersionDTO> selectExecVersion(PmAutoPdVersionDTO autoPdVersion, Long organizationId) {
        PmRequestInfo pmRequestInfo = pmRequestInfoRepository.selectByPrimaryKey(autoPdVersion.getRequestId());
        if (pmRequestInfo == null) {
            return Lists.newArrayList();
        }
        List<PmAutoPdVersionDTO> versionDTOs = pmAutoPdResultRepository.selectExecVersion(autoPdVersion.getRequestId(),
                organizationId);
        BigDecimal totRemainingFlagQty = pmRuntimeContractRepository
                .selectAllNumberByRemainingFlag(pmRequestInfo.getRequestId(), organizationId);
        List<PmAutoPdVersionDTO> versionRemainingQty = pmAutoPdContractRepository
                .selectNumberByRemainingFlag(pmRequestInfo.getRequestId(), organizationId);
        Map<Integer, PmAutoPdVersionDTO> remainQtyMap = Maps.uniqueIndex(versionRemainingQty,
                PmAutoPdVersionDTO::getVersion);
        for (PmAutoPdVersionDTO pmAutoPdVersionDTO : versionDTOs) {
            pmAutoPdVersionDTO.setRequestCode(pmRequestInfo.getRequestCode());
            pmAutoPdVersionDTO.setPublishedVersion(pmRequestInfo.getPublishedVersion());
            pmAutoPdVersionDTO.setPolicyGroupId(pmRequestInfo.getPolicyGroupId());
            // 合约尾量
            pmAutoPdVersionDTO.setContractQty(totRemainingFlagQty);
            // 剩余合约尾量
            if (remainQtyMap.containsKey(pmAutoPdVersionDTO.getVersion())) {
                pmAutoPdVersionDTO.setRemainingContractQty(
                        remainQtyMap.get(pmAutoPdVersionDTO.getVersion()).getRemainingContractQty());
            } else {
                pmAutoPdVersionDTO.setRemainingContractQty(BigDecimal.ZERO);
            }
            // 剩余合同数量
            pmAutoPdVersionDTO.setTotSmallPlateNum(pmRequestInfo.getTotSmallPlateNum() == null ? BigDecimal.ZERO
                    : pmRequestInfo.getTotSmallPlateNum());
            pmAutoPdVersionDTO.setRemainingOrderQty(
                    pmAutoPdVersionDTO.getTotSmallPlateNum().subtract(pmAutoPdVersionDTO.getSmallPlateNum()));
            if (pmAutoPdVersionDTO.getTotSmallPlateNum().compareTo(BigDecimal.ZERO) != 0) {
                pmAutoPdVersionDTO.setBoardYield(pmAutoPdVersionDTO.getSmallPlateNum().divide(
                        pmAutoPdVersionDTO.getTotSmallPlateNum(), PmPlateConstants.YIELD_SCALE, RoundingMode.HALF_UP));
            } else {
                pmAutoPdVersionDTO.setBoardYield(BigDecimal.ZERO);
            }
        }
        return versionDTOs;
    }

    @Override
    public Page<PmAutoPdResult> selectList(PageRequest pageRequest, PmAutoPdResultRequestDTO pmAutoPdResultRequestDTO,
            Long organizationId) {
        Page<PmAutoPdResult> result =  PageHelper.doPageAndSort(pageRequest,
                () -> pmAutoPdResultRepository.selectList(pmAutoPdResultRequestDTO, organizationId));
        if(pmAutoPdResultRequestDTO.isQueryDetail()) {
            List<String> virtualSlabNoList = new ArrayList<>();
            for (PmAutoPdResult pmAutoPdResult : result) {
                virtualSlabNoList.add(pmAutoPdResult.getVirtualSlabNo());
            }
            if(virtualSlabNoList != null && !virtualSlabNoList.isEmpty()) {
                List<PmAutoPdContractSummaryDTO> virtualSlabInfo = pmAutoPdResultRepository.selectPmAutoPdContractSummary(virtualSlabNoList, pmAutoPdResultRequestDTO.getRequestId()
                        , pmAutoPdResultRequestDTO.getVersion(), organizationId);
                if(virtualSlabInfo != null && !virtualSlabInfo.isEmpty()) {
                    Map<String , PmAutoPdContractSummaryDTO> map = Maps.uniqueIndex(virtualSlabInfo, PmAutoPdContractSummaryDTO::getVirtualSlabNo);
                    for (PmAutoPdResult pmAutoPdResult : result) {
                        PmAutoPdContractSummaryDTO pmAutoPdContractSummaryDTO = map.get(pmAutoPdResult.getVirtualSlabNo());
                        if(pmAutoPdContractSummaryDTO != null) {
                            pmAutoPdResult.setOrderCustCnameCount(pmAutoPdContractSummaryDTO.getOrderCustCnameCount());
                        }
                    }
                }
            }
        }
        return result;
    }

    @Override
    public List<List<PmAutoPdPosition>> slabDetail(String virtualSlabNo, Long organizationId) {
        List<List<PmAutoPdPosition>> positionList = new ArrayList<>();
        PmAutoPdPosition record = new PmAutoPdPosition();
        record.setVirtualSlabNo(virtualSlabNo);
        record.setTenantId(organizationId);
        List<PmAutoPdPosition> positions = this.pmAutoPdPositionRepository.selectList(virtualSlabNo, organizationId);
        positionList.add(new ArrayList<>());
        positionList.add(new ArrayList<>());
        for (PmAutoPdPosition pmAutoPdPosition : positions) {
            positionList.get(pmAutoPdPosition.getPickModeWidDir().intValue() - 1).add(pmAutoPdPosition);
        }
        Collections.reverse(positionList);
        if (positionList.get(0).isEmpty()) {
            positionList.remove(0);
        }
        return positionList;
    }

    @Override
    public Page<PmAutoPdContract> orderList(PageRequest pageRequest, PmAutoPdResultRequestDTO pmAutoPdResultRequest,
            Long organizationId) {
        return PageHelper.doPageAndSort(pageRequest,
                () -> pmAutoPdContractRepository.selectList(pmAutoPdResultRequest, organizationId));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveCalcResult(PmRequestInfo pmRequestInfo, List<PmAutoBoardExecResult> results,
            PmAutoBoardPolicyGroupDTO policyGroup, Long tenantId) {
        int spCount = 0;
        int virtualCount = 0;
        int contractCount = 0;
        for (PmAutoBoardExecResult pmAutoBoardExecResult : results) {
            spCount += pmAutoBoardExecResult.getSpCount();
            virtualCount += pmAutoBoardExecResult.getSlabNoCount();
            contractCount += pmAutoBoardExecResult.getPdQty().size();
        }
        List<PmAutoPdResult> pmAutoPdResults = new ArrayList<PmAutoPdResult>(virtualCount);
        List<PmAutoPdPosition> positions = new ArrayList<>(spCount);
        List<PmAutoPdContract> contracts = new ArrayList<>(contractCount);
        // 虚拟板坯号规则待定
        for (PmAutoBoardExecResult pmAutoBoardExecResult : results) {
            String virtualSlabNoPrefix = String.format("%sV%02dC", pmRequestInfo.getRequestCode(),
                    pmAutoBoardExecResult.getVersion());
            int i = 1;
            for (PmPdResultDTO pmPdResult : pmAutoBoardExecResult.getPmPdResultDTOs()) {
                PmAutoPdResult pmAutoPdResult = buildPmAutoPdResult(pmAutoBoardExecResult, pmPdResult);
                pmAutoPdResult.setPolicyGroupId(policyGroup.getPolicyGroupId());
                pmAutoPdResult.setVirtualSlabNo(virtualSlabNoPrefix + String.format("%05d", i++));
                pmAutoPdResult.setRequestId(pmRequestInfo.getRequestId());
                pmAutoPdResult.setTenantId(tenantId);
                pmAutoPdResult.setPublishedStatus(0);
                long seq = 1L;
                Map<String, Long> orderSeqNo = new HashMap<String, Long>();
                long j = 1L;
                long k = 1L;
                Map<String, PmAutoPdContract> pmAutoPdContractMap = new HashMap<String, PmAutoPdContract>();
                int index = 0;
                for (String orderNo : pmPdResult.getBlock1()) {
                    PmAutoPdPosition pmAutoPdPosition = new PmAutoPdPosition();
                    pmAutoPdPosition.setOrderNo(orderNo);
                    // 合同排序
                    if(!orderSeqNo.containsKey(orderNo)) {
                        orderSeqNo.put(orderNo, seq++);
                    }
                    pmAutoPdPosition.setOrderSeqNo(orderSeqNo.get(orderNo));
                    if(pmPdResult.getBlock2() != null && pmPdResult.getBlock2().size() > index) {
                        String orderNoTwo = pmPdResult.getBlock2().get(index);
                        if(!orderSeqNo.containsKey(orderNoTwo)) {
                            orderSeqNo.put(orderNoTwo, seq++);
                        }
                    }
                    
                    if (pmAutoPdContractMap.containsKey(orderNo)) {
                        PmAutoPdContract pmAutoPdContract = pmAutoPdContractMap.get(orderNo);
                        pmAutoPdContract.setOrderPlateNum(BigDecimal.ONE.add(pmAutoPdContract.getOrderPlateNum()));
                    } else {
                        PmAutoPdContract pmAutoPdContract = new PmAutoPdContract();
                        if (orderNo.equals(pmPdResult.getAxisPmContBoardParam().getOrderNo())) {
                            pmAutoPdContract.setAxisFlag(BaseConstants.Flag.YES.longValue());
                        } else {
                            pmAutoPdContract.setAxisFlag(BaseConstants.Flag.NO.longValue());
                        }
                        pmAutoPdContract.setOrderNo(orderNo);
                        pmAutoPdContract.setOrderSeqNo(pmAutoPdPosition.getOrderSeqNo());
                        pmAutoPdContract.setOrderPlateNum(BigDecimal.ONE);
                        pmAutoPdContractMap.put(orderNo, pmAutoPdContract);
                        pmAutoPdContract.setTenantId(tenantId);
                        pmAutoPdContract.setRequestId(pmRequestInfo.getRequestId());
                        pmAutoPdContract.setVersionId(Long.valueOf(pmAutoBoardExecResult.getVersion()));
                        pmAutoPdContract.setVirtualSlabNo(pmAutoPdResult.getVirtualSlabNo());
                        contracts.add(pmAutoPdContract);
                    }
                    index ++ ;
                    pmAutoPdPosition.setPickModeWidDir(1L);
                    pmAutoPdPosition.setPickModeLenDir(j++);
                    pmAutoPdPosition.setVirtualSlabNo(pmAutoPdResult.getVirtualSlabNo());
                    pmAutoPdPosition.setTenantId(tenantId);
                    positions.add(pmAutoPdPosition);
                }
                
                if (pmPdResult.getBlock2() != null) {
                    for (String orderNo : pmPdResult.getBlock2()) {
                        PmAutoPdPosition pmAutoPdPosition = new PmAutoPdPosition();
                        pmAutoPdPosition.setOrderSeqNo(orderSeqNo.get(orderNo));
                        pmAutoPdPosition.setOrderNo(orderNo);
                        if (pmAutoPdContractMap.containsKey(orderNo)) {
                            PmAutoPdContract pmAutoPdContract = pmAutoPdContractMap.get(orderNo);
                            pmAutoPdContract.setOrderPlateNum(BigDecimal.ONE.add(pmAutoPdContract.getOrderPlateNum()));
                        } else {
                            orderSeqNo.put(orderNo, pmAutoPdPosition.getOrderSeqNo());
                            PmAutoPdContract pmAutoPdContract = new PmAutoPdContract();
                            if (orderNo.equals(pmPdResult.getAxisPmContBoardParam().getOrderNo())) {
                                pmAutoPdContract.setAxisFlag(BaseConstants.Flag.YES.longValue());
                            } else {
                                pmAutoPdContract.setAxisFlag(BaseConstants.Flag.NO.longValue());
                            }
                            pmAutoPdContract.setOrderNo(orderNo);
                            pmAutoPdContract.setOrderSeqNo(pmAutoPdPosition.getOrderSeqNo());
                            pmAutoPdContract.setOrderPlateNum(BigDecimal.ONE);
                            pmAutoPdContractMap.put(orderNo, pmAutoPdContract);
                            pmAutoPdContract.setTenantId(tenantId);
                            pmAutoPdContract.setRequestId(pmRequestInfo.getRequestId());
                            pmAutoPdContract.setVersionId(Long.valueOf(pmAutoBoardExecResult.getVersion()));
                            pmAutoPdContract.setVirtualSlabNo(pmAutoPdResult.getVirtualSlabNo());
                            contracts.add(pmAutoPdContract);
                        }
                        pmAutoPdPosition.setPickModeWidDir(2L);
                        pmAutoPdPosition.setPickModeLenDir(k++);
                        pmAutoPdPosition.setVirtualSlabNo(pmAutoPdResult.getVirtualSlabNo());
                        pmAutoPdPosition.setTenantId(tenantId);
                        positions.add(pmAutoPdPosition);
                    }
                }
                pmAutoPdResult.setOrderNumInPlate(BigDecimal.valueOf(orderSeqNo.size()));
                pmAutoPdResult.setVersionId(Long.valueOf(pmAutoBoardExecResult.getVersion()));
                pmAutoPdResults.add(pmAutoPdResult);
            }
        }
        batchInsertUtils.execBatchInsert(contracts, PmAutoPdContract.class, "PM_AUTO_PD_CONTRACT", 2000L);
        batchInsertUtils.execBatchInsert(pmAutoPdResults, PmAutoPdResult.class, "PM_AUTO_PD_RESULT", 1000L);
        batchInsertUtils.execBatchInsert(positions, PmAutoPdPosition.class, "PM_AUTO_PD_POSITION", 2000L);

        pmRequestInfoRepository.markExecFinshed(pmRequestInfo, tenantId);
    }

    /**
     * 构造组板结果
     * 
     * @param pmAutoBoardExecResult
     * @param pmPdResult
     * @return
     */
    private PmAutoPdResult buildPmAutoPdResult(PmAutoBoardExecResult pmAutoBoardExecResult, PmPdResultDTO pmPdResult) {
        PmProContYieldResposeDTO respose = pmPdResult.getRespose();
        PmAutoPdResult pmAutoPdResult = new PmAutoPdResult();
        pmAutoPdResult.setBroadFlag(respose.getBroadFlag());
        pmAutoPdResult.setRsCode(respose.getRsCode().toString());
        pmAutoPdResult.setCombinePlateLen(pmPdResult.getSzLen());
        pmAutoPdResult.setCombinePlateWidth(pmPdResult.getSzWid());
        pmAutoPdResult.setComboSlabMethod(pmPdResult.getFormPlateCode());
        pmAutoPdResult.setCommandYield(respose.getCommandYield());
        pmAutoPdResult.setInfurSlabLen(respose.getInfurSlabLen());
        pmAutoPdResult.setInfurSlabMaxLen(respose.getInfurSlabMaxLen());
        pmAutoPdResult.setInfurSlabMaxWt(respose.getInfurSlabMaxWt());
        pmAutoPdResult.setInfurSlabMinLen(respose.getInfurSlabMinLen());
        pmAutoPdResult.setInfurSlabMinWt(respose.getInfurSlabMinWt());
        pmAutoPdResult.setInfurSlabWt(respose.getInfurSlabWt());
        pmAutoPdResult.setInfurSlabThick(pmPdResult.getCurrent().getMoldThick());
        pmAutoPdResult.setInfurSlabWid(pmPdResult.getCurrent().getMoldWidth());
        pmAutoPdResult.setMoldThick(pmPdResult.getCurrent().getMoldThick());
        pmAutoPdResult.setMoldWid(pmPdResult.getCurrent().getMoldWidth());
        pmAutoPdResult.setMscLineNo(pmPdResult.getCurrent().getMscLineNo());
        pmAutoPdResult.setNeedSlabLen(respose.getNeedSlabLen());
        pmAutoPdResult.setNeedSlabWt(respose.getNeedSlabWt());
        pmAutoPdResult.setNormYield(respose.getNormYield());
        pmAutoPdResult.setOrder1Thick(pmPdResult.getAxisPmContBoardParam().getOrderThick());
        pmAutoPdResult.setOrderNoAxis(pmPdResult.getAxisPmContBoardParam().getOrderNo());
        pmAutoPdResult.setPickModeLenDir(BigDecimal.valueOf(respose.getPmCompositeSlabCalc().getPickModeLenDir()));
        pmAutoPdResult.setPickModeWidDir(BigDecimal.valueOf(respose.getPmCompositeSlabCalc().getPickModeWidDir()));
        pmAutoPdResult.setPreCleanSlabLen(respose.getPreCleanSlabLen());
        pmAutoPdResult.setPreCleanSlabMaxLen(respose.getPreCleanSlabMaxLen());
        pmAutoPdResult.setPreCleanSlabMaxWt(respose.getPreCleanSlabMaxWt());
        pmAutoPdResult.setPreCleanSlabMinLen(respose.getPreCleanSlabMinLen());
        pmAutoPdResult.setPreCleanSlabMinWt(respose.getPreCleanSlabMinWt());
        pmAutoPdResult.setPreCleanSlabWt(respose.getPreCleanSlabWt());
        pmAutoPdResult.setPreCleanSlabThick(pmPdResult.getCurrent().getMoldThick());
        pmAutoPdResult.setPreCleanSlabWidth(pmPdResult.getCurrent().getMoldWidth());
        pmAutoPdResult.setTransFlag(pmPdResult.getTransFlag());
        pmAutoPdResult.setTotSmallPlateNum(pmPdResult.getSpCount());
        pmAutoPdResult.setSingleWeight(pmPdResult.getSumWt());
        pmAutoPdResult.setTailCut(respose.getTailCut());
        pmAutoPdResult.setHeadCut(respose.getHeadCut());
        pmAutoPdResult.setSampleLenTail(respose.getPmCompositeSlabCalc().getSampleLenTail());
        pmAutoPdResult.setSampleLenHead(respose.getPmCompositeSlabCalc().getSampleLenHead());
        pmAutoPdResult.setSampleLenMid(respose.getPmCompositeSlabCalc().getSampleLenMid());
        pmAutoPdResult.setRollYield(respose.getRollYield());
        pmAutoPdResult.setRollWtHp(respose.getRollWtHp());
        pmAutoPdResult.setRollThickTolMin(respose.getRollThickTolMin());
        pmAutoPdResult.setRollThickTolMax(respose.getRollThickTolMax());
        pmAutoPdResult.setRollAimWidth(respose.getWaim());
        pmAutoPdResult.setRollAimThick(respose.getTaim());
        pmAutoPdResult.setRollAimLen(respose.getLaim());
        if(pmPdResult.getRespose().getPmCompositeSlabCalc() != null) {
            PmCompositeSlabCalcDTO pmCompositeSlabCalc = pmPdResult.getRespose().getPmCompositeSlabCalc();
            if(pmCompositeSlabCalc.getCommandCut() != null && !pmCompositeSlabCalc.getCommandCut().isEmpty()) {
                pmAutoPdResult.setCommandCut(pmCompositeSlabCalc.getCommandCut().stream().map(Objects::toString).collect(Collectors.joining(",")));
            }
            if(pmCompositeSlabCalc.getDiffCut() != null && !pmCompositeSlabCalc.getDiffCut().isEmpty()) {
                pmAutoPdResult.setDiffCut(pmCompositeSlabCalc.getDiffCut().stream().map(Objects::toString).collect(Collectors.joining(",")));
            }
        }
        return pmAutoPdResult;
    }

    @Override
    public Boolean published(List<PmAutoPdPublishedRequestDTO> publishedRequestList, Long organizationId) {
        boolean key = redisHelper.hasKey(PUBLISH_LOCK);
        if(key) {
            throw new CommonException("存在正在运行的发布任务，请稍后重试");
        }
        try {
            redisHelper.strSet(PUBLISH_LOCK, "1", 5, TimeUnit.MINUTES);
            for (PmAutoPdPublishedRequestDTO pmAutoPdPublishedRequestDTO : publishedRequestList) {
    
                if (pmAutoPdPublishedRequestDTO.getMoldList() != null
                        && !pmAutoPdPublishedRequestDTO.getMoldList().isEmpty()
                        && pmAutoPdPublishedRequestDTO.getVirtualSlabNoList() != null
                        && pmAutoPdPublishedRequestDTO.getVirtualSlabNoList().isEmpty()) {
                    throw new CommonException("不能同时选择断面与板坯号发布！");
                }
                if (pmAutoPdPublishedRequestDTO.getMoldList() != null) {
                    
                    for (String mold : pmAutoPdPublishedRequestDTO.getMoldList()) {
                        String arr[] = mold.split("\\" + SPLIT);
                        PmAutoPdResultRequestDTO request = new PmAutoPdResultRequestDTO();
                        request.setRequestId(pmAutoPdPublishedRequestDTO.getRequestId());
                        request.setVersion(pmAutoPdPublishedRequestDTO.getVersion());
                        request.setStNo(pmAutoPdPublishedRequestDTO.getStNo());
                        request.setMscLineNo(arr[0]);
                        request.setMoldThick(new BigDecimal(arr[1]));
                        request.setMoldWid(new BigDecimal(arr[2]));
                        List<Integer> publishedStatusList = new ArrayList<>();
                        publishedStatusList.add(0);
                        publishedStatusList.add(1);
                        request.setPublishedStatusList(publishedStatusList);
                        // 查询未发布的数据
                        List<PmAutoPdResult> results = pmAutoPdResultRepository.selectList(request, organizationId);
                        this.self().execPublishedSplit(pmAutoPdPublishedRequestDTO, results, organizationId , request.getMscLineNo());
                    }
                    
                } else if (pmAutoPdPublishedRequestDTO.getVirtualSlabNoList() != null) {
                    PmAutoPdResultRequestDTO request = new PmAutoPdResultRequestDTO();
                    request.setRequestId(pmAutoPdPublishedRequestDTO.getRequestId());
                    request.setVersion(pmAutoPdPublishedRequestDTO.getVersion());
                    List<Integer> publishedStatusList = new ArrayList<>();
                    publishedStatusList.add(0);
                    publishedStatusList.add(1);
                    request.setPublishedStatusList(publishedStatusList);
                    request.setVirtualSlabNoList(pmAutoPdPublishedRequestDTO.getVirtualSlabNoList());
                    // 查询未发布的数据
                    List<PmAutoPdResult> results = pmAutoPdResultRepository.selectList(request, organizationId);
                    Map<String , List<PmAutoPdResult>> map = results.stream().collect(Collectors.groupingBy(PmAutoPdResult::getMscLineNo));
                    for (Entry<String, List<PmAutoPdResult>> entry : map.entrySet()) {
                        this.self().execPublishedSplit(pmAutoPdPublishedRequestDTO, entry.getValue(), organizationId , entry.getKey());
                    }
                }
    
            }
            return true;
        } finally {
            redisHelper.delKey(PUBLISH_LOCK);
        }
    }
    
    /**
     * 分割计算，避免数量太大导致SQL异常
     * @param pmAutoPdPublishedRequestDTO
     * @param results
     * @param organizationId
     * @return
     */
    @Override
    @GlobalTransactional(rollbackFor = Exception.class , timeoutMills = 120000)
    @Transactional(rollbackFor = Exception.class)
    public Boolean execPublishedSplit(PmAutoPdPublishedRequestDTO pmAutoPdPublishedRequestDTO, List<PmAutoPdResult> results,
            Long organizationId ,String mscLineNo) {
        int spCount = 0 ;
        List<PmAutoPdResult> tmp = new ArrayList<>();
        List<List<PmAutoPdResult>> res = new ArrayList<>();
        List<String> virtualSlabNoList = new ArrayList<>(); 
        for (PmAutoPdResult pmAutoPdResult : results) {
            virtualSlabNoList.add(pmAutoPdResult.getVirtualSlabNo());
            tmp.add(pmAutoPdResult);
            spCount += pmAutoPdResult.getTotSmallPlateNum().intValue();
            spCount += 2;
            if(spCount > 900) {
                res.add(new ArrayList<>(tmp));
                List<PmAutoPdCheckDTO> checkResult = pmAutoPdResultRepository.checkStockNum(virtualSlabNoList, pmAutoPdPublishedRequestDTO.getRequestId()
                        , pmAutoPdPublishedRequestDTO.getVersion(), organizationId);
                if(checkResult != null && !checkResult.isEmpty()) {
                    throw new CommonException(String.format("合同【%s】欠量【%s】不够，组板小板总计【%s】",checkResult.get(0).getOrderNo() 
                          ,checkResult.get(0).getStockNum().toPlainString(), checkResult.get(0).getOrderPlateNum().toPlainString()));
                }
                tmp.clear();
                virtualSlabNoList.clear();
                spCount = 0;
            }
        }
        if(!tmp.isEmpty()) {
            List<PmAutoPdCheckDTO> checkResult = pmAutoPdResultRepository.checkStockNum(virtualSlabNoList, pmAutoPdPublishedRequestDTO.getRequestId()
                    , pmAutoPdPublishedRequestDTO.getVersion(), organizationId);
            if(checkResult != null && !checkResult.isEmpty()) {
                throw new CommonException(String.format("合同【%s】欠量【%s】不够，组板小板总计【%s】",checkResult.get(0).getOrderNo() 
                      ,checkResult.get(0).getStockNum().toPlainString(), checkResult.get(0).getOrderPlateNum().toPlainString()));
            }
            res.add(tmp);
        }
        Collection<PmAutoPdContract> contracts = pmAutoPdContractRepository.lockPdContract(pmAutoPdPublishedRequestDTO.getRequestId(), virtualSlabNoList,
                pmAutoPdPublishedRequestDTO.getVersion(), organizationId);
        for (List<PmAutoPdResult> list : res) {
            execPublished(pmAutoPdPublishedRequestDTO, list, organizationId , mscLineNo);
        }
        pmAutoPdContractRepository.commitPdContract(contracts, organizationId);
        return true ;
    }
    
    private Boolean execPublished(PmAutoPdPublishedRequestDTO pmAutoPdPublishedRequestDTO, List<PmAutoPdResult> results,
            Long organizationId ,String mscLineNo) {
        if (results == null || results.isEmpty()) {
            return true;
        }
        List<Long> publishedList = new ArrayList<>(results.size());
        // 暂存中的数据
        List<Long> savingList = new ArrayList<>(results.size());
        List<String> savingSlabNoList = new ArrayList<>(results.size());
        List<String> allSlabNoList = new ArrayList<>(results.size());

        Map<String , PmPdCcSlab> pmPdCcSlabMap = new HashMap<>();
        
        List<String> axisOrderNoList = new ArrayList<>();
        List<String> slabNos = codeRuleBuilder.generateCode(results.size() , organizationId, Constants.CodeRule.AUTO_VIRTUAL_SLAB_NO,
                CodeConstants.CodeRuleLevelCode.GLOBAL, Constants.CodeRule.GLOBAL_LEVEL_VALUE, new HashMap<>(1));
        ListIterator<String> iterator = slabNos.listIterator();
        List<ProContBoardEndDTO> boardEndEventList = new ArrayList<>();
        List<PmPdPlateCut> pmPdPlateCuts = new ArrayList<>();
        List<PmAutoPdPubllished> pdPubllisheds = new ArrayList<>();
        for (PmAutoPdResult pmAutoPdResult : results) {
            PmAutoPdPubllished pdPubllished = new PmAutoPdPubllished();
            pdPubllisheds.add(pdPubllished);
            publishedList.add(pmAutoPdResult.getResultId());
            allSlabNoList.add(pmAutoPdResult.getVirtualSlabNo());
            if (pmAutoPdResult.getPublishedStatus() == 1) {
                savingList.add(pmAutoPdResult.getResultId());
                savingSlabNoList.add(pmAutoPdResult.getVirtualSlabNo());
            }
            PmPdCcSlab pmPdCcSlab = buildPmPdCcSlab(pmAutoPdResult); 
            pmPdCcSlab.setVirtualSlabNo(iterator.next());
            pdPubllished.setVirtualSlabNo(pmAutoPdResult.getVirtualSlabNo());
            pdPubllished.setNewVirtualSlabNo(pmPdCcSlab.getVirtualSlabNo());
            pdPubllished.setObjectVersionNumber(1L);
            pdPubllished.setTenantId(organizationId);
            
            pmPdCcSlabMap.put(pmAutoPdResult.getVirtualSlabNo(), pmPdCcSlab);
            axisOrderNoList.add(pmPdCcSlab.getOrderNoAxis());
            // 虚拟板坯维度
            boardEndEventList.add(new ProContBoardEndDTO(pmPdCcSlab.getOrderNoAxis()).setMatNo(pmPdCcSlab.getVirtualSlabNo())
                                .setLen(pmPdCcSlab.getPreCleanSlabLen()).setMoMatNo(null)
                                .setMscLineNo(pmPdCcSlab.getMscLineNo())
                                .setPdMatStatus(PdStatusHp.PD_STATUS_HP_12).setPpFlag(PdProdFlag.VIRTUAL_SLAB.getCode())
                                .setThk(pmPdCcSlab.getMoldThick())
                                .setWid(pmPdCcSlab.getMoldWid())
                                .setWgt(pmPdCcSlab.getPreCleanSlabWt())
                                .setWholeBacklogCode(Constants.WholeBacklogCode.CODE_14)
                                .setStNo(pmPdCcSlab.getStNo())
                                .setSgSign(pmPdCcSlab.getSgSign())
                                .setProcCd(Constants.ProdcCd.CD_14A));
            // 大板维度
            boardEndEventList.add(new ProContBoardEndDTO(pmPdCcSlab.getOrderNoAxis()).setMatNo(pmPdCcSlab.getVirtualSlabNo())
                    .setLen(pmPdCcSlab.getRollAimLen()).setMoMatNo(null)
                    .setMscLineNo(pmPdCcSlab.getMscLineNo())
                    .setPdMatStatus(PdStatusHp.PD_STATUS_HP_12).setPpFlag(PdProdFlag.VIRTUAL_COMPOSITE_SLAB.getCode())
                    .setThk(pmPdCcSlab.getRollAimThick())
                    .setWid(pmPdCcSlab.getRollAimWidth())
                    .setWgt(pmPdCcSlab.getRollWtHp())
                    .setWholeBacklogCode(Constants.WholeBacklogCode.CODE_14)
                    .setStNo(pmPdCcSlab.getStNo())
                    .setSgSign(pmPdCcSlab.getSgSign())
                    .setProcCd(Constants.ProdcCd.CD_14A));
            if(StringUtils.isNotBlank(pmAutoPdResult.getCommandCut())) {
                for (String index : pmAutoPdResult.getCommandCut().split(",")) {
                    PmPdPlateCut pdPlateCutF = new PmPdPlateCut();
                    pdPlateCutF.setCutType(CutType.P.getCode());
                    pdPlateCutF.setPdMatNo(pmPdCcSlab.getVirtualSlabNo());
                    pdPlateCutF.setPositionSeq(Long.valueOf(index));
                    pdPlateCutF.setPositionType(CutPositionType.F.getCode());
                    pdPlateCutF.setTenantId(organizationId);
                    
                    PmPdPlateCut pdPlateCutM = new PmPdPlateCut();
                    pdPlateCutM.setCutType(CutType.P.getCode());
                    pdPlateCutM.setPdMatNo(pmPdCcSlab.getVirtualSlabNo());
                    pdPlateCutM.setPositionSeq(Long.valueOf(index));
                    pdPlateCutM.setPositionType(CutPositionType.M.getCode());
                    pdPlateCutM.setTenantId(organizationId);
                    pmPdPlateCuts.add(pdPlateCutM);
                    pmPdPlateCuts.add(pdPlateCutF);
                }
            }
            if(StringUtils.isNotBlank(pmAutoPdResult.getDiffCut())) {
                for (String index : pmAutoPdResult.getDiffCut().split(",")) {
                    PmPdPlateCut pdPlateCutF = new PmPdPlateCut();
                    pdPlateCutF.setCutType(CutType.D.getCode());
                    pdPlateCutF.setPdMatNo(pmPdCcSlab.getVirtualSlabNo());
                    pdPlateCutF.setPositionSeq(Long.valueOf(index));
                    pdPlateCutF.setPositionType(CutPositionType.F.getCode());
                    pdPlateCutF.setTenantId(organizationId);
                    
                    PmPdPlateCut pdPlateCutM = new PmPdPlateCut();
                    pdPlateCutM.setCutType(CutType.D.getCode());
                    pdPlateCutM.setPdMatNo(pmPdCcSlab.getVirtualSlabNo());
                    pdPlateCutM.setPositionSeq(Long.valueOf(index));
                    pdPlateCutM.setPositionType(CutPositionType.M.getCode());
                    pdPlateCutM.setTenantId(organizationId);
                    pmPdPlateCuts.add(pdPlateCutM);
                    pmPdPlateCuts.add(pdPlateCutF);
                }
            }
        }
        
        this.pmAutoPdResultRepository.markPublishedSuccess(organizationId, publishedList);
        pmAutoPdContractRepository.subLockQty(pmAutoPdPublishedRequestDTO.getRequestId(), savingSlabNoList,
                pmAutoPdPublishedRequestDTO.getVersion(), organizationId);
        
        PmRequestInfo pmRequestInfo = pmRequestInfoRepository.selectByPrimaryKey(pmAutoPdPublishedRequestDTO.getRequestId());
        pmRequestInfoRepository.markPublishing(pmRequestInfo , organizationId);
        // 执行生成连铸出钢材表
        List<PmAutoPdContract> pmAutoPdContracts = pmAutoPdContractRepository.selectByVirtualSlabNoList(pmAutoPdPublishedRequestDTO.getRequestId(), allSlabNoList
                , pmAutoPdPublishedRequestDTO.getVersion(), organizationId);
        Set<String> orderSet = new HashSet<>();
        List<PmPdContSum> pmPdContSums = new ArrayList<>(pmAutoPdContracts.size());
        // 生产合同总量表
        for (PmAutoPdContract pmAutoPdContract : pmAutoPdContracts) {
            orderSet.add(pmAutoPdContract.getOrderNo());
        }
        Map<String , PmProContFilterResposeDTO> orderMap = pmProContRepository.orderFilterMap(Lists.newArrayList(orderSet), organizationId, mscLineNo);
        Map<String , List<PmProContFilterResposeDTO>> virtualSlabNoContMap = new HashMap<>();
        // 生产合同总量表
//        Map<String , BigDecimal> contSumMap = new HashMap<>();
        for (PmAutoPdContract pmAutoPdContract : pmAutoPdContracts) {
//            if(!contSumMap.containsKey(pmAutoPdContract.getOrderNo())) {
//                contSumMap.put(pmAutoPdContract.getOrderNo(), BigDecimal.ZERO);
//            }
//            contSumMap.put(pmAutoPdContract.getOrderNo() , contSumMap.get(pmAutoPdContract.getOrderNo()).add(pmAutoPdContract.getOrderPlateNum()));
            PmPdContSum pmPdContSum = new PmPdContSum();
            PmPdCcSlab pmPdCcSlab = pmPdCcSlabMap.get(pmAutoPdContract.getVirtualSlabNo());
            PmProContFilterResposeDTO resposeDTO = orderMap.get(pmAutoPdContract.getOrderNo());
            if(!virtualSlabNoContMap.containsKey(pmPdCcSlab.getVirtualSlabNo())) {
                virtualSlabNoContMap.put(pmPdCcSlab.getVirtualSlabNo(), new ArrayList<>());
            }
            virtualSlabNoContMap.get(pmPdCcSlab.getVirtualSlabNo()).add(resposeDTO);
            pmPdContSum.setAxisFlag(pmAutoPdContract.getAxisFlag());
            pmPdContSum.setOrderLen(resposeDTO.getLenAim());
            pmPdContSum.setOrderLenMax(resposeDTO.getOrderMaxLen());
            pmPdContSum.setOrderLenMin(resposeDTO.getOrderMinLen());
            pmPdContSum.setOrderNo(resposeDTO.getOrderNo());
            pmPdContSum.setOrderThick(resposeDTO.getOrderThick());
            pmPdContSum.setOrderWidth(resposeDTO.getOrderWidth());
            pmPdContSum.setPdMatNo(pmPdCcSlab.getVirtualSlabNo());
            pmPdContSum.setPdMatType(PdMatType.C.getCode());
            pmPdContSum.setProContId(resposeDTO.getProContId());
            pmPdContSum.setSmallPlateLen(resposeDTO.getLenAim());
            pmPdContSum.setSmallPlateThick(resposeDTO.getOrderThick());
            pmPdContSum.setSmallPlateWidth(resposeDTO.getOrderWidth());
            pmPdContSum.setTenantId(organizationId);
            pmPdContSums.add(pmPdContSum);
        }
//        Map<String , CtMainVO> ctMainMap = selectCtMainByOrderNoList(Lists.newArrayList(orderSet), organizationId);
//        for (Entry<String, BigDecimal> entry : contSumMap.entrySet()) {
//            CtMainVO ctMainVO = ctMainMap.get(entry.getKey());
//            if(ctMainVO == null || ctMainVO.getStockNum() == null || ctMainVO.getStockNum().compareTo(entry.getValue()) < 0) {
//                throw new CommonException(String.format("合同【%s】欠量【%s】不够，组板小板总计【%s】",entry.getKey() 
//                        ,(ctMainVO == null || ctMainVO.getStockNum() == null)  ? BigDecimal.ZERO : ctMainVO.getStockNum().toPlainString(), entry.getValue().toPlainString()));
//            }
//        }
        
        List<PmAutoPdPosition> pmAutoPdPositions = pmAutoPdPositionRepository.selectByVirtualSlabNoList(allSlabNoList, organizationId);
        List<PmContMscTech> contMscTechs = this.pmContMscTechRepository.selectByOrderNoAndMscLineNo(axisOrderNoList, mscLineNo, organizationId);
        Map<String , PmContMscTech> contMscTechMap = Maps.uniqueIndex(contMscTechs, PmContMscTech::getOrderNo);
        // 生产小板位置表 & 组合子板位置表
        List<PmSmallPltPos> pmSmallPltPoss = new ArrayList<>();
        List<PmPdBlockPos> pmPdBlockPoss = new ArrayList<>();
        
        Map<String , PmPdBlockPos> contAddFlag = new HashMap<>();
        
        for (PmAutoPdPosition pmAutoPdPosition : pmAutoPdPositions) {
            PmSmallPltPos pmSmallPltPos = new PmSmallPltPos();
            PmProContFilterResposeDTO resposeDTO = orderMap.get(pmAutoPdPosition.getOrderNo());
            PmPdCcSlab pmPdCcSlab = pmPdCcSlabMap.get(pmAutoPdPosition.getVirtualSlabNo());
            pmSmallPltPos.setOrderLen(resposeDTO.getLenAim());
            pmSmallPltPos.setOrderLenMax(resposeDTO.getOrderMaxLen());
            pmSmallPltPos.setOrderLenMin(resposeDTO.getOrderMinLen());
            pmSmallPltPos.setOrderNo(pmAutoPdPosition.getOrderNo());
            pmSmallPltPos.setOrderSeqNo(pmAutoPdPosition.getOrderSeqNo());
            pmSmallPltPos.setPdMatNo(pmPdCcSlab.getVirtualSlabNo());
            pmSmallPltPos.setOrderThick(resposeDTO.getOrderThick());
            pmSmallPltPos.setOrderWidth(resposeDTO.getOrderWidth());
            pmSmallPltPos.setPickModeLenDir(pmAutoPdPosition.getPickModeLenDir());
            pmSmallPltPos.setPickModeWidDir(pmAutoPdPosition.getPickModeWidDir());
            pmSmallPltPos.setProContId(resposeDTO.getProContId());
            pmSmallPltPos.setSmallPlateDivNo(getSmallPlateDivNo(null, resposeDTO.getTrimCode(), pmSmallPltPos, pmPdCcSlab));
            pmSmallPltPos.setSmallPlateLen(resposeDTO.getLenAim());
            pmSmallPltPos.setSmallPlateThick(resposeDTO.getOrderThick());
            pmSmallPltPos.setSmallPlateWidth(resposeDTO.getOrderWidth());
            pmSmallPltPos.setTenantId(organizationId);
            pmSmallPltPoss.add(pmSmallPltPos);
            
            String key = pmPdCcSlab.getVirtualSlabNo() + "_" + pmAutoPdPosition.getOrderNo() + "_" + pmAutoPdPosition.getPickModeWidDir().toString();
            if (!contAddFlag.containsKey(key)) {
                // 如果不在标记中，则需要添加到组板子板位置表 和合同总量表中
                PmPdBlockPos pmPdBlockPos = new PmPdBlockPos();
                pmPdBlockPos.setPdMatNo(pmPdCcSlab.getVirtualSlabNo());
                pmPdBlockPos.setOrderBlockNo(pmAutoPdPosition.getPickModeWidDir());
                pmPdBlockPos.setOrderNo(pmAutoPdPosition.getOrderNo());
                pmPdBlockPos.setOrderSeqNo(pmAutoPdPosition.getOrderSeqNo());
                pmPdBlockPos.setBlockPlateNum(BigDecimal.ONE);
                pmPdBlockPos.setProContId(resposeDTO.getProContId());
                pmPdBlockPos.setTenantId(organizationId);
                pmPdBlockPoss.add(pmPdBlockPos);
                contAddFlag.put(key ,pmPdBlockPos);
            } else {
                PmPdBlockPos pmPdBlockPos = contAddFlag.get(key);
                pmPdBlockPos.setBlockPlateNum(BigDecimal.ONE.add(pmPdBlockPos.getBlockPlateNum()));
            }
            boardEndEventList
            .add(new ProContBoardEndDTO(pmSmallPltPos.getOrderNo()).setMatNo(pmPdCcSlab.getVirtualSlabNo()+pmSmallPltPos.getSmallPlateDivNo())
                    .setLen(pmSmallPltPos.getOrderLen()).setMoMatNo(pmPdCcSlab.getVirtualSlabNo())
                    .setMscLineNo(pmPdCcSlab.getMscLineNo())
                    .setPdMatStatus(PdStatusHp.PD_STATUS_HP_12).setPpFlag(PdProdFlag.VIRTUAL_SUB_SLAB.getCode())
                    .setThk(pmSmallPltPos.getOrderThick()).setWid(pmSmallPltPos.getOrderWidth())
                    .setWgt(resposeDTO.getOrderUnitAimWt())
                    .setWholeBacklogCode(Constants.WholeBacklogCode.CODE_14)
                    .setStNo(resposeDTO.getStNo())
                    .setSgSign(resposeDTO.getSgSign())
                    .setProcCd(Constants.ProdcCd.CD_14A));
        }
        List<PmPdCcSlab> pmPdCcSlabList = new ArrayList<>();
        for (Entry<String, PmPdCcSlab> entry : pmPdCcSlabMap.entrySet()) {
            pmPdCcSlabList.add(buildPmPdCcSlab(entry.getValue() , orderMap.get(entry.getValue().getOrderNoAxis()) , contMscTechMap.get(entry.getValue().getOrderNoAxis()) , virtualSlabNoContMap.get(entry.getValue().getVirtualSlabNo())));
        }
        batchInsertUtils.batchInsert(pdPubllisheds, 1000L);
        batchInsertUtils.batchInsert(pmPdBlockPoss, 2000L);
        batchInsertUtils.batchInsert(pmPdContSums, 1000L);
        batchInsertUtils.batchInsert(pmSmallPltPoss, 2000L);
        batchInsertUtils.batchInsert(pmPdPlateCuts, 2000L);
        batchInsertUtils.batchInsert(pmPdCcSlabList, 200L);
        // 发送合同跟踪
        eventClient.sendEventWithOutResponse(organizationId, CtEventConstants.EVENT_PM_BOARD_END, boardEndEventList);
        return true;
    }
    
    private PmPdCcSlab buildPmPdCcSlab(PmPdCcSlab pmPdCcSlab, PmProContFilterResposeDTO axisOrder , PmContMscTech pmContMscTech, List<PmProContFilterResposeDTO> pmProContFilterResposeList) {
        pmPdCcSlab.setMatDesignKind(PdMatType.C.getCode());
        pmPdCcSlab.setPdStatusHp(PdStatusHp.PD_STATUS_HP_12);
        pmPdCcSlab.setPdResp(DetailsHelper.getUserDetails().getUserId().toString());
        pmPdCcSlab.setFurType(PmPlateConstants.FUR_TYPR_C);
        pmPdCcSlab.setSlabCleanWtLossRateSt(BigDecimal.ZERO);
        pmPdCcSlab.setSlabCleanWtLossRateFr(BigDecimal.ZERO);
        
        pmPdCcSlab.setTwoRollInterimFlag(Long.valueOf(BaseConstants.Flag.NO));
        pmPdCcSlab.setRfPath(axisOrder.getRfPath());
        pmPdCcSlab.setCcType(CcType.TYPE_1);
        pmPdCcSlab.setOrderRemainDiv(BaseConstants.Flag.YES.toString());
        pmPdCcSlab.setCanDelFlag(BaseConstants.Flag.YES.toString());
        
        pmPdCcSlab.setHpFlameCleanDiv(pmContMscTech.getFlameCleanDiv());
        pmPdCcSlab.setSlabFinishCode(pmContMscTech.getSlabFinishCode());
        pmPdCcSlab.setProdDensity(axisOrder.getProdDensity());
        
        Date steelPlanDate = null;
        Date steelLatestDate = null;
        Set<String> ultCode = new TreeSet<>();
        String hotSendDiv = "H";
        Long hotChargeFlag = 0L;
        for (PmProContFilterResposeDTO resposeDTO : pmProContFilterResposeList) {
            // 对PM_PD_CC_SLAB，遍历所有合同及其产线，取PM_CONT_MSC_TECH 的SLAB_PLACE_CODE，若出现X或出现B和T，则落X；否则若仅出现B或T，则落对应的值，否则落0.
            if ("X".equals(resposeDTO.getSlabPlaceCode())) {
                pmPdCcSlab.setSlabPlaceCode("X");
            }
            if(resposeDTO.getHotChargeFlag() != null) {
                hotChargeFlag = resposeDTO.getHotChargeFlag();
            }
            if("C".equals(resposeDTO.getHotSendDiv())) {
                hotSendDiv = "C";
            }
            if (StringUtils.isNotBlank(pmPdCcSlab.getSlabPlaceCode())) {
                if(!resposeDTO.getSlabPlaceCode().equals(pmPdCcSlab.getSlabPlaceCode())){
                    pmPdCcSlab.setSlabPlaceCode("X");
                }
            } else {
                pmPdCcSlab.setSlabPlaceCode(resposeDTO.getSlabPlaceCode());
            }
            if (StringUtils.isBlank(pmPdCcSlab.getUrgOrderFlag()) && resposeDTO.getUrgOrderFlag() != null) {
                pmPdCcSlab.setUrgOrderFlag(resposeDTO.getUrgOrderFlag().toString());
            }
            if (steelPlanDate == null || steelPlanDate.after(resposeDTO.getSteelPlanDate())) {
                steelPlanDate = resposeDTO.getSteelPlanDate();
            }
            if (steelLatestDate == null || steelLatestDate.after(resposeDTO.getSteelLatestDate())) {
                steelLatestDate = resposeDTO.getSteelLatestDate();
            }
            if (StringUtils.isNotBlank(resposeDTO.getErpUtSpec1())) {
               ultCode.add(resposeDTO.getErpUtSpec1());
            }
            if (StringUtils.isNotBlank(resposeDTO.getErpUtSpec2())) {
                ultCode.add(resposeDTO.getErpUtSpec2());
            }
            if (StringUtils.isNotBlank(resposeDTO.getErpUtSpec3())) {
                ultCode.add(resposeDTO.getErpUtSpec3());
            }
            if (StringUtils.isBlank(pmPdCcSlab.getCoolCode()) && StringUtils.isNotBlank(resposeDTO.getCoolCode())) {
                pmPdCcSlab.setCoolCode(resposeDTO.getCoolCode());
            }
            if (StringUtils.isBlank(pmPdCcSlab.getUltDetectMethodCode())
                    && StringUtils.isNotBlank(resposeDTO.getUltDetectMethodCode())) {
                pmPdCcSlab.setUltDetectMethodCode(resposeDTO.getUltDetectMethodCode());
            }
        }
        if(ultCode != null && !ultCode.isEmpty()) {
            pmPdCcSlab.setUltCode(String.join("@", ultCode));
        }

        if (steelPlanDate == null) {
            // 获取当前时间往前推15天
            LocalDate now = LocalDate.now().minusDays(15);
            steelPlanDate = Date.from(now.atStartOfDay(ZoneId.systemDefault()).toInstant());
        }
        pmPdCcSlab.setSteelPlanDate(steelPlanDate);
        pmPdCcSlab.setSteelLatestDate(steelLatestDate);

        pmPdCcSlab.setTmpSlabNo("");
        pmPdCcSlab.setPrecPono("");
        pmPdCcSlab.setPrecCastLotNo("");
        pmPdCcSlab.setSgDecideTime(null);
        pmPdCcSlab.setManualOm("");
        pmPdCcSlab.setHpOmTime(null);
        pmPdCcSlab.setHotSendFlag(hotSendDiv);
        pmPdCcSlab.setHotChargeFlag(hotChargeFlag);
        pmPdCcSlab.setSteelGroup("");
        pmPdCcSlab.setSlabPlaceCode("");
        pmPdCcSlab.setIgMatDesignKind("");
        pmPdCcSlab.setIngotType("");
        pmPdCcSlab.setShpCode(""); 

        pmPdCcSlab.setAdTypeCode(axisOrder.getAdTypeCode());
        pmPdCcSlab.setAdModeCode(axisOrder.getAdModeCode());
        pmPdCcSlab.setCheckMethodCode(axisOrder.getCheckMethodCode());
        pmPdCcSlab.setCtrlRollCode(axisOrder.getCtrlRollCode());
        pmPdCcSlab.setWithSideFlag(axisOrder.getProdSideMark());
        pmPdCcSlab.setCutModeCode(axisOrder.getCutModeCode());
        pmPdCcSlab.setSgSign(axisOrder.getSgSign());
        pmPdCcSlab.setGFlag(pmContMscTech.getGFlag() == null ? "" : pmContMscTech.getGFlag().toString());
        pmPdCcSlab.setCsFlag(pmContMscTech.getCsFlag() == null ? "" : pmContMscTech.getCsFlag().toString());
        pmPdCcSlab.setDssFlag(pmContMscTech.getDssFlag() == null ? "" : pmContMscTech.getDssFlag().toString());
        pmPdCcSlab.setSsFlag(pmContMscTech.getSsFlag() == null ? "" : pmContMscTech.getSsFlag().toString());
        pmPdCcSlab.setDsFlag(pmContMscTech.getDsFlag() == null ? "" : pmContMscTech.getDsFlag().toString());
        pmPdCcSlab.setProdCodeHp(axisOrder.getProdCodeHp());
        pmPdCcSlab.setAxisOrderThick(axisOrder.getOrderThick());
        pmPdCcSlab.setAxisOrderWidth(axisOrder.getOrderWidth());
        pmPdCcSlab.setOrderNoAxis(axisOrder.getOrderNo());
        pmPdCcSlab.setRollDirectCode(axisOrder.getRollDirectCode());

        return pmPdCcSlab;
    }
    
    /**
     * 获取小板分割号
     * @param trimCode
     * @param
     * @return
     */
    private String getSmallPlateDivNo(String plateNo, String trimCode ,PmSmallPltPos pmSmallPltPos,
            PmPdCcSlab pmPdCcSlab) {
        int index = pmSmallPltPos.getPickModeLenDir().intValue();
        if(pmSmallPltPos.getPickModeWidDir() == 2) {
            index = (pmPdCcSlab.getTotSmallPlateNum().intValue() / 2) + index;
        }
        if ("0".equals(trimCode)) {
            return PmPlateConstants.SMALL_PLATE_SPLIT_NO[0];
        } else {
            return PmPlateConstants.SMALL_PLATE_SPLIT_NO[index];
        }
    }
    
    private PmPdCcSlab buildPmPdCcSlab(PmAutoPdResult pmAutoPdResult) {
        PmPdCcSlab pmPdCcSlab = new PmPdCcSlab();
        pmPdCcSlab.setMoldThick(pmAutoPdResult.getMoldThick());
        pmPdCcSlab.setMoldWid(pmAutoPdResult.getMoldWid());
        pmPdCcSlab.setMscLineNo(pmAutoPdResult.getMscLineNo());
        pmPdCcSlab.setVirtualSlabNo(pmAutoPdResult.getVirtualSlabNo());
        pmPdCcSlab.setTenantId(pmAutoPdResult.getTenantId());
        pmPdCcSlab.setStNo(pmAutoPdResult.getStNo());
        pmPdCcSlab.setFixSlabLen(BigDecimal.ZERO);
        pmPdCcSlab.setFixSlabLenFlag(0L);
        pmPdCcSlab.setFormPlateMode(pmAutoPdResult.getComboSlabMethod());
        // 清理器板坯宽厚 = 进加热炉板坯宽厚 = 结晶器宽厚
        pmPdCcSlab.setPreCleanSlabThick(pmAutoPdResult.getMoldThick());
        pmPdCcSlab.setPreCleanSlabWidth(pmAutoPdResult.getMoldWid());
        pmPdCcSlab.setInfurSlabThick(pmAutoPdResult.getMoldThick());
        pmPdCcSlab.setInfurSlabWid(pmAutoPdResult.getMoldWid());
        pmPdCcSlab.setAutoManualFlag(AutoManualFlag.AUTO_MANUA_FLAG_C);
        pmPdCcSlab.setPreCleanSlabLen(pmAutoPdResult.getPreCleanSlabLen());
        pmPdCcSlab.setPreCleanSlabWt(pmAutoPdResult.getPreCleanSlabWt());
        pmPdCcSlab.setInfurSlabLen(pmAutoPdResult.getInfurSlabLen());
        pmPdCcSlab.setInfurSlabWt(pmAutoPdResult.getInfurSlabWt());
        pmPdCcSlab.setPreCleanSlabMaxLen(pmAutoPdResult.getPreCleanSlabMaxLen());
        pmPdCcSlab.setPreCleanSlabMinLen(pmAutoPdResult.getPreCleanSlabMinLen());
        pmPdCcSlab.setPreCleanSlabMaxWt(pmAutoPdResult.getPreCleanSlabMaxWt());
        pmPdCcSlab.setPreCleanSlabMinWt(pmAutoPdResult.getPreCleanSlabMinWt());
        pmPdCcSlab.setInfurSlabMaxLen(pmAutoPdResult.getInfurSlabMaxLen());
        pmPdCcSlab.setInfurSlabMinLen(pmAutoPdResult.getInfurSlabMinLen());
        pmPdCcSlab.setInfurSlabMaxWt(pmAutoPdResult.getInfurSlabMaxWt());
        pmPdCcSlab.setInfurSlabMinWt(pmAutoPdResult.getInfurSlabMinWt());
        pmPdCcSlab.setNeedSlabLen(pmAutoPdResult.getNeedSlabLen());
        // 清理前板坯重量 ＝ 进加热炉板坯重量 = 必要板坯重量
        pmPdCcSlab.setNeedSlabWt(pmAutoPdResult.getNeedSlabWt());
        pmPdCcSlab.setCommandYield(pmAutoPdResult.getCommandYield());
        pmPdCcSlab.setRollYield(pmAutoPdResult.getRollYield());
        pmPdCcSlab.setNormYield(pmAutoPdResult.getNormYield());
        pmPdCcSlab.setRollWtHp(pmAutoPdResult.getRollWtHp());
        pmPdCcSlab.setPickModeLenDir(pmAutoPdResult.getPickModeLenDir().longValue());
        pmPdCcSlab.setPickModeWidDir(pmAutoPdResult.getPickModeWidDir().longValue());
        pmPdCcSlab.setTotSmallPlateNum(pmAutoPdResult.getTotSmallPlateNum().longValue());
        pmPdCcSlab.setCombinePlateLen(pmAutoPdResult.getCombinePlateLen());
        pmPdCcSlab.setCombinePlateWidth(pmAutoPdResult.getCombinePlateWidth());
        pmPdCcSlab.setSampleLenHead(pmAutoPdResult.getSampleLenHead());
        pmPdCcSlab.setSampleLenMid(pmAutoPdResult.getSampleLenMid());
        pmPdCcSlab.setSampleLenTail(pmAutoPdResult.getSampleLenTail());
        pmPdCcSlab.setOrderNumInPlate(pmAutoPdResult.getOrderNumInPlate().longValue());

        pmPdCcSlab.setRollThickTolMax(pmAutoPdResult.getRollThickTolMax());
        pmPdCcSlab.setRollThickTolMin(pmAutoPdResult.getRollThickTolMin());
        pmPdCcSlab.setHeadCut(pmAutoPdResult.getHeadCut());
        pmPdCcSlab.setTailCut(pmAutoPdResult.getTailCut());
        pmPdCcSlab.setRollAimLen(pmAutoPdResult.getRollAimLen());
        pmPdCcSlab.setRollAimThick(pmAutoPdResult.getRollAimThick());
        pmPdCcSlab.setRollAimWidth(pmAutoPdResult.getRollAimWidth());
        pmPdCcSlab.setBroadMasUseFlag("Y");
        pmPdCcSlab.setEdgerUseFlag("N");
        pmPdCcSlab.setFormMasUseFlag("N");
        pmPdCcSlab.setBroadFlag(pmAutoPdResult.getBroadFlag());
        pmPdCcSlab.setRsCode(pmAutoPdResult.getRsCode().toString());
        pmPdCcSlab.setOrderNoAxis(pmAutoPdResult.getOrderNoAxis());
        if(pmAutoPdResult.getTransFlag() != null) {
            pmPdCcSlab.setTransFlag(pmAutoPdResult.getTransFlag().toString());
        }
        return pmPdCcSlab;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean waitingPublished(PmAutoPdPublishedRequestDTO publishedRequest, Long organizationId) {
        boolean key = redisHelper.hasKey(PUBLISH_LOCK);
        if(key) {
            throw new CommonException("存在正在运行的发布任务，请稍后重试");
        }
        PmAutoPdResultRequestDTO request = new PmAutoPdResultRequestDTO();
        request.setRequestId(publishedRequest.getRequestId());
        request.setVersion(publishedRequest.getVersion());
        request.setStNo(publishedRequest.getStNo());
        List<Integer> publishedStatusList = new ArrayList<>();
        publishedStatusList.add(0);
        request.setPublishedStatusList(publishedStatusList);
        request.setVirtualSlabNoList(publishedRequest.getVirtualSlabNoList());
        List<PmAutoPdResult> results = pmAutoPdResultRepository.selectList(request, organizationId);
        List<Long> savingList = new ArrayList<>(results.size());
        List<String> slabNoList = new ArrayList<>(results.size());
        for (PmAutoPdResult pmAutoPdResult : results) {
            slabNoList.add(pmAutoPdResult.getVirtualSlabNo());
            savingList.add(pmAutoPdResult.getResultId());
        }
        this.pmAutoPdResultRepository.markSaveSuccess(organizationId, savingList);
        this.pmAutoPdResultRepository.initContLock(slabNoList, publishedRequest.getRequestId(),
                publishedRequest.getVersion(), organizationId);
        pmAutoPdContractRepository.addLockQty(publishedRequest.getRequestId(), slabNoList,
                publishedRequest.getVersion(), organizationId);
        
        PmRequestInfo pmRequestInfo = pmRequestInfoRepository.selectByPrimaryKey(publishedRequest.getRequestId());
        pmRequestInfoRepository.markPublishing(pmRequestInfo , organizationId);
        
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean removeWaitingPublished(PmAutoPdPublishedRequestDTO publishedRequest, Long organizationId) {
        boolean key = redisHelper.hasKey(PUBLISH_LOCK);
        if(key) {
            throw new CommonException("存在正在运行的发布任务，请稍后重试");
        }
        PmAutoPdResultRequestDTO request = new PmAutoPdResultRequestDTO();
        request.setRequestId(publishedRequest.getRequestId());
        request.setVersion(publishedRequest.getVersion());
        List<Integer> publishedStatusList = new ArrayList<>();
        publishedStatusList.add(1);
        request.setPublishedStatusList(publishedStatusList);
        request.setVirtualSlabNoList(publishedRequest.getVirtualSlabNoList());
        List<PmAutoPdResult> results = pmAutoPdResultRepository.selectList(request, organizationId);
        List<Long> savingList = new ArrayList<>(results.size());
        for (PmAutoPdResult pmAutoPdResult : results) {
            savingList.add(pmAutoPdResult.getResultId());
        }
        pmAutoPdContractRepository.subLockQty(publishedRequest.getRequestId(), publishedRequest.getVirtualSlabNoList(),
                publishedRequest.getVersion(), organizationId);
        this.pmAutoPdResultRepository.markRemovePublishedSave(organizationId, savingList);

        return true;
    }

    @Override
    public PmAutoPdPublishedDTO publishList(PmAutoPdResultRequestDTO pmAutoPdResultRequest, Long organizationId) {
        PmAutoPdPublishedDTO pmAutoPdPublished = new PmAutoPdPublishedDTO();
        List<PmAutoPdPublishedDetailDTO> publishedDetailList = pmAutoPdResultRepository.selectSummaryDetailList(
                pmAutoPdResultRequest.getRequestId(), pmAutoPdResultRequest.getVersion(), organizationId);
        Map<String, PmRuntimeContract> pmRuntimeContractMap = pmRuntimeContractRepository
                .selectWt(pmAutoPdResultRequest.getRequestId(), organizationId);
        Set<String> stNoList = new HashSet<>();
        for (PmAutoPdPublishedDetailDTO pmAutoPdPublishedDetailDTO : publishedDetailList) {
            stNoList.add(pmAutoPdPublishedDetailDTO.getStNo());
        }
            
        List<PmSteelTypeGroup> pmSteelTypeGroups = pmSteelTypeGroupRepository.selectByCondition(Condition.builder(PmSteelTypeGroup.class).andWhere(Sqls.custom()
                .andIn(PmSteelTypeGroup.FIELD_ST_NO, stNoList)
                .andEqualTo(PmSteelTypeGroup.FIELD_TENANT_ID, organizationId)).build());
        Map<String , String> stGroupCodeMap = new HashMap<>();
        for (PmSteelTypeGroup pmSteelTypeGroup : pmSteelTypeGroups) {
            if(stGroupCodeMap.containsKey(pmSteelTypeGroup.getStNo())) {
                stGroupCodeMap.put(pmSteelTypeGroup.getStNo(), stGroupCodeMap.get(pmSteelTypeGroup.getStNo()) + "," + pmSteelTypeGroup.getSteelGroupCode());
            } else {
                stGroupCodeMap.put(pmSteelTypeGroup.getStNo(), pmSteelTypeGroup.getSteelGroupCode());
            }
        }
        
        Map<String, Map<String, Object>> summaryDataByStNo = new HashMap<>();
        for (PmAutoPdPublishedDetailDTO pmAutoPdPublishedDetailDTO : publishedDetailList) {
            if (!pmAutoPdPublished.getTitle().containsKey(pmAutoPdPublishedDetailDTO.getMscLineNo())) {
                pmAutoPdPublished.getTitle().put(pmAutoPdPublishedDetailDTO.getMscLineNo(), Sets.newTreeSet());
            }
            pmAutoPdPublished.getTitle().get(pmAutoPdPublishedDetailDTO.getMscLineNo())
                    .add(pmAutoPdPublishedDetailDTO.getMoldThick().toPlainString() + SPLIT
                            + pmAutoPdPublishedDetailDTO.getMoldWid().toPlainString());

            BigDecimal wt = pmAutoPdPublishedDetailDTO.getWt() == null ? BigDecimal.ZERO
                    : pmAutoPdPublishedDetailDTO.getWt();
            BigDecimal publisedWt = pmAutoPdPublishedDetailDTO.getPublishedWt() == null ? BigDecimal.ZERO
                    : pmAutoPdPublishedDetailDTO.getPublishedWt();
            String key = pmAutoPdPublishedDetailDTO.getMscLineNo() + SPLIT
                    + pmAutoPdPublishedDetailDTO.getMoldThick().toPlainString() + SPLIT
                    + pmAutoPdPublishedDetailDTO.getMoldWid().toPlainString();

            if (summaryDataByStNo.containsKey(pmAutoPdPublishedDetailDTO.getStNo())) {
                Map<String, Object> line = summaryDataByStNo.get(pmAutoPdPublishedDetailDTO.getStNo());
                line.put(PmAutoPdPublishedDTO.FIELD_BOARD_WT,
                        wt.add((BigDecimal) line.get(PmAutoPdPublishedDTO.FIELD_BOARD_WT)));
                line.put(key, publisedWt.toPlainString() + "/" + wt.toPlainString());
            } else {
                Map<String, Object> line = new HashMap<>();
                line.put(PmAutoPdPublishedDTO.FIELD_SG_SIGN, pmAutoPdPublishedDetailDTO.getSgSign());
                line.put(PmAutoPdPublishedDTO.FIELD_ST_NO, pmAutoPdPublishedDetailDTO.getStNo());
                summaryDataByStNo.put(pmAutoPdPublishedDetailDTO.getStNo(), line);
                PmRuntimeContract pmRuntimeContract = pmRuntimeContractMap.get(pmAutoPdPublishedDetailDTO.getStNo());
                if (pmRuntimeContract != null) {
                    line.put(PmAutoPdPublishedDTO.FIELD_ALL_WT, pmRuntimeContract.getOrderWt());
                }
                line.put(PmAutoPdPublishedDTO.FIELD_BOARD_WT, wt);
                line.put(key, publisedWt.toPlainString() + "/" + wt.toPlainString());
                line.put(PmAutoPdPublishedDTO.FIELD_ST_GROUP_CODE , stGroupCodeMap.get(pmAutoPdPublishedDetailDTO.getStNo()));
                
            }
        }
        pmAutoPdPublished.getData().addAll(summaryDataByStNo.values());
        return pmAutoPdPublished;
    }
    
    @Override
    public Boolean deleteRequestInfo(List<PmRequestInfo> infos, Long organizationId) {
        List<Long> requestIds = new ArrayList<>();
        List<String> requestIdStr = new ArrayList<>();
        for (PmRequestInfo pmRequestInfo : infos) {
            requestIds.add(pmRequestInfo.getRequestId());
            requestIdStr.add(pmRequestInfo.getRequestId().toString());
        }
        List<PmRequestInfo> infoDbs = pmRequestInfoRepository.selectByIds(String.join(",", requestIdStr));
        Map<String, String> lov = Utils.getLovMeaning(lovAdapter, organizationId, "PM.REQUEST_STATUS");
        for (PmRequestInfo pmRequestInfo : infoDbs) {
            if(!AutoPdRequestStatus.EXECUTION.name().equals(pmRequestInfo.getRequestStatus())
                    && !AutoPdRequestStatus.UNPUBLISHED.name().equals(pmRequestInfo.getRequestStatus())
                    && !AutoPdRequestStatus.EXEC_ERROR.name().equals(pmRequestInfo.getRequestStatus())) {
                throw new CommonException("当前状态不允许删除请求！当前状态【" + lov.getOrDefault("PM.REQUEST_STATUS" + Utils.SPLIT_CHAR + pmRequestInfo.getRequestStatus()
                , pmRequestInfo.getRequestStatus()) +"】");
            }
        }
        
        pmAutoPdPositionRepository.deleteByRequestId(requestIds);
        pmAutoPdResultRepository.deleteByRequestId(requestIds);
        pmAutoPdContractRepository.deleteByRequestId(requestIds);
        pmRuntimeContractRepository.deleteByRequestId(requestIds);
        pmRequestInfoRepository.batchDelete(infoDbs);
        Query query = new Query();
        Criteria criteriaDefinition = Criteria.where("requestId").in(requestIds);
        query.addCriteria(criteriaDefinition);
        mongoTemplate.remove(query, CalcLog.COLLECTION_AUTO_PD_LOG);
        return true ;
    }
}
