package com.jwipc.finance.logic.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.jwipc.api.constant.RestCode;
import com.jwipc.exception.DaoException;
import com.jwipc.finance.constant.AccountStatementSapClient;
import com.jwipc.finance.convert.PaymentAdvanceApplyConvert;
import com.jwipc.finance.convert.PaymentAdvanceCodConvert;
import com.jwipc.finance.dto.*;
import com.jwipc.finance.entity.*;
import com.jwipc.finance.logic.*;
import com.jwipc.finance.model.po.*;
import com.jwipc.finance.model.query.PaymentApplyItemQuery;
import com.jwipc.finance.service.IPaymentAdvanceApplyDetailService;
import com.jwipc.finance.service.IPaymentAdvanceApplyService;
import com.jwipc.finance.service.IPaymentCodApplyDetailService;
import com.jwipc.order.clent.dto.PurchaseDetailDTO;
import com.jwipc.order.client.PurchaseOrderClient;
import com.jwipc.page.PageUtil;
import com.jwipc.page.PageView;
import com.jwipc.util.DateUtils;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.baomidou.dynamic.datasource.support.DdConstants.SLAVE;

/**
 * <p>
 *
 * </p>
 *
 * @author wt
 * @version 1.0
 * @since 2024/3/8
 */
@Service
@RequiredArgsConstructor
public class PaymentAdvanceApplyDetailLogicImpl implements PaymentAdvanceApplyDetailLogic {
    private static final Logger logger = LoggerFactory.getLogger(PaymentAdvanceApplyDetailLogicImpl.class);

    private final IPaymentAdvanceApplyDetailService paymentAdvanceApplyDetailService;
    private final IPaymentAdvanceApplyService paymentAdvanceApplyService;
    private final IPaymentCodApplyDetailService paymentCodApplyDetailService;
    private final PaymentAdvanceApplyConvert paymentAdvanceApplyConvert;
    private final PaymentAdvanceCodConvert paymentAdvanceCodConvert;

    private final PaymentAdvanceCodDetailLogic paymentAdvanceCodDetailLogic;
    private final PurchaseOrderClient purchaseOrderClient;
    private final AccountStatementSapClient accountStatementSapClient;
    private final PaymentAdvanceRefundTransferApplyDetailLogic paymentAdvanceRefundTransferApplyDetailLogic;
    private final AccountStatementDetailLogic accountStatementDetailLogic;
    private final ReceiptVoucherLogic receiptVoucherLogic;
    @Override
    public PageView findPaaDetailByPaaId(Long applyId, Integer dataShowType, Integer optType) {
        List<CreatePaaDetailPO> poList = paymentAdvanceApplyDetailService.findPaaDetailByPaaId(applyId);
        List<CreatePaaDetailDto> detailDtoList = paymentAdvanceApplyConvert.POToDtoDetailList(poList);
        List<Long> existedItemIdList = Lists.newArrayList();
        for (CreatePaaDetailDto dto : detailDtoList) {
            existedItemIdList.add(dto.getId());
            dto.setBudOutMoney(dto.getBudOutMoney()==null?BigDecimal.ZERO:dto.getBudOutMoney());
            dto.setDiscountMoney(dto.getDiscountMoney()==null?BigDecimal.ZERO:dto.getDiscountMoney());
            dto.setActualityPayMoney(dto.getBudOutMoney().subtract(dto.getDiscountMoney()));
        }
        if (CollectionUtils.isNotEmpty(detailDtoList) && 1 == dataShowType) {
            // 调用SRM接口获取相关金额数据
            this.findPoAdvanceApplySituation(detailDtoList, existedItemIdList, applyId,optType);
        }
        Page<CreatePaaDetailDto> toPage = new Page<>(1, detailDtoList.size());
        toPage.setRecords(detailDtoList);
        PageView pageView = PageUtil.getPV(detailDtoList, toPage.getTotal());

        // ntAmount -> 未税金额合计; itAmount -> 含税金额合计; dtAmount -> 税额合计;
        BigDecimal ntAmount = BigDecimal.ZERO, itAmount = BigDecimal.ZERO, dtAmount = BigDecimal.ZERO;
        // caAmount -> 本次申请预付金额合计; applyAmount -> 已申请预付金额合计; advanceAmount -> 已预付金额合计;
        BigDecimal budInnerMoney = BigDecimal.ZERO, budOutMoney = BigDecimal.ZERO, applyAmount = BigDecimal.ZERO,
                discountMoney = BigDecimal.ZERO,
                reversalMoney = BigDecimal.ZERO,
                poReversalMoney = BigDecimal.ZERO,
                storeAmount = BigDecimal.ZERO,
                alreadyAccountAmount = BigDecimal.ZERO,
                alreadyOutAmount = BigDecimal.ZERO,
                alreadyIntoAmount = BigDecimal.ZERO,
                advanceAmount = BigDecimal.ZERO;
        for (CreatePaaDetailDto dto : toPage.getRecords()) {
            itAmount = itAmount.add(dto.getItAmount());
            budInnerMoney = budInnerMoney.add(dto.getBudInnerMoney());
            discountMoney = discountMoney.add(dto.getDiscountMoney());
            budOutMoney = budOutMoney.add(dto.getBudOutMoney());
            applyAmount = applyAmount.add(dto.getAlreadyApplyAmount());
            advanceAmount = advanceAmount.add(dto.getAlreadyAdvanceAmount());
            reversalMoney = reversalMoney.add(dto.getReversalMoney()==null?BigDecimal.ZERO:dto.getReversalMoney());
            poReversalMoney = poReversalMoney.add(dto.getPoReversalMoney()==null?BigDecimal.ZERO:dto.getPoReversalMoney());
            storeAmount = storeAmount.add(dto.getStoreAmount()==null?BigDecimal.ZERO:dto.getStoreAmount());
            dto.setAlreadyAccountAmount(dto.getAlreadyAccountAmount()==null?BigDecimal.ZERO:dto.getAlreadyAccountAmount());
            alreadyAccountAmount = alreadyAccountAmount.add(dto.getAlreadyAccountAmount()==null?BigDecimal.ZERO:dto.getAlreadyAccountAmount());
            alreadyOutAmount = alreadyOutAmount.add(dto.getAlreadyOutAmount()==null?BigDecimal.ZERO:dto.getAlreadyOutAmount());
            alreadyIntoAmount = alreadyIntoAmount.add(dto.getAlreadyIntoAmount()==null?BigDecimal.ZERO:dto.getAlreadyIntoAmount());
        }

        //加入千分位保留2位小数
        DecimalFormat df = new DecimalFormat("###,###.##");

        JSONArray footer = new JSONArray();
        JSONObject obj = new JSONObject();
        obj.put("poCode", "合计");
        obj.put("ntAmount", df.format(ntAmount));
        obj.put("itAmount", df.format(itAmount));
        obj.put("dtAmount", df.format(dtAmount));
        obj.put("discountMoney", df.format(discountMoney));
        obj.put("budInnerMoney", df.format(budInnerMoney));
        obj.put("actualityPayMoney", df.format(budOutMoney.subtract(discountMoney)));
        obj.put("reversalMoney", df.format(reversalMoney));
        obj.put("alreadyAccountAmount", df.format(alreadyAccountAmount));
        obj.put("alreadyOutAmount", df.format(alreadyOutAmount));
        obj.put("alreadyIntoAmount", df.format(alreadyIntoAmount));
        obj.put("budOutMoney", df.format(budOutMoney));
        obj.put("applyAmount", df.format(applyAmount));
        obj.put("storeAmount", df.format(storeAmount));
        obj.put("poReversalMoney", df.format(poReversalMoney));
        obj.put("alreadyApplyAmount", df.format(applyAmount));
        obj.put("alreadyAdvanceAmount", df.format(advanceAmount));

        footer.add(obj);
        pageView.setFooter(footer);
        return pageView;
    }

    @Override
    public List<CreatePaaDetailDto> findPaaDetailListByPaaIdAndType(Long applyId,Integer dataShowType) {
        List<CreatePaaDetailPO> poList = paymentAdvanceApplyDetailService.findPaaDetailByPaaId(applyId);
        List<CreatePaaDetailDto> detailDtoList = paymentAdvanceApplyConvert.POToDtoDetailList(poList);
        List<Long> existedItemIdList = Lists.newArrayList();
        for (CreatePaaDetailDto dto : detailDtoList) {
            existedItemIdList.add(dto.getId());
        }
        if (CollectionUtils.isNotEmpty(detailDtoList) && 1 == dataShowType) {
            // 调用SRM接口获取相关金额数据
            this.findPoAdvanceApplySituation(detailDtoList, existedItemIdList, applyId,null);
        }
        return detailDtoList;
    }
    @Override
    public List<CreatePaaDetailDto> findPaaDetailListByPaaId(Long applyId) {
        List<CreatePaaDetailPO> poList = paymentAdvanceApplyDetailService.findPaaDetailByPaaId(applyId);
        List<CreatePaaDetailDto> detailDtoList = paymentAdvanceApplyConvert.POToDtoDetailList(poList);
        List<Long> existedItemIdList = Lists.newArrayList();
        for (CreatePaaDetailDto dto : detailDtoList) {
            existedItemIdList.add(dto.getId());
        }
        if (CollectionUtils.isNotEmpty(detailDtoList)) {
            // 调用SRM接口获取相关金额数据
            this.findPoAdvanceApplySituation(detailDtoList, existedItemIdList, applyId,null);
        }
       return detailDtoList;
    }

