package com.sunxung.factoring.service.financing.payment.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.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.deepoove.poi.XWPFTemplate;
import com.sunxung.factoring.component.enums.FinancingCurrentStageEnum;
import com.sunxung.factoring.component.exception.BusinessException;
import com.sunxung.factoring.component.exception.ValidatorException;
import com.sunxung.factoring.component.util.*;
import com.sunxung.factoring.dict.impl.FileModuleDict;
import com.sunxung.factoring.dict.impl.IncomeExpenditureTypeDict;
import com.sunxung.factoring.dict.impl.PaymentApplyStatusDict;
import com.sunxung.factoring.dict.impl.ProjectInitiationStatusDict;
import com.sunxung.factoring.entity.ResponseJson;
import com.sunxung.factoring.entity.entprise.Enterprise;
import com.sunxung.factoring.entity.financing.apply.CFinancingAccountsReceivableInfo;
import com.sunxung.factoring.entity.financing.apply.CFinancingBasicInfo;
import com.sunxung.factoring.entity.financing.contract.ContractFinancingInfo;
import com.sunxung.factoring.entity.financing.contract.ContractInfo;
import com.sunxung.factoring.entity.financing.contract.ContractLoanConditionSetting;
import com.sunxung.factoring.entity.financing.contract.ContractMasterContract;
import com.sunxung.factoring.entity.financing.payment.*;
import com.sunxung.factoring.entity.financing.review.*;
import com.sunxung.factoring.entity.financing.sop.*;
import com.sunxung.factoring.entity.purchcontractmanagement.PurchContractBasicInfo;
import com.sunxung.factoring.entity.purchcontractmanagement.PurchContractManagement;
import com.sunxung.factoring.entity.salescontractmanagement.CSalesContractBasicInfo;
import com.sunxung.factoring.entity.sys.FileStorage;
import com.sunxung.factoring.entity.tradingPlatform.Platform;
import com.sunxung.factoring.entity.underlying.sop.DomesticAccountsReceivableToSop;
import com.sunxung.factoring.entity.underlying.sop.UnderlyingAssetsDomesticToSop;
import com.sunxung.factoring.mapper.financing.payment.PaymentApplyMapper;
import com.sunxung.factoring.service.entprise.IEnterpriseService;
import com.sunxung.factoring.service.financing.apply.ICFinancingAccountsReceivableInfoService;
import com.sunxung.factoring.service.financing.apply.ICFinancingBasicInfoService;
import com.sunxung.factoring.service.financing.contract.IContractFinancingInfoService;
import com.sunxung.factoring.service.financing.contract.IContractInfoService;
import com.sunxung.factoring.service.financing.contract.IContractLoanConditionSettingService;
import com.sunxung.factoring.service.financing.contract.IContractMasterContractService;
import com.sunxung.factoring.service.financing.payment.*;
import com.sunxung.factoring.service.financing.review.*;
import com.sunxung.factoring.service.loanmanagement.IExemptionMattersService;
import com.sunxung.factoring.service.project.BusinessAssigneeService;
import com.sunxung.factoring.service.purchcontractmanagement.PurchContractBasicInfoService;
import com.sunxung.factoring.service.purchcontractmanagement.PurchContractService;
import com.sunxung.factoring.service.salescontractmanagement.SalesContractService;
import com.sunxung.factoring.service.sys.DictionaryService;
import com.sunxung.factoring.service.sys.FileStorageService;
import com.sunxung.factoring.service.sys.SerialNumberGenerator;
import com.sunxung.factoring.service.sys.UserService;
import com.sunxung.factoring.service.sys.flowable.FlowableService;
import com.sunxung.factoring.service.tradingPlatform.PlatformService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
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.io.File;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description :
 * @Author : L.Jia
 * @Date: 2024-02-28 15:17
 */
@Service
public class PaymentApplyServiceImpl extends ServiceImpl<PaymentApplyMapper, PaymentApply> implements IPaymentApplyService {

    @Autowired
    private IPaymentInfoService paymentInfoService;
    @Autowired
    private SerialNumberGenerator serialNumGenerator;
    @Autowired
    private ReviewQuotaDisburseService reviewQuotaDisburseService;
    @Autowired
    private ReviewMasterContractService reviewMasterContractService;
    @Autowired
    private ReviewMasterContractDebtorService reviewMasterContractDebtorService;
    @Autowired
    private ReviewIncomeExpenditurePlanService reviewIncomeExpenditurePlanService;
    @Autowired
    private ReviewFinancingInfoService reviewFinancingInfoService;
    @Autowired
    private ReviewMortgageBasicInfoService reviewMortgageBasicInfoService;
    @Autowired
    private ReviewRltRepayService reviewRltRepayService;
    @Autowired
    private IContractInfoService contractInfoService;
    @Autowired
    private IContractMasterContractService contractMasterContractService;
    @Autowired
    private IContractFinancingInfoService contractFinancingInfoService;
    @Autowired
    private IContractLoanConditionSettingService contractLoanConditionSettingService;
    @Autowired
    private IPaymentConditionService paymentConditionService;
    @Autowired
    private ICFinancingBasicInfoService financingBasicInfoService;
    @Autowired
    private IPaymentConditionFileRefService paymentConditionFileRefService;
    @Autowired
    private BusinessAssigneeService assigneeService;
    @Autowired
    private FlowableService flowableService;
    @Autowired
    private UserService userService;
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private IPaymentApplyHisService paymentApplyHisService;
    @Autowired
    private IPaymentConditionHisService paymentConditionHisService;
    @Autowired
    private IPaymentConditionFileRefHisService paymentConditionFileRefHisService;
    @Autowired
    private IPaymentApprovalService paymentApprovalService;
    @Value("${sop.getIndustryUrl}")
    private String getIndustry;
    @Value("${sop.getBusinessNoByTrade}")
    private String getBusinessNoByTrade;
    @Value("${sop.underlyingAssetsBasicId}")
    private String underlyingAssetsBasicIdUrl;
    @Value("${sop.underlyingAssetsDomesticAdd}")
    private String underlyingAssetsDomesticAddUrl;
    @Value("${sop.domesticAccountsReceivableAdd}")
    private String domesticAccountsReceivableAddUrl;
    @Value("${sop.quotaDisburseReportUrl}")
    private String quotaDisburseReportUrl;
    @Autowired
    private IEnterpriseService enterpriseService;
    @Autowired
    private PlatformService platformService;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DictionaryService dictService;
    @Autowired
    private IReceivablesRegisterInfoService receivablesRegisterInfoService;
    @Autowired
    private IReceivablesRegisterFileService receivablesRegisterFileService;
    @Autowired
    private IExemptionMattersService exemptionMattersService;
    @Autowired
    private PurchContractBasicInfoService purchContractBasicInfoService;
    @Autowired
    private PurchContractService purchContractService;
    @Autowired
    private SalesContractService salesContractService;
    @Autowired
    private ICFinancingAccountsReceivableInfoService financingAccountsReceivableInfoService;

