package com.inkasso.factoring.financingmanagement.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.inkasso.adapter.exception.BusinessException;
import com.inkasso.adapter.util.CodeUtil;
import com.inkasso.adapter.web.LoginUserHolder;
import com.inkasso.factoring.acceptanceManagement.entity.CAcceptanceBasicInfo;
import com.inkasso.factoring.acceptanceManagement.entity.CAcceptanceGoodsInfo;
import com.inkasso.factoring.acceptanceManagement.service.ICAcceptanceBasicInfoService;
import com.inkasso.factoring.acceptanceManagement.service.ICAcceptanceGoodsInfoService;
import com.inkasso.factoring.common.entity.GridPage;
import com.inkasso.factoring.common.entity.ResponseJson;
import com.inkasso.factoring.common.enums.ProjectInitiationStatusEnum;
import com.inkasso.factoring.creditmanagement.entity.Enterprise;
import com.inkasso.factoring.creditmanagement.entity.ProjectInformation;
import com.inkasso.factoring.creditmanagement.service.IEnterpriseService;
import com.inkasso.factoring.creditmanagement.service.IProjectInformationService;
import com.inkasso.factoring.dict.service.DictionaryService;
import com.inkasso.factoring.file.entity.FileStorageDO;
import com.inkasso.factoring.file.enums.FileTypeEnum;
import com.inkasso.factoring.file.service.FileService;
import com.inkasso.factoring.financingmanagement.dao.FinancingApplyMapper;
import com.inkasso.factoring.financingmanagement.entity.*;
import com.inkasso.factoring.financingmanagement.entity.vo.*;
import com.inkasso.factoring.financingmanagement.enums.FinancingCurrentStageEnum;
import com.inkasso.factoring.financingmanagement.service.*;
import com.inkasso.factoring.purchManagement.entity.*;
import com.inkasso.factoring.purchManagement.service.*;
import com.inkasso.factoring.salesManagement.entity.CSalesContractBasicInfo;
import com.inkasso.factoring.salesManagement.entity.SalesContractApproval;
import com.inkasso.factoring.salesManagement.entity.SalesContractRetentionInfo;
import com.inkasso.factoring.salesManagement.service.ICSalesContractManagementService;
import com.inkasso.factoring.salesManagement.service.ISalesContractApprovalService;
import com.inkasso.factoring.salesManagement.service.ISalesContractRetentionInfoService;
import com.inkasso.factoring.settlement.entity.SettlementBasicInfo;
import com.inkasso.factoring.settlement.entity.SettlementGoodsInfo;
import com.inkasso.factoring.settlement.service.SettlementBasicInfoService;
import com.inkasso.factoring.settlement.service.SettlementGoodsInfoService;
import com.inkasso.factoring.system.user.entity.UserDO;
import com.inkasso.factoring.system.user.service.UserService;
import com.inkasso.factoring.tradingPlatform.entity.Platform;
import com.inkasso.factoring.tradingPlatform.service.ITradingPlatformService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description :
 * @Author : L.Jia
 * @Date: 2023-12-20 11:22
 */
@Service
public class FinancingApplyServiceImpl implements FinancingApplyService {

    @Autowired
    private ICAcceptanceBasicInfoService acceptanceBasicInfoService;
    @Autowired
    private ICAcceptanceGoodsInfoService acceptanceGoodsInfoService;
    @Autowired
    private SettlementBasicInfoService settlementBasicInfoService;
    @Autowired
    private SettlementGoodsInfoService settlementGoodsInfoService;
    @Autowired
    private ICFinancingBasicInfoService financingBasicInfoService;
    @Autowired
    private ICFinancingGoodsInfoService financingGoodsInfoService;
    @Autowired
    private ICSalesContractManagementService salesContractManagementService;
    @Autowired
    private ISalesContractApprovalService salesContractApprovalService;
    @Autowired
    private ISalesContractRetentionInfoService salesContractRetentionInfoService;
    @Autowired
    private ICPurchContractManagementService purchContractManagementService;
    @Autowired
    private ICPurchContractBasicInfoService purchContractBasicInfoService;
    @Autowired
    private ICPurchContractPriceRuleService purchContractPriceRuleService;
    @Autowired
    private ICPurchContractRetentionInfoService purchContractRetentionInfoService;
    @Autowired
    private ICFinancingAccountsReceivableInfoService financingAccountsReceivableInfoService;
    @Autowired
    private ICFinancingApplicantInfoService financingApplicantInfoService;
    @Autowired
    private ICPurchContractSettlePaymentService purchContractSettlePaymentService;
    @Autowired
    private DictionaryService dictService;
    @Autowired
    private RestTemplate restTemplate;
    @Value("${trade.financingApplyUrl}")
    private String financingApplyUrl;
    @Value("${sop.viewLatestPlanUrl}")
    private String viewLatestPlanUrl;
    @Autowired
    private FinancingApplyMapper financingApplyMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private ICFinancingHisInfoService financingHisInfoService;
    @Autowired
    private ICFinancingHisGoodsInfoService financingHisGoodsInfoService;
    @Autowired
    private ICFinancingHisApplicantInfoService financingHisApplicantInfoService;
    @Autowired
    private ICFinancingHisAccountsReceivableInfoService financingHisAccountsReceivableInfoService;
    @Autowired
    private FileService fileService;
    @Autowired
    private IEnterpriseService enterpriseService;
    @Autowired
    private ITradingPlatformService platformService;
    @Autowired
    private IProjectInformationService projectInformationService;

    @Override
    public GridPage<FinancingApplyListVo> list(FinancingSearch search) {

        search.setSysUserId(LoginUserHolder.get().getId());
        Page<Object> page = PageHelper.startPage(search.getPage(), search.getRows());
        List<FinancingApplyListVo> list = financingApplyMapper.list(search);
        return new GridPage<>(search.getRows(), search.getPage(), page.getTotal(), list);
    }