    @Override
    public PageView findPaymentDetail(Long applyId, String type, List<String> poCodeListFromParams) {
        List<String> poCodeList = null;
        if(CollectionUtil.isNotEmpty(poCodeListFromParams)){
            poCodeList = poCodeListFromParams;
        }else {
            if("advance_payment".equals(type)&&applyId!=null){
                //预付款
                List<CreatePaaDetailPO> poList = paymentAdvanceApplyDetailService.findPaaDetailByPaaId(applyId);
                List<CreatePaaDetailDto> detailDtoList = paymentAdvanceApplyConvert.POToDtoDetailList(poList);
                if(CollectionUtil.isNotEmpty(detailDtoList)){
                    poCodeList = detailDtoList.stream().map(CreatePaaDetailDto::getPoCode).collect(Collectors.toList());
                }
            }else if("cash_on_delivery".equals(type)&&applyId!=null){
                //货到付款
                List<CreatePcaDetailDto> detailList = paymentAdvanceCodDetailLogic.findItemDateById(applyId);
                if(CollectionUtil.isNotEmpty(detailList)){
                    poCodeList = detailList.stream().map(CreatePcaDetailDto::getPoCode).collect(Collectors.toList());
                }
            }
        }
        if(CollectionUtil.isNotEmpty(poCodeList)){
            //不想修改其他东西，所以来回转换
            Set<String> hashSet = new HashSet<>(poCodeList);
            poCodeList  = new ArrayList<>(hashSet);
            //根据订单号在预付款表中查询每个订单的付款记录
            List<CreatePaaDetailPO> list = paymentAdvanceApplyDetailService.findPaymentDetailByPoCodeList(poCodeList);
            //采购订单+行号的set集合
            Set<String> poCodeAndItemNoSet = list.stream().collect(Collectors.groupingBy(createPaaDetailDto -> {
                String poCode = createPaaDetailDto.getPoCode();
                String poItemNo = createPaaDetailDto.getPoItemNo();
                return poCode + "-" + poItemNo;
            })).keySet();

            Map<String, List<CreatePaaDetailPO>> map = list.stream().collect(Collectors.groupingBy(CreatePaaDetailPO::getPoCode));
            Set<Map.Entry<String, List<CreatePaaDetailPO>>> entries = map.entrySet();
            List<PaymentRecordDTO> dtos = new ArrayList<>();
            for (Map.Entry<String, List<CreatePaaDetailPO>> entry : entries) {
                PaymentRecordDTO dto = new PaymentRecordDTO();
                dto.setPoCode(entry.getKey());
                List<CreatePaaDetailPO> value = entry.getValue();
                for (CreatePaaDetailPO createPaaDetailDto : value) {
                    //采购员
                    dto.setBuyer(createPaaDetailDto.getBuyer());
                    BigDecimal budInnerMoney = createPaaDetailDto.getBudInnerMoney();
                    BigDecimal budOutMoney = createPaaDetailDto.getBudOutMoney();
                    Integer status = createPaaDetailDto.getStatus();
                    Integer codFlag = createPaaDetailDto.getCodFlag();
                    //计算已申请预付金额= 审批中以及付款成功且未删除得所有单据
                    BigDecimal prepaid = dto.getPrepaid();
                    BigDecimal decimal = budInnerMoney.add(budOutMoney);
                    if(prepaid==null){
                        dto.setPrepaid(decimal);
                    }else {
                        dto.setPrepaid(prepaid.add(decimal));
                    }
                    //计算实际付款预付金额 = 付款成功且未删除得所有单据
                    BigDecimal actualPrepaid = dto.getActualPrepaid();
                    if(status!=null&&status ==5){
                        if(actualPrepaid == null){
                            dto.setActualPrepaid(decimal);
                        }else {
                            dto.setActualPrepaid(actualPrepaid.add(decimal));
                        }
                        dto.setTotalPayment(dto.getActualPrepaid());
                    }
                    //计算已抵扣预付金额 = 已消费标识为1的
                    BigDecimal deductionPrepaid = dto.getDeductionPrepaid();
                    if(codFlag!=null&&codFlag==1){
                        if(deductionPrepaid==null){
                            dto.setDeductionPrepaid(decimal);
                        }else {
                            dto.setDeductionPrepaid(deductionPrepaid.add(decimal));
                        }
                    }
                }
                dtos.add(dto);
            }
            //根据订单号在货到付款中查询每个订单得付款记录
            List<CreatePcaDetailDto> pcaDetailDtos = paymentAdvanceCodDetailLogic.findPaymentDetailByPoCodeList(poCodeList);
            //货到付款中订单号+行号
            Set<String> poCodeAndItemNoSet2 = pcaDetailDtos.stream().collect(Collectors.groupingBy(createPcaDetailDto -> {
                String poCode = createPcaDetailDto.getPoCode();
                String poItemNo = createPcaDetailDto.getPoItemNo();
                return poCode + "-" + poItemNo;
            })).keySet();
            Map<String, List<CreatePcaDetailDto>> ticketPaymentMap = pcaDetailDtos.stream().collect(Collectors.groupingBy(CreatePcaDetailDto::getPoCode));
            Set<Map.Entry<String, List<CreatePcaDetailDto>>> set = ticketPaymentMap.entrySet();
            for (Map.Entry<String, List<CreatePcaDetailDto>> entry : set) {
                //统计预付款的金额
                BigDecimal bigDecimal = new BigDecimal("0");
                //统计已支付的票到付款的金额
                BigDecimal totalPayment = new BigDecimal("0");
                String key = entry.getKey();
                PaymentRecordDTO paymentRecordDTO ;
                List<PaymentRecordDTO> paymentRecordDTOS = dtos.stream().filter(paymentRecordDTO2 -> paymentRecordDTO2.getPoCode().equals(key)).collect(Collectors.toList());
                if(CollectionUtil.isEmpty(paymentRecordDTOS)){
                    paymentRecordDTO = new PaymentRecordDTO();
                    paymentRecordDTO.setPoCode(key);
                    paymentRecordDTO.setBuyer(entry.getValue().get(0).getBuyer());
                    paymentRecordDTO.setPrepaid(BigDecimal.ZERO);
                    paymentRecordDTO.setDeductionPrepaid(BigDecimal.ZERO);
                    paymentRecordDTO.setActualPrepaid(BigDecimal.ZERO);
                }else {
                    paymentRecordDTO = paymentRecordDTOS.get(0);
                }
                List<CreatePcaDetailDto> value = entry.getValue();
                for (CreatePcaDetailDto createPcaDetailDto : value) {
                    BigDecimal budInnerMoney = createPcaDetailDto.getBudInnerMoney();
                    BigDecimal budOutMoney = createPcaDetailDto.getBudOutMoney();
                    Integer status = createPcaDetailDto.getStatus();
                    String amountType = createPcaDetailDto.getAmountType();
                    //计算票到付款 = 货到付款表中类型是票到付款，状态是审批中以及已支付的未删除
                    BigDecimal ticketPrepaid = paymentRecordDTO.getTicketPrepaid();
                    BigDecimal decimal = budInnerMoney.add(budOutMoney);
                    if("Z003".equals(amountType)){
                        if(status!=null&&status==5){
                            totalPayment = totalPayment.add(decimal);
                        }
                        if(ticketPrepaid==null){
                            paymentRecordDTO.setTicketPrepaid(decimal);
                        }else {
                            paymentRecordDTO.setTicketPrepaid(ticketPrepaid.add(decimal));
                        }
                    }
                    //实际票到付款 =货到付款中订单号+行号已支付 -  订单号+行号的已支付预付款
                    //换种方式实现就是：已支付的票到付款总和 - 将所有的已支付的预付款加起来。
                    if("Z001".equals(amountType)){
                        bigDecimal = bigDecimal.add(decimal);
                    }
                }
                //实际票到付款 = 用总的已支付的票到付款总和 - 所有的已支付的预付款
                if(totalPayment.compareTo(BigDecimal.ZERO)<=0){
                    //说明当前已支付的票到付款金额为0
                    paymentRecordDTO.setActualTicketPrepaid(BigDecimal.ZERO);
                }else {
                    paymentRecordDTO.setActualTicketPrepaid(totalPayment.add(bigDecimal));
                }

                //累计已付金额 = 实际预付金额+实际票到付款金额
                paymentRecordDTO.setTotalPayment(paymentRecordDTO.getActualPrepaid().add(paymentRecordDTO.getActualTicketPrepaid()));

                if(CollectionUtil.isEmpty(paymentRecordDTOS)){
                    dtos.add(paymentRecordDTO);
                }
            }

            //计算订单的剩余付款金额 = (行项目订单数量*数量 --> 行项目总金额相加得到总金额 - 已结案的订单行的未清数量*单价-->需扣除订单行金额相加得到总的需要扣除的金额 - 累计已付款金额 )
            Set<String> setItem = new HashSet<>();
            setItem.addAll(poCodeAndItemNoSet);
            setItem.addAll(poCodeAndItemNoSet2);
            List<PurchaseDetailDTO> details = setItem.stream().map(s -> {
                String[] split = s.split("-");
                //订单号
                String poCode = split[0];
                //行号
                String poItemNo = split[1];
                PurchaseDetailDTO detail = new PurchaseDetailDTO();
                detail.setOrderCode(poCode);
                detail.setOrderRow(poItemNo);
                detail.setDelFlag(0);
                return detail;
            }).collect(Collectors.toList());
            if(CollectionUtils.isNotEmpty(details)){
                List<PurchaseDetailDTO> orderDetailList = purchaseOrderClient.getOrderDetailInfo(details);
                Map<String, List<PurchaseDetailDTO>> poCodeMap = orderDetailList.stream().collect(Collectors.groupingBy(PurchaseDetailDTO::getOrderCode));
                for (Map.Entry<String, List<PurchaseDetailDTO>> entry : poCodeMap.entrySet()) {
                    String key = entry.getKey();
                    List<PaymentRecordDTO> dtoList = dtos.stream().filter(paymentRecordDTO -> paymentRecordDTO.getPoCode().equals(key)).collect(Collectors.toList());
                    PaymentRecordDTO paymentRecordDTO =null;
                    if(CollectionUtils.isNotEmpty(dtoList)){
                        paymentRecordDTO = dtoList.get(0);
                    }
                    //采购订单总金额
                    BigDecimal purchaseOrderTotalPrice = new BigDecimal("0");
                    //未清数量金额
                    BigDecimal noClearToatlPrice = new BigDecimal("0");
                    List<PurchaseDetailDTO> value = entry.getValue();
                    for (PurchaseDetailDTO purchaseOrderDetail : value) {
                        //订单数量
                        BigDecimal num = purchaseOrderDetail.getNum();
                        //单价
                        BigDecimal price = purchaseOrderDetail.getPrice();
                        //交货即结案标识
                        String finishJaoHuo = purchaseOrderDetail.getFinishFlag();
                        //未清数量
                        BigDecimal noClearNum = purchaseOrderDetail.getNoClearNum();
                        if("Y".equals(finishJaoHuo)){
                            //已结案，未清数量*单价-->扣减金额
                            BigDecimal bigDecimal = noClearNum.multiply(price).setScale(5, RoundingMode.HALF_UP);
                            noClearToatlPrice = noClearToatlPrice.add(bigDecimal);
                        }
                        BigDecimal bigDecimal = num.multiply(price).setScale(5, RoundingMode.HALF_UP);
                        purchaseOrderTotalPrice = purchaseOrderTotalPrice.add(bigDecimal);
                    }
                    if(paymentRecordDTO!=null){
                        BigDecimal remainingPrice = purchaseOrderTotalPrice.subtract(noClearToatlPrice).subtract(paymentRecordDTO.getTotalPayment() == null ? new BigDecimal("0") : paymentRecordDTO.getTotalPayment());
                        paymentRecordDTO.setRemaining(remainingPrice);
                    }
                }
            }
            //兜底策略，没有值的赋值0
            if(CollectionUtil.isNotEmpty(dtos)){
                dtos.forEach(paymentRecordDTO -> {
                    if (paymentRecordDTO.getDeductionPrepaid() == null) {
                        paymentRecordDTO.setDeductionPrepaid(BigDecimal.ZERO);
                    }
                    if(paymentRecordDTO.getPrepaid()==null){paymentRecordDTO.setPrepaid(BigDecimal.ZERO);}
                    if(paymentRecordDTO.getActualPrepaid()==null){paymentRecordDTO.setActualPrepaid(BigDecimal.ZERO);}
                    if(paymentRecordDTO.getActualTicketPrepaid()==null){paymentRecordDTO.setActualTicketPrepaid(BigDecimal.ZERO);}
                    if(paymentRecordDTO.getTicketPrepaid()==null){paymentRecordDTO.setTicketPrepaid(BigDecimal.ZERO);}
                    if(paymentRecordDTO.getTotalPayment()==null) {paymentRecordDTO.setTotalPayment(BigDecimal.ZERO);}
                    if(paymentRecordDTO.getRemaining()==null) {paymentRecordDTO.setRemaining(BigDecimal.ZERO);}
                });
            }
            Page<PaymentRecordDTO> toPage = new Page<>(1, dtos.size());
            toPage.setRecords(dtos);
            PageView pageView = PageUtil.getPV(toPage);
            return pageView;
        }else {
            Page<PaymentRecordDTO> toPage = new Page<>(1, 0);
            toPage.setRecords(new ArrayList<PaymentRecordDTO>());
            PageView pageView = PageUtil.getPV(toPage);
            return pageView;
        }
    }

