package com.jwipc.finance.logic.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jwipc.api.constant.RestCode;
import com.jwipc.api.dto.ApiResult;
import com.jwipc.api.dto.ErpApiResult;
import com.jwipc.api.dto.ErpApiResult1;
import com.jwipc.api.dto.OaFileParamDTO;
import com.jwipc.constant.DictCode;
import com.jwipc.exception.DaoException;
import com.jwipc.finance.constant.PaymentOaClient;
import com.jwipc.finance.convert.PaymentCodApplyConvert;
import com.jwipc.finance.dto.*;
import com.jwipc.finance.entity.*;
import com.jwipc.finance.logic.*;
import com.jwipc.finance.model.po.AccountStatementPO;
import com.jwipc.finance.model.po.CreatePcaDetailPO;
import com.jwipc.finance.model.po.PaymentCodApplyPO;
import com.jwipc.finance.model.query.*;
import com.jwipc.finance.service.*;
import com.jwipc.page.PageUtil;
import com.jwipc.page.PageView;
import com.jwipc.prop.PriceHandle;
import com.jwipc.security.LoginUtil;
import com.jwipc.supplier.clent.dto.SupplierBankDTO;
import com.jwipc.supplier.clent.dto.SupplierContactsDTO;
import com.jwipc.supplier.client.SupplierClient;
import com.jwipc.sys.client.*;
import com.jwipc.sys.client.dto.*;
import com.jwipc.sys.dto.BusinessAttachmentDTO;
import com.jwipc.sys.dto.KingdeeInvoiceCloudImageDTO;
import com.jwipc.sys.entity.Attachment;
import com.jwipc.sys.logic.KingdeeImageLogic;
import com.jwipc.sys.service.IAttachmentService;
import com.jwipc.sys.util.FinancialShareUtil;
import com.jwipc.util.DateUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.jwipc.util.DateUtils.formatYYYYMMDDDash;