    @Override
    public GridPage<AcceptanceGoodsInfoVo> findGoodsByAcceptance(GoodsSearch search) {

        CAcceptanceBasicInfo basicInfo = new CAcceptanceBasicInfo();
        basicInfo.setBusinessNumber(search.getBusinessNumber());
        basicInfo.setcSupplierInfoId(search.getSupplierId());


        basicInfo.setAcceptanceStatus(ProjectInitiationStatusEnum.COMPLETED.getCode());
        //取未做底层的数据
        basicInfo.setReceivables(false);

        Page<Object> page = PageHelper.startPage(search.getPage(), search.getRows());
        List<CAcceptanceBasicInfo> list = acceptanceBasicInfoService.findByCondition(basicInfo, false);

        List<AcceptanceGoodsInfoVo> result = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(list)) {
            for (CAcceptanceBasicInfo cAcceptanceBasicInfo : list) {
                AcceptanceGoodsInfoVo vo = new AcceptanceGoodsInfoVo(cAcceptanceBasicInfo);
                if (cAcceptanceBasicInfo.getAcceptanceStatus() != null) {
                    vo.setAcceptanceStatus(dictService.getByCode(cAcceptanceBasicInfo.getAcceptanceStatus()).getName());
                }
                if (cAcceptanceBasicInfo.getSettlement()) {
                    //如果该笔验收单做过结算、直接从结算单获取

                    //获取结算单编号和结算状态
                    List<SettlementGoodsInfo> goodsInfoList = settlementGoodsInfoService.list(new QueryWrapper<SettlementGoodsInfo>()
                            .eq("c_acceptance_basic_info_id", cAcceptanceBasicInfo.getId()));
                    if (CollectionUtil.isNotEmpty(goodsInfoList)) {
                        List<Long> settlementBasicInfoIds = goodsInfoList.stream().map(SettlementGoodsInfo::getSettlementBasicInfoId).distinct().collect(Collectors.toList());
                        SettlementBasicInfo settlementBasicInfo = settlementBasicInfoService.getById(settlementBasicInfoIds.get(0));
                        if (settlementBasicInfo != null) {
                            vo.setSettlementNumber(settlementBasicInfo.getSettlementNumber());
                            vo.setSettlementStatus(dictService.getByCode(settlementBasicInfo.getSettlementStatus()).getName());
                        }
                    }
                    List<SettlementGoodsInfo> settlementGoodsInfoList = settlementGoodsInfoService.list(new QueryWrapper<SettlementGoodsInfo>()
                            .eq("acceptance_goods_number", cAcceptanceBasicInfo.getAcceptanceGoodsNumber()));
                    if (CollectionUtil.isNotEmpty(settlementGoodsInfoList)) {
                        List<CAcceptanceGoodsInfo> acceptanceGoodsInfoList = settlementGoodsInfoList.stream().map(settlementGoodsInfo -> {
                            CAcceptanceGoodsInfo cAcceptanceGoodsInfo = acceptanceGoodsInfoService.getById(settlementGoodsInfo.getAcceptanceGoodsInfoId());
                            cAcceptanceGoodsInfo.setSettlementGoodsInfoId(settlementGoodsInfo.getId());
                            cAcceptanceGoodsInfo.setSettlementBasicInfoId(settlementGoodsInfo.getSettlementBasicInfoId());
                            cAcceptanceGoodsInfo.setSalesPrice(settlementGoodsInfo.getSalesPrice());
                            cAcceptanceGoodsInfo.setSalesTotalPrice(settlementGoodsInfo.getSalesTotalPrice());
                            cAcceptanceGoodsInfo.setSalesGuaranteeMoney(settlementGoodsInfo.getSalesGuaranteeMoney());
                            cAcceptanceGoodsInfo.setPurchasePrice(settlementGoodsInfo.getPurchasePrice());
                            cAcceptanceGoodsInfo.setPurchaseTotalPrice(settlementGoodsInfo.getPurchaseTotalPrice());
                            cAcceptanceGoodsInfo.setPurchGuaranteeMoney(settlementGoodsInfo.getPurchaseGuaranteeMoney());
                            cAcceptanceGoodsInfo.setFloatingPrice(settlementGoodsInfo.getFloatingPrice());
                            cAcceptanceGoodsInfo.setReferencePrice(settlementGoodsInfo.getReferencePrice());
                            return cAcceptanceGoodsInfo;
                        }).collect(Collectors.toList());
                        //计算验收数量
                        BigDecimal acceptanceNumTotal = settlementGoodsInfoList.stream().filter(goods -> goods.getGoodsQuantity() != null).map(SettlementGoodsInfo::getGoodsQuantity)
                                .reduce(BigDecimal.ZERO, BigDecimal::add);
                        vo.setAcceptanceNumTotal(acceptanceNumTotal);
                        //计算结算总价
                        BigDecimal settlementAmountTotal = settlementGoodsInfoList.stream().filter(goods -> goods.getSalesTotalPrice() != null).map(SettlementGoodsInfo::getSalesTotalPrice)
                                .reduce(BigDecimal.ZERO, BigDecimal::add);
                        vo.setSettlementAmountTotal(settlementAmountTotal);
                        vo.setAcceptanceGoodInfos(acceptanceGoodsInfoList);
                    }
                } else {
                    //如果该笔验收单未做过结算
                    List<CAcceptanceGoodsInfo> goodsInfoList = acceptanceGoodsInfoService
                            .list(new QueryWrapper<CAcceptanceGoodsInfo>().eq("acceptance_goods_number", cAcceptanceBasicInfo.getAcceptanceGoodsNumber()));
                    if (CollectionUtil.isNotEmpty(goodsInfoList)) {
                        //计算销售质保金占用
                        BigDecimal occupationSalesRetention = calculateOccupationSalesRetention(cAcceptanceBasicInfo);
                        //计算采购质保金占用
                        BigDecimal occupationPurchRetention = calculateOccupationPurchRetention(cAcceptanceBasicInfo);
                        //计算销售总价、销售质保金、采购总价、采购质保金等
                        calculateGoodsAmount(cAcceptanceBasicInfo.getBusinessNumber(), goodsInfoList);
                        //校正销售质保金金额
                        SalesContractRetentionInfo salesContractRetentionInfo = getSalesContractRetentionInfo(cAcceptanceBasicInfo.getBusinessNumber());
                        if (salesContractRetentionInfo != null && salesContractRetentionInfo.getRetention()) {
                            if (salesContractRetentionInfo.getTop().equals(1)) {
                                //如果质保金有上限，校正销售质保金金额
                                BigDecimal retentionLimit = salesContractRetentionInfo.getRetentionLimit();
                                if (retentionLimit == null) {
                                    throw new BusinessException(CodeUtil.FAIL, "销售质保金上限不能为空");
                                }
                                BigDecimal surplus = retentionLimit.subtract(occupationSalesRetention);
                                if (surplus.compareTo(BigDecimal.ZERO) > 0) {
                                    goodsInfoList = calculateSalesGuaranteeMoney(surplus, goodsInfoList);
                                } else if (surplus.compareTo(BigDecimal.ZERO) == 0) {
                                    for (CAcceptanceGoodsInfo goodsInfo : goodsInfoList) {
                                        goodsInfo.setSalesGuaranteeMoney(BigDecimal.ZERO);
                                    }
                                }
                            }
                        }
                        //校正采购质保金金额
                        CPurchContractRetentionInfo purchContractRetention = getPurchContractRetentionInfo(cAcceptanceBasicInfo.getBusinessNumber());
                        if (purchContractRetention != null && purchContractRetention.getRetention()) {
                            if (purchContractRetention.getTop().equals(1)) {
                                //如果质保金有上限，校正销售质保金金额
                                BigDecimal retentionLimit = purchContractRetention.getRetentionLimit();
                                if (retentionLimit == null) {
                                    throw new BusinessException(CodeUtil.FAIL, "采购质保金上限不能为空");
                                }
                                BigDecimal surplus = retentionLimit.subtract(occupationPurchRetention);
                                if (surplus.compareTo(BigDecimal.ZERO) > 0) {
                                    goodsInfoList = calculatePurchGuaranteeMoney(surplus, goodsInfoList);
                                } else if (surplus.compareTo(BigDecimal.ZERO) == 0) {
                                    for (CAcceptanceGoodsInfo goodsInfo : goodsInfoList) {
                                        goodsInfo.setPurchGuaranteeMoney(BigDecimal.ZERO);
                                    }
                                }
                            }
                        }
                    }
                    //计算验收数量
                    BigDecimal acceptanceNumTotal = goodsInfoList.stream().filter(goods -> goods.getGoodsQuantity() != null).map(CAcceptanceGoodsInfo::getGoodsQuantity)
                            .reduce(BigDecimal.ZERO, BigDecimal::add);
                    vo.setAcceptanceNumTotal(acceptanceNumTotal);
                    vo.setAcceptanceGoodInfos(goodsInfoList);
                }
                result.add(vo);
            }
        }
        return new GridPage<>(search.getRows(), search.getPage(), page.getTotal(), result);
    }

    @Override
    public List<CFinancingAccountsReceivableInfo> generateAccountsReceivable(List<CAcceptanceGoodsInfo> goodsInfoList) {

        if (CollectionUtil.isNotEmpty(goodsInfoList)) {
            List<CFinancingAccountsReceivableInfo> accountsReceivableInfoList = goodsInfoList.stream().map(goods -> {

                CAcceptanceGoodsInfo acceptanceGoodsInfo = acceptanceGoodsInfoService.getById(goods.getId());
                CFinancingAccountsReceivableInfo accountsReceivableInfo = new CFinancingAccountsReceivableInfo();
                accountsReceivableInfo.setAcceptanceGoodsNumber(goods.getAcceptanceGoodsNumber());
                accountsReceivableInfo.setAcceptanceDate(goods.getAcceptanceDate());
                accountsReceivableInfo.setExpectedSettlementDate(goods.getExpectedSettlementDate());
                accountsReceivableInfo.setAcceptanceBasicInfoId(acceptanceGoodsInfo.getcAcceptanceBasicInfoId());
                accountsReceivableInfo.setAcceptanceGoodsInfoId(acceptanceGoodsInfo.getId());
                accountsReceivableInfo.setGoodsName(acceptanceGoodsInfo.getGoodsName());
                accountsReceivableInfo.setGoodsFactory(acceptanceGoodsInfo.getGoodsFactory());
                accountsReceivableInfo.setGoodsType(acceptanceGoodsInfo.getGoodsType());
                accountsReceivableInfo.setGoodsUnit(acceptanceGoodsInfo.getGoodsUnit());
                accountsReceivableInfo.setGoodsQuantity(acceptanceGoodsInfo.getGoodsQuantity());
                //应收账款金额=采购总价
                accountsReceivableInfo.setAccountsReceivableAmount(goods.getPurchaseTotalPrice());
                //应收账款净额=采购总价-采购质保金
                accountsReceivableInfo.setNetAccountsReceivableAmount(goods.getPurchGuaranteeMoney() == null ?
                        goods.getPurchaseTotalPrice() : goods.getPurchaseTotalPrice().subtract(goods.getPurchGuaranteeMoney()));
                return accountsReceivableInfo;
            }).collect(Collectors.toList());
            return accountsReceivableInfoList;
        }
        return null;
    }

    @Override
    public CFinancingApplicantInfo getApplicantInfo(String businessNumber) {

        //取最新的
        CFinancingApplicantInfo cFinancingApplicantInfo = financingApplicantInfoService.getOne(new QueryWrapper<CFinancingApplicantInfo>()
                .eq("business_number", businessNumber).orderByDesc("id").last("LIMIT 1"));
        if (cFinancingApplicantInfo == null) {
            cFinancingApplicantInfo = new CFinancingApplicantInfo();

            CPurchContractManagement purchContractManagement = purchContractManagementService.getOne(new QueryWrapper<CPurchContractManagement>().eq("business_number", businessNumber));
            if (purchContractManagement == null || purchContractManagement.getId() == null) {
                throw new BusinessException(CodeUtil.FAIL, "采购合同管理不能为空");
            }
            CPurchContractBasicInfo purchContractBasicInfo = purchContractBasicInfoService.getOne(new QueryWrapper<CPurchContractBasicInfo>()
                    .eq("c_purch_contract_management_id", purchContractManagement.getId()));
            if (purchContractBasicInfo != null) {
                CPurchContractSettlePayment purchContractSettlePayment = purchContractSettlePaymentService.getOne(new QueryWrapper<CPurchContractSettlePayment>()
                        .eq("c_purch_contract_basic_info_id", purchContractBasicInfo.getId()));
                if (purchContractSettlePayment != null) {
                    cFinancingApplicantInfo.setApplicantDesignatedAccountName(purchContractSettlePayment.getBankAccountName());
                    cFinancingApplicantInfo.setApplicantDesignatedAccount(purchContractSettlePayment.getBankAccount());
                    cFinancingApplicantInfo.setApplicantDesignatedBank(purchContractSettlePayment.getBankName());
                }
            }

        }
        return cFinancingApplicantInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void apply(FinancingApplyVo financingApplyVo) {

        Boolean visible = financingApplyVo.getVisible();

        //保存融资申请信息
        CFinancingBasicInfo financingBasicInfo = financingApplyVo.getFinancingBasicInfo();
        financingBasicInfo.setVisible(financingApplyVo.getVisible());
        financingBasicInfo.setSysUserId(LoginUserHolder.get().getId());

        List<CFinancingGoodsInfo> financingGoodsInfoList = financingApplyVo.getFinancingGoodsInfoList();
        if (visible) {
            //检验验收单货物是否已经融资
            checkAcceptanceGoods(financingGoodsInfoList);
            //状态为处理中
            financingBasicInfo.setFinancingStatus(ProjectInitiationStatusEnum.PROCESSING.getCode());
            //当前阶段为额度支用
            financingBasicInfo.setCurrentStage(FinancingCurrentStageEnum.REVIEW_QUOTA_DISBURSE.getCode());
        }
        financingBasicInfoService.saveOrUpdate(financingBasicInfo);

        //货物信息
        financingGoodsInfoService.remove(new QueryWrapper<CFinancingGoodsInfo>().eq("c_financing_basic_info_id", financingBasicInfo.getId()));
        if (CollectionUtil.isNotEmpty(financingGoodsInfoList)) {
            financingGoodsInfoList.stream().forEach(cFinancingGoodsInfo -> {
                cFinancingGoodsInfo.setAcceptanceGoodsInfoId(cFinancingGoodsInfo.getId());
                cFinancingGoodsInfo.setFinancingBasicInfoId(financingBasicInfo.getId());
                cFinancingGoodsInfo.setId(null);
                financingGoodsInfoService.save(cFinancingGoodsInfo);
                if (visible) {
                    //提交时 更新验收单货物的融资状态
                    CAcceptanceGoodsInfo acceptanceGoodsInfo = acceptanceGoodsInfoService.getById(cFinancingGoodsInfo.getAcceptanceGoodsInfoId());
                    if (acceptanceGoodsInfo != null) {
                        acceptanceGoodsInfoService.lambdaUpdate().eq(CAcceptanceGoodsInfo::getId, acceptanceGoodsInfo.getId())
                                .set(CAcceptanceGoodsInfo::getFinancing, true).update();
                    }
                }
            });
        }
        //底层信息
        financingAccountsReceivableInfoService.remove(new QueryWrapper<CFinancingAccountsReceivableInfo>().eq("c_financing_basic_info_id", financingBasicInfo.getId()));
        List<CFinancingAccountsReceivableInfo> financingAccountsReceivableInfoList = financingApplyVo.getFinancingAccountsReceivableInfoList();
        if (CollectionUtil.isNotEmpty(financingAccountsReceivableInfoList)) {
            financingAccountsReceivableInfoList.stream().forEach(accountsReceivableInfo -> {
                accountsReceivableInfo.setFinancingBasicInfoId(financingBasicInfo.getId());
                financingAccountsReceivableInfoService.save(accountsReceivableInfo);
            });
        }

        //保存文件
        fileService.lambdaUpdate().eq(FileStorageDO::getBusinessId, financingBasicInfo.getId())
                .eq(FileStorageDO::getBusinessType, FileTypeEnum.FINANCING_NET_PRICE_FILE.getCode())
                .set(FileStorageDO::getBusinessId, null).update();
        if (CollectionUtil.isNotEmpty(financingApplyVo.getFileIds())) {
            financingApplyVo.getFileIds().forEach(c -> {
                FileStorageDO fileStorageDO = fileService.getById(c);
                fileStorageDO.setBusinessId(financingBasicInfo.getId());
                fileStorageDO.setBusinessType(FileTypeEnum.FINANCING_NET_PRICE_FILE.getCode());
                fileService.updateById(fileStorageDO);
            });
        }
        //融资申请人信息
        financingApplicantInfoService.remove(new QueryWrapper<CFinancingApplicantInfo>().eq("c_financing_basic_info_id", financingBasicInfo.getId()));
        CFinancingApplicantInfo financingApplicantInfo = financingApplyVo.getFinancingApplicantInfo();
        financingApplicantInfo.setBusinessNumber(financingBasicInfo.getBusinessNumber());
        financingApplicantInfo.setSupplierId(financingBasicInfo.getMainEnterpriseId());
        financingApplicantInfo.setFinancingBasicInfoId(financingBasicInfo.getId());
        financingApplicantInfoService.save(financingApplicantInfo);


        if (visible) {
            //保存历史信息
            CFinancingHisInfo financingHisInfo = addHistory(financingBasicInfo);
            //提交申请到B端进行审核
            UserDO userDO = userService.getById(LoginUserHolder.get().getId());
            if (userDO != null && userDO.getProjectManager() != null) {
                financingBasicInfo.setProjectManagerId(userDO.getProjectManager());
            }
            if (userDO != null && userDO.getRiskManager() != null) {
                financingBasicInfo.setRiskManagerId(userDO.getRiskManager());
            }
            financingBasicInfo.setFinancingHisInfoId(financingHisInfo.getId());
            //todo 添加应收账款净额
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(financingApplyUrl, financingBasicInfo, String.class);
            ResponseJson responseJson = JSONUtil.toBean(responseEntity.getBody(), ResponseJson.class);
            if (responseEntity.getStatusCode().value() != HttpStatus.OK.value() || !responseJson.isSuccess()) {
                throw new BusinessException(CodeUtil.FAIL, "融资申请提交到B端失败：" + responseJson.getMsg());
            }
        }
    }

    /**
     * 校验验收单货物是否已融资
     *
     * @param financingGoodsInfoList
     */
    private void checkAcceptanceGoods(List<CFinancingGoodsInfo> financingGoodsInfoList) {
        if (CollectionUtil.isNotEmpty(financingGoodsInfoList)) {
            List<String> acceptanceGoodsNumbers = financingGoodsInfoList.stream().map(CFinancingGoodsInfo::getAcceptanceGoodsNumber).distinct()
                    .collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(acceptanceGoodsNumbers)) {
                for (String acceptanceGoodsNumber : acceptanceGoodsNumbers) {
                    List<CAcceptanceGoodsInfo> acceptanceGoodsInfoList = acceptanceGoodsInfoService.list(new QueryWrapper<CAcceptanceGoodsInfo>()
                            .eq("acceptance_goods_number", acceptanceGoodsNumber));
                    if (CollectionUtil.isNotEmpty(acceptanceGoodsInfoList)) {
                        for (CAcceptanceGoodsInfo goodsInfo : acceptanceGoodsInfoList) {
                            if (goodsInfo.getFinancing() != null && goodsInfo.getFinancing()) {
                                throw new BusinessException(CodeUtil.FAIL, "验收单中存在已融资的货物，无法提交，请修改");
                            }
                        }
                    }
                }
            }
        }
    }

    @Override
    public FinancingApplyVo getDetail(Long id) {
        FinancingApplyVo financingApplyVo = new FinancingApplyVo();

        //基础信息
        CFinancingBasicInfo financingBasicInfo = financingBasicInfoService.getById(id);
        if (financingBasicInfo.getCoreEnterpriseId() != null) {
            Enterprise enterprise = enterpriseService.getById(financingBasicInfo.getCoreEnterpriseId());
            financingBasicInfo.setCoreEnterpriseName(enterprise.getCorporateName());
        }
        if (financingBasicInfo.getMainEnterpriseId() != null) {
            Enterprise enterprise = enterpriseService.getById(financingBasicInfo.getMainEnterpriseId());
            financingBasicInfo.setMainEnterpriseName(enterprise.getCorporateName());
        }
        if (financingBasicInfo.getPlatformId() != null) {
            Platform platform = platformService.getById(financingBasicInfo.getPlatformId());
            financingBasicInfo.setPlatformName(platform.getPlatformName());
        }
        if (financingBasicInfo.getBusinessNumber() != null) {
            ProjectInformation projectInformation = projectInformationService.getOne(new QueryWrapper<ProjectInformation>().eq("business_number", financingBasicInfo.getBusinessNumber()));
            if (projectInformation != null) {
                financingBasicInfo.setSupplierId(projectInformation.getcSupplierInfoId());
            }
        }

        financingApplyVo.setFinancingBasicInfo(financingBasicInfo);

        //底层货物
        List<CFinancingGoodsInfo> goodsInfoList = financingGoodsInfoService.list(new QueryWrapper<CFinancingGoodsInfo>().eq("c_financing_basic_info_id", id));
        if (CollectionUtil.isNotEmpty(goodsInfoList)) {
            goodsInfoList.stream().forEach(goods -> {
                if (goods.getAcceptanceGoodsInfoId() != null) {
                    CAcceptanceGoodsInfo cAcceptanceGoodsInfo = acceptanceGoodsInfoService.getById(goods.getAcceptanceGoodsInfoId());
                    if (cAcceptanceGoodsInfo != null) {
                        goods.setId(cAcceptanceGoodsInfo.getId());
                        goods.setGoodsName(cAcceptanceGoodsInfo.getGoodsName());
                        goods.setGoodsFactory(cAcceptanceGoodsInfo.getGoodsFactory());
                        goods.setGoodsType(cAcceptanceGoodsInfo.getGoodsType());
                        goods.setGoodsUnit(cAcceptanceGoodsInfo.getGoodsUnit());
                        goods.setGoodsQuantity(cAcceptanceGoodsInfo.getGoodsQuantity());
                        goods.setAcceptanceDate(cAcceptanceGoodsInfo.getAcceptanceDate());
                    }
                }
                if (goods.getcAcceptanceBasicInfoId() != null) {
                    CAcceptanceBasicInfo cAcceptanceBasicInfo = acceptanceBasicInfoService.getById(goods.getcAcceptanceBasicInfoId());
                    if (cAcceptanceBasicInfo != null) {
                        goods.setExpectedSettlementDate(cAcceptanceBasicInfo.getExpectedSettlementDate());
                    }
                }
            });
        }
        financingApplyVo.setFinancingGoodsInfoList(goodsInfoList);

        //底层信息
        List<CFinancingAccountsReceivableInfo> accountsReceivableInfoList = financingAccountsReceivableInfoService.list(new QueryWrapper<CFinancingAccountsReceivableInfo>()
                .eq("c_financing_basic_info_id", id));
        financingApplyVo.setFinancingAccountsReceivableInfoList(accountsReceivableInfoList);

        //联系人信息
        CFinancingApplicantInfo financingApplicantInfo = financingApplicantInfoService.getOne(new QueryWrapper<CFinancingApplicantInfo>().eq("c_financing_basic_info_id", id));
        financingApplyVo.setFinancingApplicantInfo(financingApplicantInfo);

        //网价附件
        List<FileStorageDO> fileStorageList = fileService.findByBusinessId(financingBasicInfo.getId(), FileTypeEnum.FINANCING_NET_PRICE_FILE.getCode());
        financingApplyVo.setFileStorageDOList(fileStorageList);
        return financingApplyVo;
    }

    @Override
    public PaymentCollectionBasic getViewLatestPlan(Long id) {

        CFinancingBasicInfo financingBasicInfo = financingBasicInfoService.getById(id);
        if (financingBasicInfo != null && financingBasicInfo.getSopAccountsReceivableId() != null) {
            JSONObject jsonObject = restTemplate.getForObject(viewLatestPlanUrl + "?sopAccountsReceivableId=" + financingBasicInfo.getSopAccountsReceivableId(), JSONObject.class);
            Integer code = jsonObject.getInt("code");
            Boolean success = jsonObject.getBool("success");
            if (code != HttpStatus.OK.value() || !success) {
                throw new BusinessException(CodeUtil.FAIL, "查询sop最新收放款计划失败：" + jsonObject.getStr("msg"));
            }
            JSONObject data = jsonObject.getJSONObject("data");
            return JSONUtil.toBean(data, PaymentCollectionBasic.class);
        }
        return null;
    }

    /**
     * 保存历史
     *
     * @param financingBasicInfo
     * @return
     */
    private CFinancingHisInfo addHistory(CFinancingBasicInfo financingBasicInfo) {

        //保存历史信息
        CFinancingHisInfo financingHisInfo = new CFinancingHisInfo();
        financingHisInfo.setFinancingBasicInfoId(financingBasicInfo.getId());
        BeanUtils.copyProperties(financingBasicInfo, financingHisInfo, "id");
        financingHisInfoService.save(financingHisInfo);

        List<CFinancingGoodsInfo> goodsInfoList = financingGoodsInfoService.list(new QueryWrapper<CFinancingGoodsInfo>().eq("c_financing_basic_info_id", financingBasicInfo.getId()));
        if (CollectionUtil.isNotEmpty(goodsInfoList)) {
            goodsInfoList.stream().forEach(cFinancingGoodsInfo -> {
                //保存历史信息
                CFinancingHisGoodsInfo financingHisGoodsInfo = new CFinancingHisGoodsInfo();
                BeanUtils.copyProperties(cFinancingGoodsInfo, financingHisGoodsInfo, "id");
                financingHisGoodsInfo.setAcceptanceBasicInfoId(cFinancingGoodsInfo.getcAcceptanceBasicInfoId());
                financingHisGoodsInfo.setFinancingHisInfoId(financingHisInfo.getId());
                financingHisGoodsInfoService.save(financingHisGoodsInfo);
            });
        }
        List<CFinancingAccountsReceivableInfo> accountsReceivableInfoList = financingAccountsReceivableInfoService.list(new QueryWrapper<CFinancingAccountsReceivableInfo>().eq("c_financing_basic_info_id", financingBasicInfo.getId()));
        if (CollectionUtil.isNotEmpty(accountsReceivableInfoList)) {
            accountsReceivableInfoList.stream().forEach(accountsReceivableInfo -> {
                //保存历史信息
                CFinancingHisAccountsReceivableInfo financingHisAccountsReceivableInfo = new CFinancingHisAccountsReceivableInfo();
                BeanUtils.copyProperties(accountsReceivableInfo, financingHisAccountsReceivableInfo, "id");
                financingHisAccountsReceivableInfo.setFinancingHisInfoId(financingHisInfo.getId());
                financingHisAccountsReceivableInfoService.save(financingHisAccountsReceivableInfo);
            });
        }
        //保存文件历史
        List<FileStorageDO> fileStorageList = fileService.findByBusinessId(financingBasicInfo.getId(), FileTypeEnum.FINANCING_NET_PRICE_FILE.getCode());
        if (CollectionUtil.isNotEmpty(fileStorageList)) {
            fileStorageList.stream().forEach(fileStorageDO -> {
                FileStorageDO fileStorageHis = new FileStorageDO();
                BeanUtils.copyProperties(fileStorageDO, fileStorageHis, "id");
                fileStorageHis.setBusinessId(financingHisInfo.getId());
                fileStorageHis.setBusinessType(FileTypeEnum.FINANCING_NET_PRICE_HIS_FILE.getCode());
                fileService.save(fileStorageHis);
            });
        }

        CFinancingApplicantInfo financingApplicantInfo = financingApplicantInfoService.getOne(new QueryWrapper<CFinancingApplicantInfo>().eq("c_financing_basic_info_id", financingBasicInfo.getId()));
        if (financingApplicantInfo != null) {
            CFinancingHisApplicantInfo financingHisApplicantInfo = new CFinancingHisApplicantInfo();
            BeanUtils.copyProperties(financingApplicantInfo, financingHisApplicantInfo, "id");
            financingHisApplicantInfo.setFinancingHisInfoId(financingHisInfo.getId());
            financingHisApplicantInfoService.save(financingHisApplicantInfo);
        }
        return financingHisInfo;
    }

    /**
     * 计算
     *
     * @param businessNumber 业务编号
     * @param goodsInfoList  货物列表
     */
    private void calculateGoodsAmount(String businessNumber, List<CAcceptanceGoodsInfo> goodsInfoList) {

        if (CollectionUtil.isNotEmpty(goodsInfoList)) {
            for (CAcceptanceGoodsInfo goodsInfo : goodsInfoList) {
                //计算销售总价
                BigDecimal salesPrice = goodsInfo.getSalesPrice() == null ? BigDecimal.ZERO : goodsInfo.getSalesPrice();
                BigDecimal salesTotalPrice = salesPrice.multiply(goodsInfo.getGoodsQuantity())
                        .setScale(2, RoundingMode.HALF_UP);
                goodsInfo.setSalesTotalPrice(salesTotalPrice);

                //计算销售质保金=销售总价*销售合同中的质保金比例
                SalesContractRetentionInfo retentionInfo = getSalesContractRetentionInfo(businessNumber);
                BigDecimal salesGuaranteeMoney = BigDecimal.ZERO;
                if (retentionInfo != null && retentionInfo.getRetention()) {
                    salesGuaranteeMoney = salesTotalPrice.multiply(retentionInfo.getRetentionPercent())
                            .divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
                }
                goodsInfo.setSalesGuaranteeMoney(salesGuaranteeMoney);

                //计算采购相关金额
                CPurchContractManagement purchContractManagement = purchContractManagementService.getOne(new QueryWrapper<CPurchContractManagement>().eq("business_number", businessNumber));
                if (purchContractManagement == null || purchContractManagement.getId() == null) {
                    throw new BusinessException(CodeUtil.FAIL, "采购合同管理不能为空");
                }
                CPurchContractBasicInfo purchContractBasicInfo = purchContractBasicInfoService.getOne(new QueryWrapper<CPurchContractBasicInfo>()
                        .eq("c_purch_contract_management_id", purchContractManagement.getId()));
                CPurchContractPriceRule priceRule = purchContractPriceRuleService.getOne(new QueryWrapper<CPurchContractPriceRule>()
                        .eq("c_purch_contract_basic_info_id", purchContractBasicInfo.getId()));

                BigDecimal purchasePrice = BigDecimal.ZERO;
                if (priceRule.getAccrualMarginCalcMethod().equals(1)) {
                    //如果利差计算规则=固定差额  采购单价=销售单价-差额
                    purchasePrice = salesPrice.subtract(priceRule.getDifferAmount() == null ? BigDecimal.ZERO : priceRule.getDifferAmount());
                }
                if (priceRule.getAccrualMarginCalcMethod().equals(0)) {
                    //如果利差计算规则=固定利率 采购单价=销售单价-销售单价*(月利率)*（预估保理融资期限/30），--不足30按30算
                    //月利率
                    BigDecimal monthlyRate = priceRule.getMonthlyInterestRate().divide(new BigDecimal(100));
                    //预估保理融资期限/30），--不足30按30算
                    BigDecimal param = new BigDecimal(priceRule.getFactoringFinanceDeadline()).divide(new BigDecimal("30"), RoundingMode.UP);
                    purchasePrice = salesPrice.subtract(salesPrice.multiply(monthlyRate).multiply(param)).setScale(2, RoundingMode.HALF_UP);
                }
                goodsInfo.setPurchasePrice(purchasePrice);

                //采购总价
                BigDecimal purchaseTotalPrice = purchasePrice.multiply(goodsInfo.getGoodsQuantity()).setScale(4, RoundingMode.HALF_UP);
                goodsInfo.setPurchaseTotalPrice(purchaseTotalPrice);

                //采购质保金
                CPurchContractRetentionInfo purchContractRetentionInfo = purchContractRetentionInfoService.getOne(new QueryWrapper<CPurchContractRetentionInfo>()
                        .eq("c_purch_contract_basic_info_id", purchContractBasicInfo.getId()));
                BigDecimal purchaseGuaranteeMoney = BigDecimal.ZERO;
                if (purchContractRetentionInfo != null && purchContractRetentionInfo.getRetention()) {
                    purchaseGuaranteeMoney = purchaseTotalPrice.multiply(purchContractRetentionInfo.getRetentionPercent())
                            .divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
                }
                goodsInfo.setPurchGuaranteeMoney(purchaseGuaranteeMoney);
            }
        }
    }

    /**
     * 销售质保金计算
     *
     * @param surplusAmount
     * @param goodsList
     * @return
     */
    public List<CAcceptanceGoodsInfo> calculateSalesGuaranteeMoney(BigDecimal surplusAmount, List<CAcceptanceGoodsInfo> goodsList) {

        //分配销售质保金
        BigDecimal guaranteeMoneyTotal = goodsList.stream().filter(goods -> goods.getSalesGuaranteeMoney() != null)
                .map(CAcceptanceGoodsInfo::getSalesGuaranteeMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
        if (surplusAmount.compareTo(guaranteeMoneyTotal) >= 0) {
            //如果质保金上限大于等于货物质保金之和
            return goodsList;
        } else {
            //如果质保金上限小于货物质保金之和，需要重新分配
            for (CAcceptanceGoodsInfo goodsInfo : goodsList) {
                if (goodsInfo.getSalesGuaranteeMoney() != null) {
                    BigDecimal currentGuaranteeMoney = goodsInfo.getSalesGuaranteeMoney();
                    if (goodsInfo.getSalesGuaranteeMoney().compareTo(surplusAmount) >= 0) {
                        currentGuaranteeMoney = surplusAmount.setScale(2, RoundingMode.HALF_UP);
                    }
                    goodsInfo.setSalesGuaranteeMoney(currentGuaranteeMoney);
                    surplusAmount = surplusAmount.subtract(currentGuaranteeMoney);
                }
            }
        }
        return goodsList;
    }

    /**
     * 采购质保金计算
     *
     * @param surplusAmount
     * @param goodsList
     * @return
     */
    public List<CAcceptanceGoodsInfo> calculatePurchGuaranteeMoney(BigDecimal surplusAmount, List<CAcceptanceGoodsInfo> goodsList) {

        //分配采购质保金
        BigDecimal guaranteeMoneyTotal = goodsList.stream().filter(goods -> goods.getPurchGuaranteeMoney() != null)
                .map(CAcceptanceGoodsInfo::getPurchGuaranteeMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
        if (surplusAmount.compareTo(guaranteeMoneyTotal) >= 0) {
            //如果质保金上限大于等于货物质保金之和
            return goodsList;
        } else {
            //如果质保金上限小于货物质保金之和，需要重新分配
            for (CAcceptanceGoodsInfo goodsInfo : goodsList) {
                if (goodsInfo.getPurchGuaranteeMoney() != null) {
                    BigDecimal currentGuaranteeMoney = goodsInfo.getPurchGuaranteeMoney();
                    if (goodsInfo.getPurchGuaranteeMoney().compareTo(surplusAmount) >= 0) {
                        currentGuaranteeMoney = surplusAmount.setScale(4, RoundingMode.HALF_UP);
                    }
                    goodsInfo.setPurchGuaranteeMoney(currentGuaranteeMoney);
                    surplusAmount = surplusAmount.subtract(currentGuaranteeMoney);
                }
            }
        }
        return goodsList;
    }

    /**
     * 获取销售质保金信息
     *
     * @param businessNumber
     * @return
     */
    public SalesContractRetentionInfo getSalesContractRetentionInfo(String businessNumber) {

        CSalesContractBasicInfo salesContractBasicInfo = salesContractManagementService.findByBusinessNumber(businessNumber);
        if (salesContractBasicInfo == null || salesContractBasicInfo.getId() == null) {
            throw new BusinessException(CodeUtil.FAIL, "销售合同基础信息不能为空");
        }
        SalesContractApproval salesContractApproval = salesContractApprovalService.getOne(new QueryWrapper<SalesContractApproval>()
                .eq("c_sales_contract_basic_info_id", salesContractBasicInfo.getId())
                .orderByDesc("id").last("limit 1"));
        if (salesContractApproval == null || salesContractApproval.getId() == null) {
            throw new BusinessException(CodeUtil.FAIL, "销售合同审批信息不能为空");
        }
        return salesContractRetentionInfoService.getOne(new QueryWrapper<SalesContractRetentionInfo>()
                .eq("sales_contract_approval_id", salesContractApproval.getId()).orderByDesc("id").last("limit 1"));
    }

    /**
     * 获取采购质保金信息
     *
     * @param businessNumber
     * @return
     */
    private CPurchContractRetentionInfo getPurchContractRetentionInfo(String businessNumber) {

        CPurchContractManagement purchContractManagement = purchContractManagementService.getOne(new QueryWrapper<CPurchContractManagement>().eq("business_number", businessNumber));
        if (purchContractManagement == null || purchContractManagement.getId() == null) {
            throw new BusinessException(CodeUtil.FAIL, "采购合同管理不能为空");
        }
        CPurchContractBasicInfo purchContractBasicInfo = purchContractBasicInfoService.getOne(new QueryWrapper<CPurchContractBasicInfo>()
                .eq("c_purch_contract_management_id", purchContractManagement.getId()));
        CPurchContractRetentionInfo purchContractRetentionInfo = purchContractRetentionInfoService.getOne(new QueryWrapper<CPurchContractRetentionInfo>()
                .eq("c_purch_contract_basic_info_id", purchContractBasicInfo.getId()));
        return purchContractRetentionInfo;
    }

    /**
     * 计算采购质保金占用
     *
     * @param acceptanceBasicInfo
     * @return
     */
    private BigDecimal calculateOccupationPurchRetention(CAcceptanceBasicInfo acceptanceBasicInfo) {

        List<CAcceptanceBasicInfo> acceptanceBasicInfoList = acceptanceBasicInfoService.list(new QueryWrapper<CAcceptanceBasicInfo>()
                .eq("business_number", acceptanceBasicInfo.getBusinessNumber())
                .eq("c_supplier_info_id", acceptanceBasicInfo.getcSupplierInfoId())
                .eq("acceptance_status", ProjectInitiationStatusEnum.COMPLETED.getCode()));

        BigDecimal occupationPurchRetention = BigDecimal.ZERO;
        if (acceptanceBasicInfoList != null && acceptanceBasicInfoList.size() > 0) {
            for (CAcceptanceBasicInfo basicInfo : acceptanceBasicInfoList) {
                //验收单下做过结算的货物
                List<SettlementGoodsInfo> settlementGoodsInfoList = settlementGoodsInfoService.listByAcceptanceId(basicInfo.getId());
                if (settlementGoodsInfoList != null && settlementGoodsInfoList.size() > 0) {
                    for (SettlementGoodsInfo settlementGoodsInfo : settlementGoodsInfoList) {
                        occupationPurchRetention = occupationPurchRetention.add(settlementGoodsInfo.getPurchaseGuaranteeMoney() == null ? BigDecimal.ZERO : settlementGoodsInfo.getPurchaseGuaranteeMoney());
                    }
                } else {
                    //验收单下做过底层的货物
                    List<CFinancingGoodsInfo> financingGoodsInfoList = financingGoodsInfoService.listByAcceptanceId(basicInfo.getId());
                    if (financingGoodsInfoList != null && financingGoodsInfoList.size() > 0) {
                        for (CFinancingGoodsInfo financingGoodsInfo : financingGoodsInfoList) {
                            occupationPurchRetention = occupationPurchRetention.add(financingGoodsInfo.getPurchGuaranteeMoney() == null ? BigDecimal.ZERO : financingGoodsInfo.getPurchGuaranteeMoney());
                            //即做了底层又做了结算 不能重复计算
                            for (SettlementGoodsInfo settlementGoodsInfo : settlementGoodsInfoList) {
                                if (settlementGoodsInfo.getAcceptanceGoodsInfoId().equals(financingGoodsInfo.getAcceptanceGoodsInfoId())) {
                                    occupationPurchRetention = occupationPurchRetention.subtract(financingGoodsInfo.getPurchGuaranteeMoney() == null ? BigDecimal.ZERO : financingGoodsInfo.getPurchGuaranteeMoney());
                                }
                            }
                        }
                    }
                }
            }
        }
        return occupationPurchRetention;
    }

    /**
     * 计算销售质保金占用
     *
     * @param acceptanceBasicInfo
     * @return
     */
    private BigDecimal calculateOccupationSalesRetention(CAcceptanceBasicInfo acceptanceBasicInfo) {

        List<CAcceptanceBasicInfo> acceptanceBasicInfos = acceptanceBasicInfoService.list(new QueryWrapper<CAcceptanceBasicInfo>()
                .eq("business_number", acceptanceBasicInfo.getBusinessNumber())
                .eq("acceptance_status", ProjectInitiationStatusEnum.COMPLETED.getCode()));

        BigDecimal occupationSalesRetention = BigDecimal.ZERO;
        if (acceptanceBasicInfos != null && acceptanceBasicInfos.size() > 0) {
            for (CAcceptanceBasicInfo basicInfo : acceptanceBasicInfos) {
                //验收单下做过结算的货物
                List<SettlementGoodsInfo> settlementGoodsInfoList = settlementGoodsInfoService.listByAcceptanceId(basicInfo.getId());
                if (settlementGoodsInfoList != null && settlementGoodsInfoList.size() > 0) {
                    for (SettlementGoodsInfo settlementGoodsInfo : settlementGoodsInfoList) {
                        occupationSalesRetention = occupationSalesRetention.add(settlementGoodsInfo.getSalesGuaranteeMoney() == null ? BigDecimal.ZERO : settlementGoodsInfo.getSalesGuaranteeMoney());
                    }
                } else {
                    //验收单下做过融资的货物
                    List<CFinancingGoodsInfo> financingGoodsInfoList = financingGoodsInfoService.listByAcceptanceId(basicInfo.getId());
                    if (financingGoodsInfoList != null && financingGoodsInfoList.size() > 0) {
                        for (CFinancingGoodsInfo financingGoodsInfo : financingGoodsInfoList) {
                            occupationSalesRetention = occupationSalesRetention.add(financingGoodsInfo.getSalesGuaranteeMoney() == null ? BigDecimal.ZERO : financingGoodsInfo.getSalesGuaranteeMoney());
                            //即做了底层又做了结算 不能重复计算
                            for (SettlementGoodsInfo settlementGoodsInfo : settlementGoodsInfoList) {
                                if (settlementGoodsInfo.getAcceptanceGoodsInfoId().equals(financingGoodsInfo.getAcceptanceGoodsInfoId())) {
                                    occupationSalesRetention = occupationSalesRetention.subtract(financingGoodsInfo.getSalesGuaranteeMoney() == null ? BigDecimal.ZERO : financingGoodsInfo.getSalesGuaranteeMoney());
                                }
                            }
                        }
                    }
                }
            }
        }
        return occupationSalesRetention;
    }
}