    @Override
    public List<PaymentRecordDTO> findDetailByPoCode(String poCode) {
        //从预付申请表中查询数据,预付表中不存在发票号以及行号,也没有抵扣预付金额的概念
        List<PaymentRecordPO> poList = paymentAdvanceApplyDetailService.findDetailByPoCode(poCode);
        List<PaymentRecordDTO> dtoList = paymentAdvanceApplyConvert.poToDtoRecordList(poList);
        for (PaymentRecordDTO paymentRecordDTO : dtoList) {
            BigDecimal budInnerMoney = paymentRecordDTO.getBudInnerMoney();
            BigDecimal budOutMoney = paymentRecordDTO.getBudOutMoney();
            Integer status = paymentRecordDTO.getStatus();
            paymentRecordDTO.setPrepaid(budInnerMoney.add(budOutMoney));
            if(status!=null&&status==5){
                //付款成功
                paymentRecordDTO.setActualPrepaid(budInnerMoney.add(budOutMoney));
            }else {
                paymentRecordDTO.setActualPrepaid(BigDecimal.ZERO);
            }
            paymentRecordDTO.setDeductionPrepaid(BigDecimal.ZERO);
        }
        //从货到付款表中查询数据
        List<PaymentRecordPO> recordPOS = paymentCodApplyDetailService.findDetailByPoCode(poCode);
        List<PaymentRecordDTO> list = paymentAdvanceCodConvert.poToDtoRecordList(recordPOS);
        //过滤出预付款的数据并根据采购订单号+行号分组
        Map<String, List<PaymentRecordDTO>> map = list.stream().filter(paymentRecordDTO -> "Z001".equals(paymentRecordDTO.getAmountType())).collect(Collectors.groupingBy(paymentRecordDTO -> {
            return paymentRecordDTO.getPoCode() + paymentRecordDTO.getItemNo();
        }));
        //key :采购订单号+行号  value: 预付金额
        Map<String, BigDecimal> hashMap = new HashMap<>();
        for (Map.Entry<String, List<PaymentRecordDTO>> entry : map.entrySet()) {
            BigDecimal totalDeci = new BigDecimal("0");
            String key = entry.getKey();
            List<PaymentRecordDTO> dtos = entry.getValue();
            for (PaymentRecordDTO dto : dtos) {
                BigDecimal budOutMoney = dto.getBudOutMoney();
                BigDecimal budInnerMoney = dto.getBudInnerMoney();
                totalDeci = totalDeci.add(budInnerMoney.add(budOutMoney).abs());
            }
            hashMap.put(key,totalDeci);
        }
        //过滤出票到付款的数据
        List<PaymentRecordDTO> ticketList = list.stream().filter(paymentRecordDTO -> "Z003".equals(paymentRecordDTO.getAmountType())).collect(Collectors.toList());
        for (PaymentRecordDTO paymentRecordDTO : ticketList) {
            String code = paymentRecordDTO.getPoCode();
            String itemNo = paymentRecordDTO.getItemNo();
            BigDecimal decimal = hashMap.get(code + itemNo);
            BigDecimal budInnerMoney = paymentRecordDTO.getBudInnerMoney();
            BigDecimal budOutMoney = paymentRecordDTO.getBudOutMoney();
            Integer status = paymentRecordDTO.getStatus();
            //申请付款的金额
            paymentRecordDTO.setPrepaid(budInnerMoney.add(budOutMoney));
            if(status!=null&&status==5){
                //已付款的单据，实际付款 = 申请付款-抵扣付款
                if(decimal!=null){
                    //判断当前的抵扣付款是否大于当前申请的付款金额
                    // 抵扣 > 申请 ==> 抵扣 - 申请 ，余下的抵扣用于下一个同一个采购单号+行号抵扣
                    if(decimal.compareTo(budInnerMoney.add(budOutMoney))>0){
                        paymentRecordDTO.setActualPrepaid(BigDecimal.ZERO);
                        paymentRecordDTO.setDeductionPrepaid(budInnerMoney.add(budOutMoney));
                        hashMap.put(code+itemNo,decimal.subtract(budInnerMoney.add(budOutMoney)));
                    }else {
                        paymentRecordDTO.setActualPrepaid(decimal.subtract(budInnerMoney.add(budOutMoney)).abs());
                        paymentRecordDTO.setDeductionPrepaid(decimal);
                        hashMap.put(code + itemNo,BigDecimal.ZERO);
                    }
                }else {
                    //没有抵扣付款的单据
                    paymentRecordDTO.setActualPrepaid(budInnerMoney.add(budOutMoney));
                    //抵扣付款
                    paymentRecordDTO.setDeductionPrepaid(BigDecimal.ZERO);
                }
            }else {
                paymentRecordDTO.setDeductionPrepaid(BigDecimal.ZERO);
                paymentRecordDTO.setActualPrepaid(BigDecimal.ZERO);
            }
        }
        dtoList.addAll(ticketList);
        return dtoList;
    }