    @Override
    public PaymentApply getToEditPageById(Long id) {

        PaymentInfo paymentInfo = paymentInfoService.getOne(new QueryWrapper<PaymentInfo>().eq("c_financing_basic_info_id", id));
        if (paymentInfo == null) {
            throw new ValidatorException(CodeUtil.FAIL, "查询不到对应的付款信息！");
        }
        PaymentApply paymentApply = baseMapper.selectOne(new QueryWrapper<PaymentApply>().eq("payment_info_id", paymentInfo.getId()));
        if (paymentApply == null) {
            paymentApply = new PaymentApply();
            paymentApply.setPaymentInfoId(paymentInfo.getId());
            paymentApply.setPaymentNo(serialNumGenerator.nextValue(ConstantUtil.PAYMENT_APPLY_CODE));
            paymentApply.setPlanNo("第1笔");
            paymentApply.setStatusCode(PaymentApplyStatusDict.ChildEnum.APPLY.getCode());
            paymentApply.setPaymentAmount(paymentInfo.getTotalLoanAmount());

            List<ReviewIncomeExpenditurePlan> principalLoanList = getPrincipalLoanList(paymentInfo.getQuotaDisburseId());
            if (CollectionUtil.isNotEmpty(principalLoanList)) {
                paymentApply.setPaymentType(principalLoanList.get(0).getIncomeExpenditureType());
                paymentApply.setCurrencyCode(principalLoanList.get(0).getCurrencyCode());
                paymentApply.setPlanPaymentDate(principalLoanList.get(0).getIncomeExpenditureDate());
            }
        }
        ReviewFinancingInfo reviewFinancingInfo = reviewFinancingInfoService.getOne(new QueryWrapper<ReviewFinancingInfo>()
                .eq("review_quota_disburse_id", paymentInfo.getQuotaDisburseId()));
        if (reviewFinancingInfo != null) {
            paymentApply.setFinancingRateStr(reviewFinancingInfo.getFinancingRate().multiply(new BigDecimal("100")) + "%");
            paymentApply.setManagementFeeRateStr(reviewFinancingInfo.getManagementFeeRatio().multiply(new BigDecimal("100")) + "%");
            paymentApply.setInterestCalculate(reviewFinancingInfo.getInterestCalculate());
            paymentApply.setPayBackMethod(reviewFinancingInfo.getPayBackMethod());
        }

        List<PaymentCondition> conditionList = getPaymentConditions(paymentInfo, paymentApply);
        paymentApply.setConditionList(conditionList);

        return paymentApply;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void doEdit(PaymentApply paymentApply) {
        if (null == paymentApply || paymentApply.getPaymentInfoId() == null) {
            throw new ValidatorException(CodeUtil.FAIL, "付款申请不能为空");
        }
        saveOrUpdate(paymentApply);

        List<PaymentCondition> oldPaymentConditions = paymentConditionService.list(new QueryWrapper<PaymentCondition>().eq("payment_apply_id", paymentApply.getId()));
        if (CollectionUtil.isNotEmpty(oldPaymentConditions)) {
            for (PaymentCondition oldPaymentCondition : oldPaymentConditions) {
                List<PaymentConditionFileRef> fileRefList = paymentConditionFileRefService.list(new QueryWrapper<PaymentConditionFileRef>()
                        .eq("payment_condition_id", oldPaymentCondition.getId()));
                if (CollectionUtil.isNotEmpty(fileRefList)) {
                    List<Long> fileRefIds = fileRefList.stream().map(PaymentConditionFileRef::getId).collect(Collectors.toList());
                    paymentConditionFileRefService.removeByIds(fileRefIds);
                }
                paymentConditionService.removeById(oldPaymentCondition.getId());
            }
        }

        List<PaymentCondition> conditionList = paymentApply.getConditionList();
        if (CollectionUtil.isNotEmpty(conditionList)) {
            for (PaymentCondition paymentCondition : conditionList) {
                paymentCondition.setPaymentApplyId(paymentApply.getId());
                paymentConditionService.save(paymentCondition);
                List<Long> exemptionFileIds = paymentCondition.getExemptionFileIds();
                if (CollectionUtil.isNotEmpty(exemptionFileIds)) {
                    for (Long exemptionFileId : exemptionFileIds) {
                        PaymentConditionFileRef ref = new PaymentConditionFileRef(paymentCondition.getId(), exemptionFileId);
                        paymentConditionFileRefService.save(ref);
                    }
                }
            }
        }
        if (paymentApply.getVisible()) {
            PaymentApplyHis paymentApplyHis = addHistory(paymentApply);
            PaymentInfo paymentInfo = paymentInfoService.getById(paymentApply.getPaymentInfoId());
            if (paymentInfo == null) {
                throw new BusinessException(CodeUtil.FAIL, "获取不到对应付款信息");
            }
            CFinancingBasicInfo financingBasicInfo = financingBasicInfoService.getById(paymentInfo.getFinancingBasicInfoId());
            String key = ConstantUtil.FINANCING_APPLY;

            Map<String, Object> msgVariables = new HashMap<>(2);
            msgVariables.put(ConstantUtil.FLOWABLE_MSG_TITLE, financingBasicInfo.getBusinessNumber());
            msgVariables.put(ConstantUtil.FLOWABLE_MSG_CONTENT, "业务编号为“" + financingBasicInfo.getBusinessNumber() + "”的项目已inOut“"
                    + ConstantConversionUtil.flowBusinessKeyNames.get(key) + "—formBusiness”阶段，");

            boolean exempt = conditionList.stream().anyMatch(r -> r.getExempt().equals(1));
            Boolean result;
            if (exempt) {
                Map<String, Object> procVariables = new HashMap<>(1);
                String candidate = assigneeService.getCandidateByBusiness(financingBasicInfo.getId(), key, ConstantUtil.ASSIGNEE_PROJECT_MANAGER_OWNER);
                procVariables.put(ConstantUtil.EXEMPTION_APPROVAL_BUSINESS_CANDIDATE, candidate);
                List<Long> projectOwnerList = userService.findUserIdByRole(ConstantUtil.PROJECT_MANAGER_OWNER);
                if (projectOwnerList == null || projectOwnerList.size() == 0) {
                    throw new ValidatorException(CodeUtil.FAIL, ConstantUtil.PROJECT_MANAGER_OWNER + "角色内无任何用户！");
                }
                result = flowableService.completeMyTask(paymentApply.getTaskId(), financingBasicInfo, procVariables,
                        "有豁免", paymentApplyHis.getId(), msgVariables, key, projectOwnerList);
            } else {
                Map<String, Object> procVariables = new HashMap<>(1);
                String candidate = assigneeService.getCandidateByBusiness(financingBasicInfo.getId(), key, ConstantUtil.ASSIGNEE_LEGAL_SPECIALIST);
                procVariables.put(ConstantUtil.PAYMENT_APPROVAL_CANDIDATE, candidate);
                List<Long> legalSpecialists = userService.findUserIdByRole(ConstantUtil.LEGAL_SPECIALIST);
                if (legalSpecialists == null || legalSpecialists.size() == 0) {
                    throw new ValidatorException(CodeUtil.FAIL, ConstantUtil.LEGAL_SPECIALIST + "角色内无任何用户！");
                }
                result = flowableService.completeMyTask(paymentApply.getTaskId(), financingBasicInfo, procVariables,
                        "无豁免", paymentApplyHis.getId(), msgVariables, key, legalSpecialists);
            }
            if (result == null || !result) {
                throw new ValidatorException(CodeUtil.FAIL, "法务终审提交时出错啦！");
            }
        }
    }

    @Override
    public PaymentApproval getToApprovalPageById(Long id) {
        PaymentInfo paymentInfo = paymentInfoService.getOne(new QueryWrapper<PaymentInfo>().eq("c_financing_basic_info_id", id));
        if (paymentInfo == null) {
            throw new ValidatorException(CodeUtil.FAIL, "查询不到对应的付款信息！");
        }
        PaymentApply paymentApply = baseMapper.selectOne(new QueryWrapper<PaymentApply>().eq("payment_info_id", paymentInfo.getId()));
        if (paymentApply == null) {
            throw new ValidatorException(CodeUtil.FAIL, "查询不到对应的付款申请信息！");
        }
        PaymentApproval paymentApproval = paymentApprovalService.getOne(new QueryWrapper<PaymentApproval>().eq("payment_apply_id", paymentApply.getId())
                .eq("visible", false));
        if (paymentApproval == null) {
            paymentApproval = new PaymentApproval();
            paymentApproval.setPaymentApplyId(paymentApply.getId());
            //生成应收账款登记信息
            ReceivablesRegisterInfo receivablesRegister = createReceivablesRegister(id, paymentApply.getId());
            paymentApproval.setReceivablesRegisterInfo(receivablesRegister);
            //付款条件
            List<PaymentCondition> paymentConditionList = paymentConditionService.list(new QueryWrapper<PaymentCondition>()
                    .eq("payment_apply_id", paymentApply.getId()));
            if (CollectionUtil.isNotEmpty(paymentConditionList)) {
                for (PaymentCondition paymentCondition : paymentConditionList) {
                    //默认为满足
                    paymentCondition.setMeet(1);
                    List<PaymentConditionFileRef> fileRefList = paymentConditionFileRefService.list(new QueryWrapper<PaymentConditionFileRef>()
                            .eq("payment_condition_id", paymentCondition.getId()));
                    if (CollectionUtil.isNotEmpty(fileRefList)) {
                        List<FileStorage> fileStorageList = fileRefList.stream().map(fileRef -> fileStorageService.get(fileRef.getFileId())).collect(Collectors.toList());
                        paymentCondition.setExemptionFile(fileStorageList);
                    }
                }
            }
            paymentApproval.setPaymentConditionList(paymentConditionList);

            //判断该笔付款对应的额度支用-抵质押信息中是否有-抵押合同
            Boolean flag = false;
            List<ReviewMortgageBasicInfo> reviewMortgageBasicInfoList = reviewMortgageBasicInfoService.findByQuotaDisburseId(paymentInfo.getQuotaDisburseId());
            if (CollectionUtil.isNotEmpty(reviewMortgageBasicInfoList)) {
                for (ReviewMortgageBasicInfo reviewMortgageBasicInfo : reviewMortgageBasicInfoList) {
                    List<ReviewMortgageCollateralInfo> mortgageCollateralInfoList = reviewMortgageBasicInfo.getMortgageCollateralInfoList();
                    if (CollectionUtil.isNotEmpty(mortgageCollateralInfoList)) {
                        flag = true;
                        break;
                    }
                }
            }
            paymentApproval.setHasCollateralInfo(flag);

        }
        return paymentApproval;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editApproval(PaymentApproval paymentApproval) {
        if (null == paymentApproval || paymentApproval.getPaymentApplyId() == null) {
            throw new ValidatorException(CodeUtil.FAIL, "付款审核不能为空");
        }
        paymentApprovalService.saveOrUpdate(paymentApproval);

        ReceivablesRegisterInfo oldReceivablesRegisterInfo = receivablesRegisterInfoService.getOne(new QueryWrapper<ReceivablesRegisterInfo>().eq("payment_approval_id", paymentApproval.getId()));
        if (oldReceivablesRegisterInfo != null) {
            List<ReceivablesRegisterFile> registerFiles = receivablesRegisterFileService.list(new QueryWrapper<ReceivablesRegisterFile>()
                    .eq("receivables_register_id", oldReceivablesRegisterInfo.getId()));
            if (CollectionUtil.isNotEmpty(registerFiles)) {
                List<Long> fileIds = registerFiles.stream().map(ReceivablesRegisterFile::getFileId).collect(Collectors.toList());
                receivablesRegisterFileService.removeByIds(fileIds);
            }
            receivablesRegisterInfoService.removeById(oldReceivablesRegisterInfo.getId());
        }

        //保存应收账款登记信息
        ReceivablesRegisterInfo receivablesRegisterInfo = paymentApproval.getReceivablesRegisterInfo();
        if (receivablesRegisterInfo != null) {
            receivablesRegisterInfo.setPaymentApprovalId(paymentApproval.getId());
            receivablesRegisterInfoService.save(receivablesRegisterInfo);
            if (CollectionUtil.isNotEmpty(receivablesRegisterInfo.getReceivablesFileIds())) {
                for (Long fileId : receivablesRegisterInfo.getReceivablesFileIds()) {
                    ReceivablesRegisterFile receivablesRegisterFile = new ReceivablesRegisterFile(fileId, receivablesRegisterInfo.getId(), "receivables");
                    receivablesRegisterFileService.save(receivablesRegisterFile);
                }
            }
            if (CollectionUtil.isNotEmpty(receivablesRegisterInfo.getMortgageFileIds())) {
                for (Long fileId : receivablesRegisterInfo.getMortgageFileIds()) {
                    ReceivablesRegisterFile receivablesRegisterFile = new ReceivablesRegisterFile(fileId, receivablesRegisterInfo.getId(), "mortgage");
                    receivablesRegisterFileService.save(receivablesRegisterFile);
                }
            }
            if (CollectionUtil.isNotEmpty(receivablesRegisterInfo.getOwnershipFileIds())) {
                for (Long fileId : receivablesRegisterInfo.getOwnershipFileIds()) {
                    ReceivablesRegisterFile receivablesRegisterFile = new ReceivablesRegisterFile(fileId, receivablesRegisterInfo.getId(), "ownership");
                    receivablesRegisterFileService.save(receivablesRegisterFile);
                }
            }
        }
        //付款条件
        List<PaymentCondition> paymentConditionList = paymentApproval.getPaymentConditionList();
        if (CollectionUtil.isNotEmpty(paymentConditionList)) {
            for (PaymentCondition paymentCondition : paymentConditionList) {
                paymentConditionService.update(new UpdateWrapper<PaymentCondition>()
                        .eq("id", paymentCondition.getId())
                        .set("meet", paymentCondition.getMeet()));
            }
        }
        if (paymentApproval.getVisible()) {
            PaymentApply paymentApply = getById(paymentApproval.getPaymentApplyId());
            if (paymentApply == null) {
                throw new BusinessException(CodeUtil.FAIL, "获取不到对应付款申请信息");
            }
            PaymentInfo paymentInfo = paymentInfoService.getById(paymentApply.getPaymentInfoId());
            if (paymentInfo == null) {
                throw new BusinessException(CodeUtil.FAIL, "获取不到对应付款信息");
            }
            CFinancingBasicInfo financingBasicInfo = financingBasicInfoService.getById(paymentInfo.getFinancingBasicInfoId());
            String key = ConstantUtil.FINANCING_APPLY;

            Map<String, Object> msgVariables = new HashMap<>(2);
            msgVariables.put(ConstantUtil.FLOWABLE_MSG_TITLE, financingBasicInfo.getBusinessNumber());
            msgVariables.put(ConstantUtil.FLOWABLE_MSG_CONTENT, "业务编号为“" + financingBasicInfo.getBusinessNumber() + "”的项目已inOut“"
                    + ConstantConversionUtil.flowBusinessKeyNames.get(key) + "—formBusiness”阶段，");

            String conclusion = ConstantConversionUtil.processApprovalResult.get(paymentApproval.getApprovalConclusion()).equals("驳回") ?
                    "退回" : ConstantConversionUtil.processApprovalResult.get(paymentApproval.getApprovalConclusion());
            Boolean result = flowableService.completeMyTask(paymentApproval.getTaskId(), financingBasicInfo, null,
                    conclusion, paymentApproval.getId(), msgVariables, key);
            if (result == null || !result) {
                throw new ValidatorException(CodeUtil.FAIL, "法务终审提交时出错啦！");
            }
            if (paymentApproval.getApprovalConclusion().equals(ConstantConversionUtil.APPROVAL_RESULT_PASS)) {
                //修改融资申请当前阶段
                financingBasicInfo.setCurrentStage(FinancingCurrentStageEnum.PAYMENT_APPROVAL.getCode());
                //修改融资申请状态
                financingBasicInfo.setFinancingStatus(ProjectInitiationStatusDict.ChildEnum.COMPLETED.getCode());
                financingBasicInfoService.updateById(financingBasicInfo);
                //开启豁免跟进流程
                exemptionMattersService.startProcess(paymentApply.getId());
                //向sop推送融资信息
                financingToSop(financingBasicInfo);
            } else if (paymentApproval.getApprovalConclusion().equals(ConstantConversionUtil.APPROVAL_RESULT_BACK)) {
                //修改融资申请当前阶段
                financingBasicInfo.setCurrentStage(FinancingCurrentStageEnum.PAYMENT_APPLY.getCode());
                financingBasicInfoService.updateById(financingBasicInfo);
            }
        }
    }

    @Override
    public List<PaymentCondition> findConditions(Long applyId) {
        return paymentConditionService.lambdaQuery().eq(PaymentCondition::getPaymentApplyId,applyId).list();
    }

    /**
     * 向sop推送融资信息
     */
    private void financingToSop(CFinancingBasicInfo financingBasicInfo) {
        //查询sop对应的业务编号
        String getBusinessNoByTradeUrl = getBusinessNoByTrade + "?businessNumber=" + financingBasicInfo.getBusinessNumber();
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(getBusinessNoByTradeUrl, String.class);
        ResponseJson responseJson = JSONUtil.toBean(responseEntity.getBody(), ResponseJson.class);
        if (responseEntity.getStatusCode().value() != HttpStatus.OK.value() || !responseJson.isSuccess()) {
            throw new BusinessException(CodeUtil.FAIL, "查询sop对应的业务编号失败：" + responseJson.getMsg());
        }
        //推送底层
        if (financingBasicInfo.getSopAccountsReceivableId() == null || financingBasicInfo.getSopAccountsReceivableId().equals(0L)) {
            addUnderlyingInfoToSop(financingBasicInfo);
        }
        ReviewQuotaDisburse reviewQuotaDisburse = reviewQuotaDisburseService.getOne(new QueryWrapper<ReviewQuotaDisburse>()
                .eq("c_financing_basic_info_id", financingBasicInfo.getId())
                .eq("approval_conclusion", ConstantConversionUtil.APPROVAL_RESULT_PASS));

        QuotaDisburseReport quotaDisburseReport = new QuotaDisburseReport();
        quotaDisburseReport.setTransCode(ConstantUtil.QUOTA_DISBURSE_REPORT_TRANS_CODE);
        quotaDisburseReport.setCustomerId(ConstantUtil.QUOTA_DISBURSE_REPORT_CUSTOMER_ID);
        quotaDisburseReport.setSopAccountsReceivableId(financingBasicInfo.getSopAccountsReceivableId());
        quotaDisburseReport.setReportMethod(reviewQuotaDisburse.getReportMethod());

        JSONObject jsonObject = (JSONObject) responseJson.getData();
        quotaDisburseReport.setBusinessNo(jsonObject.getStr("businessNo"));
        quotaDisburseReport.setQuotaDisburseBatch(reviewQuotaDisburse.getQuotaDisburseBatch());
        //交易对手取贸易平台
        quotaDisburseReport.setCounterpartyCode(platformService.getById(financingBasicInfo.getPlatformId()).getSocialCreditCode());
        //填充主合同信息
        quotaDisburseReport = autoReviewMasterContractApi(reviewQuotaDisburse, quotaDisburseReport);
        //填充融资信息
        ReviewFinancingInfoApi reviewFinancingInfoApi = autoFinancingInfoApi(reviewQuotaDisburse);

        quotaDisburseReport.setReviewFinancingInfo(reviewFinancingInfoApi);
        //收支计划
        List<ReviewIncomeExpenditurePlan> planList = reviewIncomeExpenditurePlanService.list(new QueryWrapper<ReviewIncomeExpenditurePlan>()
                .eq("review_quota_disburse_id", reviewQuotaDisburse.getId()));
        List<IncomExpenditurePlanApi> planApiList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(planList)) {
            planList.stream().forEach(plan -> {
                IncomExpenditurePlanApi planApi = new IncomExpenditurePlanApi();
                BeanUtils.copyProperties(plan, planApi);
                planApi.setIncormExpenditureDate(plan.getIncomeExpenditureDate());
                planApi.setIncormExpenditureType(plan.getIncomeExpenditureType());
                planApiList.add(planApi);
            });
        }
        quotaDisburseReport.setIncomeExpenditurePlanList(planApiList);
        //保证信息(此字段其实已作废默认给1就行)
        quotaDisburseReport.setGuaranteeInformation(1);
        //相关还款责任人
        Boolean respRepay = reviewQuotaDisburse.getRespRepay();
        if (respRepay != null && respRepay) {
            //有相关还款责任人
            quotaDisburseReport.setRespRepay(1);
            List<ReviewRltRepay> rltRepayList = reviewRltRepayService.list(new QueryWrapper<ReviewRltRepay>()
                    .eq("review_quota_disburse_id", reviewQuotaDisburse.getId()));
            if (CollectionUtil.isNotEmpty(rltRepayList)) {
                List<RltRepay> rltRepayApiList = new ArrayList<>();
                rltRepayList.stream().forEach(reviewRltRepay -> {
                    RltRepay rltRepay = new RltRepay();
                    BeanUtils.copyProperties(reviewRltRepay, rltRepay);
                    rltRepayApiList.add(rltRepay);
                });
                quotaDisburseReport.setRltRepayList(rltRepayApiList);
            }
        } else {
            //无相关还款责任人
            quotaDisburseReport.setRespRepay(0);
        }
        //sop支用上报
        ResponseEntity<String> postResponseEntity = restTemplate.postForEntity(quotaDisburseReportUrl, quotaDisburseReport, String.class);
        ResponseJson postResponseJson = JSONUtil.toBean(postResponseEntity.getBody(), ResponseJson.class);
        if (postResponseEntity.getStatusCode().value() != HttpStatus.OK.value() || !postResponseJson.isSuccess()) {
            throw new BusinessException(CodeUtil.FAIL, "sop支用上报失败：" + postResponseJson.getMsg());
        }
    }

    /**
     * 填充主合同信息
     *
     * @param reviewQuotaDisburse
     * @param quotaDisburseReport
     * @return
     */
    private QuotaDisburseReport autoReviewMasterContractApi(ReviewQuotaDisburse reviewQuotaDisburse, QuotaDisburseReport quotaDisburseReport) {
        ReviewMasterContract reviewMasterContract = reviewMasterContractService.getOne(new QueryWrapper<ReviewMasterContract>()
                .eq("review_quota_disburse_id", reviewQuotaDisburse.getId()));
        quotaDisburseReport.setContractNo(reviewMasterContract.getContractNo());
        ReviewMasterContractApi reviewMasterContractApi = new ReviewMasterContractApi();
        BeanUtils.copyProperties(reviewMasterContract, reviewMasterContractApi);
        reviewMasterContractApi.setApplicantDesignatedbank(reviewMasterContract.getApplicantDesignatedBank());

        ContractInfo contractInfo = contractInfoService.getOne(new QueryWrapper<ContractInfo>()
                .eq("review_quota_disburse_id", reviewQuotaDisburse.getId())
                .orderByDesc("id").last("LIMIT 1"));
        if (contractInfo != null) {
            ContractMasterContract contractMasterContract = contractMasterContractService.getOne(new QueryWrapper<ContractMasterContract>()
                    .eq("contract_info_id", contractInfo.getId()));
            if (contractMasterContract != null) {
                reviewMasterContractApi.setContractNum(contractMasterContract.getContractNum());
                reviewMasterContractApi.setSpecialAgreement(contractMasterContract.getSpecialAgreement());
                reviewMasterContractApi.setFinancingConfirmAgreement(contractMasterContract.getFinancingConfirmAgreement());
                reviewMasterContractApi.setFactoringContractAgreement(contractMasterContract.getFactoringContractAgreement());
            }
            ContractFinancingInfo contractFinancingInfo = contractFinancingInfoService.getOne(new QueryWrapper<ContractFinancingInfo>()
                    .eq("contract_info_id", contractInfo.getId()));
            if (contractFinancingInfo != null) {
                reviewMasterContractApi.setPrincipalCollectionMethod(contractFinancingInfo.getPrincipalCollectionMethod());
                reviewMasterContractApi.setInterestCollectionMethod(contractFinancingInfo.getInterestCollectionMethod());
                reviewMasterContractApi.setManagementFeeCollectionMethod(contractFinancingInfo.getManagementFeeCollectionMethod());
                reviewMasterContractApi.setMarginCollectionMethod(contractFinancingInfo.getMarginCollectionMethod());
                reviewMasterContractApi.setMarginReturnMethod(contractFinancingInfo.getMarginReturnMethod());
                reviewMasterContractApi.setMarginReturnCondition(contractFinancingInfo.getMarginReturnCondition());
                reviewMasterContractApi.setOtherFeeCollectionMethod(contractFinancingInfo.getOtherFeeCollectionMethod());
            }
            //主合同债务人信息
            List<ReviewMasterContractDebtor> debtorList = reviewMasterContractDebtorService.list(new QueryWrapper<ReviewMasterContractDebtor>()
                    .eq("review_master_contract_id", reviewMasterContract.getId()));
            List<ReviewMasterContractDebtorApi> debtorApiList = new ArrayList<>();
            if (CollectionUtil.isNotEmpty(debtorList)) {
                debtorList.stream().forEach(debtor -> {
                    ReviewMasterContractDebtorApi debtorApi = new ReviewMasterContractDebtorApi();
                    BeanUtils.copyProperties(debtor, debtorApi);
                    debtorApi.setEnterpriseTag(0);
                    debtorApi.setSocialCreditCode(platformService.getOne(new QueryWrapper<Platform>().eq("platform_name", debtor.getCompanyName())).getSocialCreditCode());
                    debtorApiList.add(debtorApi);
                });
                quotaDisburseReport.setReviewMasterContractDebtor(debtorApiList.get(0));
            }
        }
        quotaDisburseReport.setReviewMasterContract(reviewMasterContractApi);
        return quotaDisburseReport;
    }

    /**
     * 填充融资信息
     *
     * @param reviewQuotaDisburse
     * @return
     */
    private ReviewFinancingInfoApi autoFinancingInfoApi(ReviewQuotaDisburse reviewQuotaDisburse) {
        ReviewFinancingInfo reviewFinancingInfo = reviewFinancingInfoService.getOne(new QueryWrapper<ReviewFinancingInfo>()
                .eq("review_quota_disburse_id", reviewQuotaDisburse.getId()));
        ReviewFinancingInfoApi reviewFinancingInfoApi = new ReviewFinancingInfoApi();
        BeanUtils.copyProperties(reviewFinancingInfo, reviewFinancingInfoApi);
        reviewFinancingInfoApi.setStartingDate(DateUtil.formateYMD(reviewFinancingInfo.getStartingDate()));
        reviewFinancingInfoApi.setCurrency(reviewFinancingInfo.getCurrencyCode());
        reviewFinancingInfoApi.setManagementRate(reviewFinancingInfo.getManagementFeeRatio());
        if ("paymentMethodForInterestManagementFee_A".equals(reviewFinancingInfo.getPayBackMethod())) {
            reviewFinancingInfoApi.setPayBackMethod("0");
        } else if ("paymentMethodForInterestManagementFee_B".equals(reviewFinancingInfo.getPayBackMethod())) {
            reviewFinancingInfoApi.setPayBackMethod("1");
        } else if ("paymentMethodForInterestManagementFee_C".equals(reviewFinancingInfo.getPayBackMethod())) {
            reviewFinancingInfoApi.setPayBackMethod("4");
        }
        if (reviewFinancingInfo.getDisburseExpiryDate() != null) {
            reviewFinancingInfoApi.setDisburseExpiryDate(DateUtil.formateYMD(reviewFinancingInfo.getDisburseExpiryDate()));
        }
        reviewFinancingInfoApi.setRefinancingManagement(reviewFinancingInfo.getInstitutionName());
        return reviewFinancingInfoApi;
    }

    /**
     * 同步底层信息到sop
     *
     * @param financingBasicInfo 融资信息
     */
    private void addUnderlyingInfoToSop(CFinancingBasicInfo financingBasicInfo) {
        //1.获取供应商的统一社会信用代码，取sop的底层基础信息获取对应的客户信息
        Enterprise supplier = enterpriseService.getById(financingBasicInfo.getMainEnterpriseId());
        if (supplier == null || supplier.getSocialCreditCode() == null) {
            throw new ValidatorException(CodeUtil.FAIL, "供应商或供应商的统一社会信用代码不存在");
        }
        ResponseEntity<Long> responseEntity = restTemplate.getForEntity(underlyingAssetsBasicIdUrl
                + "?socialCreditCode=" + supplier.getSocialCreditCode() + "&businessType=" + ConstantConversionUtil.DOMESTIC_FACTORING, Long.class);

        if (responseEntity.getBody() == null) {
            throw new BusinessException(CodeUtil.FAIL, "SOP中供应商不存在、请先前往sop-底层资产管理-国内保理中新增该客户！");
        }

        Long underlyingAssetsBasicId = responseEntity.getBody();

        //2.包装底层资产基本信息、同步至Sop
        PurchContractBasicInfo purchContractBasicInfo = getPurchContractBasicInfo(financingBasicInfo.getBusinessNumber());
        UnderlyingAssetsDomesticToSop domestic = new UnderlyingAssetsDomesticToSop(financingBasicInfo);
        domestic.setUnderlyingAssetsBasicId(underlyingAssetsBasicId);
        domestic.setContractName(purchContractBasicInfo.getContractName());
        domestic.setContractNo(purchContractBasicInfo.getContractNumber());
        domestic.setContractAmount(purchContractBasicInfo.getContractPlanAmount());
        domestic.setCustomerIdentity("creditor");
        //这里不能用核心企业、需要去取平台
        Platform platform = platformService.getById(financingBasicInfo.getPlatformId());
        if (platform == null || platform.getSocialCreditCode() == null) {
            throw new ValidatorException(CodeUtil.FAIL, "贸易平台或贸易平台的统一社会信用代码不存在");
        }
        Enterprise coreEnterprise = enterpriseService.getById(financingBasicInfo.getCoreEnterpriseId());
        if (coreEnterprise == null || coreEnterprise.getSocialCreditCode() == null) {
            throw new ValidatorException(CodeUtil.FAIL, "核心企业或核心企业的统一社会信用代码不存在");
        }
        domestic.setThirdPartyCustomerCode(platform.getSocialCreditCode());
        domestic.setThirdPartyIdentity("debtor");
        //核心企业名称
        domestic.setPurchaserName(coreEnterprise.getCorporateName());
        //销售合同编号
        CSalesContractBasicInfo salesContractBasicInfo = salesContractService.findByBusinessNumber(financingBasicInfo.getBusinessNumber());
        if (salesContractBasicInfo != null) {
            domestic.setSalesContractNumber(salesContractBasicInfo.getContractNumber());
            domestic.setSalesContractName(salesContractBasicInfo.getContractName());
        }
        ResponseEntity<Long> postForEntity = restTemplate.postForEntity(underlyingAssetsDomesticAddUrl, domestic, Long.class);

        if (postForEntity == null || postForEntity.getBody() == null) {
            throw new BusinessException(CodeUtil.FAIL, "添加底层基础信息失败");
        }
        Long assetsDomesticId = postForEntity.getBody();
        //3.包装应收账款数据、同步至sop
        List<CFinancingAccountsReceivableInfo> informationList = financingAccountsReceivableInfoService.list(new QueryWrapper<CFinancingAccountsReceivableInfo>()
                .eq("c_financing_basic_info_id", financingBasicInfo.getId()));
        ReviewQuotaDisburse reviewQuotaDisburse = reviewQuotaDisburseService.getOne(new QueryWrapper<ReviewQuotaDisburse>()
                .eq("c_financing_basic_info_id", financingBasicInfo.getId()));
        if (informationList != null && informationList.size() > 0) {
            DomesticAccountsReceivableToSop accountsReceivableToSop = new DomesticAccountsReceivableToSop(reviewQuotaDisburse);
            accountsReceivableToSop.setUnderlyingAssetsDomesticId(assetsDomesticId);
            //计算应收账款金额总和
            BigDecimal accountsReceivableAmount = informationList.stream().filter(accountsReceivable -> accountsReceivable.getAccountsReceivableAmount() != null)
                    .map(CFinancingAccountsReceivableInfo::getAccountsReceivableAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
            accountsReceivableToSop.setAccountsReceivableAmount(accountsReceivableAmount);
            //计算应收账款净额总和
            BigDecimal netAccountsReceivableAmount = informationList.stream().filter(accountsReceivable -> accountsReceivable.getNetAccountsReceivableAmount() != null)
                    .map(CFinancingAccountsReceivableInfo::getNetAccountsReceivableAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
            accountsReceivableToSop.setNetAccountsReceivableAmount(netAccountsReceivableAmount);
            accountsReceivableToSop.setAccountsReceivableGoodsList(informationList);
            ResponseEntity<Long> accountsReceivableEntity = restTemplate.postForEntity(domesticAccountsReceivableAddUrl, accountsReceivableToSop, Long.class);
            if (accountsReceivableEntity == null || accountsReceivableEntity.getBody() == null) {
                throw new BusinessException(CodeUtil.FAIL, "添加底层应收账款信息失败");
            }
            Long sopAccountsReceivableId = accountsReceivableEntity.getBody();
            financingBasicInfo.setSopAccountsReceivableId(sopAccountsReceivableId);
            financingBasicInfoService.updateById(financingBasicInfo);
        }
    }

    /**
     * 获取采购合同信息
     *
     * @param businessNumber
     * @return
     */
    private PurchContractBasicInfo getPurchContractBasicInfo(String businessNumber) {
        PurchContractManagement purchContractManagement = purchContractService.lambdaQuery().eq(PurchContractManagement::getBusinessNumber, businessNumber).one();
        if (purchContractManagement == null) {
            throw new BusinessException(CodeUtil.FAIL, "获取不到对应采购合同管理信息！");
        }
        PurchContractBasicInfo purchContractBasicInfo = purchContractBasicInfoService.lambdaQuery().eq(PurchContractBasicInfo::getPurchContractManagementId, purchContractManagement.getId()).one();
        if (purchContractBasicInfo == null) {
            throw new BusinessException(CodeUtil.FAIL, "获取不到对应采购合同信息！");
        }
        return purchContractBasicInfo;
    }

    /**
     * 生成应收账款登记信息
     *
     * @param id
     */
    private ReceivablesRegisterInfo createReceivablesRegister(Long id, Long paymentApplyId) {
        ReceivablesRegisterInfo registerInfo = new ReceivablesRegisterInfo();
        FileStorage fileStorage = createTemplate(id);
        registerInfo.setPaymentApplyId(paymentApplyId);
        registerInfo.setFileStorage(fileStorage);
        registerInfo.setFileId(fileStorage.getId());
        return registerInfo;
    }

    public FileStorage createTemplate(Long financingBasicInfoId) {
        CFinancingBasicInfo financingBasicInfo = financingBasicInfoService.getById(financingBasicInfoId);
        if (financingBasicInfo == null) {
            throw new ValidatorException(CodeUtil.FAIL, "查询不到对应的融资申请信息！");
        }
        ReviewQuotaDisburse reviewQuotaDisburse = reviewQuotaDisburseService.getOne(new QueryWrapper<ReviewQuotaDisburse>()
                .eq("c_financing_basic_info_id", financingBasicInfoId)
                .eq("approval_conclusion", ConstantConversionUtil.APPROVAL_RESULT_PASS));
        if (reviewQuotaDisburse == null) {
            throw new ValidatorException(CodeUtil.FAIL, "查询不到对应的额度支用信息！");
        }
        //主合同信息
        ReviewMasterContract reviewMasterContract = reviewMasterContractService.getOne(new QueryWrapper<ReviewMasterContract>()
                .eq("review_quota_disburse_id", reviewQuotaDisburse.getId()));
        if (reviewMasterContract == null) {
            throw new ValidatorException(CodeUtil.FAIL, "查询不到对应的主合同信息！");
        }
        //债务人信息
        List<ReviewMasterContractDebtor> debtorList = reviewMasterContractDebtorService.list(new QueryWrapper<ReviewMasterContractDebtor>()
                .eq("review_master_contract_id", reviewMasterContract.getId()));

        //融资信息
        ReviewFinancingInfo reviewFinancingInfo = reviewFinancingInfoService.getOne(new QueryWrapper<ReviewFinancingInfo>()
                .eq("review_quota_disburse_id", reviewQuotaDisburse.getId()));
        if (reviewFinancingInfo == null) {
            throw new ValidatorException(CodeUtil.FAIL, "查询不到对应的融资信息！");
        }

        Map<String, Object> paramMap = new HashMap<>();
        //登记期限
        Integer financingPeriod = reviewFinancingInfo.getFinancingPeriod();
        paramMap.put("registerMonth", financingPeriod.intValue() % 30 != 0 ? financingPeriod.intValue() / 30 + 4 : financingPeriod.intValue() / 30 + 3);
        //出让人名字
        paramMap.put("boliApplyName", reviewMasterContract.getApplicantCompanyName());
        //统一社会信用代码
        paramMap.put("socialCreditCode", reviewMasterContract.getApplicantSocialCreditCode());
        //法定代表人
        paramMap.put("legalPerson", reviewMasterContract.getApplicantCompanyLegalPerson());
        //所属行业
        Enterprise applicantCompany = enterpriseService.getOne(new QueryWrapper<Enterprise>().eq("social_credit_code", reviewMasterContract.getApplicantSocialCreditCode()));
        String getIndustryUrl = getIndustry + "?comprehensiveRiskInvestigationId=" + applicantCompany.getcComprehensiveRiskInvestigationId();
        String industry = restTemplate.getForObject(getIndustryUrl, String.class);
        paramMap.put("businessType", industry.replaceAll("\"", ""));
        //企业规模
        paramMap.put("companySize", "小型企业");
        //住所
        paramMap.put("registerAddress", reviewMasterContract.getApplicantCompanyAddress());
        //融资合同号码
        paramMap.put("boliContractNumber", reviewMasterContract.getContractNo());
        //合同名称
        paramMap.put("boliContractName", reviewMasterContract.getContractName());
        //融资币种
        paramMap.put("moneyType", dictService.getByCode(reviewFinancingInfo.getCurrencyCode()).getName());
        //融资金额
        BigDecimal financingAmount = reviewFinancingInfo.getOccupation() == 0 ? BigDecimal.ZERO : reviewFinancingInfo.getFinancingAmount();
        paramMap.put("amount", financingAmount);
        //转让币种
        paramMap.put("receivablesAmountType", dictService.getByCode(reviewFinancingInfo.getCurrencyCode()).getName());
        //转让金额
        paramMap.put("receivablesAmount", reviewQuotaDisburse.getAccountsReceivableNetAmountTotal());
        //产品类型-贸理通
        paramMap.put("productTypeDesc", "贸理通");
        paramMap.put("oneType", true);
        paramMap.put("twoType", false);
        paramMap.put("threeType", false);
        paramMap.put("fourType", false);
        //债务人
        if (CollectionUtil.isNotEmpty(debtorList)) {
            String debtorStr = debtorList.stream().map(ReviewMasterContractDebtor::getCompanyName).collect(Collectors.joining(","));
            paramMap.put("debtorName", debtorStr);
        }
        List<Map<String, Object>> childParamList = new ArrayList<>();
        Map<String, Object> childParamMap = new HashMap<>();

        PurchContractBasicInfo purchContractBasicInfo = getPurchContractBasicInfo(financingBasicInfo.getBusinessNumber());
        if (purchContractBasicInfo != null) {
            childParamMap.put("contractName", purchContractBasicInfo.getContractName());
            childParamMap.put("contractNo", purchContractBasicInfo.getContractNumber());
        }
        childParamMap.put("diCengAmount", reviewQuotaDisburse.getAccountsReceivableNetAmountTotal());
        childParamMap.put("diCengAmountCn", MoneyToCNFormatUtil.formatToCN(reviewQuotaDisburse.getAccountsReceivableNetAmountTotal().doubleValue()));
        childParamMap.put("invoice", "暂无");
        childParamMap.put("invoiceSize", "暂无");
        childParamList.add(childParamMap);
        paramMap.put("basicContractVOs", childParamList);


        List<ReviewMortgageBasicInfo> reviewMortgageBasicInfoList = reviewMortgageBasicInfoService.findByQuotaDisburseId(reviewQuotaDisburse.getId());
        BigDecimal amountTotal = BigDecimal.ZERO;
        String date = "";
        List<String> diyaContractNumber = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(reviewMortgageBasicInfoList)) {
            List<Map<String, Object>> machineList = new ArrayList<>();
            for (ReviewMortgageBasicInfo mortgageBasicInfo : reviewMortgageBasicInfoList) {
                if (mortgageBasicInfo.getGuarType() != 1) {
                    continue;
                }
                date = DateUtil.formateYMD(mortgageBasicInfo.getStartDate()) + "," + DateUtil.formateYMD(mortgageBasicInfo.getEndDate());
                if (!StringUtils.isEmpty(mortgageBasicInfo.getContractNo())) {
                    diyaContractNumber.add(mortgageBasicInfo.getContractNo());
                } else {
                    diyaContractNumber.add(mortgageBasicInfo.getMortgageNo());
                }
                List<ReviewMortgageCollateralInfo> mortgageCollateralInfoList = mortgageBasicInfo.getMortgageCollateralInfoList();
                if (CollectionUtil.isNotEmpty(mortgageCollateralInfoList)) {
                    for (int i = 0; i < mortgageCollateralInfoList.size(); i++) {
                        ReviewMortgageCollateralInfo reviewChattelMortgageDetail = mortgageCollateralInfoList.get(i);

                        Map<String, Object> machineMap = new HashMap<>();
                        machineMap.put("name", reviewChattelMortgageDetail.getCollateralName());
                        machineMap.put("number", reviewChattelMortgageDetail.getNumber());
                        machineMap.put("model", reviewChattelMortgageDetail.getCollateralType());
                        machineMap.put("engineNumber", reviewChattelMortgageDetail.getEngineNumber());
                        machineMap.put("trackNumber", reviewChattelMortgageDetail.getTrackNumber());
                        machineMap.put("location", reviewChattelMortgageDetail.getCollDistrictStr());
                        machineMap.put("deviceNumber", reviewChattelMortgageDetail.getCollCertId());
                        machineMap.put("amount", new BigDecimal(reviewChattelMortgageDetail.getCollValue()));
                        BigDecimal amount = new BigDecimal(reviewChattelMortgageDetail.getCollValue());
                        amountTotal = amountTotal.add(amount);
                        machineList.add(machineMap);
                    }
                }
            }
            paramMap.put("machineList", machineList);
            paramMap.put("diyaThingsFlag", true);
        } else {
            paramMap.put("diyaThingsFlag", false);
        }
        paramMap.put("diyaAmountTotal", amountTotal);
        paramMap.put("starEndTime", date);
        paramMap.put("diyaContractNumber", StringUtils.join(diyaContractNumber, ","));

        String s = UUID.randomUUID().toString();
        String fileName = s + ".docx";
        String path = FileUtil.getAbsolutePath(s, ".docx", FileModuleDict.ChildEnum.RECEIVABLES_ZHONGDENG_FILE);
        String filePath = createWord(new ClassPathResource("ftl/receivablesRegisterTemplate/zhongdeng-1.docx"), path, paramMap);
        FileStorage fileStorage = new FileStorage(fileName, "中登网登记模板.docx", filePath, FileModuleDict.ChildEnum.RECEIVABLES_ZHONGDENG_FILE);
        fileStorageService.add(fileStorage);
        return fileStorage;
    }

    public static String createWord(ClassPathResource classPathResource, String fileDir, Map<String, Object> paramMap) {
        try {
            File file = new File(fileDir);
            if (!file.exists()) {
                FileUtils.createParentDirectories(file);
            }
            // 读取模板渲染参数
            XWPFTemplate template = XWPFTemplate.compile(classPathResource.getInputStream()).render(paramMap);
            // 将模板参数写入路径
            template.writeToFile(fileDir);
            template.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileDir;
    }


    /**
     * 保存付款历史
     *
     * @param paymentApply
     */
    private PaymentApplyHis addHistory(PaymentApply paymentApply) {
        PaymentApplyHis paymentApplyHis = new PaymentApplyHis();
        BeanUtils.copyProperties(paymentApply, paymentApplyHis, "id");
        paymentApplyHis.setPaymentApplyId(paymentApply.getId());
        paymentApplyHisService.save(paymentApplyHis);

        List<PaymentCondition> conditionList = paymentApply.getConditionList();
        for (PaymentCondition paymentCondition : conditionList) {
            PaymentConditionHis paymentConditionHis = new PaymentConditionHis();
            BeanUtils.copyProperties(paymentCondition, paymentConditionHis, "id");
            paymentConditionHis.setPaymentApplyHisId(paymentApplyHis.getId());
            paymentConditionHisService.save(paymentConditionHis);
            if (CollectionUtil.isNotEmpty(paymentCondition.getExemptionFileIds())) {
                for (Long exemptionFileId : paymentCondition.getExemptionFileIds()) {
                    PaymentConditionFileRefHis refHis = new PaymentConditionFileRefHis(paymentConditionHis.getId(), exemptionFileId);
                    paymentConditionFileRefHisService.save(refHis);
                }
            }
        }
        return paymentApplyHis;
    }

    private List<PaymentCondition> getPaymentConditions(PaymentInfo paymentInfo, PaymentApply paymentApply) {
        List<PaymentCondition> conditionList = new ArrayList<>();

        if (paymentApply.getId() != null) {
            conditionList = paymentConditionService.list(new QueryWrapper<PaymentCondition>().eq("payment_apply_id", paymentApply.getId()));
            for (PaymentCondition condition : conditionList) {
                List<PaymentConditionFileRef> conditionFileRefs = paymentConditionFileRefService.list(new QueryWrapper<PaymentConditionFileRef>()
                        .eq("payment_condition_id", condition.getId()));
                List<FileStorage> exemptionFile = new ArrayList<>();
                if (CollectionUtil.isNotEmpty(conditionFileRefs)) {
                    for (PaymentConditionFileRef conditionFileRef : conditionFileRefs) {
                        FileStorage fileStorage = fileStorageService.get(conditionFileRef.getFileId());
                        exemptionFile.add(fileStorage);
                    }
                }
                condition.setExemptionFile(exemptionFile);
            }
        } else {
            List<ContractLoanConditionSetting> loanConditionSettings = contractLoanConditionSettingService.list(new QueryWrapper<ContractLoanConditionSetting>()
                    .eq("contract_info_id", paymentInfo.getContractInfoId()));
            if (CollectionUtil.isNotEmpty(loanConditionSettings)) {
                for (ContractLoanConditionSetting loanConditionSetting : loanConditionSettings) {
                    if (loanConditionSetting.getChecked()) {
                        PaymentCondition paymentCondition = new PaymentCondition();
                        paymentCondition.setConditionContent(loanConditionSetting.getLoanCondition());
                        paymentCondition.setExempt(0);
                        conditionList.add(paymentCondition);
                    }
                }
            }
        }
        return conditionList;
    }

    /**
     * 获取本金放款计划
     *
     * @param reviewQuotaDisburseId
     * @return
     */
    public List<ReviewIncomeExpenditurePlan> getPrincipalLoanList(Long reviewQuotaDisburseId) {
        List<ReviewIncomeExpenditurePlan> filterlist = new ArrayList<>();
        if (reviewQuotaDisburseId != null) {
            List<ReviewIncomeExpenditurePlan> list = reviewIncomeExpenditurePlanService.list(new QueryWrapper<ReviewIncomeExpenditurePlan>()
                    .eq("review_quota_disburse_id", reviewQuotaDisburseId));
            filterlist = list.stream()
                    .filter((e) -> StringUtil.isNotBlank(e.getIncomeExpenditureType()))
                    .filter((e) -> e.getIncomeExpenditureType().equals(IncomeExpenditureTypeDict.ChildEnum.PRINCIPAL.getCode()))
                    .filter((e) -> e.getLoan() != null).collect(Collectors.toList());
        }
        return filterlist;
    }
}