/**
 * @author shenyang.ou
 * @date 2024/3/15 13:12
 * @desc
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class PaymentCodApplyLogicImpl implements PaymentCodApplyLogic {
    private final IPaymentCodApplyService paymentCodApplyService;
    private final SequenceClient sequenceClient;
    private final UserClient userClient;
    private final CompanyClient companyClient;
    private final PaymentOaClient paymentOaClient;
    private final AttachmentManualCheckLogic attachmentManualCheckLogic;
    private final DictClient dictClient;
    private final EmailSendClient emailSendClient;
    private final PurchaseGroupClient purchaseGroupClient;
    private final FileClient fileClient;
    private final IPaymentCodApplyDetailService paymentCodApplyDetailService;
    private final IInvoicedApplyService invoicedApplyService;
    private final IAccountStatementService accountStatementService;
    private final IInvoicedApplyPostResultService invoicedApplyPostResultService;
    private final IPaymentAdvanceApplyDetailService paymentAdvanceApplyDetailService;
    private final IInvoicedApplyDetailService invoicedApplyDetailService;
    private final ICostInvoicedApplyDetailService costInvoicedApplyDetailService;
    private final ICompanyInvoicedApplyService companyInvoicedApplyService;
    private final InvoicedApplyLogic invoicedApplyLogic;
    private final PaymentAdvanceApplyLogic paymentAdvanceApplyLogic;
    private final PaymentCodApplyConvert paymentCodApplyConvert;
    private final PriceHandle priceHandle;
    private final SupplierClient supplierClient;
    private final IPaymentPlanSummaryService paymentPlanSummaryService;
    private final IPaymentPlanService paymentPlanService;
    private final PaymentPlanLogic paymentPlanLogic;
    private final TaxClient taxClient;
    private final KingdeeImageLogic kingdeeImageLogic;
    private final IAttachmentService attachmentService;
    private final static String PaymentCodLock = "PaymentCodLock_";
    private final StringRedisTemplate redisTemplate;
    private final FinancialShareUtil financialShareUtil;
    private final IFinPaymentConfirmLogService finPaymentConfirmLogService;
    private final IPaymentAdvanceApplyService paymentAdvanceApplyService;

    @Override
    public PageView selectDataByQuery(PaymentApplyHeadQuery query) {
        final Page<PaymentCodApply> dbPage = PageUtil.toPage(query);
        List<PaymentCodApplyPO> poList = paymentCodApplyService.selectListByPage(dbPage, query);

        List<PaymentCodApplyDTO> dtoList = paymentCodApplyConvert.POToDTOList(poList);
        return PageUtil.getPV(dtoList, dbPage.getTotal());
    }

    @Override
    public PaymentCodApplyDTO getById(Long id) {
        PaymentCodApply paymentCodApply = paymentCodApplyService.getById(id);
        return paymentCodApplyConvert.entity2DTO(paymentCodApply);
    }

    /**
     * 获取货到付款相关信息
     *
     * @param query 查询条件
     * @return
     */
    @Override
    public List<CreatePcaDetailDto> readCodPaymentInvoiceData(PaymentApplyItemQuery query) {
        //已过账没有付款或没有付款完全的数据
        List<CreatePcaDetailPO> paymentData = invoicedApplyLogic.readCodPaymentInvoiceData(query);
        //已经预付数据
        List<CreatePcaDetailPO> applyData = paymentAdvanceApplyLogic.findByQuery(query);
        if (CollectionUtils.isNotEmpty(paymentData)) {
            //根据已获取的过账数据筛选已经货到付款的数据
            List<CreatePcaDetailPO> alreadyData = paymentCodApplyDetailService.findByApplyCodeAndItem(paymentData, null);
            //处理数据开票数据
            for (CreatePcaDetailPO detailDto : paymentData) {
                for (CreatePcaDetailPO dto : alreadyData) {
                    if (detailDto.getDataKey().equals(dto.getDataKey())) {
                        //已申请金额
                        detailDto.setAlreadyApplyAmount(detailDto.getAlreadyApplyAmount().add(dto.getBudInnerMoney()).add(dto.getBudOutMoney()));
                        //已付款金额
                        if (dto.getStatus() == 5) {
                            detailDto.setAlreadyPaymentAmount(detailDto.getAlreadyPaymentAmount().add(dto.getBudInnerMoney()).add(dto.getBudOutMoney()));
                        }
                        break;
                    }
                }
                detailDto.setApplyAmount(detailDto.getItAmount().subtract(detailDto.getAlreadyApplyAmount() == null ? BigDecimal.ZERO : detailDto.getAlreadyApplyAmount()));
            }
        }

        List<CreatePcaDetailPO> paymentAdvanceApplyList = Lists.newArrayList();

        if (CollectionUtils.isNotEmpty(applyData)) {
            //货到付款中已经消费的预付数据
            List<CreatePcaDetailPO> alreadyApply = paymentCodApplyDetailService.findByAlreadyData(applyData);
            //处理预付数据
            aa:
            for (CreatePcaDetailPO detailDto : applyData) {

                for (CreatePcaDetailPO dto : alreadyApply) {
                    if (detailDto.getDataKey().equals(dto.getDataKey()) && detailDto.getDetailId().equals(dto.getDetailId())) {
                        //可申请金额
                        detailDto.setApplyAmount(detailDto.getApplyAmount().subtract(dto.getBudInnerMoney().add(dto.getBudOutMoney())));
                        //预算内申请金额
                        detailDto.setBudInnerMoney(detailDto.getBudInnerMoney().subtract(dto.getBudInnerMoney()));
                        //预算外申请金额
                        detailDto.setBudOutMoney(detailDto.getBudOutMoney().subtract(dto.getBudOutMoney()));
                        //剩余可消费金额大于等于0表示消费完全，不用记录
                        if (detailDto.getApplyAmount().compareTo(BigDecimal.ZERO) < 0) {
                            paymentAdvanceApplyList.add(detailDto);
                        }
                        continue aa;
                    }
                }
                paymentAdvanceApplyList.add(detailDto);
            }
        }

        //预付款订单+行号分组集合
        Map<String, List<CreatePcaDetailPO>> listMap2 = paymentAdvanceApplyList.stream().collect(Collectors.groupingBy(e -> e.getPoCode() + "_" + e.getPoItemNo()));

        //根据订单号匹配预付款数据
        aa:
        for (CreatePcaDetailPO paymentDatum : paymentData) {
            String poCode = paymentDatum.getPoCode();
            String poItemNo = paymentDatum.getPoItemNo();
            for (String s : listMap2.keySet()) {
                //根据订单号+行号匹配相应的预付款
                if (s.equals(poCode + "_" + poItemNo)) {
                    paymentDatum.setCreatePcaDetailDtos(listMap2.get(s));
                    continue aa;
                }
            }
        }

        return paymentCodApplyConvert.createPcaDetailPO2DTOList(paymentData);
    }

    @Override
    @Transactional
    public void saveOrUpdate(PaymentCodApplySaveDTO data) {
        if (ObjectUtil.isNull(data)) {
            throw new DaoException("参数异常, 请重新操作");
        }
        //货到明细数据
        List<PaymentCodApplyDetail> pcaDetailList = Lists.newArrayList();
//        for (PaymentCodApplySaveDTO.ApplyDetail ad : data.getItemList()) {
//            pcaDetailList.add(ad.toPcaDetail());
//        }
        //查询对账付款申请数据

        PaymentCodApply byId = paymentCodApplyService.getById(data.getId());
        PaymentCodApply headData = data.toPca();
        //新增
        if (data.getId() == null) {
            String orderCode = sequenceClient.getCodeSequenceNo("payment_cod_apply", 6);
            data.setCpApplyNo(orderCode);
            headData.setCpApplyNo(orderCode);
            headData.setCreateTime(LocalDateTime.now());
            headData.setCreateUserId(LoginUtil.getUserId());
            headData.setCreateUserCode(LoginUtil.getAccount());
            headData.setCreateUserName(LoginUtil.getName());
            //计算预算外超额
            if (headData.getOaBudOutMoney() != null && headData.getBudOutMoney() != null) {
                headData.setOaOutExcess(headData.getOaBudOutMoney().add(headData.getBudOutMoney()));
                //计算预算外超出比
                if (headData.getOaQuaeterBud() != null && headData.getOaQuaeterBud().compareTo(BigDecimal.ZERO) > 0) {
                    headData.setOaExcessScale(headData.getOaOutExcess().divide(headData.getOaQuaeterBud(), priceHandle.getPrecision(), priceHandle.getCutType() == 0 ? RoundingMode.HALF_UP : RoundingMode.HALF_DOWN));
                }
            }
            // 1.付款申请累计请款金额等于0时，允许保存请款单,2.保存时，请款单状态自动更新为“付款完成”
            if (headData.getActualityPayMoney() == null || (headData.getActualityPayMoney() != null && headData.getActualityPayMoney().compareTo(new BigDecimal(BigInteger.ZERO)) == 0)) {
                headData.setOaAleradyPayMoney(headData.getOaBorrowMoney());
                headData.setStatus(5);
            }
            // 退货采购订单场景，请款单状态自动更新为“付款完成”
            if (StringUtils.equals(headData.getSupplierReturn(), "1")) {
                headData.setStatus(5);
            }
            paymentCodApplyService.save(headData);
            // 设置确认日志
            if (CollectionUtils.isNotEmpty(data.getLogDetailList())) {
                setConfirmLog(data.getLogDetailList(), headData.getId(), headData.getCpApplyNo());
            }

            //开票申请明细
            List<InvoicedApplyDetail> invoicedApplyDetails = Lists.newArrayList();
            //预付款明细
            List<PaymentAdvanceApplyDetail> advanceApplyDetails = Lists.newArrayList();
            for (PaymentCodApplySaveDTO.ApplyDetail ad : data.getItemList()) {
                PaymentCodApplyDetail codApplyDetail = ad.toPcaDetail();
                codApplyDetail.setCppId(headData.getId());
                codApplyDetail.setCppNo(headData.getCpApplyNo());
                pcaDetailList.add(codApplyDetail);
                //判断是否已经全部被消费
                if (ad.getIsUsed() == 1) {
                    //预付款
                    if ("Z001".equals(ad.getAmountType())) {
                        PaymentAdvanceApplyDetail paymentAdvanceApplyDetail = new PaymentAdvanceApplyDetail();
                        paymentAdvanceApplyDetail.setId(ad.getSourceId());
                        paymentAdvanceApplyDetail.setCodFlag(1);
                        advanceApplyDetails.add(paymentAdvanceApplyDetail);
                    } else {
                        InvoicedApplyDetail applyDetail = new InvoicedApplyDetail();
                        applyDetail.setId(ad.getSourceId());
                        applyDetail.setCodFlag(1);
                        invoicedApplyDetails.add(applyDetail);
                    }
                }
                //付款申请新增时，需要更新付款计划汇总数据 邓京术 2025-07-31
//                initPaymentPlan(codApplyDetail, null, headData, 1);
            }

            if (CollectionUtils.isNotEmpty(pcaDetailList)) {
                paymentCodApplyDetailService.saveBatch(pcaDetailList);
            }

            // 更新明细行号
            paymentCodApplyDetailService.updateDetailItemNo(headData.getId());
            //更新预付款
            if (CollectionUtils.isNotEmpty(advanceApplyDetails)) {
                paymentAdvanceApplyDetailService.updateBatchById(advanceApplyDetails);
            }
//            //开票申请状态
//            if (CollectionUtils.isNotEmpty(invoicedApplyDetails)) {
//                invoicedApplyDetailService.updateBatchById(invoicedApplyDetails);
//            }
            String backStr = initPaymentPlanSummary(headData, true);
            if (StringUtils.isNotEmpty(backStr) && backStr.equals("F")) {
//                暂时去掉付款计划的约束，方便测试，上生产时，需要恢复，邓京术 2025-09-25
                throw new DaoException("本月付款计划没有发布，请先发布付款计划！");
            }
        } else {

            // 1.付款申请累计请款金额等于0时，允许保存请款单,2.保存时，请款单状态自动更新为“付款完成”
            if (headData.getActualityPayMoney() == null || (headData.getActualityPayMoney() != null && headData.getActualityPayMoney().compareTo(new BigDecimal(BigInteger.ZERO)) == 0)) {
                headData.setOaAleradyPayMoney(headData.getOaBorrowMoney());
                headData.setStatus(5);
            }
            headData.setUpdateTime(LocalDateTime.now());
            headData.setUpdateUserId(LoginUtil.getUserId());
            headData.setUpdateUserCode(LoginUtil.getAccount());
            headData.setUpdateUserName(LoginUtil.getName());
            paymentCodApplyService.updateById(headData);
            // 设置确认日志
            PaymentCodApply entity = paymentCodApplyService.getById(headData.getId());
            if (CollectionUtils.isNotEmpty(data.getLogDetailList())) {
                setConfirmLog(data.getLogDetailList(), headData.getId(), entity.getCpApplyNo());
            }
            //开票申请明细
            List<InvoicedApplyDetail> invoicedApplyDetails = Lists.newArrayList();
            //预付款明细
            List<PaymentAdvanceApplyDetail> advanceApplyDetails = Lists.newArrayList();

            if (CollectionUtils.isNotEmpty(data.getItemList())) {
                for (PaymentCodApplySaveDTO.ApplyDetail paymentCodApplyDetail : data.getItemList()) {
                    PaymentCodApplyDetail detail = paymentCodApplyDetail.toPcaDetail();
                    detail.setCppNo(StringUtils.isEmpty(paymentCodApplyDetail.getCppNo()) ? byId.getCpApplyNo() : paymentCodApplyDetail.getCppNo());
                    detail.setCppId(Objects.isNull(paymentCodApplyDetail.getCppId()) ? byId.getId() : paymentCodApplyDetail.getCppId());
                    pcaDetailList.add(detail);
                    //货到付款
                    if ("Z003".equals(paymentCodApplyDetail.getAmountType())) {
                        InvoicedApplyDetail invoicedApplyDetail = new InvoicedApplyDetail();
                        invoicedApplyDetail.setId(paymentCodApplyDetail.getSourceId());
                        if (paymentCodApplyDetail.getIsUsed() == 1) {
                            invoicedApplyDetail.setCodFlag(1);
                        } else {
                            invoicedApplyDetail.setCodFlag(0);
                        }
                        invoicedApplyDetails.add(invoicedApplyDetail);
                    }

                    //请款明细有金额有更新时，需要更新付款计划汇总，减少付款计划汇总的本月已请款金额， fin_payment_plan_summary applied_payment_amount 2025-07-30 邓京术
//                    PaymentCodApplyDetail detailDel = paymentCodApplyDetailService.getById(detail.getId());
//                    initPaymentPlan(detail, detailDel, headData,1);

                }
                paymentCodApplyDetailService.saveOrUpdateBatch(pcaDetailList);
            }
            //删除的行根据类型释放 预付款和开票申请
            if (CollectionUtils.isNotEmpty(data.getDelItemIdList())) {
                List<PaymentCodApplyDetail> detailList = Lists.newArrayList();
                for (PaymentCodApplySaveDTO.DelDetail delDetail : data.getDelItemIdList()) {
                    PaymentCodApplyDetail ad = new PaymentCodApplyDetail();
                    ad.setId(delDetail.getId());
                    ad.setDeleteFlag(1);
                    detailList.add(ad);
                    //可能传空过来
                    if (delDetail.getId() == null) continue;

                    if ("Z003".equals(delDetail.getAmountType())) {
                        InvoicedApplyDetail invoicedApplyDetail = new InvoicedApplyDetail();
                        invoicedApplyDetail.setId(delDetail.getSourceId());
                        invoicedApplyDetail.setCodFlag(0);
                        invoicedApplyDetails.add(invoicedApplyDetail);
                    } else {
                        PaymentAdvanceApplyDetail advanceApplyDetail = new PaymentAdvanceApplyDetail();
                        advanceApplyDetail.setId(delDetail.getSourceId());
                        advanceApplyDetail.setCodFlag(0);
                        advanceApplyDetails.add(advanceApplyDetail);
                    }
                    //请款明细有删除时，需要更新付款计划汇总，减少付款计划汇总的本月已请款金额， fin_payment_plan_summary applied_payment_amount 2025-07-30 邓京术
//                    PaymentCodApplyDetail adtDel = paymentCodApplyDetailService.getById(delDetail.getSourceId());
//                    initPaymentPlan(null, adtDel, headData, 3);
                }
                paymentCodApplyDetailService.updateBatchById(detailList);
            }
//            if (CollectionUtils.isNotEmpty(invoicedApplyDetails)) {
//                invoicedApplyDetailService.updateBatchById(invoicedApplyDetails);
//            }
            if (CollectionUtils.isNotEmpty(advanceApplyDetails)) {
                paymentAdvanceApplyDetailService.updateBatchById(advanceApplyDetails);
            }

            // 更新明细行号
            paymentCodApplyDetailService.updateDetailItemNo(Objects.isNull(headData.getId()) ? byId.getId() : headData.getId());
            initPaymentPlanSummary(byId, false);
        }
        this.deleteImg(headData.getId());
        this.toImg(String.valueOf(headData.getId()));
    }

    @Override
    public List<String> saveOrUpdateCheck(PaymentCodApplySaveDTO data) {
        List<String> resultList = new ArrayList<>();
        //提醒：三个月内相同供应商、相同金额提醒；

        //查询三个月内相同供应商、相同金额
        List<PaymentCodApply> list = paymentCodApplyService.findDataBySupplierAndAmount(data.getSupplierCode(), data.getOaBorrowMoney(), 3,data.getId());
        if (CollectionUtils.isNotEmpty(list)){
            resultList.add(StrUtil.format("供应商：{}、申请金额：{}在三个月内存在重复申请的数据，单号：{}", data.getSupplierName(), data.getOaBorrowMoney(), list.get(0).getCpApplyNo()));
        }



        LambdaQueryWrapper<PaymentCodApply> query = new LambdaQueryWrapper<PaymentCodApply>()
                .eq(PaymentCodApply::getPaymentCompanyName, data.getPaymentCompanyName())
                .eq(PaymentCodApply::getSupBankName, data.getSupBankName())
                .eq(PaymentCodApply::getSupBankAccount, data.getSupBankAccount())
                .eq(PaymentCodApply::getSupBankCode, data.getSupBankCode())
                .eq(PaymentCodApply::getBankInterCode, data.getBankInterCode())
                .eq(PaymentCodApply::getBankAddress, data.getBankAddress());
//        if (ObjectUtil.isNotNull(data.getId())){
//            query.ne(PaymentCodApply::getId, data.getId());
//        }
        query.last(" limit 1");
        PaymentCodApply bank = paymentCodApplyService.getOne(query);
        if (ObjectUtil.isNull( bank)&&ObjectUtil.isNull(data.getId())){
//            return StrUtil.format("供应商：{}、银行名称：{}、银行账号：{}、银行代码：{}、银行国际代码：{}、银行地址：{}为第一次付款，请核对银行信息", data.getSupplierName(), data.getPaymentCompanyName(), data.getSupBankName(), data.getSupBankAccount(), data.getSupBankCode(), data.getBankInterCode(), data.getBankAddress());
            resultList.add(StrUtil.format("此供应商的银行信息为第一次付款，请核对银行信息"));
        }
        for (PaymentCodApplySaveDTO.ApplyDetail ad : data.getItemList()) {
            //对账请款，相同供应商、相同对账单、相同请款金额，弹窗提醒请款人
            List<PaymentCodApplyDetail> list2 = paymentCodApplyService.findDataBySupplierAndAccountAndAmount(data.getSupplierCode(), ad.getAccountStatementNo(), ad.getBudOutMoney(),data.getId());
            if (CollectionUtils.isNotEmpty(list2)){
                resultList.add(StrUtil.format("供应商：{}、对账单：{}、本次申请金额：{}存在重复申请的数据，单号：{}", data.getSupplierName(), ad.getAccountStatementNo(), ad.getBudOutMoney(),list2.get(0).getCppNo()));
            }
        }

        // 防多付
        // 逾期款项与本月到期款项与本次支付金额的逻辑校验
        BigDecimal applyPaymentAmount = data.getOaBorrowMoney();        // 本次支付金额
        BigDecimal overdueAmount = data.getOverdueAmount();             // 逾期款项
        BigDecimal dueAmount = data.getDueAmount();                     // 本月到期款项
        BigDecimal unClearedAmount;                                     // 未清账预付款
        // 未清账预付款 = ①+②-③+④
        //①相同供应商预付款申请单状态是付款成功，且未转单，行未删除，累计行未抵扣金额，行未抵扣金额=行本次申请金额-行已冲账金额；
        BigDecimal unCleared1 = paymentAdvanceApplyService.getUnCleared1(data.getSupplierCode());
        //②相同供应商预付款申请单状态是止付，累计单头已付款金额；
        BigDecimal unCleared2 = paymentAdvanceApplyService.getUnCleared2(data.getSupplierCode());
        //③预付款退款金额：相同供应商，预付款变更单类型是退款，状态是已发布，行未删除，累计行的本次登记含税金额；
        BigDecimal unCleared3 = paymentAdvanceApplyService.getUnCleared3(data.getSupplierCode());
        //④预付款转单未抵扣金额：相同供应商，预付款变更单类型是转单，状态是已发布，行未删除，累计行未抵扣金额，行未抵扣金额=行的本次登记含税金额-行的已冲账含税金额；
        BigDecimal unCleared4 = paymentAdvanceApplyService.getUnCleared4(data.getSupplierCode());
        unClearedAmount = unCleared1.add(unCleared2).subtract(unCleared3).add(unCleared4);
        // 相同供应商，排除付款申请单（包括预付请款和对账请款）状态是“付款成功”、“共享审批作废”、“删除”、“止付”的付款申请单，累计行本次请款金额；
        BigDecimal inPaymentAmount = paymentAdvanceApplyService.getInPaymentAmount(data.getSupplierCode(),data.getCompanyCode()); // 在途请款单付款金额

        // 本次支付金额（付款申请单汇总金额）大于 逾期款项+本月到期款项-未清账预付款 - 在途请款单付款金额（已申请待支付，排除状态“付款完成”、“共享审批作废”、“删除”）
        if (applyPaymentAmount.compareTo(overdueAmount.add(dueAmount).subtract(unClearedAmount).subtract(inPaymentAmount)) > 0) {
            resultList.add(StrUtil.format("本次支付金额({})大于逾期款项({}) + 本月到期款项({}) - 未清账预付款({}) - 在途请款单付款金额({})",
                    applyPaymentAmount.setScale(2, RoundingMode.HALF_UP),
                    overdueAmount.setScale(2, RoundingMode.HALF_UP),
                    dueAmount.setScale(2, RoundingMode.HALF_UP),
                    unClearedAmount.setScale(2, RoundingMode.HALF_UP),
                    inPaymentAmount.setScale(2, RoundingMode.HALF_UP)));
        }
        BigDecimal accountsPayableBalance = data.getAccountsPayableBalance();   // 应付账款余额
        BigDecimal provisionalBalance = data.getProvisionalBalance();           // 应付暂估余额
        // 本次付款金额（付款申请单汇总金额） 大于  应付账款余额（已包含未清账预付款）+应付暂估余额 - 在途请款单付款金额（已申请待支付，排除状态“付款完成”、“共享审批作废”、“删除”）
        if (applyPaymentAmount.compareTo(accountsPayableBalance.add(provisionalBalance).subtract(inPaymentAmount)) > 0) {
            resultList.add(StrUtil.format("本次付款金额({})大于应付账款余额({}) + 应付暂估余额({}) - 在途请款单付款金额({})",
                    applyPaymentAmount.setScale(2, RoundingMode.HALF_UP),
                    accountsPayableBalance.setScale(2, RoundingMode.HALF_UP),
                    provisionalBalance.setScale(2, RoundingMode.HALF_UP),
                    inPaymentAmount.setScale(2, RoundingMode.HALF_UP)));
        }

        return resultList;
    }

    @Override
    @Transactional
    public void deleteCodApply(String applyIds) {
        final List<Long> appIdList = JSONArray.parseArray(applyIds, Long.class);
        // 校验对账付款申请单状态
        final List<PaymentCodApply> list = paymentCodApplyService.findDataStatusByIdList(appIdList);
        // 不允许删除的对账付款申请单号
        String pcaCode = "";
        for (PaymentCodApply pca : list) {
            if (5 == pca.getStatus()||3 == pca.getStatus()||7 == pca.getStatus()||8 == pca.getStatus()||9 == pca.getStatus()||10 == pca.getStatus()) {
                pcaCode = pca.getCpApplyNo();
                break;
            }
        }
        if (StringUtils.isNotEmpty(pcaCode)) {
            throw new DaoException("对账付款申请单: " + pcaCode + ", 当前状态不可删除, 请检查");
        }

        //根据oaProcessCode查询相同审批单号的申请单，进行删除动作 2024-08-20 邓京术
        for (PaymentCodApply paymentCodApply : list) {
            if (StringUtils.isNotEmpty(paymentCodApply.getOaProcessCode())) {
                //根据oa流程号查询相同流程号的申请单
                List<PaymentCodApply> oaSamePaymentCodApplyList = paymentCodApplyService.list(
                        new LambdaQueryWrapper<PaymentCodApply>().eq(PaymentCodApply::getOaProcessCode, paymentCodApply.getOaProcessCode()));
                //如果id相同，则filter
                for (PaymentCodApply tempPaymentCodApply : oaSamePaymentCodApplyList) {
                    boolean flag = false;
                    for (Long ll : appIdList) {
                        if (ll.equals(tempPaymentCodApply.getId())) {
                            flag = true;
                            break;
                        }
                    }
                    if (!flag) {
                        appIdList.add(tempPaymentCodApply.getId());
                    }
                }
            }
        }

        List<PaymentCodApply> applyList = Lists.newArrayList();
        for (Long applyId : appIdList) {
            PaymentCodApply apply = new PaymentCodApply();
            apply.setId(applyId);
            apply.setDeleteFlag(1);
            apply.setUpdateTime(LocalDateTime.now());
            apply.setUpdateUserId(LoginUtil.getUserId());
            apply.setUpdateUserCode(LoginUtil.getAccount());
            apply.setUpdateUserName(LoginUtil.getName());
            applyList.add(apply);


            PaymentCodApply old = paymentCodApplyService.getById(applyId);
            PayApplyDeleteDTO payImportToOpenDTO = new PayApplyDeleteDTO();
            payImportToOpenDTO.setBillno(old.getCpApplyNo());
            if (StrUtil.isEmpty(old.getOaProcessCode())){
                continue;
            }
            //提交到共享
            String accessToken = financialShareUtil.getShareAccessToken();
            ErpApiResult1<PayImportToOpenResultDTO> result = paymentOaClient.payApplyDelete(accessToken,payImportToOpenDTO);
            if (!result.getStatus()) {
                throw new DaoException("共享系统接口报错：" + result.getMessage());
            }
        }

        if (!paymentCodApplyService.updateBatchById(applyList)) {
            throw new DaoException("删除对账付款申请单失败");
        }

        // 删除对账付款申请明细数据
        paymentCodApplyDetailService.delDetailByApplyId(appIdList);
        //去除绑定的预付款和开票申请
        List<PaymentCodApplyDetail> details = paymentCodApplyDetailService.findByPaymentDetail(appIdList);
        //开票申请明细
        List<InvoicedApplyDetail> invoicedApplyDetails = Lists.newArrayList();
        //预付款明细
        List<PaymentAdvanceApplyDetail> advanceApplyDetails = Lists.newArrayList();
        for (PaymentCodApplyDetail detail : details) {
            if ("Z001".equals(detail.getAmountType())) {
                PaymentAdvanceApplyDetail detail1 = new PaymentAdvanceApplyDetail();
                detail1.setId(detail.getSourceId());
                detail1.setCodFlag(0);
                advanceApplyDetails.add(detail1);
            } else {
                InvoicedApplyDetail invoicedApplyDetail = new InvoicedApplyDetail();
                invoicedApplyDetail.setId(detail.getSourceId());
                invoicedApplyDetail.setCodFlag(0);
                invoicedApplyDetails.add(invoicedApplyDetail);
            }

        }


        if (CollectionUtils.isNotEmpty(invoicedApplyDetails)) {
            invoicedApplyDetailService.updateBatchById(invoicedApplyDetails);
        }
        if (CollectionUtils.isNotEmpty(advanceApplyDetails)) {
            paymentAdvanceApplyDetailService.updateBatchById(advanceApplyDetails);
        }
        //重新计算汇总
        //付款申请删除时，需要同时更新付款计划汇总数据 邓京术 2025-07-31
        for (PaymentCodApply paymentCodApply : list) {
            PaymentCodApply byId = paymentCodApplyService.getById(paymentCodApply.getId());
            initPaymentPlanSummary(byId, false);
        }
    }

    @Override
    public List<CreatePcaDetailDto> queryCodApplyInvoiceById(Long id, Integer totalFlag, String businessType) {
        List<CreatePcaDetailPO> createPcaDetailPOS = new ArrayList<>();
        if (StringUtils.isNotEmpty(businessType) && "002".equals(businessType)) {
            createPcaDetailPOS = costInvoicedApplyDetailService.queryCodApplyInvoiceById(id);
        }else if (StringUtils.isNotEmpty(businessType) && "005".equals(businessType)) {
            createPcaDetailPOS = companyInvoicedApplyService.queryCodApplyInvoiceById(id);
        } else {
            createPcaDetailPOS = invoicedApplyDetailService.queryCodApplyInvoiceById(id);
        }
        List<CreatePcaDetailDto> createPcaDetailDtos = paymentCodApplyConvert.createPcaDetailPO2DTOList(createPcaDetailPOS);
        if (CollectionUtils.isNotEmpty(createPcaDetailDtos)) {
            //根据已获取的过账数据筛选已经货到付款的数据
            List<CreatePcaDetailPO> alreadyData = paymentCodApplyDetailService.findByAccountCodeAndItem1(createPcaDetailPOS, totalFlag == null ? id : null);
            //处理数据开票数据
            for (CreatePcaDetailDto detailDto : createPcaDetailDtos) {
                BigDecimal alreadyApplyAmount = BigDecimal.ZERO;
                BigDecimal alreadyPaymentAmount = BigDecimal.ZERO;
                if (CollectionUtils.isNotEmpty(alreadyData)) {
                    for (CreatePcaDetailPO dto : alreadyData) {
                        if (detailDto.getAccountStatementNo().equals(dto.getDataKey())) {
                            alreadyApplyAmount = alreadyApplyAmount.add(dto.getBudOutMoney());
                            if (dto.getStatus() == 5) {
                                alreadyPaymentAmount = alreadyPaymentAmount.add(dto.getBudOutMoney());
                            }
                        }
                    }
                }
                //根据对账单号查询付款到期日 2024-10-31 邓京术
                AccountStatementQuery query = new AccountStatementQuery();
                query.setStatementNo(detailDto.getAccountStatementNo());
                List<AccountStatementPO> accountStatementPOS = accountStatementService.accountOrApplyListByNo(query);
                if (CollectionUtils.isNotEmpty(accountStatementPOS)) {
                    detailDto.setPaymentExpireDate(accountStatementPOS.get(0).getPaymentExpireDate());
                }

                //已申请金额
                detailDto.setAlreadyApplyAmount(alreadyApplyAmount);
                //已付款金额
                detailDto.setAlreadyPaymentAmount(alreadyPaymentAmount);
                detailDto.setApplyAmount(detailDto.getActualUnpaidAmount().subtract(detailDto.getAlreadyApplyAmount() == null ? BigDecimal.ZERO : detailDto.getAlreadyApplyAmount()));
            }
        }
        return createPcaDetailDtos;
    }

    @Override
    public List<CreatePcaDetailDto> queryCodApplyInvoiceByAccountStatementNo(String accountStatementNo) {
        List<CreatePcaDetailPO> createPcaDetailPOS = invoicedApplyDetailService.queryCodApplyInvoiceByAccountStatementNo(accountStatementNo);
        List<CreatePcaDetailDto> createPcaDetailDtos = paymentCodApplyConvert.createPcaDetailPO2DTOList(createPcaDetailPOS);
        return createPcaDetailDtos;
    }

    @Override
    public void pushOa(String ids) {
        String sameKey = "";
        List<String> idList = Arrays.asList(StringUtils.split(ids, ","));
        List<PaymentCodApply> paymentCodApplyConfirmList = Lists.newArrayList();
        List<PaymentCodApply> paymentCodApplyList = paymentCodApplyService.listByIds(idList);
        //先检查申请单是否有oa流程单号，如果有的话，要把这些有单号的全部搜索出来一并提交，
        //判断提交的申请单中，如果没有流程单号的，也可以一起提交OA审批

        String oAProcessCode = "";
        BigDecimal benCiFuKuanHeJiJinE = BigDecimal.ZERO;
        List<String> supplierCodeList = new ArrayList<>();
        List<String> srmNoList = new ArrayList<>();
        for (PaymentCodApply paymentCodApply : paymentCodApplyList) {
            //取页面的应付总金额汇总 2024-08-16 邓京术 ，下面这个是错的
//            benCiFuKuanHeJiJinE = benCiFuKuanHeJiJinE.add(paymentCodApply.getBudOutMoney());
//            benCiFuKuanHeJiJinE = benCiFuKuanHeJiJinE.add(paymentCodApply.getActualityPayMoney());
//            supplierCodeList.add(paymentCodApply.getSupplierCode());
            //付款公司、币种、付款方式、是否提前付款、承兑期限、报关公司、申请人  抬头7个信息必须一致才可以提交OA审批
            if (sameKey.equals("")) {
                sameKey = new StringBuilder(paymentCodApply.getCompanyCode()).append(paymentCodApply.getCurrencyCode()).append(paymentCodApply.getPaymentWayCode())
                        .append(paymentCodApply.getAdvancePaymentFlag()).append(paymentCodApply.getAcceptanceMethod()).append(paymentCodApply.getFaSupplierName())
                        .append(paymentCodApply.getCreateUserCode()).toString();
            } else {
                String sameKey2 = new StringBuilder(paymentCodApply.getCompanyCode()).append(paymentCodApply.getCurrencyCode()).append(paymentCodApply.getPaymentWayCode())
                        .append(paymentCodApply.getAdvancePaymentFlag()).append(paymentCodApply.getAcceptanceMethod()).append(paymentCodApply.getFaSupplierName())
                        .append(paymentCodApply.getCreateUserCode()).toString();
                if (!sameKey2.equals(sameKey)) {
                    throw new DaoException(StrUtil.format("付款公司、币种、付款方式、是否提前付款、承兑期限、报关公司、申请人信息必须全部相同才可以同时提交OA审批。"));
                }
            }
            paymentCodApplyConfirmList.add(paymentCodApply);
            if (StringUtils.isEmpty(paymentCodApply.getOaProcessCode())) {
                continue;
            } else {
                oAProcessCode = paymentCodApply.getOaProcessCode();
            }
        }


        //判断oa流程号是否为空
        if (StringUtils.isNotEmpty(oAProcessCode)) {
            List<PaymentCodApply> oaSamePaymentCodApplyList = paymentCodApplyService.list(
                    new LambdaQueryWrapper<PaymentCodApply>().eq(PaymentCodApply::getOaProcessCode, oAProcessCode));
            //如果id相同，则filter
            for (PaymentCodApply paymentCodApply : oaSamePaymentCodApplyList) {
                boolean flag = false;
                for (PaymentCodApply prePaymentCodApply : paymentCodApplyList) {
                    //判断id号是否相同
                    if (paymentCodApply.getId().equals(prePaymentCodApply.getId())) {
                        flag = true;
                        break;
                    }
                }
                //如果没有不存在相同的申请单号，并且又有相同的oa流程单号，则加入至oa审批单中
                if (!flag) {
                    paymentCodApplyList.add(paymentCodApply);
                    paymentCodApplyConfirmList.add(paymentCodApply);
                }
            }
        }

        List<OaFileParamDTO> list1 = new ArrayList<>();
        for (PaymentCodApply paymentCodApply : paymentCodApplyConfirmList) {
            supplierCodeList.add(paymentCodApply.getSupplierCode());
            srmNoList.add(paymentCodApply.getCpApplyNo());
            if (StringUtils.isNotEmpty(paymentCodApply.getFiles())) {
                List<FileResposePreviewCDTO> fileResposePreviewDTOS = fileClient.getPreviewUrl(Arrays.asList(StringUtils.split(paymentCodApply.getFiles(), ",")));
                for (FileResposePreviewCDTO fileResposePreviewDTO : fileResposePreviewDTOS) {
                    OaFileParamDTO build = OaFileParamDTO.builder().fileName(fileResposePreviewDTO.getFileName()).url(fileResposePreviewDTO.getPreviewUrl()).downloadUrl(fileResposePreviewDTO.getDownloadUrl()).build();
                    list1.add(build);
                }
                //附件
                //head.setFd_pageUrl(JSON.toJSONString(list1));
            }
        }
        PaymentCodApply codApply = paymentCodApplyConfirmList.get(0);
        SupplierPayImportDTO supplierPayImportDTO = new SupplierPayImportDTO();
        //插入头
        SupplierPayImportDTO.Head head = new SupplierPayImportDTO.Head();
        //SRM业务类型
        head.setFd_srmType("13");
        //申请人工号  取付款单的申请人姓名
//        head.setFd_shenQingRenXingMing(LoginUtil.getAccount());
        head.setFd_shenQingRenXingMing(codApply.getCreateUserCode());

        head.setProcessId(StringUtils.isNotEmpty(oAProcessCode) ? oAProcessCode : "");
        //SRM单号 多个单号要逗号分开
        head.setFd_shenQingDanHao(Joiner.on(",").join(srmNoList));
        //抄送人员工号（经办人）
//        head.setFd_jingBanRen(codApply.getCreateUserCode());
        head.setFd_jingBanRen(StringUtils.isNotEmpty(codApply.getOaHandlerCode()) ? codApply.getOaHandlerCode() : codApply.getCreateUserCode());
        if (StringUtils.isNotEmpty(codApply.getPaymentWayCode())) {
            DictDTO dict = dictClient.getDictByTypeAndCode(DictCode.PAYMENT_WAY.getCode(), codApply.getPaymentWayCode());
            //付款方式
            head.setFd_fuKuanFangShi(ObjectUtil.isNotNull(dict) ? dict.getName() : "");
        } else {
            //付款方式
            head.setFd_fuKuanFangShi("");
        }

        if (null != codApply.getAdvancePaymentFlag()) {
            //是否提前付款
            head.setFd_shiFuTiQianFuKuan(codApply.getAdvancePaymentFlag() == 1 ? "是" : "否");
        } else {
            //是否提前付款
            head.setFd_shiFuTiQianFuKuan("");
        }
        if (StringUtils.isNotEmpty(codApply.getAcceptanceMethod())) {
            DictDTO dict = dictClient.getDictByTypeAndCode(DictCode.SUPPLIER_ACCETP_DEADLINE.getCode(), codApply.getAcceptanceMethod());
            //承兑期限
            head.setFd_chengDuiQiXian(ObjectUtil.isNotNull(dict) ? dict.getName() : "");
        } else {
            //承兑期限
            head.setFd_chengDuiQiXian("");
        }

        //付款类型
        head.setFd_fuKuanLeiXing("SAP应付");
        //本次付款合计金额  所有付款单抬头应付总金额
        head.setFd_benCiFuKuanHeJiJinE(benCiFuKuanHeJiJinE);
//        //大写金额
//        head.setFd_daXieJinE(Convert.digitToChinese(benCiFuKuanHeJiJinE));
        //备注
        List<String> nonEmptyRemarks = paymentCodApplyConfirmList.stream()
                .filter(apply -> apply.getApplyRemark() != null && !apply.getApplyRemark().isEmpty())
                .map(PaymentCodApply::getApplyRemark)
                .collect(Collectors.toList());
        String remark = "";
        if (CollectionUtils.isNotEmpty(nonEmptyRemarks)) {
            remark = String.join(",", nonEmptyRemarks);
        }
        head.setFd_beiZhu(StringUtils.isNotEmpty(remark) ? remark : "");
        CompanyDTO companyDTO = companyClient.getByCode(codApply.getCompanyCode());
        //付款公司
        head.setFd_fuKuanGongSi(companyDTO.getCompanyName());
        //付款公司编码
        head.setFd_fuKuanGongSiBianMa(codApply.getCompanyCode());
        //供应商代码 多个要逗号分开
        head.setFd_gongYingShangDaiMa(Joiner.on(",").join(supplierCodeList));
        //报关公司
        head.setFd_baoGuanGongSi(StrUtil.isNotEmpty(codApply.getFaSupplierName()) ? codApply.getFaSupplierName() : "");
        //公司代码
        head.setFd_gongSiDaiMa(Joiner.on(",").join(supplierCodeList));
        //币种
        head.setFd_biZhong(codApply.getCurrencyCode());
        if (CollectionUtils.isNotEmpty(list1)) {
            //2024-12-18修改
//            List<FileResposePreviewCDTO> fileResposePreviewDTOS = fileClient.getPreviewUrl(Arrays.asList(StringUtils.split(codApply.getFiles(), ",")));
//            List<OaFileParamDTO> list1 = new ArrayList<>();
//            for (FileResposePreviewCDTO fileResposePreviewDTO : fileResposePreviewDTOS) {
//                OaFileParamDTO build = OaFileParamDTO.builder().fileName(fileResposePreviewDTO.getFileName()).url(fileResposePreviewDTO.getPreviewUrl()).downloadUrl(fileResposePreviewDTO.getDownloadUrl()).build();
//                list1.add(build);
//            }
            //附件
            head.setFd_pageUrl(JSON.toJSONString(list1));
        } else {
            //附件
            head.setFd_pageUrl("");
        }
        supplierPayImportDTO.setHead(head);
        //付款条件
        List<DictDTO> paymentMethods = dictClient.getDicByType(DictCode.PAYMENT_TERMS.getCode());
        final Map<String, DictDTO> paymentMethodCache = paymentMethods.stream().collect(Collectors.toMap(DictDTO::getCode, a -> a));
        final Set<String> paymentMethodCodes = paymentMethodCache.keySet();
        //插入明细
        SupplierPayImportDTO.KuanItem kuanItem = new SupplierPayImportDTO.KuanItem();
        List<SupplierPayImportDTO.KuanItem.Item> kuanItemList = new ArrayList<>();

        SupplierPayImportDTO.ZongItem zongItem = new SupplierPayImportDTO.ZongItem();
        List<SupplierPayImportDTO.ZongItem.Item> zongItemList = new ArrayList<>();
//        SupplierPayImportDTO.ZongItem.Item item1 = new SupplierPayImportDTO.ZongItem.Item();
        Map<String, SupplierPayImportDTO.ZongItem.Item> item1Map = new HashMap<>();
        Map<String, String> paymentExpireStrMap = new HashMap<>();
        for (PaymentCodApply paymentCodApply : paymentCodApplyConfirmList) {
            String supplierCode = paymentCodApply.getSupplierCode();
            List<CreatePcaDetailDto> detailDtoList = this.queryCodApplyInvoiceById(paymentCodApply.getId(), null, codApply.getBusinessType());
            BigDecimal fd_benCiWeiFuHeJi = BigDecimal.ZERO;
            BigDecimal fd_benCiFuKuanJinE = BigDecimal.ZERO;
            //判断供应商付款金额是否超计划付款，邓京术 2025-08-02
//            BigDecimal exceedPlanPayMonthAmount = paymentPlanLogic.findSupplierPaymentPlanSummary(paymentCodApply.getSupplierCode(), paymentCodApply.getCompanyCode(), 2);
//            if (exceedPlanPayMonthAmount.floatValue() > 0f) {
//                //打上超计划标识，及金额
//            }

            if (CollectionUtils.isNotEmpty(detailDtoList)) {
                for (CreatePcaDetailDto detailDto : detailDtoList) {
                    SupplierPayImportDTO.KuanItem.Item item = new SupplierPayImportDTO.KuanItem.Item();
                    if (!paymentExpireStrMap.keySet().contains(detailDto.getAccountStatementNo())) {
                        //根据对账单号查询付款到期日付给OA 2024-11-06 邓京术
                        AccountStatementQuery query = new AccountStatementQuery();
                        query.setStatementNo(detailDto.getAccountStatementNo());
                        List<AccountStatementPO> accountStatementPOS = accountStatementService.accountOrApplyListByNo(query);
                        String paymentExpireStr = "";
                        if (CollectionUtils.isNotEmpty(accountStatementPOS)) {
                            paymentExpireStr = accountStatementPOS.get(0).getPaymentExpireDate() == null ? "" :
                                    formatYYYYMMDDDash(accountStatementPOS.get(0).getPaymentExpireDate());
                        }
                        paymentExpireStrMap.put(detailDto.getAccountStatementNo(), paymentExpireStr);
                    }
                    item.setFd_daoQiRi(paymentExpireStrMap.get(detailDto.getAccountStatementNo()));
                    //采购对账单号/订单号
                    item.setFd_caiGouDuiZhangDanHao(detailDto.getAccountStatementNo());
                    //对账月份 要取对账单的对账月份，不能取new date() 邓京术 2024-08-13
                    item.setFd_duiZhangYueFen(detailDto.getAccountStatementMonth());
//                    item.setFd_duiZhangYueFen(DateUtil.format(new Date(),"MM"));
//                    : 'actualUnpaidAmount' '实际应付金额' ,    -- 应付金额
//                    : 'applyAmount', '可申请金额',            -- 未付金额
//                    : 'discountMoney',  '折扣金额',           -- 坏账外币等扣款 OA叫这个名字
//                    : applyAmount - discountMoney 可申请金额 - 折扣金额                   --本次未付

//                    item.setFd_duiZhangDanJinE(detailDto.getItAmount());
                    //对账单金额  = 取页面实际应付金额（ActualUnpaidAmount） 2024-08-16 邓京术
                    item.setFd_duiZhangDanJinE(detailDto.getActualUnpaidAmount());
                    //未付余额  取页面的行 可申请金额（ApplyAmount） 2024-08-16 邓京术
//                    item.setFd_weiFuJinE(detailDto.getItAmount().subtract(detailDto.getAlreadyApplyAmount()));
                    item.setFd_weiFuJinE(detailDto.getApplyAmount());
                    //本次付款金额 = 取页面的本次申请金额(getBudOutMoney) -  行 折扣金额(getDiscountMoney) 2024-08-16 邓京术
                    item.setFd_benCiFuKuanJinE(detailDto.getBudOutMoney().subtract(detailDto.getDiscountMoney()));
                    //本次付款金额 合计，按供应商汇总
                    fd_benCiFuKuanJinE = fd_benCiFuKuanJinE.add(item.getFd_benCiFuKuanJinE());
                    //sap采购对账单号
                    item.setFd_sapCaiGouDuiZhangDanHao("");
                    //TODO 坏账/外币等扣款(OA叫这个名字，所以传zheKouJinE)
                    item.setFd_zheKouJinE(detailDto.getDiscountMoney());
                    //
                    item.setFd_huaiZhangHeXiao(detailDto.getDiscountMoney());
                    //TODO 尾差调整
                    item.setFd_weiChaDiaoZheng(BigDecimal.ZERO);
                    //TODO 本次未付 本次未付= 未付余额-坏账-尾差调整   2024-08-14根据财务调整  applyAmount - discountMoney 可申请金额 - 折扣金额
//                    item.setFd_benCiWeiFu(detailDto.getItAmount().subtract(detailDto.getAlreadyApplyAmount()));
                    item.setFd_benCiWeiFu(detailDto.getApplyAmount().subtract(detailDto.getDiscountMoney()));

                    //本次未付合计 = 本次未付金额汇总   然后按供应商分别汇总
                    fd_benCiWeiFuHeJi = fd_benCiWeiFuHeJi.add(item.getFd_benCiWeiFu());


                    if (StringUtils.isNotEmpty(detailDto.getInvoiceNo())) {
                        InvoicedApply invoicedApply = invoicedApplyService.getOne(Wrappers.lambdaQuery(InvoicedApply.class).eq(InvoicedApply::getInvoiceApplyNo, detailDto.getInvoiceNo()).last(" limit 1"));
                        if (ObjectUtil.isNotNull(invoicedApply)) {
                            InvoicedApplyPostResult invoicedApplyPostResult = invoicedApplyPostResultService.getOne(Wrappers.lambdaQuery(InvoicedApplyPostResult.class).eq(InvoicedApplyPostResult::getInvoiceApplyId, invoicedApply.getId()).last(" limit 1"));
                            if (ObjectUtil.isNotNull(invoicedApplyPostResult)) {
                                //SAP凭证号
                                item.setFd_pingZhengHao(StrUtil.isNotEmpty(invoicedApplyPostResult.getInvoiceVoucher()) ? invoicedApplyPostResult.getInvoiceVoucher() : "-");
                            } else {
                                //对于USD的，根据account_statement_no 去对账单表 fin_account_statement 查询出 invoiced_code 邓京术 2024-08-23
                                AccountStatement accountStatement = accountStatementService.getOne(Wrappers.lambdaQuery(AccountStatement.class).eq(AccountStatement::getAccountStatementNo, detailDto.getAccountStatementNo()).last(" limit 1"));
                                if (Objects.nonNull(accountStatement)) {
                                    item.setFd_pingZhengHao(accountStatement.getInvoicedCode());
                                }
                            }
                            if (StringUtils.isEmpty(item.getFd_pingZhengHao()) || item.getFd_pingZhengHao().equals("-")) {
                                //对于USD的，根据account_statement_no 去对账单表 fin_account_statement 查询出 invoiced_code 邓京术 2024-08-23
                                AccountStatement accountStatement = accountStatementService.getOne(Wrappers.lambdaQuery(AccountStatement.class).eq(AccountStatement::getAccountStatementNo, detailDto.getAccountStatementNo()).last(" limit 1"));
                                if (Objects.nonNull(accountStatement)) {
                                    item.setFd_pingZhengHao(accountStatement.getInvoicedCode());
                                }
                            }
                        }
                    } else {
                        //SAP凭证号
                        item.setFd_pingZhengHao("-");
                    }

                    //供应商代码1
                    item.setFd_gongYingShangDaiMa1(paymentCodApply.getSupplierCode());
                    //供应商1
                    item.setFd_gongYingShang1(paymentCodApply.getSupplierName());
                    //收款单位1
                    item.setFd_shouKuanDanWei1(paymentCodApply.getPaymentCompanyName());
                    //开户银行1
                    item.setFd_kaiHuYinXing1(paymentCodApply.getSupBankName());
                    //银行账号1
                    item.setFd_yinXingZhangHao1(paymentCodApply.getSupBankAccount());
                    //付款条件1
                    DictDTO dictDTO = paymentMethodCache.get(StringUtils.isNotEmpty(detailDto.getIpwCode()) ? detailDto.getIpwCode() : "");
                    item.setFd_fuKuanTiaoJian1(ObjectUtil.isNotNull(dictDTO) ? dictDTO.getCodeWithDesc() : "");
                    //银行行号
                    item.setFd_yinHangHao(StringUtils.isNotEmpty(paymentCodApply.getSupBankCode()) ? paymentCodApply.getSupBankCode() : "");
                    //银行国际代码
                    item.setFd_yinHangCode(StringUtils.isNotEmpty(paymentCodApply.getBankInterCode()) ? paymentCodApply.getBankInterCode() : "");
                    kuanItemList.add(item);
                }
            }
            //如果供应商明细汇总已经存在
            if (item1Map.containsKey(supplierCode)) {
                SupplierPayImportDTO.ZongItem.Item item1 = item1Map.get(supplierCode);
                //本次未付合计
                item1.setFd_benCiWeiFuHeJi(fd_benCiWeiFuHeJi.add(item1.getFd_benCiWeiFuHeJi()));
                //本次付款金额合计
                item1.setFd_benCiFuKuanJinEHeJi(fd_benCiFuKuanJinE.add(item1.getFd_benCiFuKuanJinEHeJi()));
            } else {
                SupplierPayImportDTO.ZongItem.Item item1 = new SupplierPayImportDTO.ZongItem.Item();
                //供应商汇总代码
                item1.setFd_gongYingShangHuiZongDaiMa(paymentCodApply.getSupplierCode());
//                SupplierDTO supplierDTO = supplierClient.getSupplierByCode(paymentCodApply.getSupplierCode());
//                String en = ObjectUtil.isNull(supplierDTO)?"":supplierDTO.getSupplierNameEn();
                //供应商汇总收款单位
//            item1.setFd_gongYingShangHuiZongShouKua(paymentCodApply.getSupplierName()+(StrUtil.isNotEmpty(en)?("/"+en):""));
                List<SupplierBankDTO> supplierBankDTOS = supplierClient.supplierBankDate(paymentCodApply.getSupplierCode());
                if (CollectionUtils.isNotEmpty(supplierBankDTOS)) {
                    item1.setFd_gongYingShangHuiZongShouKua(StringUtils.isNotEmpty(supplierBankDTOS.get(0).getCompanyName()) ? supplierBankDTOS.get(0).getCompanyName() : "");
                } else {
                    item1.setFd_gongYingShangHuiZongShouKua("");
                }
                //供应商汇总开户银行
                item1.setFd_gongYingShangHuiZongKaiHuYi(paymentCodApply.getSupBankName());
                //供应商汇总银行账号
                item1.setFd_gongYingShangHuiZongYinXing(paymentCodApply.getSupBankAccount());
                //银行行号
                item1.setFd_yinHangHao(StringUtils.isNotEmpty(paymentCodApply.getSupBankCode()) ? paymentCodApply.getSupBankCode() : "");
                //银行国际代码
                item1.setFd_yinHangCode(StringUtils.isNotEmpty(paymentCodApply.getBankInterCode()) ? paymentCodApply.getBankInterCode() : "");
                //本次未付合计
                item1.setFd_benCiWeiFuHeJi(fd_benCiWeiFuHeJi);
                //本次付款金额合计
                item1.setFd_benCiFuKuanJinEHeJi(fd_benCiFuKuanJinE);
                //设置供应商付款计划是否超期
//                item1.setFd_yinHangCode();
                item1Map.put(supplierCode, item1);
            }

            //2024-08-12修改本次付款金额汇总取值逻辑
            head.setFd_benCiFuKuanHeJiJinE(head.getFd_benCiFuKuanHeJiJinE().add(fd_benCiFuKuanJinE));
            head.setFd_daXieJinE(Convert.digitToChinese(head.getFd_benCiFuKuanHeJiJinE()));
        }

        zongItemList.addAll(item1Map.values());
        kuanItem.setItem(kuanItemList);
        supplierPayImportDTO.setFuKuanItem(kuanItem);
        zongItem.setItem(zongItemList);
        supplierPayImportDTO.setHuiZongItem(zongItem);
        ApiResult<String> orUpdate = paymentOaClient.supplierPayImport(supplierPayImportDTO);
        final String code = orUpdate.getCode();
        if (code.equals(RestCode.SAP_SUCCESS.getCode())) {
            //成功就更新流程id
            final String oaId = orUpdate.getData();
            paymentCodApplyConfirmList.forEach(paymentCodApply -> {
                paymentCodApply.setOaProcessCode(oaId);
                paymentCodApply.setStatus(3);
                paymentCodApplyService.updateById(paymentCodApply);
            });
        } else {
            throw new DaoException(StrUtil.format("OA接口报错：{}", orUpdate.getMessage()));
        }
    }

    @Override
    public void pushOpen(String ids) {
        List<String> idList = Arrays.asList(StringUtils.split(ids, ","));
//        for (String id : idList) {
//            this.deleteImg(Long.valueOf(id));
//            this.toImg(id);
//        }
        //付款条件
        List<DictDTO> paymentMethods = dictClient.getDicByType(DictCode.PAYMENT_TERMS.getCode());
        final Map<String, DictDTO> paymentMethodCache = paymentMethods.stream().collect(Collectors.toMap(DictDTO::getCode, a -> a));

        List<PaymentCodApply> paymentCodApplyList = paymentCodApplyService.listByIds(idList);
        if (CollectionUtils.isNotEmpty(paymentCodApplyList)) {


            String accessToken = financialShareUtil.getShareAccessToken();
            for (PaymentCodApply paymentCodApply : paymentCodApplyList) {
                 //增加redis锁如果这个单据的数据正在处理就直接返回
                final String lockKey = PaymentCodLock + paymentCodApply.getCpApplyNo();
                if (!redisTemplate.opsForValue().setIfAbsent(lockKey, "1", 30, TimeUnit.SECONDS)) {
                    log.info("此单据："+paymentCodApply.getCpApplyNo()+"正在处理，请稍后提交!");
                    throw new DaoException("此单据："+paymentCodApply.getCpApplyNo()+"正在处理，请稍后提交!");
                }
                if (paymentCodApply.getStatus() != 1&&paymentCodApply.getStatus() != 2&&paymentCodApply.getStatus() != 4){
                    throw new DaoException("此单据："+paymentCodApply.getCpApplyNo()+"状态不可推送!");
                }
                PayImportToOpenDTO payImportToOpenDTO = new PayImportToOpenDTO();
                PayImportToOpenDTO.DataHead dataHead = new PayImportToOpenDTO.DataHead();
                // 结算组织.编码
                dataHead.setSettleorg_number(paymentCodApply.getCompanyCode());
                // 单据编号
                dataHead.setBillno(paymentCodApply.getCpApplyNo());
                // 单据类型.编码
                dataHead.setBilltype_number("ap_payapply_BT_S");
                // 申请日期
                dataHead.setApplydate(LocalDateTimeUtil.format(paymentCodApply.getCreateTime(), "yyyy-MM-dd"));
                // 申请组织.编码
                dataHead.setApplyorg_number(paymentCodApply.getCompanyCode());
                // 采购组织.编码
                dataHead.setPurorg_number(paymentCodApply.getCompanyCode());
                // 付款组织.编码
                dataHead.setPayorg_number(paymentCodApply.getPaymentCompanyCode());
                // 收款供应商.编码
                dataHead.setM4p4_supplier_number(paymentCodApply.getSupplierCode());
                // 供应商开户行
                dataHead.setM4p4_assacct(paymentCodApply.getSupBankName());
                // 开户行账号
                dataHead.setM4p4_deposit_bank(paymentCodApply.getSupBankAccount());
                // 银行代码
                dataHead.setM4p4_bank_code(StringUtils.isNotEmpty(paymentCodApply.getSupBankCode()) ? paymentCodApply.getSupBankCode() : "");
                //收款地址
                dataHead.setM4p4_pay_address(StringUtils.isNotEmpty(paymentCodApply.getBankAddress()) ? paymentCodApply.getBankAddress() : "");
                //收款单位
                dataHead.setM4p4_payee(StringUtils.isNotEmpty(paymentCodApply.getPaymentCompanyName()) ? paymentCodApply.getPaymentCompanyName() : "");
                // 业务类型
                dataHead.setM4p4_business_type(paymentCodApply.getBusinessType());
                // 提前支付 财务康玉华说不需要传 2026-01-17
//                dataHead.setM4p4_advancepayment(String.valueOf(paymentCodApply.getAdvancePaymentFlag()));

                BigDecimal exceedPlanPayMonthAmount = paymentPlanLogic.findSupplierPaymentPlanSummary(paymentCodApply.getSupplierCode(), paymentCodApply.getCompanyCode(), 2,"D");
                if (exceedPlanPayMonthAmount.floatValue() > 0f) {
                    //打上超计划标识，及金额
                    dataHead.setM4p4_ex_pay_plan("1");
                    dataHead.setM4p4_ex_pay_planamt(exceedPlanPayMonthAmount.stripTrailingZeros().toPlainString());
                }else {
                    dataHead.setM4p4_ex_pay_plan("0");
                    dataHead.setM4p4_ex_pay_planamt("0");
                }
//                if (paymentCodApply.getPayPlanMoney() != null && paymentCodApply.getPayPlanMoney().compareTo(BigDecimal.ZERO) > 0) {
//                    if (paymentCodApply.getPayPlanMoney() != null && paymentCodApply.getOaBorrowMoney().compareTo(paymentCodApply.getPayPlanMoney()) > 0) {
//                        dataHead.setM4p4_ex_pay_plan("1");
//                        dataHead.setM4p4_ex_pay_planamt(paymentCodApply.getOaBorrowMoney().subtract(paymentCodApply.getPayPlanMoney()).stripTrailingZeros().toPlainString());
//                    } else {
//                        dataHead.setM4p4_ex_pay_plan("0");
//                        dataHead.setM4p4_ex_pay_planamt("0");
//                    }
//                } else {
//                    dataHead.setM4p4_ex_pay_plan("0");
//                    dataHead.setM4p4_ex_pay_planamt("0");
//                }

                // 付款用途
                dataHead.setM4p4_pay_purpose(paymentCodApply.getPaymentPurposeDesc());
                // 影像文件
                dataHead.setImageno(paymentCodApply.getImgCode());
                // 承兑期限
                if (StrUtil.isNotEmpty(paymentCodApply.getAcceptanceMethod())) {
                    DictDTO dict = dictClient.getDictByTypeAndCode(DictCode.SUPPLIER_ACCETP_DEADLINE.getCode(), paymentCodApply.getAcceptanceMethod());
                    dataHead.setM4p4_accep_period(ObjectUtil.isNotNull(dict) ? dict.getName() : "");
                } else {
                    dataHead.setM4p4_accep_period("");
                }

                // 报关公司
                dataHead.setM4p4_customs_broker(paymentCodApply.getFaSupplier());
                // 供应商退款
                dataHead.setM4p4_supplier_refund(paymentCodApply.getSupplierReturn());
                if (paymentCodApply.getCompanyCode().equals(paymentCodApply.getPaymentCompanyCode()) && paymentCodApply.getPaymentWayCode().equals("B")) {
                    // 付款方式.编码
                    dataHead.setM4p4_pay_type_number("101");
                } else if (!paymentCodApply.getCompanyCode().equals(paymentCodApply.getPaymentCompanyCode()) && paymentCodApply.getPaymentWayCode().equals("B")) {
                    // 付款方式.编码
                    dataHead.setM4p4_pay_type_number("105");
                } else if (paymentCodApply.getPaymentWayCode().equals("C")) {
                    // 付款方式.编码
                    dataHead.setM4p4_pay_type_number("201");
                } else if (paymentCodApply.getPaymentWayCode().equals("D")) {
                    // 付款方式.编码
                    dataHead.setM4p4_pay_type_number("701");
                }
                // 备注
                dataHead.setM4p4_remarks(paymentCodApply.getApplyRemark());
                // 经办人.工号
                dataHead.setM4p4_handler_number("admin".equals(paymentCodApply.getOaHandlerCode()) ? "ID-000005" : paymentCodApply.getOaHandlerCode());
                dataHead.setCreator_number("admin".equals(LoginUtil.getAccount()) ? "ID-000005" : LoginUtil.getAccount());
                // 付款币种.货币代码
                dataHead.setPaycurrency_number(paymentCodApply.getCurrencyCode());
                // 结算币.货币代码
                dataHead.setSettlecurrency_number(paymentCodApply.getCurrencyCode());
                // 汇率表.编码
//                dataHead.setExratetable_number("");
                // 汇率日期
//                dataHead.setExratedate("");
                // 换算方式
//                dataHead.setQuotation("");

                // 已付款金额
                BigDecimal actualPayAmount = paymentPlanLogic.findSupplierPaymentPlanSummary(paymentCodApply.getSupplierCode(), paymentCodApply.getCompanyCode(), 1,"Y");

                dataHead.setM4p4_amt_paid(actualPayAmount == null ? "0" : actualPayAmount.stripTrailingZeros().toPlainString());
                // 申请金额
                dataHead.setApplyamount(paymentCodApply.getOaBorrowMoney() == null ? "0" : paymentCodApply.getOaBorrowMoney().stripTrailingZeros().toPlainString());
                // 折扣总金额
                dataHead.setM4p4_discount_amt_sum((paymentCodApply.getOaBorrowMoney() == null ? BigDecimal.ZERO : paymentCodApply.getOaBorrowMoney()).subtract(paymentCodApply.getActualityPayMoney() == null ? BigDecimal.ZERO : paymentCodApply.getActualityPayMoney()).stripTrailingZeros().toPlainString());
                // 应付总金额
                dataHead.setM4p4_pay_amt_amt(paymentCodApply.getActualityPayMoney() == null ? "0" : paymentCodApply.getActualityPayMoney().stripTrailingZeros().toPlainString());
                dataHead.setM4p4_ex_planamt(paymentCodApply.getPayPlanMoney() == null ? "0" : paymentCodApply.getPayPlanMoney().stripTrailingZeros().toPlainString());
                dataHead.setM4p4_intelbank_code(StringUtils.isNotEmpty(paymentCodApply.getBankInterCode()) ? paymentCodApply.getBankInterCode() : "");
                // 申请金额折结算币
//                dataHead.setAppseleamount("");
//                // 交易类型.编码
//                dataHead.setM4p4_crosstrantype_number("");
//                // 核准金额
                dataHead.setApprovalamount(paymentCodApply.getActualityPayMoney()== null ? "0" : paymentCodApply.getActualityPayMoney().stripTrailingZeros().toPlainString());
                //逾期款项
                dataHead.setM4p4_overdue_payamt(paymentCodApply.getOverdueAmount() == null ? "0" : paymentCodApply.getOverdueAmount().stripTrailingZeros().toPlainString());
                //到期款项
                dataHead.setM4p4_due_payamt(paymentCodApply.getDueAmount() == null ? "0" : paymentCodApply.getDueAmount().stripTrailingZeros().toPlainString());
                //应付账款余额
                dataHead.setM4p4_ac_paybalance(paymentCodApply.getAccountsPayableBalance() == null ? "0" : paymentCodApply.getAccountsPayableBalance().stripTrailingZeros().toPlainString());
                //暂估余额
                dataHead.setM4p4_estimate_balance(paymentCodApply.getProvisionalBalance() == null ? "0" : paymentCodApply.getProvisionalBalance().stripTrailingZeros().toPlainString());
                //代收
                dataHead.setM4p4_collection(String.valueOf(paymentCodApply.getCollectionFlag()));
                //
                dataHead.setFeepayer(paymentCodApply.getFeePayer());
                dataHead.setM4p4_pay_behalf(paymentCodApply.getCompanyCode().equals(paymentCodApply.getPaymentCompanyCode())?"0":"1");
                dataHead.setM4p4_emergency_degree(String.valueOf(paymentCodApply.getUrgentFlag()));
//                // 核准金额折结算币
//                dataHead.setAprseleamount("");

                //代收供应商
                dataHead.setM4p4_agency_supplier_number(paymentCodApply.getPaymentSupplierCode());

                List<PayImportToOpenDTO.Entry> entryList = new ArrayList<>();

                List<CreatePcaDetailDto> pcaDetailList = this.queryCodApplyInvoiceById(paymentCodApply.getId(), null, paymentCodApply.getBusinessType());
                List<String> businessCodeList = new ArrayList<>();
                for (CreatePcaDetailDto pcaDetail : pcaDetailList) {
                    businessCodeList.add(pcaDetail.getAccountStatementNo());
                    PayImportToOpenDTO.Entry entry = new PayImportToOpenDTO.Entry();
                    // 明细.id
                    entry.setId("201-" + String.valueOf(pcaDetail.getId()));
                    // 明细.摘要
                    entry.setM4p4_summary(pcaDetail.getItemRemark());
                    // 明细.付款条件
                    DictDTO dictDTO = paymentMethodCache.get(StringUtils.isNotEmpty(pcaDetail.getIpwCode()) ? pcaDetail.getIpwCode() : "");
                    entry.setM4p4_pay_term(ObjectUtil.isNotNull(dictDTO) ? dictDTO.getName() : "");
                    // 明细.报关公司
                    entry.setM4p4_custom_broker(pcaDetail.getSupplierCode2());
                    // 明细.已申请金额
                    entry.setM4p4_applied_amt(pcaDetail.getAlreadyApplyAmount() == null ? "0" : pcaDetail.getAlreadyApplyAmount().setScale(2, RoundingMode.HALF_UP).stripTrailingZeros().toPlainString());
                    // 明细.折扣金额
                    entry.setM4p4_discount_amt(pcaDetail.getDiscountMoney() == null ? "0" : pcaDetail.getDiscountMoney().setScale(2, RoundingMode.HALF_UP).stripTrailingZeros().toPlainString());
                    // 明细.本次申请金额
                    entry.setM4p4_applied_amt_e(pcaDetail.getBudOutMoney() == null ? "0" : pcaDetail.getBudOutMoney().setScale(2, RoundingMode.HALF_UP).stripTrailingZeros().toPlainString());
                    // 明细.可申请金额
                    entry.setM4p4_applied_amt_a(pcaDetail.getApplyAmount() == null ? "0" : pcaDetail.getApplyAmount().setScale(2, RoundingMode.HALF_UP).stripTrailingZeros().toPlainString());
                    // 明细.冲账金额
                    entry.setM4p4_offset_amt(pcaDetail.getStrikePriceAmount() == null ? "0" : pcaDetail.getStrikePriceAmount().setScale(2, RoundingMode.HALF_UP).stripTrailingZeros().toPlainString());
                    // 明细.付款到期日
                    entry.setM4p4_pay_due_date(pcaDetail.getPaymentExpireDate() == null ? null : LocalDateTimeUtil.format(pcaDetail.getPaymentExpireDate(), "yyyy-MM-dd"));
                    // 明细.付款到期日
                    entry.setE_expaydate(pcaDetail.getExpectationPaymentDate() == null ? "" : LocalDateTimeUtil.format(pcaDetail.getExpectationPaymentDate(), "yyyy-MM-dd"));
                    // 明细.采购组
                    if (StrUtil.isNotEmpty(pcaDetail.getPurchaseGroup())) {
                        PurchaseGroupDTO purchaseGroupDTO = purchaseGroupClient.getByCode(pcaDetail.getPurchaseGroup());
                        entry.setM4p4_procure_group(ObjectUtil.isNotNull(purchaseGroupDTO) ? StrUtil.format("({}){}", purchaseGroupDTO.getPurchaseGroupCode(), purchaseGroupDTO.getPurchaseGroupName()) : "");
                    } else {
                        entry.setM4p4_procure_group("");
                    }
                    // 明细.开票申请单号
                    entry.setM4p4_inv_apply(pcaDetail.getInvoiceNo());
                    // 明细.对账单号
                    entry.setM4p4_statementnumber(pcaDetail.getAccountStatementNo());
                    // 明细.申请金额
                    entry.setE_applyamount(pcaDetail.getBudOutMoney() == null ? "0" : pcaDetail.getBudOutMoney().setScale(2, RoundingMode.HALF_UP).stripTrailingZeros().toPlainString());
                    //含税金额
                    entry.setM4p4_taxandamt(pcaDetail.getItAmount() == null ? "0" : pcaDetail.getItAmount().setScale(2, RoundingMode.HALF_UP).stripTrailingZeros().toPlainString());
                    // 明细.税率
                    TaxDTO taxDTO = taxClient.getByCode(pcaDetail.getTaxCode());
                    if (ObjectUtil.isNotNull(taxDTO)) {
                        //获取taxName中的数字，前面加上V
                        String taxCode = "V" + taxDTO.getTaxName().chars()
                                .filter(Character::isDigit)
                                .mapToObj(c -> String.valueOf((char) c))
                                .collect(Collectors.joining());

                        entry.setM4p4_taxrate_number(taxCode);
                    }
                    // 明细.申请金额折结算币
//                    entry.setE_appseleamount("");
                    //TODO 付款类型.编码
                    entry.setE_paymenttype_number("201");
                    // 明细.往来类型
                    entry.setE_asstacttype("bd_supplier");
                    // 往来户.编码
                    entry.setE_asstact_number(paymentCodApply.getSupplierCode());
                    entry.setE_settlementtype_number(dataHead.getM4p4_pay_type_number());
                    entry.setM4p4_supplier_number(paymentCodApply.getSupplierCode());
                    if (pcaDetail.getDiscountMoney()==null){
                        pcaDetail.setDiscountMoney(BigDecimal.ZERO);
                    }
                    // 结算方式.编码
//                    entry.setE_settlementtype_number("");
                    // 明细.实际应付金额
                    entry.setE_payamount(pcaDetail.getBudOutMoney().stripTrailingZeros().toPlainString());
                    // 明细.核准金额
                    entry.setE_approvedamt(pcaDetail.getBudOutMoney().subtract(pcaDetail.getDiscountMoney()).stripTrailingZeros().toPlainString());
                    //明细.对账合并影像

                    entry.setM4p4_reconcilia_image(pcaDetail.getImageAllCode());
                    if (paymentCodApply.getBusinessType().equals("001")){
                        if (StrUtil.isEmpty(pcaDetail.getImageAllCode())){
                            InvoicedApply invoicedApply = invoicedApplyService.getOne(new LambdaQueryWrapper<>(InvoicedApply.class)
                                    .eq(InvoicedApply::getInvoiceApplyNo, pcaDetail.getInvoiceNo()));
                            if (ObjectUtil.isNotNull(invoicedApply)){
                                String accountImageCode = invoicedApplyLogic.toAllImg(invoicedApply.getId());
                                entry.setM4p4_reconcilia_image(accountImageCode);
                            }
                        }
                    }else if (paymentCodApply.getBusinessType().equals("002")){
                        entry.setM4p4_reconcilia_image(pcaDetail.getInvoicedImageCode());
                    }

                    //明细.开票影像
                    entry.setM4p4_invoice_image(pcaDetail.getInvoicedImageCode());
                    // 明细.核准金额折结算币
//                    entry.setE_approvedseleamt("");

                    entryList.add(entry);
                }
                dataHead.setEntry(entryList);


                AttachmentManualCheckQuery query = new AttachmentManualCheckQuery();
                query.setCurrencyCode(paymentCodApply.getCurrencyCode());
                query.setPaymentWay(paymentCodApply.getPaymentWayCode());
                query.setBusinessCodes(Joiner.on(",").join(businessCodeList));
                //businessType==='001'?1:businessType==='002'?2:businessType==='005'?3:1
                query.setBusinessType(paymentCodApply.getBusinessType().equals("001")?1:
                        paymentCodApply.getBusinessType().equals("002")?2:paymentCodApply.getBusinessType().equals("005")?3:1);

                List<AttachmentManualCheckDTO> attachmentTypeConfigDTOList = attachmentManualCheckLogic.findByPaymentList(query);

                List<PayImportToOpenDTO.Entry2> entryList2 = new ArrayList<>();
                attachmentTypeConfigDTOList.forEach(attachmentTypeConfigDTO -> {
                    PayImportToOpenDTO.Entry2 entry3 = new PayImportToOpenDTO.Entry2();
                    entry3.setM4p4_complete(String.valueOf(attachmentTypeConfigDTO.getManualCheck()));
                    entry3.setM4p4_attachment_type(attachmentTypeConfigDTO.getTypeName());
                    entryList2.add(entry3);
                });
                dataHead.setM4p4_3ord_matc_entry(entryList2);


                //pcaDetailList中根据期望付款日进行分组
                Map<LocalDateTime, List<CreatePcaDetailDto>> pcaDetailListMap = pcaDetailList.stream().collect(Collectors.groupingBy(CreatePcaDetailDto::getExpectationPaymentDate));
                List<PayImportToOpenDTO.Entry3> entryList3 = new ArrayList<>();
                pcaDetailListMap.forEach((key, value) -> {
                    //根据期望付款日统计本次申请金额
                    BigDecimal applyAmount = BigDecimal.ZERO;
                    BigDecimal autalApplyAmount = BigDecimal.ZERO;
                    for (CreatePcaDetailDto pcaDetail : value){
                        if (pcaDetail.getDiscountMoney()==null){
                            pcaDetail.setDiscountMoney(BigDecimal.ZERO);
                        }
                        applyAmount = applyAmount.add(pcaDetail.getBudOutMoney());
                        autalApplyAmount = autalApplyAmount.add(pcaDetail.getBudOutMoney().subtract(pcaDetail.getDiscountMoney()));
                    }
                    //根据期望付款日合并对账单号，“/”隔开
                    String accountStatementNo = value.stream().map(CreatePcaDetailDto::getAccountStatementNo).collect(Collectors.joining("/"));
                    PayImportToOpenDTO.Entry3 entry3 = new PayImportToOpenDTO.Entry3();
                    entry3.setM4p4_approved_amount(autalApplyAmount.stripTrailingZeros().toPlainString());
                    entry3.setM4p4_account_number(accountStatementNo);
//                    entry3.setM4p4_purchase_num(accountStatementNo);
                    entry3.setM4p4_ex_payment_date(LocalDateTimeUtil.format( key, "yyyy-MM-dd"));
                    entry3.setM4p4_settlement_modes_number(dataHead.getM4p4_pay_type_number());
                    entry3.setM4p4_srm_entry_id(String.valueOf(value.get(0).getId()));

                    entry3.setSeq(String.valueOf(value.get(0).getId()));
                    entry3.setE_paymenttype_number("201");
                    entry3.setE_asstact_number(paymentCodApply.getSupplierCode());
                    entry3.setE_applyamount(applyAmount.stripTrailingZeros().toPlainString());
                    entry3.setE_asstacttype("bd_supplier");
                    entryList3.add(entry3);
                });
                dataHead.setM4p4_srm_entry(entryList3);



                payImportToOpenDTO.setData(dataHead);
                ErpApiResult<PayImportToOpenResultDTO> result = paymentOaClient.payImportToOpen(accessToken, payImportToOpenDTO);
                if (!result.getStatus()) {
                    redisTemplate.delete(lockKey);
                    throw new DaoException("金蝶系统接口报错：" + result.getMessage());
                }
                String id = result.getData().getResult().get(0).getId();
                String code = result.getData().getResult().get(0).getNumber();
                paymentCodApply.setOaProcessId(id);
                paymentCodApply.setOaProcessCode(code);
                paymentCodApply.setStatus(3);
                paymentCodApplyService.updateById(paymentCodApply);
                redisTemplate.delete(lockKey);
            }
        }
    }

    @Override
    public void toImg(String id) {
        PaymentCodApply paymentCodApply = paymentCodApplyService.getById(id);
        List<String> fileList = new ArrayList<>();
        if (StringUtils.isNotEmpty(paymentCodApply.getFiles())){
            fileList.addAll(Arrays.asList(paymentCodApply.getFiles().split(",")));
        }
        if (StringUtils.isNotEmpty(paymentCodApply.getPaymentFiles())){
            fileList.addAll(Arrays.asList(paymentCodApply.getPaymentFiles().split(",")));
        }
        if (CollUtil.isNotEmpty(fileList)) {
            List<FileResposeCDTO> fileResposeCDTOList = fileClient.getFileInfos(fileList);
            if (CollUtil.isNotEmpty(fileResposeCDTOList)) {
                KingdeeInvoiceCloudImageDTO kingdeeInvoiceCloudImageDTO = new KingdeeInvoiceCloudImageDTO();
                kingdeeInvoiceCloudImageDTO.setImageCode(StrUtil.isNotEmpty(paymentCodApply.getImgCode())?paymentCodApply.getImgCode():sequenceClient.createSequenceNo("image_code"));
                if (CollUtil.isNotEmpty(fileResposeCDTOList)) {
                    List<BusinessAttachmentDTO> businessAttachmentList = new ArrayList<>();
                    fileResposeCDTOList.forEach(file -> {
                        BusinessAttachmentDTO businessAttachmentDTO = new BusinessAttachmentDTO();
                        businessAttachmentDTO.setFileId(file.getId());
                        businessAttachmentDTO.setImageFileId(file.getImageFileId());
                        businessAttachmentDTO.setType("payment_advance_apply");
                        businessAttachmentDTO.setFileName(file.getFileName());
                        businessAttachmentList.add(businessAttachmentDTO);
                    });
                    kingdeeInvoiceCloudImageDTO.setBusinessAttachmentList(businessAttachmentList);
                    KingdeeInvoiceCloudImageDTO result = kingdeeImageLogic.pushImage(kingdeeInvoiceCloudImageDTO);
                    //更新影像
                    fileResposeCDTOList.forEach(accountStatementAttachment -> {
                        result.getBusinessAttachmentList().forEach(businessAttachmentDTO -> {
                            if (businessAttachmentDTO.getFileId().equals(accountStatementAttachment.getId())) {
                                attachmentService.update(new LambdaUpdateWrapper<Attachment>()
                                        .set(Attachment::getImageCode, result.getImageCode())
                                        .set(Attachment::getImagePath, result.getImagePath())
                                        .set(Attachment::getImageFileId, businessAttachmentDTO.getImageFileId())
                                        .eq(Attachment::getId, accountStatementAttachment.getId()));
                            }
                        });
                    });
                    paymentCodApplyService.update(new LambdaUpdateWrapper<PaymentCodApply>()
                            .set(PaymentCodApply::getImgCode, result.getImageCode())
                            .set(PaymentCodApply::getImgTime, LocalDateTime.now())
                            .set(PaymentCodApply::getImgUserId, LoginUtil.getUserId())
                            .eq(PaymentCodApply::getId, id));
                }
            }
        }
    }

    /**
     * 删除影像化
     *
     * @param id ID
     */
    @Override
    public void deleteImg(Long id) {
        //删除影像化
        PaymentCodApply paymentCodApply = paymentCodApplyService.getById(id);
        if (ObjectUtil.isNull(paymentCodApply.getImgTime())){
            return;
        }
        if (StringUtils.isNotEmpty(paymentCodApply.getImgCode())&&paymentCodApply.getImgTime()!=null) {
            KingdeeInvoiceCloudImageDTO kingdeeInvoiceCloudImageDTO = new KingdeeInvoiceCloudImageDTO();
            kingdeeInvoiceCloudImageDTO.setImageCode(paymentCodApply.getImgCode());
            kingdeeImageLogic.deleteAllImage(kingdeeInvoiceCloudImageDTO);
            paymentCodApplyService.update(new LambdaUpdateWrapper<PaymentCodApply>()
//                        .set(InvoicedApply::getImgCode,null)
                    .set(PaymentCodApply::getImgTime,null)
                    .set(PaymentCodApply::getImgUserId,null)
                    .eq(PaymentCodApply::getId,id));
        }

    }

    @Override
    public void clearOaNumber(String ids) {
        List<String> idList = Arrays.asList(StringUtils.split(ids, ","));
        List<PaymentCodApply> paymentCodApplyList = paymentCodApplyService.listByIds(idList);
        //修改
        LambdaUpdateWrapper<PaymentCodApply> updateWrapper =
                new LambdaUpdateWrapper<PaymentCodApply>().set(PaymentCodApply::getOaProcessCode, "").set(PaymentCodApply::getOaProcessId, "").set(PaymentCodApply::getOaProcessMessage, LoginUtil.getCurrentUser().getLoginName() + "清除了流程ID").in(PaymentCodApply::getId, idList);
        paymentCodApplyService.update(updateWrapper);


    }

    /**
     * 重新计算汇总
     *
     * @param headData
     */
    @Override
    public String initPaymentPlanSummary(PaymentCodApply headData, Boolean flag) {
        String paymentExpireStr = DateUtils.formatYYYYMMDDDash(headData.getCreateTime());
        PaymentPlan paymentPlan = paymentPlanService.getOne(new LambdaQueryWrapper<PaymentPlan>()
                .eq(PaymentPlan::getPaymentPlanYear, paymentExpireStr.split("-")[0])
                .eq(PaymentPlan::getPaymentPlanMonth, paymentExpireStr.split("-")[1]));
        if (Objects.nonNull(paymentPlan) && paymentPlan.getStatus() == 6) {
            PaymentPlanQuery paymentPlanQuery = new PaymentPlanQuery();
            paymentPlanQuery.setPpId(paymentPlan.getId() + "");
            paymentPlanQuery.setSupplierCode(headData.getSupplierCode());
            paymentPlanQuery.setCompanyCode(headData.getCompanyCode());
            paymentPlanQuery.setPaymentType("D");

            List<PaymentPlanSummary> paymentPlanSummaryList = paymentPlanSummaryService.findPaymentPlanSummaryBySupplier(paymentPlanQuery);
            PaymentPlanSummary paymentPlanSummary = (null != paymentPlanSummaryList && paymentPlanSummaryList.size() > 0) ? paymentPlanSummaryList.get(0) : null;

            AccountStatementQuery accountStatementQuery = new AccountStatementQuery();
            accountStatementQuery.setSupplierCode(headData.getSupplierCode());
            accountStatementQuery.setCompanyCode(headData.getCompanyCode());
            accountStatementQuery.setAccountStatementYear(paymentExpireStr.split("-")[0] + paymentExpireStr.split("-")[1]);
            List<AccountStatementPO> accountStatementPOS = accountStatementService.findAccountStatementBySupplierCodeD(accountStatementQuery);
            //计算总额
            final BigDecimal[] budOutMoney = {BigDecimal.ZERO};
            accountStatementPOS.stream().forEach(oo -> {
                if (null != oo.getActualUnpaidAmount()) {
                    budOutMoney[0] = budOutMoney[0].add(oo.getActualUnpaidAmount());
                }
            });


            if (Objects.nonNull(paymentPlanSummary)) {
                paymentPlanSummary.setAppliedPaymentAmount(budOutMoney[0]);
                if (paymentPlanSummary.getActualPayAmount() != null && paymentPlanSummary.getActualPayAmount().floatValue() > 0) {
                    paymentPlanSummary.setDifferenceAmount(paymentPlanSummary.getAppliedPaymentAmount().subtract(paymentPlanSummary.getActualPayAmount()));
                    MathContext mc = new MathContext(4, RoundingMode.HALF_UP);
                    BigDecimal result = paymentPlanSummary.getDifferenceAmount().divide(paymentPlanSummary.getActualPayAmount(), mc);
                    paymentPlanSummary.setDifferencePercent(result);
                } else {
                    paymentPlanSummary.setDifferenceAmount(paymentPlanSummary.getAppliedPaymentAmount());
                    paymentPlanSummary.setDifferencePercent(new BigDecimal(1.00));
                }
                if (null != paymentPlanSummary.getNewSign() && "X".equals(paymentPlanSummary.getNewSign()) && flag) {
                    String remark = paymentPlanSummary.getRemark();
                    if (StringUtils.isEmpty(remark)) {
                        paymentPlanSummary.setRemark(headData.getApplyRemark() == null ? "" : headData.getApplyRemark());
                    } else {
                        paymentPlanSummary.setRemark(paymentPlanSummary.getRemark() + "," + headData.getApplyRemark());
                    }
                }
                paymentPlanSummaryService.saveOrUpdate(paymentPlanSummary);
            } else {
                paymentPlanSummary = new PaymentPlanSummary();
                paymentPlanSummary.setPaymentPlanNo(paymentPlan.getPaymentPlanNo());
                paymentPlanSummary.setPaymentPlanId(paymentPlan.getId());
                paymentPlanSummary.setSupplierCode(headData.getSupplierCode());
                paymentPlanSummary.setSupplierName(headData.getSupplierName());
                paymentPlanSummary.setCurrencyCode(headData.getCurrencyCode());
                paymentPlanSummary.setCompanyCode(headData.getCompanyCode());
                paymentPlanSummary.setCompanyName(headData.getCompanyName());
                //应付金额
                paymentPlanSummary.setActualPayAmount(BigDecimal.ZERO);
                paymentPlanSummary.setAppliedUnpaidAmount(BigDecimal.ZERO);

                paymentPlanSummary.setAppliedPaymentAmount(budOutMoney[0]);
                paymentPlanSummary.setDifferenceAmount(paymentPlanSummary.getAppliedPaymentAmount());
                paymentPlanSummary.setDifferencePercent(new BigDecimal(1.00));


                paymentPlanSummary.setPaidAmountMonth(BigDecimal.ZERO);
                paymentPlanSummary.setCreateUserId(LoginUtil.getUserId());
                paymentPlanSummary.setCreateUserCode(LoginUtil.getAccount());
                paymentPlanSummary.setCreateUserName(LoginUtil.getName());
                paymentPlanSummary.setCreateTime(LocalDateTime.now());
                paymentPlanSummary.setNewSign("X");
                paymentPlanSummary.setPaymentType("D");
                paymentPlanSummary.setRemark(headData.getApplyRemark());
                paymentPlanSummaryService.saveOrUpdate(paymentPlanSummary);
            }
        } else if (flag) {
            return "F";
        }
        return "S";
    }

    @Override
    public void sendEmailCollection(Long id) {
        PaymentCodApply paymentCodApply = paymentCodApplyService.getById(id);
        //如果状态不为新建不允许发布
        if (paymentCodApply.getStatus()!=7){
            throw new DaoException("只有待付款状态的单据才能汇票催收");
        }
        if (!paymentCodApply.getPaymentWayCode().equals("C")){
            throw new DaoException("付款方式只有承兑汇票的单据才能汇票催收");
        }

        Set<String> emailList = new HashSet<>();
        UserDTO userDTO = userClient.getByUserId(paymentCodApply.getCreateUserId());
        if (ObjectUtil.isNotEmpty(userDTO)&&StringUtils.isNotEmpty(userDTO.getEmail())){
            emailList.add(userDTO.getEmail());
        }
        //1，财务驳回发票交接，增加邮件提醒，  邮件收件人：供应商（(4)财务人员、(12)业务接口人、(5)业务经理）、对账采购组窗口
        SupplierContactsDTO emailBis = supplierClient.getDefaultContact(paymentCodApply.getSupplierCode(), "12");
        SupplierContactsDTO emailFin = supplierClient.getDefaultContact(paymentCodApply.getSupplierCode(), "4");
        SupplierContactsDTO emailJl = supplierClient.getDefaultContact(paymentCodApply.getSupplierCode(), "5");
        if (Objects.nonNull(emailBis) && StringUtils.isNotEmpty(emailBis.getEmail())) {
            emailList.add(emailBis.getEmail());
        }
        if (Objects.nonNull(emailFin) && StringUtils.isNotEmpty(emailFin.getEmail())) {
            emailList.add(emailFin.getEmail());
        }
        if (Objects.nonNull(emailJl) && StringUtils.isNotEmpty(emailJl.getEmail())) {
            emailList.add(emailJl.getEmail());
        }
        if (CollUtil.isNotEmpty(emailList)){
            for (String mapKey : emailList){
                final EmailTmpSingleSendDTO emailTxtSingleSendDTO = new EmailTmpSingleSendDTO();
                emailTxtSingleSendDTO.setTemplateCode("JW_POST_200");
                Map<String, Object> params = Maps.newHashMap();
                CompanyDTO companyDTO = companyClient.getByCode(paymentCodApply.getCompanyCode());
                paymentCodApply.setCompanyName(companyDTO.getCompanyName());
                params.put("data",paymentCodApply);
                params.put("createTime", DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
                emailTxtSingleSendDTO.setParams(params);
                emailTxtSingleSendDTO.setReceiver(mapKey);
                emailTxtSingleSendDTO.setSender(LoginUtil.getUserId());
                emailSendClient.async(emailTxtSingleSendDTO);
            }
            paymentCodApply.setSendEmailCollectionFlag(1);
            paymentCodApplyService.updateById(paymentCodApply);
        }else {
            throw new DaoException("未找到可发送的邮箱，请检查创建人和供应商是否配置邮箱");
        }
    }

    @Override
    public void initPaymentPlanSummary(PaymentCodApply headData, int action) {
        List<Long> appIdList = Lists.newArrayList();
        appIdList.add(headData.getId());
        List<PaymentCodApplyDetail> details = paymentCodApplyDetailService.findByPaymentDetail(appIdList);
        if (action == 3) {
            details.stream().forEach(item -> {
                initPaymentPlanSummary(null, item, headData, action);
            });
            //付款申请oa审批通过，付款计划，本月已付款金额需要同步修改。
        } else {
            details.stream().forEach(item -> {
                initPaymentPlanSummary(null, item, headData, action);
            });
        }
    }


    public void initPaymentPlanSummaryDel(PaymentCodApplyDetail codApplyDetailDel, List<PaymentCodApply> headDataList) {
        for (PaymentCodApply paymentCodApply : headDataList) {
            if (codApplyDetailDel.getCppId() == paymentCodApply.getId()) {
                initPaymentPlanSummary(null, codApplyDetailDel, paymentCodApply, 3);
                break;
            }
        }
    }

    public void initPaymentPlanSummary(PaymentCodApplyDetail codApplyDetailAdd, PaymentCodApplyDetail codApplyDetailDel, PaymentCodApply headData, int action) {
        //查询对账单的付款到期日
//        AccountStatementQuery query = new AccountStatementQuery();
//        query.setStatementNo(codApplyDetailAdd == null?codApplyDetailDel.getAccountStatementNo():codApplyDetailAdd.getAccountStatementNo());
//        List<AccountStatementPO> accountStatementList = accountStatementService.accountOrApplyListByNo(query);
        //请款明细有金额有新增时，需要更新付款计划汇总，增加付款计划汇总的本月已请款金额， fin_payment_plan_summary applied_payment_amount 2025-07-30 邓京术
        //取本次申请金额
        BigDecimal budOutMoney = codApplyDetailAdd == null ? codApplyDetailDel.getBudOutMoney() : codApplyDetailAdd.getBudOutMoney();
        //先根据供应商及公司，付款年月 去付款汇总表中查询是否有付款计划汇总，如果没有则要新增一笔付款计划汇总
//        PaymentPlan paymentPlan = null;
//        if (Objects.nonNull(accountStatementList) && accountStatementList.size() > 0 && null != accountStatementList.get(0).getPaymentExpireDate()) {
        Calendar cl = Calendar.getInstance();
        String paymentExpireStr = DateUtils.formatYYYYMMDDDash(cl.getTime());
        PaymentPlan paymentPlan = paymentPlanService.getOne(new LambdaQueryWrapper<PaymentPlan>()
                .eq(PaymentPlan::getPaymentPlanYear, paymentExpireStr.split("-")[0])
                .eq(PaymentPlan::getPaymentPlanMonth, paymentExpireStr.split("-")[1]));
//        }
        if (Objects.nonNull(paymentPlan) && paymentPlan.getStatus() == 6) {
            PaymentPlanQuery paymentPlanQuery = new PaymentPlanQuery();
            paymentPlanQuery.setPpId(paymentPlan.getId() + "");
            paymentPlanQuery.setSupplierCode(headData.getSupplierCode());
            paymentPlanQuery.setCompanyCode(headData.getCompanyCode());
            paymentPlanQuery.setPaymentType("D");

            List<PaymentPlanSummary> paymentPlanSummaryList = paymentPlanSummaryService.findPaymentPlanSummaryBySupplier(paymentPlanQuery);
            PaymentPlanSummary paymentPlanSummary = (null != paymentPlanSummaryList && paymentPlanSummaryList.size() > 0) ? paymentPlanSummaryList.get(0) : null;
            if (Objects.nonNull(paymentPlanSummary)) {
                //删除操作
                if (action == 3) {
                    //设置本月已付款金额(本月已请款金额)
                    paymentPlanSummary.setAppliedPaymentAmount(
                            paymentPlanSummary.getAppliedPaymentAmount() == null ? BigDecimal.ZERO : paymentPlanSummary.getAppliedPaymentAmount().subtract(budOutMoney)
                    );
                    //设置差异比例
                    if (paymentPlanSummary.getActualPayAmount() != null && paymentPlanSummary.getActualPayAmount().floatValue() > 0) {
                        paymentPlanSummary.setDifferenceAmount(paymentPlanSummary.getAppliedPaymentAmount().subtract(paymentPlanSummary.getActualPayAmount()));
                        paymentPlanSummary.setDifferencePercent(paymentPlanSummary.getDifferenceAmount().divide(paymentPlanSummary.getActualPayAmount(), 2));
                    } else {
                        paymentPlanSummary.setDifferenceAmount(paymentPlanSummary.getAppliedPaymentAmount());
                        paymentPlanSummary.setDifferencePercent(new BigDecimal(1.00));
                    }
                } else if (action == 1) {
                    //如果请款金额与之前的保持一致，则不做任何动作
                    if (null != codApplyDetailDel && budOutMoney.floatValue() != codApplyDetailDel.getBudOutMoney().floatValue()) {
                        //设置本月已付款金额(本月已请款金额)
                        paymentPlanSummary.setAppliedPaymentAmount(
                                paymentPlanSummary.getAppliedPaymentAmount() == null ? budOutMoney : paymentPlanSummary.getAppliedPaymentAmount().add(budOutMoney)
                        );
                        //设置差异比例
                        if (paymentPlanSummary.getActualPayAmount() != null && paymentPlanSummary.getActualPayAmount().floatValue() > 0) {
                            paymentPlanSummary.setDifferenceAmount(paymentPlanSummary.getAppliedPaymentAmount().subtract(paymentPlanSummary.getActualPayAmount()));
                            paymentPlanSummary.setDifferencePercent(paymentPlanSummary.getDifferenceAmount().divide(paymentPlanSummary.getActualPayAmount(), 2));
                        } else {
                            paymentPlanSummary.setDifferenceAmount(paymentPlanSummary.getAppliedPaymentAmount());
                            paymentPlanSummary.setDifferencePercent(new BigDecimal(1.00));
                        }
                        if (null != paymentPlanSummary.getNewSign() && "X".equals(paymentPlanSummary.getNewSign())) {
                            paymentPlanSummary.setRemark(paymentPlanSummary.getRemark() + "\n\r" + headData.getApplyRemark());
                        }

                        //设置本月已付款金额(本月已请款金额)
                        paymentPlanSummary.setAppliedPaymentAmount(
                                paymentPlanSummary.getAppliedPaymentAmount() == null ? BigDecimal.ZERO : paymentPlanSummary.getAppliedPaymentAmount().subtract(codApplyDetailDel.getBudOutMoney())
                        );
                        //设置差异比例
                        if (paymentPlanSummary.getActualPayAmount() != null && paymentPlanSummary.getActualPayAmount().floatValue() > 0) {
                            paymentPlanSummary.setDifferenceAmount(paymentPlanSummary.getAppliedPaymentAmount().subtract(paymentPlanSummary.getActualPayAmount()));
                            paymentPlanSummary.setDifferencePercent(paymentPlanSummary.getDifferenceAmount().divide(paymentPlanSummary.getActualPayAmount(), 2));
                        } else {
                            paymentPlanSummary.setDifferenceAmount(paymentPlanSummary.getAppliedPaymentAmount());
                            paymentPlanSummary.setDifferencePercent(new BigDecimal(1.00));
                        }
                        paymentPlanSummaryService.saveOrUpdate(paymentPlanSummary);
                        //如果没有修改，则只做新增操作
                    } else {
                        //设置本月已付款金额(本月已请款金额)
                        paymentPlanSummary.setAppliedPaymentAmount(
                                paymentPlanSummary.getAppliedPaymentAmount() == null ? budOutMoney : paymentPlanSummary.getAppliedPaymentAmount().add(budOutMoney)
                        );
                        //设置差异比例
                        if (paymentPlanSummary.getActualPayAmount() != null && paymentPlanSummary.getActualPayAmount().floatValue() > 0) {
                            paymentPlanSummary.setDifferenceAmount(paymentPlanSummary.getAppliedPaymentAmount().subtract(paymentPlanSummary.getActualPayAmount()));
                            paymentPlanSummary.setDifferencePercent(paymentPlanSummary.getDifferenceAmount().divide(paymentPlanSummary.getActualPayAmount(), 2));
                        } else {
                            paymentPlanSummary.setDifferenceAmount(paymentPlanSummary.getAppliedPaymentAmount());
                            paymentPlanSummary.setDifferencePercent(new BigDecimal(1.00));
                        }
                        if (null != paymentPlanSummary.getNewSign() && "X".equals(paymentPlanSummary.getNewSign())) {
                            paymentPlanSummary.setRemark(paymentPlanSummary.getRemark() + "\n\r" + headData.getApplyRemark());
                        }
                        paymentPlanSummaryService.saveOrUpdate(paymentPlanSummary);
                    }
                } else if (action == 4) {
                    //更新本月已付款金额
                    paymentPlanSummary.setPaidAmountMonth(paymentPlanSummary.getPaidAmountMonth() == null ? budOutMoney : paymentPlanSummary.getPaidAmountMonth().add(budOutMoney));
                    paymentPlanSummaryService.saveOrUpdate(paymentPlanSummary);
                }
            } else if (action == 1) {
                paymentPlanSummary = new PaymentPlanSummary();
                paymentPlanSummary.setPaymentPlanNo(paymentPlan.getPaymentPlanNo());
                paymentPlanSummary.setPaymentPlanId(paymentPlan.getId());
                paymentPlanSummary.setSupplierCode(headData.getSupplierCode());
                paymentPlanSummary.setSupplierName(headData.getSupplierName());
                paymentPlanSummary.setCurrencyCode(headData.getCurrencyCode());
                paymentPlanSummary.setCompanyCode(headData.getCompanyCode());
                paymentPlanSummary.setCompanyName(headData.getCompanyName());
                //应付金额
                paymentPlanSummary.setActualPayAmount(BigDecimal.ZERO);
                paymentPlanSummary.setAppliedUnpaidAmount(BigDecimal.ZERO);

                paymentPlanSummary.setAppliedPaymentAmount(budOutMoney);
                paymentPlanSummary.setDifferenceAmount(paymentPlanSummary.getAppliedPaymentAmount());
                paymentPlanSummary.setDifferencePercent(new BigDecimal(1.00));


                paymentPlanSummary.setPaidAmountMonth(BigDecimal.ZERO);
                paymentPlanSummary.setCreateUserId(LoginUtil.getUserId());
                paymentPlanSummary.setCreateUserCode(LoginUtil.getAccount());
                paymentPlanSummary.setCreateUserName(LoginUtil.getName());
                paymentPlanSummary.setCreateTime(LocalDateTime.now());
                paymentPlanSummary.setNewSign("X");
                paymentPlanSummary.setPaymentType("D");
                paymentPlanSummary.setRemark(headData.getApplyRemark());
                paymentPlanSummaryService.saveOrUpdate(paymentPlanSummary);
            }
        }
    }

    /**
     * 设置确认日志
     * @param paymentId 付款ID
     * @param paymentNo 付款编号
     */
    private void setConfirmLog(List<FinPaymentConfirmLog> logDetailList, Long paymentId, String paymentNo) {
        for (FinPaymentConfirmLog log : logDetailList) {
            log.setPaymentId(paymentId);
            log.setPaymentNo(paymentNo);
            log.setWarnCode("WARN");
            log.setUserId(LoginUtil.getUserId());
            log.setUserName(LoginUtil.getName());
            log.setCreatedTime(LocalDateTime.now());
        }
        finPaymentConfirmLogService.saveOrUpdateBatch(logDetailList);
    }
}