    @Override
    @DS(SLAVE)
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public List<CreatePaaDetailDto> findAdvanceApplyDataByPoCode(PaymentApplyItemQuery query) {
        query.setPoCodes(JSONArray.parseArray(query.getMorePoQuery(), String.class));
        query.setMorePoQuery(null);
        List<CreatePaaDetailPO> result = paymentCodApplyDetailService.readAdvancePaymentPoData(query);
        if (CollectionUtils.isNotEmpty(result)) {
            for (CreatePaaDetailPO po : result){
                // 获取采购订单行在物料凭证中使用的情况
                List<ReceiveVoucherDTO> receiveVoucherDTO = receiptVoucherLogic.findByPoAndAsNoNotNull(po.getPoCode(),po.getPoItemNo(),po.getFactoryCode());
                BigDecimal alreadyAccountAmount = BigDecimal.ZERO;
                if (CollectionUtils.isNotEmpty(receiveVoucherDTO)) {
                    for (ReceiveVoucherDTO s : receiveVoucherDTO){
                        if (s.getDeductionRatio()==null){
                            s.setDeductionRatio(BigDecimal.ZERO);
                        }
                        if (s.getDeductionRatio().compareTo(BigDecimal.ZERO)!=0){
                            s.setOriginalTaxAmount(s.getTaxAmount());
                        }else{
                            s.setOriginalTaxAmount(s.getOriginalTaxPrice().multiply(s.getMvNum()));
                        }
                        if (s.getVoucherFlag().equals("H")){
                            if (s.getOriginalTaxAmount().compareTo(BigDecimal.ZERO) > 0) { // 只有正数才取负
                                s.setOriginalTaxAmount(s.getOriginalTaxAmount().negate());
                                s.setMvNum(s.getMvNum().negate());
                            }
                        }
                        alreadyAccountAmount = alreadyAccountAmount.add(s.getOriginalTaxAmount());
                    }
                }
                po.setAlreadyAccountAmount(alreadyAccountAmount);

                //根据订单号和行取物料凭证取物料凭证对应的原含税金额
                BigDecimal storeAmount = BigDecimal.ZERO;
                List<ReceiveVoucherDTO> receiveVoucherDTO1 = receiptVoucherLogic.findByPoAndItemNo(po.getPoCode(),po.getPoItemNo(),po.getFactoryCode());
                if (CollectionUtils.isNotEmpty(receiveVoucherDTO1)) {
                    for (ReceiveVoucherDTO s : receiveVoucherDTO1){
                        if (s.getDeductionRatio()==null){
                            s.setDeductionRatio(BigDecimal.ZERO);
                        }
                        if (s.getDeductionRatio().compareTo(BigDecimal.ZERO)!=0){
                            s.setOriginalTaxAmount(s.getTaxAmount());
                        }else{
                            s.setOriginalTaxAmount(s.getOriginalTaxPrice().multiply(s.getMvNum()));
                        }
                        if (s.getVoucherFlag().equals("H")){
                            if (s.getOriginalTaxAmount().compareTo(BigDecimal.ZERO) > 0) { // 只有正数才取负
                                s.setOriginalTaxAmount(s.getOriginalTaxAmount().negate());
                                s.setMvNum(s.getMvNum().negate());
                            }
                        }
                        storeAmount = storeAmount.add(s.getOriginalTaxAmount());
                    }
                }
                po.setStoreAmount(storeAmount);
            }

            paymentCodApplyDetailService.findPoAdvanceApplySituation(result, query.getExistedItemIdList(), query.getApplyId());

            //根据订单号和行号，查询订单明细的付款过期日， 邓京术 2024-11-04
            PurchaseOrderDetailSapDTO.ITItem itItem = new PurchaseOrderDetailSapDTO.ITItem();
            itItem.item = Lists.newArrayList();
            result.stream().forEach(obj -> {
                PurchaseOrderDetailSapDTO.Item item = new PurchaseOrderDetailSapDTO.Item();
                item.EBELN = obj.getPoCode();
                item.EBELP = obj.getPoItemNo();
                itItem.item.add(item);
            });
            PurchaseOrderDetailSapDTO purchaseOrderDetailSapDTO = new PurchaseOrderDetailSapDTO();
            purchaseOrderDetailSapDTO.setIT_ITEM(itItem);
            final PurchaseOrderDetailResposeDTO purchaseOrderDetailResposeDTO = accountStatementSapClient.getOrderDetailPaymentExpireDateByOrderNo(purchaseOrderDetailSapDTO);
            if (purchaseOrderDetailResposeDTO.getES_RET().getCODE().equals(RestCode.SAP_ERROR.getCode())) {
                logger.info("SAP查询订单付款日期报错，" + "SAP接口报错：" + purchaseOrderDetailResposeDTO.getES_RET().getMSG());
                return paymentAdvanceApplyConvert.POToDtoDetailList(result);
//                throw new DaoException("SAP接口报错：" + purchaseOrderDetailResposeDTO.getES_RET().getMSG());
            }
            final PurchaseOrderDetailResposeDTO.Item1 itemData = purchaseOrderDetailResposeDTO.getIT_DATA();
            final List<PurchaseOrderDetailResposeDTO.Item> itemList  = Objects.nonNull(itemData) ? itemData.item: Lists.newArrayList();
            result.stream().forEach(obj -> {
                Iterator it = itemList.iterator();
                while (it.hasNext()) {
                    PurchaseOrderDetailResposeDTO.Item item = (PurchaseOrderDetailResposeDTO.Item) it.next();
                    if (item.EBELN.equals(obj.getPoCode()) && Integer.parseInt(item.EBELP) == (Integer.parseInt(obj.getPoItemNo()))) {
//                        System.out.println("采购订单付款到期日 ==" +  obj.getPoCode() + "/" +obj.getPoItemNo() + "/" + item.ZFBDT);
                        if (StringUtils.isNotEmpty(item.ZFBDT)) {
                            obj.setPaymentExpireDate(DateUtils.formatYYYYMMDDDash(item.ZFBDT));
                        }
                        //减少循环次数，提高代码执行率
                        it.remove();
                        break;
                    }
                }
            });
        }

        result.forEach(po -> {
            //当订单金额大于0，且计算出来的可申请金额小于0时，可申请金额置换为0
            if (po.getItAmount().compareTo(BigDecimal.ZERO) > 0 && po.getApplyAmount().compareTo(BigDecimal.ZERO) < 0) {
                po.setBudOutMoney(BigDecimal.ZERO);
            }
        });
        return paymentAdvanceApplyConvert.POToDtoDetailList(result);
    }

    @Override
    public List<CreatePcaDetailDto> findAdvanceApplyDataByDataKey(List<String> dataKeys) {
        List<CreatePcaDetailPO> advanceApplyDataByDataKey = paymentCodApplyDetailService.findAdvanceApplyDataByDataKey(dataKeys);
        List<CreatePcaDetailDto> list = paymentAdvanceCodConvert.POToDtoDetailList(advanceApplyDataByDataKey);
        return list;
    }

    /**
     * 开票申请获取预付款信息
     *
     * @param query 查询条件
     * @return 结果
     */
    @Override
    public List<InvoicedApplyPaDTO> provideCreateAdvanceApply(PaymentApplyItemQuery query) {
        String poCodeItemNoList = query.getPoCodeItemNoList();
        List<String> dataKeys = new ArrayList<>();
        if(StringUtils.isNotEmpty(poCodeItemNoList)){
            dataKeys = Arrays.asList(poCodeItemNoList.split(","));

            //1.查询列表排除已经转单的订单，只查询在对账单明细里的订单 ,查出数据后需要再去预付款变更单根据预付款行号和预付款单号去汇总金额，汇总成一条数据
            List<InvoicedApplyPaPO> invoicedApplyPaPOS =  paymentAdvanceApplyDetailService.provideCreateAdvanceApplyNew1(query,dataKeys);
            Map<String, BigDecimal> map = null;
            if(CollectionUtils.isNotEmpty(invoicedApplyPaPOS)){
                List<String> prepaymentKeyword = invoicedApplyPaPOS.stream()
                        .filter(item -> Objects.nonNull(item.getApplyNo()) && !item.getApplyNo().isEmpty())
                        .filter(item -> Objects.nonNull(item.getApplyItemNo()) && !item.getApplyItemNo().isEmpty())
                        .map(item -> item.getApplyNo() + "_" + item.getApplyItemNo())
                        .collect(Collectors.toList());
                if(CollectionUtils.isNotEmpty(prepaymentKeyword)){
                    List<PaymentAdvanceRefundTransferApplyAndDetailListDTO> list = paymentAdvanceRefundTransferApplyDetailLogic.findRefundTransferApplyDetailSumRefundAmountByDateKey(prepaymentKeyword);
                    map = list.stream()
                            .filter(item -> item.getDataKey() != null && item.getRegistTaxAmount() != null)  // 过滤掉 dataKey 或 amount 为 null 的记录
                            .collect(Collectors.toMap(
                                    PaymentAdvanceRefundTransferApplyAndDetailListDTO::getDataKey,  // key: dataKey
                                    PaymentAdvanceRefundTransferApplyAndDetailListDTO::getRegistTaxAmount,   // value: amount
                                    BigDecimal::add  // 如果 key 重复，合并 value（相加）
                            ));
                }
            }

            //预付款订单明细数据
            for (InvoicedApplyPaPO invoicedApplyPaPO : invoicedApplyPaPOS) {
                //扣减掉退款金额
                BigDecimal  registTaxAmount = map.get(invoicedApplyPaPO.getApplyNo()+"_"+invoicedApplyPaPO.getApplyItemNo());
                invoicedApplyPaPO.setSurplusReversalMoney(invoicedApplyPaPO.getBudOutMoney().subtract(invoicedApplyPaPO.getReversalMoney()).subtract(registTaxAmount == null ?BigDecimal.ZERO.stripTrailingZeros() :  registTaxAmount));
                invoicedApplyPaPO.setStrikePrice(invoicedApplyPaPO.getSurplusReversalMoney());
                invoicedApplyPaPO.setRefundedTaxAmount(registTaxAmount == null ?BigDecimal.ZERO.stripTrailingZeros() :  registTaxAmount);
            }
            if(CollectionUtils.isNotEmpty(dataKeys)){
                //2.先查询是否存在转单的对账单订单(根据对账单明细中的采购订单号=预付款变更单参考采购订单、且采购订单行=预付款变更单参考采购订单行、且预付款变更单数据状态是“已发布”、且预付款变更单数据类型是“转单”、且剩余可冲账金额（开票申请）大于0)
                List<PaymentAdvanceRefundTransferApplyAndDetailListDTO> refundTransferApplyDetailByReferOrderKey = paymentAdvanceRefundTransferApplyDetailLogic.findRefundTransferApplyDetailByReferOrderKey(dataKeys);
                //3合并查询数据
                extracted(refundTransferApplyDetailByReferOrderKey, invoicedApplyPaPOS);
            }

            //List<InvoicedApplyPaPO> invoicedApplyPaPOS = paymentAdvanceApplyDetailService.provideCreateAdvanceApply(query);

//        invoicedApplyPaPOS.forEach(invoicedApplyPaPO -> {
//            //扣减掉退款金额
//            invoicedApplyPaPO.setSurplusReversalMoney(invoicedApplyPaPO.getBudOutMoney().subtract(invoicedApplyPaPO.getReversalMoney()));
//            invoicedApplyPaPO.setStrikePrice(invoicedApplyPaPO.getSurplusReversalMoney());
//        });
            if (CollUtil.isNotEmpty(invoicedApplyPaPOS)){
                invoicedApplyPaPOS.forEach(invoicedApplyPaPO -> {
                    PaymentAdvanceApply apply = paymentAdvanceApplyService.getOne(new LambdaQueryWrapper<PaymentAdvanceApply>()
                            .eq(PaymentAdvanceApply::getApApplyNo, invoicedApplyPaPO.getApplyNo()).last(" limit 1"));
                    if (apply != null){
                        invoicedApplyPaPO.setPaymentStatus(apply.getStatus());
                    }
                });
            }
            return paymentAdvanceApplyConvert.invoicedApplyPaPO2DTOList(invoicedApplyPaPOS);
        }else{
            List<InvoicedApplyPaPO> invoicedApplyPaPOS = paymentAdvanceApplyDetailService.provideCreateAdvanceApply(query);
            invoicedApplyPaPOS.forEach(invoicedApplyPaPO -> {
                invoicedApplyPaPO.setSurplusReversalMoney(invoicedApplyPaPO.getBudOutMoney().subtract(invoicedApplyPaPO.getReversalMoney()));
                invoicedApplyPaPO.setStrikePrice(invoicedApplyPaPO.getSurplusReversalMoney());
            });
            return paymentAdvanceApplyConvert.invoicedApplyPaPO2DTOList(invoicedApplyPaPOS);
        }

    }

    private static void extracted(List<PaymentAdvanceRefundTransferApplyAndDetailListDTO> refundTransferApplyDetailByReferOrderKey, List<InvoicedApplyPaPO> invoicedApplyPaPOS) {
        if(CollectionUtils.isNotEmpty(refundTransferApplyDetailByReferOrderKey)){
            //1和2的结果需要合并
            for (PaymentAdvanceRefundTransferApplyAndDetailListDTO refundTransferDetailListDTO : refundTransferApplyDetailByReferOrderKey) {
                InvoicedApplyPaPO paPO = new InvoicedApplyPaPO();
                paPO.setPaId(refundTransferDetailListDTO.getPaId());//没有
                paPO.setCompanyCode(refundTransferDetailListDTO.getCompanyCode());
                paPO.setSupplierCode(refundTransferDetailListDTO.getSupplierCode());
                paPO.setCurrencyCode(refundTransferDetailListDTO.getCurrencyCode());
                paPO.setApplyNo(refundTransferDetailListDTO.getAppNo());
                paPO.setApplyItemNo(refundTransferDetailListDTO.getAppItemNo());
                paPO.setPoCode(refundTransferDetailListDTO.getReferPurchaseOrder());
                paPO.setPoItemNo(refundTransferDetailListDTO.getReferPurchaseOrderItem());
                paPO.setApplyPrice(refundTransferDetailListDTO.getTheRegistTaxAmount());//预付款金额 applyPrice  预付款金额（开票申请）     = 本次登记含税金额（预付款变更单）
                paPO.setReversalMoney(refundTransferDetailListDTO.getAlreadyApplyAmount());//已冲账金额  已冲账金额（开票申请）     = 已冲账含税金额（预付款变更单）
                paPO.setSurplusReversalMoney((refundTransferDetailListDTO.getTheRegistTaxAmount() == null ? BigDecimal.ZERO.stripTrailingZeros() : refundTransferDetailListDTO.getTheRegistTaxAmount()).subtract(refundTransferDetailListDTO.getAlreadyApplyAmount() == null ? BigDecimal.ZERO : refundTransferDetailListDTO.getAlreadyApplyAmount()));//剩余可冲账金额
                paPO.setStrikePrice(paPO.getSurplusReversalMoney());
                paPO.setRemark(refundTransferDetailListDTO.getSummary());
                paPO.setDeleteFlag(0);
                paPO.setPaymentChangeNumber(refundTransferDetailListDTO.getPaymentChangeNumber());
                paPO.setPaymentChangeItemNo(refundTransferDetailListDTO.getItemNo());
                paPO.setDataType(refundTransferDetailListDTO.getDataType());
                // paPO.setRefundedTaxAmount(refundTransferDetailListDTO.getRegistTaxAmount());//已退款含税金额
                invoicedApplyPaPOS.add(paPO);
            }
        }
        if(CollectionUtils.isNotEmpty(invoicedApplyPaPOS)){
            invoicedApplyPaPOS.removeIf(po ->
                    po.getSurplusReversalMoney() == null || po.getSurplusReversalMoney().compareTo(BigDecimal.ZERO) == 0
            );
        }
    }

    //分组统计预付款金额
    public Map<String, BigDecimal> sumStrikePriceByPoCodeAndItemNo(List<InvoicedApplyPa> list) {
        return list.stream()
                .collect(Collectors.groupingBy(
                        item -> item.getPoCode() + "_" + item.getPoItemNo(),
                        Collectors.reducing(
                                BigDecimal.ZERO,
                                InvoicedApplyPa::getStrikePrice,
                                BigDecimal::add
                        )
                ));
    }

    @Override
    public void hasUnappliedPrepaymentBalance(InvoicedApplyDTO head, List<InvoicedApplyPa> addAdvances) {
        //通过开票申请获取到绑定的对账订单明细信息
        if(!Objects.isNull(head.getAccountStatementId())){
            //通过开票申请获取到绑定的对账订单明细信息
            Long accountStatementId = head.getAccountStatementId();//开票申请对账单id
            String factoryCode = head.getFactoryCode();//工厂编号
            //校验一：拿到对账单订单号+订单行号，到预付款明细表（排除以转单的预付款订单明细）中查找计算
            PageView page = accountStatementDetailLogic.findByStatementIdAndFactoryCodePage(accountStatementId, factoryCode, null);
            List<StatementItemDTO> rows = (List<StatementItemDTO>) page.getRows();
            //开票申请对账订单明细
            if(CollectionUtils.isNotEmpty(rows)){
                List<StatementItemDTO> statementItemDTOS = mergeAndProcess(rows);
                List<String> orderS = statementItemDTOS.stream().map(item -> (item.getPoCode() != null ? item.getPoCode() : "") + "_" +(item.getPoItemNo() != null ? item.getPoItemNo() : "")).collect(Collectors.toList());
                //进行比较
                //2025-12-22 1、累计订单行本次冲账金额   大于   累计订单行对账金额，报错”采购订单XXX行XXX累计本次冲账金额大于对账金额“
                // 本次冲账金额	累计订单行本次冲账金额：预付款明细，按采购订单行维度，汇总”本次冲账金额“
                // 对账金额	累计订单行对账金额：对账明细，按采购订单行维度，汇总物料凭证行”原含税金额“
                //如果前台页面选了预付款明细,则使用选中的预付款明细
                    if(CollectionUtils.isEmpty(addAdvances)){
                        //如果前台界面没选择预付款明细，则通过对账单明细里的订单号+行号去预付款明细表里查没有转单且状态为OA废弃和删除的
                        PaymentApplyItemQuery query = new PaymentApplyItemQuery();
                        query.setPoCodeItemNoList(String.join(",", orderS));
                        List<InvoicedApplyPaDTO> invoicedApplyPaDTOS = provideCreateAdvanceApply(query);
                        if(CollectionUtils.isNotEmpty(invoicedApplyPaDTOS)) {
                            addAdvances =  paymentAdvanceApplyConvert.invoicedApplyPaPO2List(invoicedApplyPaDTOS);
                        }
                    }
                if(CollectionUtils.isNotEmpty(addAdvances)){
                    Map<String, BigDecimal> strikePriceMap = sumStrikePriceByPoCodeAndItemNo(addAdvances);
                    List<InvoicedApplyPa> finalAddAdvances = addAdvances;
                    strikePriceMap.forEach((mapKey, mapValue) -> {
                        statementItemDTOS.stream()
                                .filter(item -> (item.getPoCode() + "_" + item.getPoItemNo()).equals(mapKey))
                                .findFirst()
                                .ifPresent(matchedItem -> {
                                    //累计订单行对账金额大于0，累计订单行本次冲账金额   大于   累计订单行对账金额，报错”采购订单XXX行XXX累计本次冲账金额大于对账金额“
                                    if(matchedItem.getSummaryReconciliationAmount().compareTo(BigDecimal.ZERO) > 0 && (matchedItem.getSummaryReconciliationAmount().compareTo(mapValue) < 0) ){//抵扣金额大于对账金额
                                        throw new DaoException("采购订单:"+matchedItem.getPoCode()+",行"+matchedItem.getPoItemNo()+"累计本次冲账金额大于对账金额");
                                    }
                                    //累计订单行对账金额小于0，累计订单行本次冲账金额   小于   累计订单行对账金额，报错”采购订单XXX行XXX累计本次冲账金额超过对账金额“
                                    if(matchedItem.getSummaryReconciliationAmount().compareTo(BigDecimal.ZERO) < 0 && (matchedItem.getSummaryReconciliationAmount().compareTo(mapValue)) > 0 ){//抵扣金额小于对账金额
                                        throw new DaoException("采购订单:"+matchedItem.getPoCode()+",行"+matchedItem.getPoItemNo()+"累计本次冲账金额超过对账金额");
                                    }

                                    //当累计订单行对账金额大于0，对账未冲账金额大于0时，判定该订单行是否有未抵扣的预付款金额
                                 //   if(matchedItem.getSummaryReconciliationAmount().compareTo(BigDecimal.ZERO) > 0 && mapValue.compareTo(BigDecimal.ZERO) > 0){}
                                //当累计订单行对账金额小于0，对账未冲账金额小于0时，判定该订单行是否有未抵扣的预付款金额
                                  //  if(matchedItem.getSummaryReconciliationAmount().compareTo(BigDecimal.ZERO) < 0 && mapValue.compareTo(BigDecimal.ZERO) < 0) {}
                                    int sign = matchedItem.getSummaryReconciliationAmount().signum();
                                    if (sign != 0 && sign == mapValue.signum()) {
                                        // sign=1 表示正向逻辑（原来 >0 分支），sign=-1 表示负向逻辑（原来 <0 分支）
                                        checkUnappliedPrepaymentBalance(head, orderS, finalAddAdvances, sign);
                                    }


                                });
                    });
                }
            }
        }
    }

    private void checkUnappliedPrepaymentBalance(InvoicedApplyDTO head,
                                                 List<String> orderS,
                                                 List<InvoicedApplyPa> finalAddAdvances,
                                                 int sign) {
        // 你原代码里这里写的是 head.getActualUnpaidAmount() > 0 才校验
        if (head.getActualUnpaidAmount() == null || head.getActualUnpaidAmount().compareTo(BigDecimal.ZERO) <= 0) {
            return;
        }

        // 1) 校验：是否存在未发布的退款/转单变更单（两分支完全一样）
        validateUnpublishedRefundOrTransfer(orderS);

        // 2) 查转单变更单数据（后续“检验二”要用）
        List<PaymentAdvanceRefundTransferApplyAndDetailListDTO> refundTransferApplyDatas =
                paymentAdvanceRefundTransferApplyDetailLogic.findRefundTransferApplyDataTypeInfoByPoCodeAndItem(orderS);

        // 3) 检验一：非转单的预付款明细表
        List<InvoicedApplyPaPO> invoicedApplyPaPOS =
                paymentAdvanceApplyDetailService.provideCreateAdvanceApplyNew(new PaymentApplyItemQuery(), orderS);

        if (CollectionUtils.isNotEmpty(invoicedApplyPaPOS)) {
            checkAdvanceApplyDetailsDeductible(sign, invoicedApplyPaPOS, finalAddAdvances);
        }

        // 4) 检验二：预付款变更单明细（转单）
        if (CollectionUtils.isNotEmpty(refundTransferApplyDatas)) {
            checkTransferApplyDetailsDeductible(sign, refundTransferApplyDatas, finalAddAdvances);
        }
    }

    /**
     * 未发布的退款/转单变更单提醒（两分支完全一样）
     */
    private void validateUnpublishedRefundOrTransfer(List<String> orderS) {
        // 1. 退款类型变更单未发布
        List<PaymentAdvanceRefundTransferApplyAndDetailListDTO> refundTransferApplyDetails =
                paymentAdvanceRefundTransferApplyDetailLogic.findRefundTApplyDataByPoCodeAndItemDateKey(orderS);

        if (CollectionUtils.isNotEmpty(refundTransferApplyDetails)) {
            for (PaymentAdvanceRefundTransferApplyAndDetailListDTO dto : refundTransferApplyDetails) {
                if (dto.getStatus() != 3) {
                    throw new DaoException("预付款申请单:" + dto.getAppNo() + ",预付款申请行" + dto.getAppItemNo()
                            + "，存在未发布的退款类型的预付款变更单:" + dto.getPaymentChangeNumber() + "行:" + dto.getItemNo());
                }
            }
        }

        // 2. 转单类型变更单未发布
        List<PaymentAdvanceRefundTransferApplyAndDetailListDTO> refundTransferApplyDatas =
                paymentAdvanceRefundTransferApplyDetailLogic.findRefundTransferApplyDataTypeInfoByPoCodeAndItem(orderS);

        if (CollectionUtils.isNotEmpty(refundTransferApplyDatas)) {
            for (PaymentAdvanceRefundTransferApplyAndDetailListDTO applyData : refundTransferApplyDatas) {
                if (applyData.getStatus() != 3) {
                    throw new DaoException("预付款申请单:" + applyData.getAppNo() + ",预付款申请行" + applyData.getAppItemNo()
                            + "，存在未发布的转单类型的预付款变更单:" + applyData.getPaymentChangeNumber() + "行:" + applyData.getItemNo());
                }
            }
        }
    }

    /**
     * 检验一：预付款明细表（非转单）—— 只差最后“方向判错”
     * sign=1：原来 >0 分支（deductibleAmount > 0 报错）
     * sign=-1：原来 <0 分支（deductibleAmount < 0 报错）
     */
    private void checkAdvanceApplyDetailsDeductible(int sign,
                                                    List<InvoicedApplyPaPO> invoicedApplyPaPOS,
                                                    List<InvoicedApplyPa> finalAddAdvances) {
        BigDecimal deductibleAmount = BigDecimal.ZERO;

        for (InvoicedApplyPaPO po : invoicedApplyPaPOS) {
            String applyNo = po.getApplyNo();
            String applyItemNo = po.getApplyItemNo();
            String uniqueKey = applyNo + "_" + applyItemNo;

            List<PaymentAdvanceRefundTransferApplyAndDetailListDTO> detailList =
                    paymentAdvanceRefundTransferApplyDetailLogic.findRefundTransferApplyDetailDateKey(
                            1, Arrays.asList(uniqueKey), null);

            BigDecimal budOutMoney = nvl(po.getBudOutMoney());
            BigDecimal reversalMoney = nvl(po.getReversalMoney());

            BigDecimal sumRefundMoney = Optional.ofNullable(detailList)
                    .orElseGet(ArrayList::new)
                    .stream()
                    .map(PaymentAdvanceRefundTransferApplyAndDetailListDTO::getTheRegistTaxAmount)
                    .filter(Objects::nonNull)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);

            BigDecimal advanceMoney = BigDecimal.ZERO;
            if (CollectionUtils.isNotEmpty(finalAddAdvances)) {
                advanceMoney = finalAddAdvances.stream()
                        .filter(item -> Objects.nonNull(item.getApplyNo()) && Objects.nonNull(item.getApplyItemNo()))
                        .filter(item -> uniqueKey.equals(item.getApplyNo() + "_" + item.getApplyItemNo()))
                        .map(InvoicedApplyPa::getStrikePrice)
                        .filter(Objects::nonNull)
                        .reduce(BigDecimal.ZERO, BigDecimal::add);
            }

            // 你的原公式保持不变
            BigDecimal line = budOutMoney
                    .subtract(reversalMoney)
                    .subtract(nvl(sumRefundMoney))
                    .subtract(nvl(advanceMoney));

            deductibleAmount = deductibleAmount.add(line);

            // ★ 唯一区别：根据 sign 决定判错方向
            if (isNeedThrowBySign(deductibleAmount, sign)) {
                throw new DaoException("预付款申请单:" + applyNo + ",预付款申请行" + applyItemNo + "存在未冲账金额请确认！");
            }
        }
    }

    /**
     * 检验二：预付款变更单明细（转单）—— 只差最后“方向判错”
     */
    private void checkTransferApplyDetailsDeductible(int sign,
                                                     List<PaymentAdvanceRefundTransferApplyAndDetailListDTO> refundTransferApplyDatas,
                                                     List<InvoicedApplyPa> finalAddAdvances) {
        BigDecimal deductibleAmount = BigDecimal.ZERO;

        for (PaymentAdvanceRefundTransferApplyAndDetailListDTO transfer : refundTransferApplyDatas) {
            String paymentChangeNumber = transfer.getPaymentChangeNumber();
            String itemNo = transfer.getItemNo();
            String uniqueKey = paymentChangeNumber + "_" + itemNo;

            BigDecimal theRegistTaxAmount = nvl(transfer.getTheRegistTaxAmount());
            BigDecimal alreadyApplyAmount = nvl(transfer.getAlreadyApplyAmount());

            BigDecimal advanceMoney = BigDecimal.ZERO;
            if (CollectionUtils.isNotEmpty(finalAddAdvances)) {
                // 你原逻辑是取 list 的第一个，这里保持一致
                advanceMoney = finalAddAdvances.stream()
                        .filter(item -> uniqueKey.equals(item.getPaymentChangeNumber() + "_" + item.getPaymentChangeItemNo()))
                        .map(InvoicedApplyPa::getStrikePrice)
                        .filter(Objects::nonNull)
                        .findFirst()
                        .orElse(BigDecimal.ZERO);
            }

            BigDecimal line = theRegistTaxAmount
                    .subtract(alreadyApplyAmount)
                    .subtract(nvl(advanceMoney));

            deductibleAmount = deductibleAmount.add(line);

            if (isNeedThrowBySign(deductibleAmount, sign)) {
                throw new DaoException("预付款变更单号:" + paymentChangeNumber + ",预付款变更行号" + itemNo + ",存在未冲账金额，请确认！");
            }
        }
    }

    /** sign=1 => >0 报错；sign=-1 => <0 报错 */
    private boolean isNeedThrowBySign(BigDecimal deductibleAmount, int sign) {
        if (deductibleAmount == null) return false;
        if (sign > 0) {
            return deductibleAmount.compareTo(BigDecimal.ZERO) > 0;
        } else if (sign < 0) {
            return deductibleAmount.compareTo(BigDecimal.ZERO) < 0;
        }
        return false;
    }

    private BigDecimal nvl(BigDecimal v) {
        return v == null ? BigDecimal.ZERO : v;
    }


    public List<StatementItemDTO> mergeAndProcess(List<StatementItemDTO> rows) {
        // 1. 按 poCode + "_" + poItemNo 分组
        Map<String, List<StatementItemDTO>> groupedByKey = rows.stream()
                .collect(Collectors.groupingBy(
                        item -> item.getPoCode() + "_" + item.getPoItemNo()
                ));

        // 2. 处理每组数据
        return groupedByKey.values().stream()
                .map(group -> {
                    // 2.1 计算总 taxAmount（如果 deductionRatio 条件不满足时使用）
                    BigDecimal totalTaxAmount = group.stream()
                            .map(StatementItemDTO::getTaxAmount)
                            .reduce(BigDecimal.ZERO, BigDecimal::add);

                    // 2.2 取第一条记录作为基础（假设所有记录的 deductionRatio 和 orderTaxPrice 等字段相同）
                    StatementItemDTO representative = group.get(0);

                    // 2.3 创建新对象（避免修改原始数据）
                    StatementItemDTO result = new StatementItemDTO();
                    result.setPoCode(representative.getPoCode());
                    result.setPoItemNo(representative.getPoItemNo());
                    result.setTaxAmount(totalTaxAmount); // 保留总 taxAmount 供可能的其他用途

                    // 2.4 根据 deductionRatio 条件设置 summaryReconciliationAmount
                    if (representative.getDeductionRatio() != null
                            && representative.getDeductionRatio().compareTo(BigDecimal.ZERO.stripTrailingZeros()) > 0) {
                        // 计算 orderTaxPrice * receiveNum 的总和
                        BigDecimal totalOrderTaxPrice = group.stream()
                                .map(item -> item.getOrderTaxPrice().multiply(item.getReceiveNum()))
                                .reduce(BigDecimal.ZERO, BigDecimal::add);

                        result.setSummaryReconciliationAmount(totalOrderTaxPrice);
                    } else {
                        // 直接使用累加后的 taxAmount
                        result.setSummaryReconciliationAmount(totalTaxAmount);
                    }

                    return result;
                })
                .collect(Collectors.toList());
    }

    @Override
    public void updatePaymentAdvanceDetailDateType(String appNo, String itemNo,Integer dataType) {
        final LambdaUpdateWrapper<PaymentAdvanceApplyDetail> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(PaymentAdvanceApplyDetail::getDataType,dataType)
                        .eq(PaymentAdvanceApplyDetail::getAppNo,appNo)
                                .eq(PaymentAdvanceApplyDetail::getItemNo,itemNo);
        paymentAdvanceApplyDetailService.update(updateWrapper);
    }

    @Override
    public void updateReversedAmount(String paymentChangeNumber, String paymentChangeItemNo, BigDecimal strikePrice) {
        paymentAdvanceApplyDetailService.updateReversedAmount(paymentChangeNumber,paymentChangeItemNo,strikePrice);
    }



    private void findPoAdvanceApplySituation(List<CreatePaaDetailDto> params, List<Long> existedItemIdList, Long applyId, Integer optType) {
        List<String> poKeyList = Lists.newArrayList();
        for (CreatePaaDetailDto dto : params) {
            poKeyList.add(dto.getPoKey());

            if (dto.getAlreadyAccountAmount()==null){
//            if (optType!=null&&optType!=2){
                // 获取采购订单行在物料凭证中使用的情况
                List<ReceiveVoucherDTO> receiveVoucherDTO = receiptVoucherLogic.findByPoAndAsNoNotNull(dto.getPoCode(),dto.getPoItemNo(),dto.getFactoryCode());
                BigDecimal alreadyAccountAmount = BigDecimal.ZERO;
                if (CollectionUtils.isNotEmpty(receiveVoucherDTO)) {
                    for (ReceiveVoucherDTO s : receiveVoucherDTO){
                        if (s.getDeductionRatio()==null){
                            s.setDeductionRatio(BigDecimal.ZERO);
                        }
                        if (s.getDeductionRatio().compareTo(BigDecimal.ZERO)!=0){
                            s.setOriginalTaxAmount(s.getTaxAmount());
                        }else{
                            s.setOriginalTaxAmount(s.getOriginalTaxPrice().multiply(s.getMvNum()));
                        }
                        if (s.getVoucherFlag().equals("H")){
                            if (s.getOriginalTaxAmount().compareTo(BigDecimal.ZERO) > 0) { // 只有正数才取负
                                s.setOriginalTaxAmount(s.getOriginalTaxAmount().negate());
                                s.setMvNum(s.getMvNum().negate());
                            }
                        }
                        alreadyAccountAmount = alreadyAccountAmount.add(s.getOriginalTaxAmount());
                    }
                }
                dto.setAlreadyAccountAmount(alreadyAccountAmount);
//            }
            }
            if (dto.getStoreAmount()==null){
//            if (optType!=null&&optType!=2){
                //根据订单号和行取物料凭证取物料凭证对应的原含税金额
                BigDecimal storeAmount = BigDecimal.ZERO;
                List<ReceiveVoucherDTO> receiveVoucherDTO1 = receiptVoucherLogic.findByPoAndItemNo(dto.getPoCode(),dto.getPoItemNo(),dto.getFactoryCode());
                if (CollectionUtils.isNotEmpty(receiveVoucherDTO1)) {
                    for (ReceiveVoucherDTO s : receiveVoucherDTO1){
                        if (s.getDeductionRatio()==null){
                            s.setDeductionRatio(BigDecimal.ZERO);
                        }
                        if (s.getDeductionRatio().compareTo(BigDecimal.ZERO)!=0){
                            s.setOriginalTaxAmount(s.getTaxAmount());
                        }else{
                            s.setOriginalTaxAmount(s.getOriginalTaxPrice().multiply(s.getMvNum()));
                        }
                        if (s.getVoucherFlag().equals("H")){
                            if (s.getOriginalTaxAmount().compareTo(BigDecimal.ZERO) > 0) { // 只有正数才取负
                                s.setOriginalTaxAmount(s.getOriginalTaxAmount().negate());
                                s.setMvNum(s.getMvNum().negate());
                            }
                        }
                        storeAmount = storeAmount.add(s.getOriginalTaxAmount());
                    }
                }
                dto.setStoreAmount(storeAmount);
//            }
            }

        }

        // 新增时检查采购订单行在SRM中使用的情况
        if (0L == applyId) {
            // 获取SRM中预付款申请单明细及金额
            final List<PaymentAdvanceApplyDetailPO> paaDetailList = paymentAdvanceApplyDetailService.createGetPoSituationByPoKey(poKeyList);
            for (PaymentAdvanceApplyDetailPO detail : paaDetailList) {
                for (CreatePaaDetailDto dto : params) {
                    if (dto.getPoKey().equals(detail.getDataKey())) {
                        dto.setAlreadyApplyAmount(dto.getAlreadyApplyAmount().add(detail.getBudInnerMoney()).add(detail.getBudOutMoney()));
//                        dto.setApplyAmount(dto.getItAmount().subtract(dto.getAlreadyApplyAmount()));
                        dto.setApplyAmount(dto.getItAmount().subtract(dto.getAlreadyApplyAmount())
                                .subtract(dto.getAlreadyAccountAmount()==null?BigDecimal.ZERO:dto.getAlreadyAccountAmount())
                                .add(dto.getPoReversalMoney()==null?BigDecimal.ZERO:dto.getPoReversalMoney())
                                .add(dto.getAlreadyOutAmount()==null?BigDecimal.ZERO:dto.getAlreadyOutAmount())
                                .subtract(dto.getAlreadyIntoAmount()==null?BigDecimal.ZERO:dto.getAlreadyIntoAmount())
                        );
                        dto.setBudInnerMoney(dto.getBudInnerMoney());
                        dto.setBudOutMoney(dto.getBudOutMoney());
                        //已付款金额
                        if (detail.getStatus() == 5) {
                            dto.setAlreadyAdvanceAmount(dto.getAlreadyAdvanceAmount().add(detail.getBudInnerMoney()).add(detail.getBudOutMoney()));
                        }

                    }
                }
            }
            //已经票到的金额
            List<PaymentAdvanceApplyDetailPO> codDetailList = paymentAdvanceApplyDetailService.findCodApplyByPoKey(poKeyList);
            if (CollectionUtils.isNotEmpty(codDetailList)) {
                for (PaymentAdvanceApplyDetailPO detail : codDetailList) {
                    for (CreatePaaDetailDto dto : params) {
                        if (dto.getPoKey().equals(detail.getDataKey())) {
                            dto.setAlreadyApplyAmount(dto.getAlreadyApplyAmount().add(detail.getBudInnerMoney()).add(detail.getBudOutMoney()));
//                            dto.setApplyAmount(dto.getItAmount().subtract(dto.getAlreadyApplyAmount()));
                            dto.setApplyAmount(dto.getItAmount().subtract(dto.getAlreadyApplyAmount())
                                    .subtract(dto.getAlreadyAccountAmount()==null?BigDecimal.ZERO:dto.getAlreadyAccountAmount())
                                    .add(dto.getPoReversalMoney()==null?BigDecimal.ZERO:dto.getPoReversalMoney())
                                    .add(dto.getAlreadyOutAmount()==null?BigDecimal.ZERO:dto.getAlreadyOutAmount())
                                    .subtract(dto.getAlreadyIntoAmount()==null?BigDecimal.ZERO:dto.getAlreadyIntoAmount())
                            );
                            dto.setBudInnerMoney(dto.getBudInnerMoney());
                            dto.setBudOutMoney(dto.getBudOutMoney());
                            //已付款金额
                            if (detail.getStatus() == 5) {
                                dto.setAlreadyAdvanceAmount(dto.getAlreadyAdvanceAmount().add(detail.getBudInnerMoney()).add(detail.getBudOutMoney()));
                            }

                        }
                    }
                }
            }

            // 临时存放所有的预付款申请明细
            List<CreatePaaDetailDto> tempList = Lists.newArrayList();
            tempList.addAll(params);

            for (CreatePaaDetailDto dto : tempList) {
                // 本次可申请金额小于0的明细行需要删除
                if (dto.getApplyAmount().compareTo(BigDecimal.ZERO) <= 0) {
                    params.remove(dto);
                }
            }
        }

        // 编辑是检查采购订单行在SRM中使用的情况
        // 1.考虑编辑不需要查本事
        // 2.临时删除的明细ID需要排除
        if (applyId > 0) {
            final List<PaymentAdvanceApplyDetailPO> paaDetailList = paymentAdvanceApplyDetailService.editGetPoSituationByApplyId(existedItemIdList, poKeyList);
            for (CreatePaaDetailDto dto : params) {

                for (PaymentAdvanceApplyDetailPO detail : paaDetailList) {
                    if (dto.getPoKey().equals(detail.getDataKey())) {
                        //已申请金额
                        dto.setAlreadyApplyAmount(dto.getAlreadyApplyAmount().add(detail.getBudInnerMoney()).add(detail.getBudOutMoney()));
                        //已付款金额
                        if (detail.getStatus() == 5) {
                            dto.setAlreadyAdvanceAmount(dto.getAlreadyAdvanceAmount().add(detail.getBudInnerMoney()).add(detail.getBudOutMoney()));
                        }
                    }
                }
                //可申请金额
//                dto.setApplyAmount(dto.getItAmount().subtract(dto.getAlreadyApplyAmount()));
                System.out.println("dto.getItAmount():"+dto.getItAmount());
                System.out.println("dto.getAlreadyApplyAmount():"+dto.getAlreadyApplyAmount());
                System.out.println("dto.getAlreadyAccountAmount():"+dto.getAlreadyAccountAmount());
                System.out.println("dto.getPoReversalMoney():"+dto.getPoReversalMoney());
                System.out.println("dto.getAlreadyOutAmount():"+dto.getAlreadyOutAmount());
                System.out.println("dto.getAlreadyIntoAmount():"+dto.getAlreadyIntoAmount());

                dto.setApplyAmount(dto.getItAmount().subtract(dto.getAlreadyApplyAmount())
                        .subtract(dto.getAlreadyAccountAmount()==null?BigDecimal.ZERO:dto.getAlreadyAccountAmount())
                        .add(dto.getPoReversalMoney()==null?BigDecimal.ZERO:dto.getPoReversalMoney())
                        .add(dto.getAlreadyOutAmount()==null?BigDecimal.ZERO:dto.getAlreadyOutAmount())
                        .subtract(dto.getAlreadyIntoAmount()==null?BigDecimal.ZERO:dto.getAlreadyIntoAmount())
                );
                System.out.println("dto.getApplyAmount:"+dto.getApplyAmount());
            }
            //已经票到的金额
            List<PaymentAdvanceApplyDetailPO> codDetailList = paymentAdvanceApplyDetailService.findCodApplyByPoKey(poKeyList);
            if (CollectionUtils.isNotEmpty(codDetailList)) {
                for (PaymentAdvanceApplyDetailPO detail : codDetailList) {
                    for (CreatePaaDetailDto dto : params) {
                        if (dto.getPoKey().equals(detail.getDataKey())) {
                            dto.setAlreadyApplyAmount(dto.getAlreadyApplyAmount().add(detail.getBudInnerMoney()).add(detail.getBudOutMoney()));
                            dto.setApplyAmount(dto.getItAmount().subtract(dto.getAlreadyApplyAmount()));
                            //已付款金额
                            if (detail.getStatus() == 5) {
                                dto.setAlreadyAdvanceAmount(dto.getAlreadyAdvanceAmount().add(detail.getBudInnerMoney()).add(detail.getBudOutMoney()));
                            }

                        }
                    }
                }
            }
        }
    }

//    public static void main(String[] args) {
//        List<CreatePaaDetailPO> result = Lists.newArrayList();
//        CreatePaaDetailPO createPaaDetailPO = new CreatePaaDetailPO();
//        createPaaDetailPO.setPoCode("4000085854");
//        createPaaDetailPO.setPoItemNo("10");
//        result.add(createPaaDetailPO);
//
//       createPaaDetailPO = new CreatePaaDetailPO();
//        createPaaDetailPO.setPoCode("4000085854");
//        createPaaDetailPO.setPoItemNo("20");
//        result.add(createPaaDetailPO);
//
//        createPaaDetailPO = new CreatePaaDetailPO();
//        createPaaDetailPO.setPoCode("4000085854");
//        createPaaDetailPO.setPoItemNo("60");
//        result.add(createPaaDetailPO);
//
//        createPaaDetailPO = new CreatePaaDetailPO();
//        createPaaDetailPO.setPoCode("4000085854");
//        createPaaDetailPO.setPoItemNo("80");
//        result.add(createPaaDetailPO);
//
////        final PurchaseOrderDetailResposeDTO.Item1 itemData = new PurchaseOrderDetailResposeDTO.Item1();
////
////        itemData.item = Lists.newArrayList();
////        PurchaseOrderDetailResposeDTO.Item2 item2 = new PurchaseOrderDetailResposeDTO.Item2();
////
////        item2.item.add()
////
////        PurchaseOrderDetailResposeDTO.Item1 item = new PurchaseOrderDetailResposeDTO.Item1();
//
//
//        PurchaseOrderDetailResposeDTO purchaseOrderDetailResposeDTO = new PurchaseOrderDetailResposeDTO();
//        //根据订单号和行号，查询订单明细的付款过期日， 邓京术 2024-11-04
//        PurchaseOrderDetailResposeDTO.Item1 itItem = new PurchaseOrderDetailResposeDTO.Item1();
//        itItem.item = Lists.newArrayList();
//        result.stream().forEach(obj -> {
//            PurchaseOrderDetailResposeDTO.Item item = new PurchaseOrderDetailResposeDTO.Item();
//            if (obj.getPoItemNo().equals("60") || obj.getPoItemNo().equals("80")) {
//            item.EBELN = obj.getPoCode();
//            item.EBELP = "0000" + obj.getPoItemNo();
//            item.ZFBDT = "2024-12-07";
//            itItem.item.add(item);
//            }
//        });
//
//
//        createPaaDetailPO = new CreatePaaDetailPO();
//        createPaaDetailPO.setPoCode("4000085854");
//        createPaaDetailPO.setPoItemNo("80");
//        result.add(createPaaDetailPO);
//
////        4000085854_10, 4000085854_20, 4000085854_30, 4000085854_40, 4000085854_50, 4000085854_60, 4000085854_70, 4000085854_80, 4000085854_90
//        purchaseOrderDetailResposeDTO.setIT_DATA(itItem);
////        PurchaseOrderDetailSapDTO purchaseOrderDetailSapDTO = new PurchaseOrderDetailSapDTO();
////        purchaseOrderDetailSapDTO.setIT_ITEM(itItem);
//
//
////        {"EBELN":"4000085854","EBELP":"00060","ZFBDT":"2024-12-07"},
////        {"EBELN":"4000085854","EBELP":"00080","ZFBDT":"2024-09-23"}
////
////        ]},"IT_ITEM":{"item":[
////
////                {"EBELN":"4000085854","EBELP":"00010"},
////        {"EBELN":"4000085854","EBELP":"00020"},
////        {"EBELN":"4000085854","EBELP":"00060"},
////        {"EBELN":"4000085854","EBELP":"00080"}]
//
//
//        final PurchaseOrderDetailResposeDTO.Item1 itemData = purchaseOrderDetailResposeDTO.getIT_DATA();
//        final List<PurchaseOrderDetailResposeDTO.Item> itemList  = Objects.nonNull(itemData) ? itemData.item: Lists.newArrayList();
//
//        result.stream().forEach(obj -> {
//            Iterator it = itemList.iterator();
//            System.out.println("=============11111111111==============");
//            while (it.hasNext()) {
//                System.out.println("===========1122222222222222222222222================");
//                PurchaseOrderDetailResposeDTO.Item item = (PurchaseOrderDetailResposeDTO.Item) it.next();
//                if (item.EBELN.equals(obj.getPoCode()) && Integer.parseInt(item.EBELP) == (Integer.parseInt(obj.getPoItemNo()))) {
//                    System.out.println("===========33333333333333333================");
////                        System.out.println("采购订单付款到期日 ==" +  obj.getPoCode() + "/" +obj.getPoItemNo() + "/" + item.ZFBDT);
//                    if (StringUtils.isNotEmpty(item.ZFBDT)) {
//                        obj.setPaymentExpireDate1(item.ZFBDT);
//                    }
//                    //减少循环次数，提高代码执行率
//                    it.remove();
//                    break;
//                }
//            }
//        });
//    }
}
