package com.sunxung.factoring.service.financing.contract.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import com.sunxung.factoring.component.exception.BusinessException;
import com.sunxung.factoring.component.util.*;
import com.sunxung.factoring.dict.impl.FactoringServiceScopeDict;
import com.sunxung.factoring.dict.impl.FileModuleDict;
import com.sunxung.factoring.dict.impl.IncomeExpenditureTypeDict;
import com.sunxung.factoring.dict.impl.TransferNoticeMethodDict;
import com.sunxung.factoring.entity.creditresolution.CreditResolution;
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.*;
import com.sunxung.factoring.entity.financing.contractTemplate.ContractTemplate;
import com.sunxung.factoring.entity.financing.review.*;
import com.sunxung.factoring.entity.project.vo.ProjectInformationVo;
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.Dictionary;
import com.sunxung.factoring.entity.sys.FileStorage;
import com.sunxung.factoring.entity.tradingPlatform.Platform;
import com.sunxung.factoring.service.creditresolution.ICreditResolutionService;
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.*;
import com.sunxung.factoring.service.financing.contractTemplate.IContractTemplateService;
import com.sunxung.factoring.service.financing.review.*;
import com.sunxung.factoring.service.project.IProjectInformationService;
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.ISysAttachmentRefService;
import com.sunxung.factoring.service.sys.dto.AttachmentDto;
import com.sunxung.factoring.service.tradingPlatform.PlatformService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description :
 * @Author : L.Jia
 * @Date: 2024-02-19 20:44
 */

@Service
public class NewContractMakingServiceImpl implements INewContractMakingService {

    @Autowired
    private ReviewQuotaDisburseService reviewQuotaDisburseService;
    @Autowired
    private ReviewQuotaDisburseApprovalService reviewQuotaDisburseApprovalService;
    @Autowired
    private IContractLoanConditionSettingService contractLoanConditionSettingService;
    @Autowired
    private ReviewMasterContractService reviewMasterContractService;
    @Autowired
    private ReviewMasterContractDebtorService reviewMasterContractDebtorService;
    @Autowired
    private ReviewFinancingInfoService reviewFinancingInfoService;
    @Autowired
    private ReviewIncomeExpenditurePlanService reviewIncomeExpenditurePlanService;
    @Autowired
    private ReviewLoanConditionService reviewLoanConditionService;
    @Autowired
    private ICFinancingBasicInfoService financingBasicInfoService;
    @Autowired
    private IEnterpriseService enterpriseService;
    @Autowired
    private SalesContractService salesContractService;
    @Autowired
    private IContractTemplateService contractTemplateService;
    @Autowired
    private ISysAttachmentRefService sysAttachmentRefService;
    @Autowired
    private ReviewRltRepayService reviewRltRepayService;
    @Autowired
    private ReviewTransferReceivableService reviewTransferReceivableService;
    @Autowired
    private ICreditResolutionService creditResolutionService;
    @Autowired
    private IProjectInformationService projectInformationService;
    @Autowired
    private ReviewMortgageBasicInfoService mortgageBasicInfoService;
    @Autowired
    private ReviewMortgagePledgeInfoService reviewMortgagePledgeInfoService;
    @Autowired
    private ReviewMortgageCollateralInfoService reviewMortgageCollateralInfoService;
    @Autowired
    private IReviewRltRepayEstateService reviewRltRepayEstateService;
    @Autowired
    private IReviewRltRepayVehicleService reviewRltRepayVehicleService;
    @Autowired
    private IReviewRltRepayEquityAssetsService reviewRltRepayEquityAssetsService;
    @Autowired
    private IReviewRltRepayOtherAssetsService reviewRltRepayOtherAssetsService;
    @Autowired
    private IReviewRltRepayLandService reviewRltRepayLandService;
    @Autowired
    private DictionaryService dictService;
    @Autowired
    private IContractMasterContractService contractMasterContractService;
    @Autowired
    private IContractFinancingInfoService contractFinancingInfoService;
    @Autowired
    private PurchContractService purchContractService;
    @Autowired
    private PurchContractBasicInfoService purchContractBasicInfoService;
    @Autowired
    private ICFinancingAccountsReceivableInfoService financingAccountsReceivableInfoService;
    @Autowired
    private IContractBasicContractService contractBasicContractService;
    @Autowired
    private PlatformService platformService;

    @Override
    public void createContractDocument(String type, Long id, ContractInfo contractInfo, List<File> list) {
        ContractTemplate contractTemplate = contractTemplateService.lambdaQuery().eq(ContractTemplate::getTemplateCode, type).eq(ContractTemplate::getVisible, 1).one();
        AttachmentDto attachmentDto = AttachmentDto.builder()
                .setEntityId(contractTemplate.getId())
                .setChildEnum(FileModuleDict.ChildEnum.CONTRACT_TEMPLATE_FILE)
                .build();
        List<FileStorage> files = sysAttachmentRefService.getFiles(attachmentDto);
        FileStorage fileStorage = files.get(0);
        String absolutePath = fileStorage.getAbsolutePath();
        String name = contractTemplate.getName();
        if (type.equals(ConstantConversionUtil.TRIPARTITE_AGREEMENT_FACTORING)) {
            // 下载(贸理通)三方协议
            dealNewtTripartiteAgreementFactoringDownload(contractInfo, list, id, absolutePath);
        } else if (type.equals(ConstantConversionUtil.TRIPARTITE_AGREEMENT)) {
            //下载三方协议
            dealNewtTripartiteAgreementDownload(contractInfo, list, id, absolutePath);
        } else if (type.equals(ConstantConversionUtil.POOL_FACTORING_BUSINESS_CONTRACT) ||
                type.equals(ConstantConversionUtil.FACTORING_BUSINESS_CONTRACT)) {
            //下载池保理业务合同
            dealNewPoolFactoringBusinessContract(contractInfo, list, absolutePath, type);
        } else if (type.equals(ConstantConversionUtil.POOL_FACTORING_FINANCING_CONFIRM) ||
                type.equals(ConstantConversionUtil.POOL_FACTORING_INFORMATION_DOMESTIC) ||
                type.equals(ConstantConversionUtil.FACTORING_SERVICE_CONFIRMATION)) {
            // 注意事项：设置excel表格的时，一定要设置ss:ExpandedRowCount行数，建议其值设置较大，如500，防止创建excel行数不够导致失败
            // 下载保理信息表或保理融资确认书
            dealNewFactoringInfo(contractInfo, list, absolutePath, type);
        } else if (type.equals(ConstantConversionUtil.ACCOUNT_RECEIVABLE_TRANSFER_NOTICE) ||
                type.equals(ConstantConversionUtil.DOMESTIC_ACCOUNT_RECEIVABLE_TRANSFER_NOTICE_BRIGHT)) {
            // 应收账款转让通知书
            dealNewNoticeDownloadAll(contractInfo, list, absolutePath, type);
        } else if (type.equals(ConstantConversionUtil.POOL_FACTORING_ACCOUNT_RECEIVABLE) ||
                type.equals(ConstantConversionUtil.DOMESTIC_ACCOUNT_RECEIVABLE_TRANSFER_CONFIRM) ||
                type.equals(ConstantConversionUtil.ACCOUNTS_RECEIVABLE_ASSIGNMENT_AGREEMENT)) {
            // 应收账款入池确认书 应收账款转让协议
            dealNewConfirmDownload(contractInfo, list, absolutePath, type);
        } else if (type.equals(ConstantConversionUtil.SPOUSE_STATEMENT_GUARANTEE_SPOUSE)) {
            // 配偶声明
            dealNewSpouseStatement(id, contractInfo, list, absolutePath, name);
        } else if (type.equals(ConstantConversionUtil.FACTORING_CONTRACT_NUMBER_GUARANTEE_COMPANY) ||
                type.equals(ConstantConversionUtil.FACTORING_CONTRACT_NUMBER_GUARANTEE_PERSON)) {
            // 财产清单
            dealNewDssetsDetail(id, contractInfo, list, absolutePath);
        } else if (type.equals(ConstantConversionUtil.MOVABLE_MORTGAGE_CONTRACT_NUMBER_GUARANTEE_COMPANY) ||
                type.equals(ConstantConversionUtil.MOVABLE_MORTGAGE_CONTRACT_NUMBER_GUARANTEE_PERSONAL)) {
            // 动产抵押合同
            dealNewChattelMortgageContract(id, contractInfo, list, absolutePath);
        } else if (type.equals(ConstantConversionUtil.STOCK_RIGHT_CONTRACT_NUMBER_PLEDGOR_COMPANY) ||
                type.equals(ConstantConversionUtil.STOCK_RIGHT_CONTRACT_NUMBER_PLEDGOR_PERSONAL)) {
            // 股权质押合同
            dealNewEquityPledgeContract(id, contractInfo, list, absolutePath);
        } else if (type.equals(ConstantConversionUtil.MAXIMUM_GUARANTEE_CULVER_COMPANY) ||
                type.equals(ConstantConversionUtil.MAXIMUM_GUARANTEE_CULVER_PERSONAL) ||
                type.equals(ConstantConversionUtil.MAXIMUM_GUARANTEE_CULVER_COMPANY_M2) ||
                type.equals(ConstantConversionUtil.MAXIMUM_GUARANTEE_CULVER_PERSONAL_M2)) {
            // 担保涵 最高额保证 2023.3.20 新增m2的最高额保障合同
            dealMaximumGuaranteeCulevert(id, contractInfo, list, absolutePath);
        } else if (type.equals(ConstantConversionUtil.GENERAL_GUARANTEE_COMPANY) ||
                type.equals(ConstantConversionUtil.GENERAL_GUARANTEE_PERSONAL) ||
                type.equals(ConstantConversionUtil.GENERAL_GUARANTEE_COMPANY_M2) ||
                type.equals(ConstantConversionUtil.GENERAL_GUARANTEE_PERSONAL_M2)) {
            // 担保涵 常规担保函 2023.3.20 新增m2的常规担保函
            dealNewGuaranteeCulevert(id, contractInfo, list, absolutePath, name);
        } else if (type.equals(ConstantConversionUtil.TRADING_INFO)) {
            // 下载交易信息表
            dealNewTradingInfoDownload(contractInfo, list, id, absolutePath);
        }
    }

    /**
     * 配偶声明
     *
     * @param reviewRltRepayId
     * @param contractInfo
     * @param list
     * @param absolutePath
     * @param contractName
     */
    private void dealNewSpouseStatement(Long reviewRltRepayId, ContractInfo contractInfo, List<File> list, String absolutePath, String contractName) {
        try {
            // 主合同信息
            ReviewMasterContract masterContract = reviewMasterContractService.lambdaQuery().eq(ReviewMasterContract::getReviewQuotaDisburseId, contractInfo.getReviewQuotaDisburseId()).one();
            // 保理合同编号
            String factoringContractNo = masterContract.getContractNo();
            // 保理申请人公司名称
            String applicantCompanyName = masterContract.getApplicantCompanyName();
            // 融资信息
            ReviewFinancingInfo contractFinancingInfo = reviewFinancingInfoService.lambdaQuery().eq(ReviewFinancingInfo::getReviewQuotaDisburseId, contractInfo.getReviewQuotaDisburseId()).one();
            // 融资金额
            BigDecimal financingAmount = BigDecimal.ZERO;
            if (null != contractFinancingInfo) {
                financingAmount = contractFinancingInfo.getFinancingAmount();
            }
            // 币种中文名称
            String currency_cn = "人民币";
            // 币种英文名称
            String currency_en = "CNY";
            ReviewRltRepay rltRepay = reviewRltRepayService.getById(reviewRltRepayId);
            //社会统一信用代码/身份证号码
            String certificateNo = rltRepay.getArlpCertNum();
            //住所
            String address = rltRepay.getAddress();
            //保证合同编号
            String guaranteeContractNo;
            if (rltRepay.getGuaranteeContractNo() != null && !rltRepay.getGuaranteeContractNo().equals("")) {
                guaranteeContractNo = rltRepay.getGuaranteeContractNo();
            } else {
                guaranteeContractNo = rltRepay.getMaxGuarMcc();
            }
            //责任人名称
            String guarantorName = rltRepay.getArlpName();
            //住所地(营业执照地址)
            String actualAddress = rltRepay.getActualAddress();
            //责任人联系方式
            String contactNumber = rltRepay.getResponsiblePhone();
            //责任人法定代表人
            String legalRepresentative = rltRepay.getLegalRepresentative();
            //责任人邮箱
            String guarantorEmail = rltRepay.getResponsibleEmail();
            // 配偶名称
            String spouseName = rltRepay.getSpouseName();
            // 配偶身份证
            String spouseIdcard = rltRepay.getSpouseIdCard();

            if (null != rltRepay && rltRepay.getArlpIdType() != null) {
                String type = rltRepay.getArlpIdType();
                // 个人
                if (type.equals(ConstantConversionUtil.IDENTITY_TYPE1)) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("guaranteeContractNo", guaranteeContractNo);
                    map.put("applicantCompanyName", applicantCompanyName);
                    map.put("factoringContractNo", factoringContractNo);
                    map.put("contractName", contractName);
                    map.put("guarantorName", guarantorName);
                    map.put("certificateNo", certificateNo);
                    map.put("spouseName", spouseName);
                    map.put("spouseIdcard", spouseIdcard);
                    map.put("currency_en", currency_en);// 英文币种
                    map.put("currency_cn", currency_cn);// 中文币种
                    String amountCname = "";
                    if (financingAmount != null) {
                        amountCname = MoneyToCNFormatUtil
                                .formatToCN(contractFinancingInfo.getFinancingAmount().doubleValue());
                        financingAmount = contractFinancingInfo.getFinancingAmount();
                    }
                    map.put("financingAmountCname", amountCname);
                    map.put("financingAmount", financingAmount);
                    Date date = new Date();
                    map.put("year", DateUtil.getYear(date));
                    map.put("month", DateUtil.getMonth(date));
                    map.put("day", DateUtil.getDay(date));
                    // 配偶声明（只有个人才有，并且配偶身份证或配偶名称至少有一个不为空）
                    if (StringUtil.isNotEmpty(spouseName) || StringUtil.isNotEmpty(spouseIdcard)) {
                        XWPFTemplate template = XWPFTemplate.compile(absolutePath).render(map);
                        String path = FileUtil.getAbsolutePath("配偶声明" + guarantorName, ".docx", FileModuleDict.ChildEnum.CONTRACT_FILE_PREVIEW);

                        File file = new File(path);
                        if (!file.exists()) {
                            FileUtils.createParentDirectories(file);
                        }
                        template.writeToFile(path);
                        list.add(file);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(CodeUtil.FAIL, "下载配偶声明出错" + e.getMessage());
        }
    }

    /**
     * 财产清单
     *
     * @param reviewRltRepayId
     * @param contractInfo
     * @param list
     * @param absolutePath
     */
    private void dealNewDssetsDetail(Long reviewRltRepayId, ContractInfo contractInfo, List<File> list, String absolutePath) {
        try {
            ReviewRltRepay rltRepay = reviewRltRepayService.getById(reviewRltRepayId);
            if (null != rltRepay && rltRepay.getArlpIdType() != null) {
                String type = rltRepay.getArlpIdType();
                //社会统一信用代码/身份证号码
                String certificateNo = rltRepay.getArlpCertNum();
                //住所
                String address = rltRepay.getAddress();
                //责任人名称
                String guarantorName = rltRepay.getArlpName();
                //住所地(营业执照地址)
                String actualAddress = rltRepay.getActualAddress();
                //责任人联系方式
                String contactNumber = rltRepay.getResponsiblePhone();
                //责任人法定代表人
                String legalRepresentative = rltRepay.getLegalRepresentative();
                //责任人邮箱
                String guarantorEmail = rltRepay.getResponsibleEmail();

                //填充资产信息
                //房产
                List<ReviewRltRepayEstate> repayEstates = reviewRltRepayEstateService
                        .lambdaQuery().eq(ReviewRltRepayEstate::getReviewRltRepayId, reviewRltRepayId).list();
                //车辆
                List<ReviewRltRepayVehicle> vehicles = reviewRltRepayVehicleService
                        .lambdaQuery().eq(ReviewRltRepayVehicle::getReviewRltRepayId, reviewRltRepayId).list();

                //股权
                List<ReviewRltRepayEquityAssets> equityAssetsList = reviewRltRepayEquityAssetsService
                        .lambdaQuery().eq(ReviewRltRepayEquityAssets::getReviewRltRepayId, reviewRltRepayId).list();

                //其它
                List<ReviewRltRepayOtherAssets> otherAssetsList = reviewRltRepayOtherAssetsService
                        .lambdaQuery().eq(ReviewRltRepayOtherAssets::getReviewRltRepayId, reviewRltRepayId).list();

                // 不动产清单（土地）
                List<ReviewRltRepayLand> landList = reviewRltRepayLandService
                        .lambdaQuery().eq(ReviewRltRepayLand::getReviewRltRepayId, reviewRltRepayId).list();

                if (type.equals(ConstantConversionUtil.IDENTITY_TYPE1)) {
                    // 个人
                    String spouseName = rltRepay.getSpouseName();
                    String spouseIdcard = rltRepay.getSpouseIdCard();
                    if (rltRepay.getPropertyList() == 1) {
                        // 房产
                        Map<String, Object> propertyMap = new HashMap<>();
                        List<Map<String, Object>> eastate = new ArrayList<>();
                        propertyMap.put("guarantorName", guarantorName);
                        propertyMap.put("certificateNo", certificateNo);
                        propertyMap.put("spouseName", spouseName);
                        propertyMap.put("spouseIdcard", spouseIdcard);
                        propertyMap.put("address", address);
                        propertyMap.put("actualAddress", actualAddress);
                        propertyMap.put("contactNumber", contactNumber);
                        Date date = new Date();
                        propertyMap.put("day", DateUtil.getDay(date));
                        propertyMap.put("month", DateUtil.getMonth(date));
                        propertyMap.put("year", DateUtil.getYear(date));
                        // 房产清单
                        if (CollectionUtil.isNotEmpty(repayEstates)) {
                            int recordNo = 0;
                            for (ReviewRltRepayEstate estate : repayEstates) {
                                recordNo = recordNo + 1;
                                Map<String, Object> estateMap = new HashMap<>();
                                estateMap.put("recordNo", recordNo);
                                estateMap.put("houseAddressDoorNumber", estate.getHouseAddressDoorNumber());
                                estateMap.put("purchaseContract", estate.getPurchaseContract());
                                estateMap.put("housePropertyNo", estate.getHousePropertyNo());
                                // 有无贷款
                                String loan = "无";
                                if (null != estate.getLoan() && estate.getLoan() == 1) {
                                    loan = "有";
                                }
                                estateMap.put("loan", loan);
                                // 贷款余额
                                String loanBalanceStr = "";
                                BigDecimal loanBalance = estate.getLoanBalance();
                                if (null != loanBalance) {
                                    loanBalanceStr = NumberFormatUtil.convertDecimal(loanBalance,
                                            NumberFormatUtil.THOUSAND_SEPARATOR_TWO_DECIMAL) + "元";
                                }
                                estateMap.put("loanBalance", loanBalanceStr);
                                // 是否出租
                                String rent = "否";
                                if (null != estate.getRent() && estate.getRent() == 1) {
                                    rent = "是";
                                }
                                estateMap.put("rent", rent);
                                eastate.add(estateMap);
                            }
                        }
                        propertyMap.put("estateList", eastate);
                        // 车辆清单
                        List<Map<String, Object>> vehicleListMap = new ArrayList<>();
                        if (CollectionUtil.isNotEmpty(vehicles)) {
                            int recordNo = 0;
                            for (ReviewRltRepayVehicle vehicle : vehicles) {
                                recordNo = recordNo + 1;
                                Map<String, Object> vehicleMap = new HashMap<>();
                                vehicleMap.put("recordNo", recordNo);
                                vehicleMap.put("vehicleNameLicenseNo", vehicle.getVehicleNameLicenseNo());
                                String purchaseDateStr = "";
                                if (null != vehicle.getPurchaseDate()) {
                                    purchaseDateStr = DateUtil.formateYMD(vehicle.getPurchaseDate());
                                }
                                vehicleMap.put("purchaseDate", purchaseDateStr);
                                vehicleMap.put("engineNo", vehicle.getEngineNo());
                                vehicleMap.put("drivingLicenseNo", vehicle.getDrivingLicenseNo());
                                // 有无贷款
                                String loanStr = "无";
                                if (null != vehicle.getLoan() && vehicle.getLoan() == 1) {
                                    loanStr = "有";
                                }
                                vehicleMap.put("loan", loanStr);
                                // 贷款余额
                                String loanBalanceStr = "";
                                BigDecimal loanBalance = vehicle.getLoanBalance();
                                if (null != loanBalance) {
                                    loanBalanceStr = NumberFormatUtil.convertDecimal(loanBalance,
                                            NumberFormatUtil.THOUSAND_SEPARATOR_TWO_DECIMAL) + "元";
                                }
                                vehicleMap.put("loanBalance", loanBalanceStr);
                                vehicleListMap.add(vehicleMap);
                            }
                        }
                        propertyMap.put("vehicleList", vehicleListMap);
                        // 股权资产
                        List<Map<String, Object>> equityAssetsListMap = new ArrayList<>();
                        if (CollectionUtil.isNotEmpty(equityAssetsList)) {
                            int recordNo = 0;
                            for (ReviewRltRepayEquityAssets equityAssets : equityAssetsList) {
                                recordNo = recordNo + 1;
                                Map<String, Object> equityAssetsMap = new HashMap<>();
                                equityAssetsMap.put("recordNo", recordNo);
                                equityAssetsMap.put("companyName", equityAssets.getCompanyName());
                                // 注册资金
                                String registeredCapitalStr = "";
                                BigDecimal registeredCapital = equityAssets.getRegisteredCapital();
                                if (null != registeredCapital) {
                                    registeredCapitalStr = NumberFormatUtil.convertDecimal(registeredCapital,
                                            NumberFormatUtil.THOUSAND_SEPARATOR_TWO_DECIMAL) + "元";
                                }
                                equityAssetsMap.put("registeredCapital", registeredCapitalStr);
                                // 投资日期
                                String investmentDateStr = "";
                                if (null != equityAssets.getInvestmentDate()) {
                                    investmentDateStr = DateUtil.formateYMD(equityAssets.getInvestmentDate());
                                }
                                String ratioStr = PercentageUtil.convertPercentage(equityAssets.getRatio().doubleValue());
                                equityAssetsMap.put("investmentDate", investmentDateStr);
                                equityAssetsMap.put("ratioStr", ratioStr);
                                // 实物/现金出资
                                String investmentAmountStr = "";
                                BigDecimal investmentAmount = equityAssets.getInvestmentAmount();
                                if (null != investmentAmount) {
                                    investmentAmountStr = NumberFormatUtil.convertDecimal(investmentAmount,
                                            NumberFormatUtil.THOUSAND_SEPARATOR_TWO_DECIMAL) + "元";
                                }
                                equityAssetsMap.put("investmentAmount", investmentAmountStr);
                                equityAssetsMap.put("position", equityAssets.getPosition());
                                equityAssetsListMap.add(equityAssetsMap);
                            }
                        }
                        propertyMap.put("equityList", equityAssetsListMap);
                        // 其他资产
                        List<Map<String, Object>> otherListMap = new ArrayList<>();
                        if (CollectionUtil.isNotEmpty(otherAssetsList)) {
                            int recordNo = 0;
                            for (ReviewRltRepayOtherAssets otherAssets : otherAssetsList) {
                                recordNo = recordNo + 1;
                                Map<String, Object> otherMap = new HashMap<>();
                                otherMap.put("recordNo", recordNo);
                                otherMap.put("otherStr", otherAssets.getOtherAssets());
                                otherListMap.add(otherMap);
                            }
                        }
                        propertyMap.put("otherList", otherListMap);
                        //模板动态表格
                        LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
                        Configure config = Configure.builder()
                                .bind("estateList", policy).bind("vehicleList", policy)
                                .bind("equityList", policy).bind("otherList", policy).build();
                        XWPFTemplate template = XWPFTemplate.compile(absolutePath, config).render(propertyMap);
                        String path = FileUtil.getAbsolutePath("财产清单（个人）" + guarantorName, ".docx",
                                FileModuleDict.ChildEnum.CONTRACT_FILE_PREVIEW);
                        File estateFile = new File(path);
                        if (!estateFile.exists()) {
                            FileUtils.createParentDirectories(estateFile);
                        }
                        template.writeToFile(path);
                        list.add(estateFile);
                    }
                } else if (type.equals(ConstantConversionUtil.IDENTITY_TYPE2)) {
                    // 公司
                    // 财产清单
                    if (rltRepay.getPropertyList() == 1) {
                        // 房产
                        Map<String, Object> propertyMap = new HashMap<>();
                        List<Map<String, Object>> eastate = new ArrayList<>();
                        propertyMap.put("guarantorName", guarantorName);
                        propertyMap.put("certificateNo", certificateNo);
                        propertyMap.put("address", address);
                        propertyMap.put("actualAddress", actualAddress);
                        propertyMap.put("contactNumber", rltRepay.getResponsiblePhone());
                        Date date = new Date();
                        propertyMap.put("day", DateUtil.getDay(date));
                        propertyMap.put("month", DateUtil.getMonth(date));
                        propertyMap.put("year", DateUtil.getYear(date));
                        // 房产清单
                        if (CollectionUtil.isNotEmpty(repayEstates)) {
                            int recordNo = 0;
                            for (ReviewRltRepayEstate estate : repayEstates) {
                                recordNo = recordNo + 1;
                                Map<String, Object> estateMap = new HashMap<>();
                                estateMap.put("recordNo", recordNo);
                                estateMap.put("houseAddressDoorNumber", estate.getHouseAddressDoorNumber());
                                estateMap.put("purchaseContract", estate.getPurchaseContract());
                                estateMap.put("housePropertyNo", estate.getHousePropertyNo());
                                // 有无贷款
                                String loan = "无";
                                if (null != estate.getLoan() && estate.getLoan() == 1) {
                                    loan = "有";
                                }
                                estateMap.put("loan", loan);
                                // 贷款余额
                                String loanBalanceStr = "";
                                BigDecimal loanBalance = estate.getLoanBalance();
                                if (null != loanBalance) {
                                    loanBalanceStr = NumberFormatUtil.convertDecimal(loanBalance,
                                            NumberFormatUtil.THOUSAND_SEPARATOR_TWO_DECIMAL) + "元";
                                }
                                estateMap.put("loanBalance", loanBalanceStr);
                                // 是否出租
                                String rent = "否";
                                if (null != estate.getRent() && estate.getRent() == 1) {
                                    rent = "是";
                                }
                                estateMap.put("rent", rent);
                                eastate.add(estateMap);
                            }
                        }
                        propertyMap.put("estateList", eastate);

                        // 不动产清单（土地）
                        List<Map<String, Object>> landListMap = new ArrayList<>();
                        if (CollectionUtil.isNotEmpty(landList)) {
                            int recordNo = 0;
                            for (ReviewRltRepayLand land : landList) {
                                recordNo = recordNo + 1;
                                Map<String, Object> landMap = new HashMap<>();
                                landMap.put("recordNo", recordNo);
                                landMap.put("location", land.getLocation());
                                landMap.put("landNo", land.getLandNo());
                                landMap.put("originalBookValue", land.getOriginalBookValue());
                                landMap.put("area", land.getArea());
                                landMap.put("landNature", land.getLandNature());
                                // 抵押/按揭
                                String mortgageInstallmentName = "";
                                String mortgageInstallment = land.getMortgageInstallment();
                                if (StringUtil.isNotEmpty(mortgageInstallment)) {
                                    if (mortgageInstallment.equals("mortgage")) {
                                        mortgageInstallmentName = "抵押";
                                    } else if (mortgageInstallment.equals("installment")) {
                                        mortgageInstallmentName = "按揭";
                                    }
                                }
                                landMap.put("mortgageInstallment", mortgageInstallmentName);
                                landMap.put("reamrk", land.getReamrk());
                                landListMap.add(landMap);
                            }
                        }
                        propertyMap.put("landList", landListMap);
                        // 车辆清单
                        List<Map<String, Object>> vehicleListMap = new ArrayList<>();
                        if (null != vehicles && vehicles.size() > 0) {
                            int recordNo = 0;
                            for (ReviewRltRepayVehicle vehicle : vehicles) {
                                recordNo = recordNo + 1;
                                Map<String, Object> vehicleMap = new HashMap<>();
                                vehicleMap.put("recordNo", recordNo);
                                vehicleMap.put("vehicleNameLicenseNo", vehicle.getVehicleNameLicenseNo());
                                String purchaseDateStr = "";
                                if (null != vehicle.getPurchaseDate()) {
                                    purchaseDateStr = DateUtil.formateYMD(vehicle.getPurchaseDate());
                                }
                                vehicleMap.put("purchaseDate", purchaseDateStr);
                                vehicleMap.put("engineNo", vehicle.getEngineNo());
                                vehicleMap.put("drivingLicenseNo", vehicle.getDrivingLicenseNo());
                                // 有无贷款
                                String loanStr = "无";
                                if (null != vehicle.getLoan() && vehicle.getLoan() == 1) {
                                    loanStr = "有";
                                }
                                vehicleMap.put("loan", loanStr);
                                // 贷款余额
                                String loanBalanceStr = "";
                                BigDecimal loanBalance = vehicle.getLoanBalance();
                                if (null != loanBalance) {
                                    loanBalanceStr = NumberFormatUtil.convertDecimal(loanBalance,
                                            NumberFormatUtil.THOUSAND_SEPARATOR_TWO_DECIMAL) + "元";
                                }
                                vehicleMap.put("loanBalance", loanBalanceStr);
                                vehicleListMap.add(vehicleMap);
                            }
                        }
                        propertyMap.put("vehicleList", vehicleListMap);
                        // 股权资产
                        List<Map<String, Object>> equityAssetsListMap = new ArrayList<>();
                        if (null != equityAssetsList && equityAssetsList.size() > 0) {
                            int recordNo = 0;
                            for (ReviewRltRepayEquityAssets equityAssets : equityAssetsList) {
                                recordNo = recordNo + 1;
                                Map<String, Object> equityAssetsMap = new HashMap<>();
                                equityAssetsMap.put("recordNo", recordNo);
                                equityAssetsMap.put("companyName", equityAssets.getCompanyName());
                                // 注册资金
                                String registeredCapitalStr = "";
                                BigDecimal registeredCapital = equityAssets.getRegisteredCapital();
                                if (null != registeredCapital) {
                                    registeredCapitalStr = NumberFormatUtil.convertDecimal(registeredCapital,
                                            NumberFormatUtil.THOUSAND_SEPARATOR_TWO_DECIMAL) + "元";
                                }
                                equityAssetsMap.put("registeredCapital", registeredCapitalStr);
                                // 投资日期
                                String investmentDateStr = "";
                                if (null != equityAssets.getInvestmentDate()) {
                                    investmentDateStr = DateUtil.formateYMD(equityAssets.getInvestmentDate());
                                }
                                // 出资比例
                                String ratioStr = PercentageUtil.convertPercentage(equityAssets.getRatio().doubleValue());
                                equityAssetsMap.put("investmentDate", investmentDateStr);
                                equityAssetsMap.put("ratioStr", ratioStr);
                                // 实物/现金出资
                                String investmentAmountStr = "";
                                BigDecimal investmentAmount = equityAssets.getInvestmentAmount();
                                if (null != investmentAmount) {
                                    investmentAmountStr = NumberFormatUtil.convertDecimal(investmentAmount,
                                            NumberFormatUtil.THOUSAND_SEPARATOR_TWO_DECIMAL) + "元";
                                }
                                // 有无验资报告
                                String report = equityAssets.getReport();
                                String reportName = "无";
                                if (null != report) {
                                    if (report.equals(1)) {
                                        reportName = "有";
                                    } else {
                                        reportName = "无";
                                    }
                                }
                                equityAssetsMap.put("investmentAmount", investmentAmountStr);
                                equityAssetsMap.put("report", reportName);
                                equityAssetsListMap.add(equityAssetsMap);
                            }
                        }
                        propertyMap.put("equityList", equityAssetsListMap);
                        // 其他资产
                        List<Map<String, Object>> otherListMap = new ArrayList<>();
                        if (null != otherAssetsList && otherAssetsList.size() > 0) {
                            int recordNo = 0;
                            for (ReviewRltRepayOtherAssets otherAssets : otherAssetsList) {
                                recordNo = recordNo + 1;
                                Map<String, Object> otherMap = new HashMap<>();
                                otherMap.put("recordNo", recordNo);
                                otherMap.put("otherStr", otherAssets.getOtherAssets());
                                otherListMap.add(otherMap);
                            }
                        }
                        propertyMap.put("otherList", otherListMap);
                        //模板动态表格
                        LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
                        Configure config = Configure.builder()
                                .bind("estateList", policy).bind("landList", policy)
                                .bind("vehicleList", policy).bind("equityList", policy)
                                .bind("otherList", policy).build();
                        XWPFTemplate template = XWPFTemplate.compile(absolutePath, config).render(propertyMap);
                        String path = FileUtil.getAbsolutePath("财产清单（公司）" + guarantorName, ".docx", FileModuleDict.ChildEnum.CONTRACT_FILE_PREVIEW);
                        File estateFile = new File(path);
                        if (!estateFile.exists()) {
                            FileUtils.createParentDirectories(estateFile);
                        }
                        template.writeToFile(path);
                        list.add(estateFile);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(CodeUtil.FAIL, "下载财产清单出错" + e.getMessage());
        }
    }

    /**
     * 动产抵押
     *
     * @param chattelMortgageId
     * @param contractInfo
     * @param list
     * @param absolutePath
     */
    private void dealNewChattelMortgageContract(Long chattelMortgageId, ContractInfo contractInfo, List<File> list, String absolutePath) {
        try {
            // 主合同信息
            ReviewMasterContract masterContract = reviewMasterContractService.lambdaQuery().eq(ReviewMasterContract::getReviewQuotaDisburseId, contractInfo.getReviewQuotaDisburseId()).one();
            // 保理申请人公司名称
            String applicantCompanyName = masterContract.getApplicantCompanyName();
            //保理商公司名称
            String factoringName = masterContract.getFactoringName();
            //保理商法人代表
            String factoringLegalPersion = masterContract.getFactoringLegalPerson();
            //保理商注册地址
            String factoringAddress = masterContract.getFactoringAddress();
            // 保理合同编号
            String factoringContractNo = masterContract.getContractNo();
            // 合同名称
            String contractName = masterContract.getContractName();
            // 设置债务人
            String debtorCompanyName = "";
            List<ReviewMasterContractDebtor> debtorList = reviewMasterContractDebtorService.lambdaQuery().eq(ReviewMasterContractDebtor::getReviewMasterContractId, masterContract.getId()).list();

            if (null != debtorList && debtorList.size() > 0) {
                for (ReviewMasterContractDebtor debtor : debtorList) {
                    debtorCompanyName = debtorCompanyName + debtor.getCompanyName() + "、";
                }
                if (StringUtil.isNotEmpty(debtorCompanyName) && debtorCompanyName.contains("、")) {
                    debtorCompanyName = debtorCompanyName.substring(0, debtorCompanyName.toString().length() - 1);
                }
            }
            // 融资金额
            BigDecimal financingAmount = BigDecimal.ZERO;
            // 币种中文名称
            String currency_cn = "人民币";
            // 币种英文名称
            String currency_en = "CNY";
            // 融资信息
            ReviewFinancingInfo contractFinancingInfo = reviewFinancingInfoService.lambdaQuery().eq(ReviewFinancingInfo::getReviewQuotaDisburseId, contractInfo.getReviewQuotaDisburseId()).one();

            if (null != contractFinancingInfo) {
                financingAmount = contractFinancingInfo.getFinancingAmount();
            }
            //抵质押基础信息
            ReviewMortgageBasicInfo mortgageBasicInfo = mortgageBasicInfoService.getById(chattelMortgageId);
            if (mortgageBasicInfo != null) {
                //抵押信息
                //动产抵押合同编号
                String chattelMortgageContractNo;
                if (mortgageBasicInfo.getContractNo() != null && !mortgageBasicInfo.getContractNo().equals("")) {
                    chattelMortgageContractNo = mortgageBasicInfo.getContractNo();
                } else {
                    chattelMortgageContractNo = mortgageBasicInfo.getMortgageNo();
                }

                //抵押人名称
                String mortgagorName = mortgageBasicInfo.getMortgagorName();
                // 法定代表人
                String legalRepresentative = mortgageBasicInfo.getLegalRepresentative();
                // 证件号
                String certificateNo = mortgageBasicInfo.getMortgagorCertNum();
                //住所地
                String address = mortgageBasicInfo.getAddress();
                //实际办公地址
                String actualAddress = mortgageBasicInfo.getActualAddress();
                //联系方式
                String contactNumber = mortgageBasicInfo.getContactNumber();
                //债务人身份类别 组织机构/自然人
                String type = mortgageBasicInfo.getDebtorIdType();

                Map<String, Object> map = new HashMap<>();

                List<ReviewMortgageCollateralInfo> collateralInfos = reviewMortgageCollateralInfoService.lambdaQuery().eq(ReviewMortgageCollateralInfo::getReviewMortgageBasicId, mortgageBasicInfo.getId()).list();
                if (CollectionUtil.isNotEmpty(collateralInfos)) {
                    collateralInfos = collateralInfos.stream().filter(c -> c.getCollType()
                            .equals(ConstantConversionUtil.COLLATERAL_TYPE_JQSB)).collect(Collectors.toList());
                    // 动产抵押详情list
                    List<Map<String, Object>> detailList = new ArrayList<>();
                    int recordNo = 0;
                    for (ReviewMortgageCollateralInfo collateral : collateralInfos) {
                        recordNo = recordNo + 1;
                        Map<String, Object> detailMap = new HashMap<>();
                        detailMap.put("recordNo", recordNo);
                        detailMap.put("collateralName", StringUtil.deleteString(collateral.getCollateralName(), '&'));
                        detailMap.put("location", collateral.getCollDistrictStr());
                        detailMap.put("number", collateral.getNumber());
                        detailMap.put("collateralType", collateral.getCollateralType());
                        detailMap.put("deviceNo", collateral.getCollCertId());
                        detailMap.put("trackNumber", collateral.getTrackNumber());
                        detailMap.put("engineNumber", collateral.getEngineNumber());
                        detailMap.put("other", collateral.getCollDesc());
                        detailMap.put("amount", collateral.getCollValue());
                        detailList.add(detailMap);
                    }


                    map.put("detailList", detailList);
                    //循环表格内容
                    LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
                    Configure config = Configure.builder().bind("detailList", policy).build();
                    map.put("chattelMortgageContractNo", chattelMortgageContractNo);
                    map.put("debtorCompanyName", debtorCompanyName);
                    map.put("mortgagorName", mortgagorName);
                    map.put("certificateNo", certificateNo);
                    map.put("address", address);
                    map.put("actualAddress", actualAddress);
                    map.put("factoringAddressOrigin", masterContract.getFactoringAddress());//地址
                    map.put("contactNumber", contactNumber);
                    map.put("applicantCompanyName", applicantCompanyName);
                    map.put("factoringName", factoringName);
                    map.put("factoringLegalPersion", factoringLegalPersion);
                    map.put("factoringAddress", ConstantUtil.OUR_COMPANY_ADDRESS_NAME);
                    map.put("factoringContractNo", factoringContractNo);
                    map.put("contractName", contractName);
                    map.put("legalRepresentative", legalRepresentative);
                    map.put("currency_cn", currency_cn);
                    map.put("currency_en", currency_en);
                    Date date = new Date();
                    map.put("year", DateUtil.getYear(date));
                    map.put("month", DateUtil.getMonth(date));
                    map.put("day", DateUtil.getDay(date));
                    if (type.equals(ConstantConversionUtil.IDENTITY_TYPE2)) {
                        Enterprise enterprise = enterpriseService.lambdaQuery().eq(Enterprise::getCorporateName, mortgagorName).one();
                        if (enterprise != null) {
                            String socialCreditCode = enterprise.getSocialCreditCode();
                            map.put("socialCreditCode", socialCreditCode);
                        }
                    }

                    // 融资金额中文
                    String financingAmount_cn = "";
                    if (null != financingAmount && StringUtil.isNotEmpty(currency_cn)) {
                        financingAmount_cn = MoneyToCNFormatUtil.formatToCN(financingAmount.doubleValue());
                    }
                    // 融资金额英文
                    String financingAmount_en = "";
                    if (null != financingAmount && StringUtil.isNotEmpty(currency_en)) {
                        financingAmount_en = currency_en + " " + financingAmount + "元";
                    }
                    map.put("financingAmountCname", financingAmount_cn);
                    map.put("financingAmountEname", financingAmount_en);
                    map.put("financingAmount", NumberFormatUtil.convertDecimal(financingAmount,
                            NumberFormatUtil.THOUSAND_SEPARATOR_TWO_DECIMAL));
                    String path = FileUtil.getAbsolutePath(UUID.randomUUID().toString(), ".docx", FileModuleDict.ChildEnum.CONTRACT_FILE_PREVIEW);
                    XWPFTemplate template = XWPFTemplate.compile(absolutePath, config).render(map);
                    File file = new File(path);
                    if (!file.exists()) {
                        FileUtils.createParentDirectories(file);
                    }
                    template.writeToFile(path);
                    list.add(file);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(CodeUtil.FAIL, "下载动产股权抵押合同错误错误" + e.getMessage());
        }
    }

    /**
     * 股权质押
     *
     * @param chattelMortgageId
     * @param contractInfo
     * @param list
     * @param absolutePath
     */
    private void dealNewEquityPledgeContract(Long chattelMortgageId, ContractInfo contractInfo, List<File> list, String absolutePath) {
        try {
            // 币种中文名称
            String currency_cn = "人民币";
            // 币种英文名称
            String currency_en = "CNY";
            ProjectInformationVo projectInformationVo = projectInformationService.getByBusinessNo(contractInfo.getBusinessNo());
            CreditResolution creditResolution = creditResolutionService.getByProjectInformationId(projectInformationVo.getProjectInformationId());
            // 融资金额
            BigDecimal financingAmount = BigDecimal.ZERO;
            // 主合同信息
            ReviewMasterContract masterContract = reviewMasterContractService.lambdaQuery().eq(ReviewMasterContract::getReviewQuotaDisburseId, contractInfo.getReviewQuotaDisburseId()).one();
            //抵质押基础信息
            ReviewMortgageBasicInfo mortgageBasicInfo = mortgageBasicInfoService.getById(chattelMortgageId);
            //抵质押合同编号
            String chattelMortgageContractNo;
            if (mortgageBasicInfo.getContractNo() != null && !mortgageBasicInfo.getContractNo().equals("")) {
                chattelMortgageContractNo = mortgageBasicInfo.getContractNo();
            } else {
                chattelMortgageContractNo = mortgageBasicInfo.getMortgageNo();
            }
            //抵押人名称
            String pledgeName = mortgageBasicInfo.getMortgagorName();
            // 法定代表人
            String legalRepresentative = mortgageBasicInfo.getLegalRepresentative();
            // 证件号
            String certificateNo = mortgageBasicInfo.getMortgagorCertNum();
            //住所地
            String address = mortgageBasicInfo.getAddress();
            //实际办公地址
            String actualAddress = mortgageBasicInfo.getActualAddress();
            //联系方式
            String contactNumber = mortgageBasicInfo.getContactNumber();
            //债务人身份类别 组织机构/自然人
            String type = mortgageBasicInfo.getDebtorIdType();
            //质押信息
            List<ReviewMortgagePledgeInfo> pledgeInfos = reviewMortgagePledgeInfoService.lambdaQuery().eq(ReviewMortgagePledgeInfo::getReviewMortgageBasicId, mortgageBasicInfo.getId()).list();

            if (CollectionUtil.isNotEmpty(pledgeInfos)) {
                pledgeInfos = pledgeInfos.stream().filter(c -> c.getPleType().equals(ConstantConversionUtil.PLEDGE_TYPE_EQUITY))
                        .collect(Collectors.toList());
                for (ReviewMortgagePledgeInfo pledgeInfo : pledgeInfos) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("pledgeContractNo", chattelMortgageContractNo);
                    map.put("pledgeName", pledgeName);
                    map.put("legalRepresentative", legalRepresentative);
                    map.put("certificateNo", certificateNo);
                    map.put("address", address);
                    map.put("actualAddress", actualAddress);
                    map.put("contactNumber", contactNumber);
                    map.put("contractNo", masterContract.getContractNo());
                    map.put("applicantCompanyName", masterContract.getApplicantCompanyName());
                    map.put("contractName", masterContract.getContractName());
                    map.put("company", pledgeInfo.getCompany());
                    map.put("equityRatioStr", PercentageUtil.convertPercentage(pledgeInfo.getEquityRatio().longValue()));
                    map.put("shareNumber", pledgeInfo.getShareNumber().toString());
                    map.put("shareAmmount", pledgeInfo.getPleValue());
                    map.put("currencyCn", currency_cn);// 币种中文
                    map.put("currencyEn", currency_en);// 币种英文
                    // 债务履行开始日
                    String startDateStr = "";
                    if (null != mortgageBasicInfo.getStartDate()) {
                        startDateStr = DateUtil.formateYMD(mortgageBasicInfo.getStartDate());
                    }
                    // 债务履行到期日
                    String endDateStr = "";
                    if (null != mortgageBasicInfo.getEndDate()) {
                        endDateStr = DateUtil.formateYMD(mortgageBasicInfo.getEndDate());
                    }
                    map.put("factoringName", masterContract.getFactoringName());
                    map.put("factoringLegalPersion", masterContract.getFactoringLegalPerson());
                    map.put("factoringAddressOrigin", masterContract.getFactoringAddress());//地址
                    map.put("factoringAddress", ConstantUtil.OUR_COMPANY_ADDRESS_NAME);
                    map.put("startDate", startDateStr);
                    map.put("endDate", endDateStr);
                    Date date = new Date();
                    map.put("year", DateUtil.getYear(date));
                    map.put("month", DateUtil.getMonth(date));
                    map.put("day", DateUtil.getDay(date));
                    String financingAmountCname = "";
                    if (null != creditResolution.getFinancingAmount()) {
                        financingAmountCname = MoneyToCNFormatUtil
                                .formatToCN(creditResolution.getFinancingAmount().doubleValue());
                        financingAmount = creditResolution.getFinancingAmount();
                    }
                    map.put("financingAmount", financingAmount.toString());
                    map.put("financingAmountCname", financingAmountCname);

                    String path = FileUtil.getAbsolutePath(UUID.randomUUID().toString(), ".docx", FileModuleDict.ChildEnum.CONTRACT_FILE_PREVIEW);
                    File file = new File(path);
                    if (!file.exists()) {
                        FileUtils.createParentDirectories(file);
                    }
                    XWPFTemplate template = XWPFTemplate.compile(absolutePath).render(map);
                    template.writeToFile(path);
                    list.add(file);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(CodeUtil.FAIL, "下载股权质押合同出错" + e.getMessage());
        }
    }

    /**
     * 担保涵 最高额
     *
     * @param reviewRltRepayId
     * @param contractInfo
     * @param list
     * @param absolutePath
     */
    private void dealMaximumGuaranteeCulevert(Long reviewRltRepayId, ContractInfo contractInfo, List<File> list, String absolutePath) {
        try {
            // 主合同信息
            ReviewMasterContract masterContract = reviewMasterContractService.lambdaQuery().eq(ReviewMasterContract::getReviewQuotaDisburseId, contractInfo.getReviewQuotaDisburseId()).one();
            // 授信信息
            ProjectInformationVo projectInformationVo = projectInformationService.getByBusinessNo(contractInfo.getBusinessNo());
            CreditResolution creditResolution = creditResolutionService.getByProjectInformationId(projectInformationVo.getProjectInformationId());
            // 币种中文名称
            String currency_cn = "人民币";
            // 币种英文名称
            String currency_en = "CNY";
            String creditLineCname = "";
            String creditLine = "";
            if (null != creditResolution.getProposedCreditLine()) {
                creditLineCname = MoneyToCNFormatUtil
                        .formatToCN(creditResolution.getProposedCreditLine().doubleValue());
                creditLine = creditResolution.getProposedCreditLine().toString();
            }
            // 合同名称
            String contractName = masterContract.getContractName();
            // 保理合同编号
            String factoringContractNo = masterContract.getContractNo();
            // 保理申请人
            String applicantContact = masterContract.getApplicantContact();
            // 保理申请人公司名称
            String applicantCompanyName = masterContract.getApplicantCompanyName();
            List<ReviewMasterContractDebtor> debtorList = reviewMasterContractDebtorService.lambdaQuery().eq(ReviewMasterContractDebtor::getReviewMasterContractId, masterContract.getId()).list();
            // 设置债务人
            String debtorCompanyName = "";
            if (null != debtorList && debtorList.size() > 0) {
                for (ReviewMasterContractDebtor debtor : debtorList) {
                    debtorCompanyName = debtorCompanyName + debtor.getCompanyName() + "、";
                }
                if (StringUtil.isNotEmpty(debtorCompanyName) && debtorCompanyName.contains("、")) {
                    debtorCompanyName = debtorCompanyName.substring(0, debtorCompanyName.toString().length() - 1);
                }
            }
            // 融资信息
            ReviewFinancingInfo contractFinancingInfo = reviewFinancingInfoService.lambdaQuery().eq(ReviewFinancingInfo::getReviewQuotaDisburseId, contractInfo.getReviewQuotaDisburseId()).one();
            // 融资金额
            BigDecimal financingAmount = null;
            if (null != contractFinancingInfo) {
                financingAmount = contractFinancingInfo.getFinancingAmount();
            }
            Date date = new Date();
            //相关还款责任人
            ReviewRltRepay rltRepay = reviewRltRepayService.getById(reviewRltRepayId);
            //社会统一信用代码/身份证号码
            String certificateNo = rltRepay.getArlpCertNum();
            //住所
            String address = rltRepay.getAddress();
            //保证合同编号
            String guaranteeContractNo;
            if (rltRepay.getGuaranteeContractNo() != null && !rltRepay.getGuaranteeContractNo().equals("")) {
                guaranteeContractNo = rltRepay.getGuaranteeContractNo();
            } else {
                guaranteeContractNo = rltRepay.getMaxGuarMcc();
            }
            //责任人名称
            String guarantorName = rltRepay.getArlpName();
            //住所地(营业执照地址)
            String actualAddress = rltRepay.getActualAddress();
            //责任人联系方式
            String contactNumber = rltRepay.getResponsiblePhone();
            //责任人法定代表人
            String legalRepresentative = rltRepay.getLegalRepresentative();
            //责任人邮箱
            String guarantorEmail = rltRepay.getResponsibleEmail();

            Map<String, Object> map = new HashMap<>();
            ;
            if (null != rltRepay && rltRepay.getArlpIdType() != null) {
                String type = rltRepay.getArlpIdType();
                // 个人
                if (type.equals(ConstantConversionUtil.IDENTITY_TYPE1)) {
                    map.put("guaranteeContractNo", guaranteeContractNo);
                    map.put("applicantCompanyName", applicantCompanyName);
                    map.put("applicantContact", applicantContact);
                    map.put("factoringContractNo", factoringContractNo);
                    map.put("receivableTransferNo", factoringContractNo + "-ZR");
                    map.put("contractName", contractName);
                    map.put("factoringName", masterContract.getFactoringName());
                    map.put("factoringLegalPerson", masterContract.getFactoringLegalPerson());
                    map.put("factoringAddressOrigin", masterContract.getFactoringAddress());//住所
                    map.put("factoringAddress", ConstantUtil.OUR_COMPANY_ADDRESS_NAME);//联系地址
                    map.put("factoringAgentPhone", masterContract.getFactoringAgentPhone());
                    map.put("factoringAgentEmail", masterContract.getFactoringAgentEmail());
                    map.put("guarantorName", guarantorName);
                    map.put("certificateNo", certificateNo);
                    map.put("address", address);
                    map.put("actualAddress", actualAddress);
                    map.put("contactNumber", contactNumber);
                    map.put("legalRepresentative", legalRepresentative);
                    map.put("guarantorEmail", guarantorEmail);
                    map.put("day", DateUtil.getDay(date));
                    map.put("month", DateUtil.getMonth(date));
                    map.put("year", DateUtil.getYear(date));
                    // 配偶名称
                    String spouseName = rltRepay.getSpouseName();
                    // 配偶身份证
                    String spouseIdcard = rltRepay.getSpouseIdCard();
                    map.put("spouseName", spouseName);
                    map.put("spouseIdcard", spouseIdcard);
                    map.put("spouseIdcard", spouseIdcard);
                    String amountEname = "";
                    String amountCname = "";
                    if (financingAmount != null) {
                        amountCname = MoneyToCNFormatUtil.formatToCN(financingAmount.doubleValue());
                        amountEname = financingAmount + "元";
                    }
                    map.put("financingAmount", amountEname);
                    map.put("financingAmountStr", amountCname);
                    // 债务人公司名称
                    map.put("debtorCompanyName", debtorCompanyName);
                    // 授信金额
                    map.put("creditLine", creditLine);
                    map.put("currency_en", currency_en);
                    map.put("creditLineCname", creditLineCname);
                    map.put("currency_cn", currency_cn);

                } else {
                    // 公司
                    map.put("guaranteeContractNo", guaranteeContractNo);
                    map.put("applicantCompanyName", applicantCompanyName);
                    map.put("applicantContact", applicantContact);
                    map.put("factoringContractNo", factoringContractNo);
                    map.put("factoringName", masterContract.getFactoringName());
                    map.put("factoringLegalPerson", masterContract.getFactoringLegalPerson());
                    map.put("factoringAddressOrigin", masterContract.getFactoringAddress());//住所
                    map.put("factoringAddress", ConstantUtil.OUR_COMPANY_ADDRESS_NAME);//联系地址
                    map.put("factoringAgentPhone", masterContract.getFactoringAgentPhone());
                    map.put("factoringAgentEmail", masterContract.getFactoringAgentEmail());
                    map.put("contractName", contractName);
                    map.put("guarantorName", guarantorName);
                    map.put("certificateNo", certificateNo);
                    map.put("address", address);
                    map.put("actualAddress", actualAddress);
                    map.put("contactNumber", contactNumber);
                    map.put("guarantorEmail", guarantorEmail);
                    map.put("legalRepresentative", legalRepresentative);
                    map.put("day", DateUtil.getDay(date));
                    map.put("month", DateUtil.getMonth(date));
                    map.put("year", DateUtil.getYear(date));
                    // 债务人公司名称
                    map.put("debtorCompanyName", debtorCompanyName);
                    // 授信金额
                    map.put("creditLine", creditLine);
                    map.put("currency_en", currency_en);
                    map.put("creditLineCname", creditLineCname);
                    map.put("currency_cn", currency_cn);

                }
                XWPFTemplate template = XWPFTemplate.compile(absolutePath).render(map);
                String path = FileUtil.getAbsolutePath(UUID.randomUUID().toString(), ".docx", FileModuleDict.ChildEnum.CONTRACT_FILE_PREVIEW);
                File file = new File(path);
                if (!file.exists()) {
                    FileUtils.createParentDirectories(file);
                }
                template.writeToFile(path);
                list.add(file);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(CodeUtil.FAIL, "下载担保函错误" + e.getMessage());
        }
    }

    /**
     * 担保涵 常规担保函
     *
     * @param reviewRltRepayId
     * @param contractInfo
     * @param list
     * @param absolutePath
     * @param contractName
     */
    private void dealNewGuaranteeCulevert(Long reviewRltRepayId, ContractInfo contractInfo, List<File> list, String absolutePath, String contractName) {
        try {
            // 主合同信息
            ReviewMasterContract masterContract = reviewMasterContractService.lambdaQuery().eq(ReviewMasterContract::getReviewQuotaDisburseId, contractInfo.getReviewQuotaDisburseId()).one();
            // 保理合同编号
            String factoringContractNo = masterContract.getContractNo();
            // 保理申请人
            String applicantContact = masterContract.getApplicantContact();
            // 保理申请人公司名称
            String applicantCompanyName = masterContract.getApplicantCompanyName();
            List<ReviewMasterContractDebtor> debtorList = reviewMasterContractDebtorService.lambdaQuery().eq(ReviewMasterContractDebtor::getReviewMasterContractId, masterContract.getId()).list();
            // 设置债务人
            String debtorCompanyName = "";
            if (null != debtorList && debtorList.size() > 0) {
                for (ReviewMasterContractDebtor debtor : debtorList) {
                    debtorCompanyName = debtorCompanyName + debtor.getCompanyName() + "、";
                }
                if (StringUtil.isNotEmpty(debtorCompanyName) && debtorCompanyName.contains("、")) {
                    debtorCompanyName = debtorCompanyName.substring(0, debtorCompanyName.toString().length() - 1);
                }
            }
            // 融资信息
            ReviewFinancingInfo contractFinancingInfo = reviewFinancingInfoService.lambdaQuery().eq(ReviewFinancingInfo::getReviewQuotaDisburseId, contractInfo.getReviewQuotaDisburseId()).one();
            // 融资金额
            BigDecimal financingAmount = null;
            if (null != contractFinancingInfo) {
                financingAmount = contractFinancingInfo.getFinancingAmount();
            }
            ReviewRltRepay rltRepay = reviewRltRepayService.getById(reviewRltRepayId);
            //社会统一信用代码/身份证号码
            String certificateNo = rltRepay.getArlpCertNum();
            //住所
            String address = rltRepay.getAddress();
            //保证合同编号
            String guaranteeContractNo;
            if (rltRepay.getGuaranteeContractNo() != null && !rltRepay.getGuaranteeContractNo().equals("")) {
                guaranteeContractNo = rltRepay.getGuaranteeContractNo();
            } else {
                guaranteeContractNo = rltRepay.getMaxGuarMcc();
            }
            //责任人名称
            String guarantorName = rltRepay.getArlpName();
            //住所地(营业执照地址)
            String actualAddress = rltRepay.getActualAddress();
            //责任人联系方式
            String contactNumber = rltRepay.getResponsiblePhone();
            //责任人法定代表人
            String legalRepresentative = rltRepay.getLegalRepresentative();
            //责任人邮箱
            String guarantorEmail = rltRepay.getResponsibleEmail();
            if (null != rltRepay && rltRepay.getArlpIdType() != null) {
                String type = rltRepay.getArlpIdType();
                // 个人
                Map<String, Object> map = new HashMap<>();
                if (type.equals(ConstantConversionUtil.IDENTITY_TYPE1)) {
                    map.put("guaranteeContractNo", guaranteeContractNo);
                    map.put("applicantCompanyName", applicantCompanyName);
                    map.put("applicantContact", applicantContact);
                    map.put("factoringContractNo", factoringContractNo);
                    map.put("receivableTransferNo", factoringContractNo + "-ZR");
                    map.put("contractName", contractName);
                    map.put("guarantorName", guarantorName);
                    map.put("certificateNo", certificateNo);
                    map.put("address", address);
                    map.put("actualAddress", actualAddress);
                    map.put("contactNumber", contactNumber);
                    Date date = new Date();
                    map.put("day", DateUtil.getDay(date));
                    map.put("month", DateUtil.getMonth(date));
                    map.put("year", DateUtil.getYear(date));
                    // 配偶名称
                    String spouseName = rltRepay.getSpouseName();
                    // 配偶身份证
                    String spouseIdcard = rltRepay.getSpouseIdCard();
                    map.put("spouseName", spouseName);
                    map.put("spouseIdcard", spouseIdcard);
                    String amountEname = "";
                    String amountCname = "";
                    if (financingAmount != null) {
                        amountCname = MoneyToCNFormatUtil.formatToCN(financingAmount.doubleValue());
                        amountEname = financingAmount + "元";
                    }
                    map.put("financingAmount", amountEname);
                    map.put("financingAmountStr", amountCname);
                    // 债务人公司名称
                    map.put("debtorCompanyName", debtorCompanyName);
                    map.put("guarantorEmail", guarantorEmail);

                } else {
                    // 公司
                    map.put("guaranteeContractNo", guaranteeContractNo);
                    map.put("applicantCompanyName", applicantCompanyName);
                    map.put("applicantContact", applicantContact);
                    map.put("factoringContractNo", factoringContractNo);
                    map.put("receivableTransferNo", factoringContractNo + "-ZR");
                    map.put("contractName", contractName);
                    map.put("guarantorName", guarantorName);
                    map.put("certificateNo", certificateNo);
                    map.put("address", address);
                    map.put("actualAddress", actualAddress);
                    Date date = new Date();
                    map.put("day", DateUtil.getDay(date));
                    map.put("month", DateUtil.getMonth(date));
                    map.put("year", DateUtil.getYear(date));
                    // 债务人公司名称
                    map.put("debtorCompanyName", debtorCompanyName);

                }
                XWPFTemplate template = XWPFTemplate.compile(absolutePath).render(map);
                String path = FileUtil.getAbsolutePath(UUID.randomUUID().toString(), ".docx", FileModuleDict.ChildEnum.CONTRACT_FILE_PREVIEW);
                File file = new File(path);
                if (!file.exists()) {
                    FileUtils.createParentDirectories(file);
                }
                template.writeToFile(path);
                list.add(file);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(CodeUtil.FAIL, "下载担保函错误" + e.getMessage());
        }
    }

    /**
     * 下载(贸理通)三方协议
     */
    public void dealNewtTripartiteAgreementFactoringDownload(ContractInfo contractInfo, List<File> list, Long basicContractId, String absolutePath) {
        try {
            Map<String, Object> map = new HashMap<>();
            // 主合同信息
            ReviewMasterContract masterContract = reviewMasterContractService.getOne(new QueryWrapper<ReviewMasterContract>()
                    .eq("review_quota_disburse_id", contractInfo.getReviewQuotaDisburseId()));
            //融资信息
            ReviewFinancingInfo financingInfo = reviewFinancingInfoService.getOne(new QueryWrapper<ReviewFinancingInfo>()
                    .eq("review_quota_disburse_id", contractInfo.getReviewQuotaDisburseId()));
            //融资利息
            BigDecimal financingInterest = financingInfo.getFinancingInterest();
            //融资金额
            BigDecimal financingAmount = financingInfo.getFinancingAmount();
            BigDecimal financingTotal = BigDecimal.ZERO;
            financingTotal = financingTotal.add(financingAmount).add(financingInterest);
            // 保理合同编号
            String factoringContractNo = masterContract.getContractNo();

            map.put("financingTotal", financingTotal);
            map.put("managementFeeAmount", financingInfo.getManagementFeeAmount());
            // 国内有追索权（正向、反向）、国内无追索权（正向，目前没有反向业务）、池保理（出口和国内）均有三方协议和交易信息表
            //贸理通默认国内池保理
            List<ContractBasicContract> basicContractList = contractBasicContractService.list(new QueryWrapper<ContractBasicContract>().eq("contract_info_id", contractInfo.getId()));
            String path;
            XWPFTemplate template;
            if (null != basicContractList && basicContractList.size() > 0) {
                // 表示有三方协议
                map.put("creditorName", masterContract.getApplicantCompanyName());// 债权人名称
                map.put("creditorAddress", masterContract.getApplicantCompanyAddress());// 债权人注册地址
                map.put("factoringContractNo", factoringContractNo);
                map.put("factoringContractName", masterContract.getContractName());
                map.put("factoringName", masterContract.getFactoringName());
                map.put("factoringAddress", ConstantUtil.OUR_COMPANY_ADDRESS_NAME);
                map.put("applicantCompany", masterContract.getApplicantCompanyName());
                map.put("telephone", masterContract.getApplicantContactNumber());//债权人联系电话
                map.put("contact", masterContract.getApplicantContact());
                map.put("applicantLegalPerson", masterContract.getApplicantCompanyLegalPerson());//债权人公司法人

                ContractBasicContract basic = null;
                for (ContractBasicContract basicContract : basicContractList) {
                    if (basicContract.getId().equals(basicContractId)) {
                        basic = basicContract;
                    }
                }
                if (basic != null && basic.getSpecialAgreement().equals("")) {
                    map.put("specialAgreement", "");
                } else {
                    String specialAgreement = "4." + basic.getSpecialAgreement();
                    map.put("specialAgreement", specialAgreement);
                }
                map.put("tripartiteAgreementNo", basic.getTripartiteAgreementNo());
                // 债务人
                ReviewMasterContractDebtor contractMasterContractDebtor = new ReviewMasterContractDebtor();
                List<ReviewMasterContractDebtor> debtorList = reviewMasterContractDebtorService.list(new QueryWrapper<ReviewMasterContractDebtor>()
                        .eq("review_master_contract_id", masterContract.getId()));
                for (ReviewMasterContractDebtor contractMasterDebtor : debtorList) {
                    if (contractMasterDebtor.getCompanyName().equals(basic.getDebtorCompanyName())) {
                        contractMasterContractDebtor = contractMasterDebtor;
                    }
                }
                String companyName = contractMasterContractDebtor.getCompanyName();
                map.put("companyName", companyName);
                if (companyName.equals("西安长银保国际贸易有限公司")) {
                    map.put("address", ConstantUtil.OUR_COMPANY_ADDRESS_NAME);
                } else {
                    map.put("address", contractMasterContractDebtor.getAddress());
                }
                map.put("legalPerson", contractMasterContractDebtor.getLegalPerson());
                map.put("contact", contractMasterContractDebtor.getContact());
                map.put("contactNumer", contractMasterContractDebtor.getContactNumber());

                ReviewQuotaDisburse reviewQuotaDisburse = reviewQuotaDisburseService.getById(contractInfo.getReviewQuotaDisburseId());
                CFinancingBasicInfo financingBasicInfo = financingBasicInfoService.getById(reviewQuotaDisburse.getFinancingBasicInfoId());
                //核心企业名称
                Enterprise coreEnterprise = enterpriseService.getById(financingBasicInfo.getCoreEnterpriseId());
                map.put("enterpriseName", coreEnterprise.getCorporateName());

                CSalesContractBasicInfo salesContractBasicInfo = salesContractService.findByBusinessNumber(financingBasicInfo.getBusinessNumber());
                if (salesContractBasicInfo == null || salesContractBasicInfo.getId() == null) {
                    throw new BusinessException(CodeUtil.FAIL, "销售合同信息不能为空");
                }
                String salesContractNumber = salesContractBasicInfo.getContractNumber();
                String salesContractName = salesContractBasicInfo.getContractName();
                map.put("salesContractNumber", salesContractNumber);
                if (salesContractName == null || salesContractName.equals("")) {
                    map.put("salesContractName", "《买卖合同》");
                } else {
                    map.put("salesContractName", "《" + salesContractName + "》");
                }
                map.put("basicContractNo", financingBasicInfo.getPurchContractNumber());
                map.put("basicContractName", "《" + financingBasicInfo.getPurchContractName() + "》");
                //时间
                Date date = new Date();
                String day = DateUtil.getDay(date);
                String month = DateUtil.getMonth(date);
                String year = DateUtil.getYear(date);
                map.put("day", day);
                map.put("month", month);
                map.put("year", year);

                LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
                Configure configure = Configure.builder()
                        .bind("details", policy).build();
                template = XWPFTemplate.compile(absolutePath, configure).render(map);
//                template = XWPFTemplate.compile(classPathResource.getPath(), configure).render(map);
                path = FileUtil.getAbsolutePath("三方协议（贸理通）" + companyName, ".docx", FileModuleDict.ChildEnum.CONTRACT_FILE_PREVIEW);
                File file = new File(path);
                if (!file.exists()) {
                    FileUtils.createParentDirectories(file);
                }
                template.writeToFile(path);
                list.add(file);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(CodeUtil.FAIL, "下载三方协议（贸理通）出错" + e.getMessage());
        }
    }

    /**
     * 下载三方协议
     */
    public void dealNewtTripartiteAgreementDownload(ContractInfo contractInfo, List<File> list, Long basicContractId, String absolutePath) {
        try {
            // 主合同信息
            ReviewMasterContract masterContract = reviewMasterContractService.getOne(new QueryWrapper<ReviewMasterContract>()
                    .eq("review_quota_disburse_id", contractInfo.getReviewQuotaDisburseId()));
            // 保理合同编号
            String factoringContractNo = masterContract.getContractNo();
            String path;
            XWPFTemplate template;
            List<ContractBasicContract> basicContractList = contractBasicContractService.list(new QueryWrapper<ContractBasicContract>().eq("contract_info_id", contractInfo.getId()));
            if (null != basicContractList && basicContractList.size() > 0) {
                // 表示有三方协议
                Map<String, Object> map = new HashMap<>();
                map.put("creditorName", masterContract.getApplicantCompanyName());// 债权人名称
                map.put("creditorAddress", masterContract.getApplicantCompanyAddress());// 债权人注册地址
                map.put("factoringContractNo", factoringContractNo);
                map.put("factoringContractName", masterContract.getContractName());
                map.put("factoringName", masterContract.getFactoringName());
                map.put("factoringAddress", ConstantUtil.OUR_COMPANY_ADDRESS_NAME);
                map.put("telephone", masterContract.getApplicantContactNumber());//债权人联系电话
                map.put("contact", masterContract.getApplicantContact());
                map.put("legalPerson", masterContract.getApplicantCompanyLegalPerson());//债权人公司法人
                // 基础交易合同，注：有几条三方协议信息，就代表需要导出几个三方协议附件，交易信息与三方协议对应
                // 债务人
                String debtorName = "";
                String debtorAddress = "";
                String entLegalPerson = "";
                String mobile = "";
                // 三方协议编号
                String tripartiteAgreementNo = "";
                ContractBasicContract basic = null;
                for (ContractBasicContract basicContract : basicContractList) {
                    if (basicContract.getId().equals(basicContractId)) {
                        basic = basicContract;
                        debtorName = basic.getDebtorCompanyName();
                        tripartiteAgreementNo = basic.getTripartiteAgreementNo();
                        Enterprise ent = enterpriseService.getById(basic.getDebtorCompanyId());
                        if (null != ent) {
                            debtorAddress = ent.getAddress();
                        }
                    }
                }
                if (basic.getSpecialAgreement().equals("")) {
                    map.put("specialAgreement", "");
                } else {
                    String specialAgreement = "4." + basic.getSpecialAgreement();
                    map.put("specialAgreement", specialAgreement);
                }
                map.put("debtorName", debtorName);
                if (debtorName.equals("西安长银保国际贸易有限公司")) {
                    map.put("debtorAddress", ConstantUtil.OUR_COMPANY_ADDRESS_NAME);
                } else {
                    map.put("debtorAddress", debtorAddress);
                }
                map.put("tripartiteAgreementNo", tripartiteAgreementNo);
                map.put("entLegalPerson", entLegalPerson);
                map.put("mobile", mobile);
                //时间
                Date date = new Date();
                String day = DateUtil.getDay(date);
                String month = DateUtil.getMonth(date);
                String year = DateUtil.getYear(date);
                map.put("day", day);
                map.put("month", month);
                map.put("year", year);
                template = XWPFTemplate.compile(absolutePath).render(map);
                path = FileUtil.getAbsolutePath("三方协议" + debtorName, ".docx", FileModuleDict.ChildEnum.CONTRACT_FILE_PREVIEW);
                File file = new File(path);
                if (!file.exists()) {
                    FileUtils.createParentDirectories(file);
                }
                template.writeToFile(path);
                list.add(file);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(CodeUtil.FAIL, "下载三方协议出错" + e.getMessage());
        }
    }

    /**
     * 下载池保理业务合同 保理业务合同
     */
    private void dealNewPoolFactoringBusinessContract(ContractInfo contractInfo, List<File> list, String absolutePath, String type) {
        XWPFTemplate template;
        String path;
        try {
            Map<String, Object> dataMap = new HashMap<>();
            // 主合同信息
            ReviewMasterContract masterContract = reviewMasterContractService.getOne(new QueryWrapper<ReviewMasterContract>()
                    .eq("review_quota_disburse_id", contractInfo.getReviewQuotaDisburseId()));
            // 保理合同编号
            String factoringContractNo = masterContract.getContractNo();
            // 保理商
            String factoringName = masterContract.getFactoringName();
            // 保理申请人
            String applicantContact = masterContract.getApplicantContact();
            // 保理申请人公司名称
            String applicantCompanyName = masterContract.getApplicantCompanyName();
            if (masterContract.getDoubleFactoringType().equals(1)) {
                if ((masterContract.getPlatformName() != null && !masterContract.getPlatformName().equals(""))) {
                    HashMap<String, String> hashMap = new HashMap<>();
                    hashMap.put("platformName", masterContract.getPlatformName());
                    dataMap.put("doubleFactoringType", hashMap);
                } else {
                    dataMap.put("doubleFactoringType", false);
                }
            } else {
                dataMap.put("doubleFactoringType", false);
            }
            dataMap.put("factoringContractNo", factoringContractNo);
            dataMap.put("factoringName", factoringName);
            dataMap.put("factoringAgentName", masterContract.getFactoringAgentName());
            dataMap.put("factoringAgentEmail", masterContract.getFactoringAgentEmail());
            dataMap.put("factoringAgentPhone", masterContract.getFactoringAgentPhone());
            dataMap.put("factoringAddress", ConstantUtil.OUR_COMPANY_ADDRESS_NAME);
            dataMap.put("applicantContact", applicantContact);
            dataMap.put("applicantCompanyName", applicantCompanyName);
            dataMap.put("applicantContactNumber", masterContract.getApplicantContactNumber());
            dataMap.put("applicantEmail", masterContract.getApplicantEmail());
            dataMap.put("applicantAddress", masterContract.getApplicantCompanyAddress());

            ContractMasterContract contractMasterContract = contractInfo.getContractMasterContract();
            if (contractMasterContract.getFactoringContractAgreement() != null && !contractMasterContract.getFactoringContractAgreement().equals("")) {
                if (type.equals(ConstantConversionUtil.POOL_FACTORING_BUSINESS_CONTRACT)) {
                    dataMap.put("factoringContractAgreement", "10、" + contractMasterContract.getFactoringContractAgreement());
                }
            }
            Date date = new Date();
            dataMap.put("year", DateUtil.getYear(date));
            dataMap.put("month", DateUtil.getMonth(date));
            dataMap.put("day", DateUtil.getDay(date));
            if (type.equals(ConstantConversionUtil.POOL_FACTORING_BUSINESS_CONTRACT)) {
                template = XWPFTemplate.compile(absolutePath).render(dataMap);
                path = FileUtil.getAbsolutePath("池保理业务合同" + applicantCompanyName, ".docx", FileModuleDict.ChildEnum.CONTRACT_FILE_PREVIEW);
                File file = new File(path);
                if (!file.exists()) {
                    FileUtils.createParentDirectories(file);
                }
                template.writeToFile(path);
                list.add(file);
            } else {
                template = XWPFTemplate.compile(absolutePath).render(dataMap);
                path = FileUtil.getAbsolutePath("保理业务合同" + applicantCompanyName, ".docx", FileModuleDict.ChildEnum.CONTRACT_FILE_PREVIEW);
                File file = new File(path);
                if (!file.exists()) {
                    FileUtils.createParentDirectories(file);
                }
                template.writeToFile(path);
                list.add(file);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(CodeUtil.FAIL, "下载池保理业务合同错误" + e.getMessage());
        }
    }

    /**
     * 下载保理信息表或保理融资确认书
     */
    private void dealNewFactoringInfo(ContractInfo contractInfo, List<File> fileAllList, String absolutePath, String type) {
        String path;
        XWPFTemplate template;
        try {
            // 主合同信息
            ReviewMasterContract master = reviewMasterContractService.getOne(new QueryWrapper<ReviewMasterContract>()
                    .eq("review_quota_disburse_id", contractInfo.getReviewQuotaDisburseId()));
            ContractMasterContract contractMasterContract = contractMasterContractService.getOne(new QueryWrapper<ContractMasterContract>()
                    .eq("contract_info_id", contractInfo.getId()));
            if (null != master) {
                Map<String, Object> dataMap = new HashMap<>();
                // 保理合同编号
                String contractNo = master.getContractNo();
                //合同名称
                String contractName = master.getContractName();
                // 保理合同名称
                String factoringContractName = master.getContractName();
                // 保理商法定代表人
                String factoringLegalPersion = master.getFactoringLegalPerson();
                //保理商联系人
                String factoringAgentName = master.getFactoringAgentName();
                //保理商联系人电话
                String factoringAgentPhone = master.getFactoringAgentPhone();
                String factoringCompanyName = master.getFactoringName();
                String factoringLegalPerson = master.getFactoringLegalPerson();
                String factoringAgent = master.getFactoringAgentName();
                //保理商名称
                String factoringName = master.getFactoringName();
                String factoringAddress = master.getFactoringAddress();
                // 保理申请人公司名称
                String applicantCompanyName = master.getApplicantCompanyName();
                // 保理申请人注册地址
                String applicantCompanyAddress = master.getApplicantCompanyAddress();
                // 保理申请人公司法定代表人
                String applicantCompanyLegalPerson = master.getApplicantCompanyLegalPerson();
                // 有或无追索权（默认有追）
                String recourseRights = "recourse";
                // 池或非池(默认池)
                String isPool = "poolFactoring";
                // 国内或出口保理(默认国内)
                String businessType = "domestic_factoring";
                // 币种，
                Dictionary currency = dictService.getByCode("CNY");
                //获取应收账款
                // 金额大写时，要求币种纯中文，如人民币，而不是CNY（人民币）的格式，故需要转化
                currency.setName(ConstantConversionUtil.currencyTypeCnameMap.get(currency.getCode()));
                // 池保理确认书特殊约定
                String poolFactoringFinancingConfirmAgree = contractMasterContract.getFinancingConfirmAgreement();
                //池保理时保理信息表特殊约定
                String specialAgreement = contractMasterContract.getSpecialAgreement();
                //E贸特殊约定
//                String specialAgreementStr = null;
//                List<ContractSpecialAgreement> eSpecialAgreements = new ArrayList<>();
//                eSpecialAgreements = master.getContractSpecialAgreementList();
//                for (ContractSpecialAgreement eSpecialAgreement : eSpecialAgreements) {
//                    specialAgreementStr = "4、" + eSpecialAgreement.getAgreementContent();
//                }
                // 池保理确认书编号
                String poolFactoringFinancingConfirmNo = master.getPoolFactoringFinancingConfirmNo();
                // 保理专户户名
                String factoringAccountName = master.getFactoringAccountName();
                // 保理专户账号
                String factoringAccount = master.getFactoringAccount();
                // 保理专户开户行
                String factoringAccountBank = master.getFactoringAccountBank();
                //保理专户(收汇)户名1
                String factoringAccountName1 = master.getFactoringAccountName();
                //保理专户（收汇）账户1
                String factoringAccount1 = master.getFactoringAccount();
                //保理专户（收汇）开户行1
                String factoringAccountBank1 = master.getFactoringAccountBank();
                //保理专户(收汇)户名2
                String factoringAccountName2 = master.getFactoringAccountName2();
                //保理专户（收汇）账户2
                String factoringAccount2 = master.getFactoringAccount2();
                //保理专户（收汇）开户行2
                String factoringAccountBank2 = master.getFactoringAccountBank2();
                //保理申请人指定账户户名
                String applicantDesignatedAccountName = master.getApplicantDesignatedAccountName();
                //保理申请人指定账户
                String applicantDesignatedAccount = master.getApplicantDesignatedAccount();
                //保理申请人指定账户开户行
                String applicantDesignatedbank = master.getApplicantDesignatedBank();
                //我司指定账户户名
                String ourAccountName = master.getOurAccountName();
                //我司指定账户
                String ourAccount = master.getOurAccount();
                //我司指定账户开户行
                String ourAccountBank = master.getOurAccountBank();
                //合同份数
                Integer contractNum = contractMasterContract.getContractNum();
                Date date = new Date();
                String year = DateUtil.getYear(date);
                String day = DateUtil.getDay(date);
                String month = DateUtil.getMonth(date);
                // 债务人个数
                int debtorNum = 0;
                // 债务人信息
                ReviewMasterContractDebtor debtor = null;
                List<ReviewMasterContractDebtor> debtorList = reviewMasterContractDebtorService.list(new QueryWrapper<ReviewMasterContractDebtor>()
                        .eq("review_master_contract_id", master.getId()));
                if (null != debtorList && debtorList.size() > 0) {
                    debtorNum = debtorList.size();
                    debtor = debtorList.get(0);
                    int i = 0;
                    ArrayList<Map<String, Object>> mapList = new ArrayList<>();
                    String debtorNames = "";
                    if (CollectionUtil.isNotEmpty(debtorList)) {
                        for (ReviewMasterContractDebtor contractDebtor : debtorList) {
                            i++;
                            Map<String, Object> iMp = new HashMap<>();
                            iMp.put("recorsNo", i);
                            iMp.put("companyName", contractDebtor.getCompanyName());
//                            if (contractDebtor.getCompanyName().equals("西安长银保国际贸易有限公司")) {
//                                iMp.put("debtorAddress", dictionaryService.getByCode(ConstantUtil.OUR_COMPANY_ADDRESS).getName());
//                            } else {
//                                iMp.put("debtorAddress", contractDebtor.getAddress());
//                            }
                            iMp.put("debtorAddress", contractDebtor.getAddress());
                            iMp.put("debtorLegalPerson", contractDebtor.getLegalPerson());
                            iMp.put("debtorContact", contractDebtor.getContact());
                            iMp.put("debtorContactNumber", contractDebtor.getContactNumber());
                            mapList.add(iMp);
                        }
                        debtorNames = debtorList.stream().map(ReviewMasterContractDebtor::getCompanyName)
                                .collect(Collectors.joining("、"));
                    }
                    dataMap.put("debtorNames", debtorNames);
                    if (null != mapList && mapList.size() > 0) {
                        dataMap.put("mapList", mapList);
                    }
                }
                // 明保理或暗保理(默认明保理)
                String disclosedUndisclosedFactoringNum = "1";
                // 保证金类型放款中最靠后的时间
                String marginLoanLastDateStr = null;
                List<ReviewIncomeExpenditurePlan> incomeExpendPlanList = reviewIncomeExpenditurePlanService.list(new QueryWrapper<ReviewIncomeExpenditurePlan>()
                        .eq("review_quota_disburse_id", contractInfo.getReviewQuotaDisburseId()));
                if (null != incomeExpendPlanList && incomeExpendPlanList.size() > 0) {
                    List<Date> dateList = incomeExpendPlanList.stream()
                            .filter(e -> null != e.getIncomeExpenditureType())
                            .filter(e -> StringUtil.isNotEmpty(e.getIncomeExpenditureType()))
                            .filter(e -> e.getIncomeExpenditureType().equals(IncomeExpenditureTypeDict.ChildEnum.MARGIN.getCode()))
                            .filter(e -> null != e.getLoan())
                            .map(ReviewIncomeExpenditurePlan::getIncomeExpenditureDate).collect(Collectors.toList());
                    if (null != dateList && dateList.size() > 0) {
                        Optional<Date> op = dateList.stream().sorted((e1, e2) -> e2.compareTo(e1)).findFirst();
                        marginLoanLastDateStr = DateUtil.formateYMD(op.get());
                    }
                }
                // 融资信息
                // 服务范围
                String serviceScopeId = "";
                // 转让通知方式
                String transferNoticeMethodId = "";
                // 融资金额
                BigDecimal financingAmmount = null;
                // 融资金额大写
                String financingAmmountCname = "";
                // 本金收取方式
                String principalCollectionMethod = "";
                // 保理融资期限
                Integer financingPeriod = null;
                // 起算日
                String startingDateTypesNum = "";
                // 具体日期
                String yearStr = null;
                String monthStr = null;
                String dayStr = null;
                // 融资利率(年化)
                String financingRateStr = null;
                //坏账担保比例
                String badDebtGuaranteeRate = null;
                // 逾期利率
                String overdueInterestRateStr = null;
                // 融资利息
                BigDecimal financingInterest = null;
                // 融资利息金额 大写
                String financingInterestName = null;
                // 保理融资利息及支付方式
                String paymentMethod = null;
                // 保证金比例
                String marginRatioStr = null;
                // 保证金支付方式
                String marginCollectionMethod = null;
                // 保证金退还方式
                String marginReturnMethod = null;
                // 保证金退还条件
                String marginReturnCondition = null;
                // 管理费金额
                BigDecimal manageFeeAmount = null;
                // 管理费金额大写
                String manageFeeAmountName = null;
                //管理费支付方式
                String manageFeeCollectionMethod = null;
                // 其他费用
                BigDecimal otherFee = null;
                // 其他费用支付方式
                String otherFeeCollectionMethod = null;
                // 其他费用大写
                String otherFeeName = null;
                // 信用风险担保金额
//                BigDecimal creditGuaranteeRiskAmount = null;
                // 信用风险担保金额 大写
//                String creditGuaranteeRiskAmountName = null;
                // 应收转让率
                String receivableTransferRateStr = null;
                //
                int loanConditionListLength = 0;
                ReviewFinancingInfo financingInfo = reviewFinancingInfoService.getOne(new QueryWrapper<ReviewFinancingInfo>()
                        .eq("review_quota_disburse_id", contractInfo.getReviewQuotaDisburseId()));
                ContractFinancingInfo contractFinancingInfo = contractFinancingInfoService.getOne(new QueryWrapper<ContractFinancingInfo>()
                        .eq("contract_info_id", contractInfo.getId()));
                if (null != financingInfo) {
                    // 池保理
                    if (isPool.equals(ConstantConversionUtil.POOL_FACTORING)) {
                        // 服务范围
                        if (StringUtil.isNotEmpty(financingInfo.getServiceScope())) {
                            List<String> stringList = StringUtil.separatorCharacter(financingInfo.getServiceScope());
                            for (String code : stringList) {
                                Dictionary dict = dictService.getByCode(code);
                                if (null != dict && StringUtil.isNotEmpty(dict.getName())) {
                                    String dictName = dict.getName();
                                    if (dictName.equals(FactoringServiceScopeDict.ChildEnum.ACCOUNTRECEIVABLEFINANCING.getCname())) {
                                        serviceScopeId = serviceScopeId + "1 ";
                                    } else if (dictName.equals(FactoringServiceScopeDict.ChildEnum.ACCOUNTRECEIVABLEMANAGEMENT.getCname())) {
                                        serviceScopeId = serviceScopeId + "2 ";
                                    } else if (dictName.equals(FactoringServiceScopeDict.ChildEnum.COLLECTIONRECEIVABLES.getCname())) {
                                        serviceScopeId = serviceScopeId + "3 ";
                                    } else if (dictName.equals(FactoringServiceScopeDict.ChildEnum.accountReceivableOther.getCname())) {
                                        serviceScopeId = serviceScopeId + "4 ";
                                    }
                                }
                            }
                        } else {
                            serviceScopeId = "-";
                        }
                        // 转让通知方式
                        if (StringUtil.isNotEmpty(financingInfo.getTransferNoticeMethod())) {
                            List<String> stringList = StringUtil.separatorCharacter(financingInfo.getTransferNoticeMethod());
                            for (String code : stringList) {
                                Dictionary dict = dictService.getByCode(code);
                                if (null != dict && StringUtil.isNotEmpty(dict.getName())) {
                                    String dictName = dict.getName();
                                    if (dictName.equals(TransferNoticeMethodDict.ChildEnum.express.getCname())) {
                                        transferNoticeMethodId = transferNoticeMethodId + "1 ";
                                    } else if (dictName.equals(TransferNoticeMethodDict.ChildEnum.REGISTEREDLETTER.getCname())) {
                                        transferNoticeMethodId = transferNoticeMethodId + "2 ";
                                    } else if (dictName.equals(TransferNoticeMethodDict.ChildEnum.DEBTORSTAMPCONFIRMATION.getCname())
                                            || dictName.equals(TransferNoticeMethodDict.ChildEnum.IMPORTERSEALCONFIRMATION.getCname())) {
                                        transferNoticeMethodId = transferNoticeMethodId + "3 ";
                                    } else if (dictName.equals(TransferNoticeMethodDict.ChildEnum.NOTARIZEDDELIVERY.getCname())) {
                                        transferNoticeMethodId = transferNoticeMethodId + "4 ";
                                    } else if (dictName.equals(TransferNoticeMethodDict.ChildEnum.TRANSFERNOTICEMETHODOTHER.getCname())) {
                                        transferNoticeMethodId = transferNoticeMethodId + "5 ";
                                    }
                                }
                            }
                        } else {
                            transferNoticeMethodId = "-";
                        }
                    }

                    //信用风险担保金额
//                    creditGuaranteeRiskAmount = financingInfo.getCreditGuaranteeRiskAmount();
//                    if (null != creditGuaranteeRiskAmount) {
//                        creditGuaranteeRiskAmountName = MoneyToCNFormatUtil.formatToCN(creditGuaranteeRiskAmount.doubleValue());
//                    }
                    // 融资金额
                    financingAmmount = financingInfo.getFinancingAmount();
                    // 本金支付方式
                    principalCollectionMethod = contractFinancingInfo.getPrincipalCollectionMethod();
                    // 保理融资期限
                    financingPeriod = financingInfo.getFinancingPeriod();
                    // 起算日
                    String startingDateType = financingInfo.getStartingDateType();
                    if (startingDateType.equals("plan_day")) {
                        // 自保理融资款实际投放之日
                        startingDateTypesNum = "1";
                    } else {
                        Date startDate = financingInfo.getStartingDate();
                        yearStr = DateUtil.getYear(startDate);
                        monthStr = DateUtil.getMonth(startDate);
                        dayStr = DateUtil.getDay(startDate);
                        startingDateTypesNum = "2";
                    }
                    // 融资利率(年化)
                    financingRateStr = PercentageUtil.convertPercentage(financingInfo.getFinancingRate().doubleValue());
                    if (StringUtil.isNotEmpty(financingRateStr)) {
                        financingRateStr = StringUtil.subZeroAndDot(financingRateStr.split("%")[0]) + "%";
                    }
                    //坏账担保比例
                    badDebtGuaranteeRate = PercentageUtil.convertPercentage(financingInfo.getBadDebtGuaranteeRate().doubleValue());
                    if (StringUtil.isNotEmpty(badDebtGuaranteeRate)) {
                        badDebtGuaranteeRate = StringUtil.subZeroAndDot(badDebtGuaranteeRate.split("%")[0]) + "%";
                    }
                    // 逾期利息
                    overdueInterestRateStr = PercentageUtil.convertPercentage(financingInfo.getOverdueInterestRate().doubleValue());
                    if (StringUtil.isNotEmpty(overdueInterestRateStr)) {
                        overdueInterestRateStr = StringUtil.subZeroAndDot(overdueInterestRateStr.split("%")[0]) + "%";
                    }
                    // 融资利息
                    financingInterest = financingInfo.getFinancingInterest();
                    if (null != financingInterest) {
                        financingInterestName = MoneyToCNFormatUtil.formatToCN(financingInterest.doubleValue());
                    }
                    // 支付方式
                    paymentMethod = contractFinancingInfo.getInterestCollectionMethod();
                    // 保证金比例
                    marginRatioStr = PercentageUtil.convertPercentage(financingInfo.getMarginRatio().doubleValue());
                    if (StringUtil.isNotEmpty(marginRatioStr)) {
                        marginRatioStr = StringUtil.subZeroAndDot(marginRatioStr.split("%")[0]) + "%";
                    }
                    // 保证金支付方式
                    marginCollectionMethod = contractFinancingInfo.getMarginCollectionMethod();
                    // 保证金退还方式
                    marginReturnMethod = contractFinancingInfo.getMarginReturnMethod();
                    // 保证金退还提交
                    marginReturnCondition = contractFinancingInfo.getMarginReturnCondition();
                    // 管理费金额
                    manageFeeAmount = financingInfo.getManagementFeeAmount();
                    // 管理费金额大写
                    if (null != manageFeeAmount) {
                        manageFeeAmountName = MoneyToCNFormatUtil.formatToCN(manageFeeAmount.doubleValue());
                    }
                    //管理费支付方式
                    manageFeeCollectionMethod = contractFinancingInfo.getManagementFeeCollectionMethod();
                    // 其他费用
                    otherFee = financingInfo.getOtherFeeAmount();
                    // 其他费用支付方式
                    otherFeeCollectionMethod = contractFinancingInfo.getOtherFeeCollectionMethod();
                    // 其他费用金额大写
                    if (null != otherFee) {
                        otherFeeName = MoneyToCNFormatUtil.formatToCN(otherFee.doubleValue());
                    }
                    // 信用风险担保金额
//                    creditGuaranteeRiskAmount = financingInfo.getCreditGuaranteeRiskAmount();
//                    if (null != creditGuaranteeRiskAmount) {
//                        creditGuaranteeRiskAmountName = MoneyToCNFormatUtil
//                                .formatToCN(creditGuaranteeRiskAmount.doubleValue());
//                    }
                    // 最高转让折率
                    // receivableTransferRateStr = PercentageUtil
                    // .convertPercentage(financingInfo.getReceivableTransferRate());
                    // if (StringUtil.isNotEmpty(receivableTransferRateStr)) {
                    // receivableTransferRateStr = StringUtil.subZeroAndDot(receivableTransferRateStr.split("%")[0])
                    // + "%";
                    // }
                }
                if (StringUtil.isNotEmpty(serviceScopeId)) {
                    serviceScopeId = serviceScopeId.trim();
                }
                if (StringUtil.isNotEmpty(transferNoticeMethodId)) {
                    transferNoticeMethodId = transferNoticeMethodId.trim();
                }
                if (null != financingAmmount) {
                    financingAmmountCname = MoneyToCNFormatUtil.formatToCN(financingAmmount.doubleValue());
                }
                // 提款条件
                ReviewQuotaDisburseApproval reviewQuotaDisburseApproval = reviewQuotaDisburseApprovalService.getOne(new QueryWrapper<ReviewQuotaDisburseApproval>()
                        .eq("review_quota_disburse_id", contractInfo.getReviewQuotaDisburseId())
                        .orderByDesc("id").last("LIMIT 1"));

                List<ReviewLoanCondition> loanConditionList = reviewLoanConditionService.list(new QueryWrapper<ReviewLoanCondition>()
                        .eq("review_quota_disburse_approval_id", reviewQuotaDisburseApproval.getId()));
                // 金额合计：
                BigDecimal amountTotal = null;
                // 金额合计大写
                String amountTotalName = "";
                List<Map<String, Object>> listMap1 = new ArrayList<>();
                List<Map<String, Object>> listMap2 = new ArrayList<>();
                int recordNo = 0;
                List<Map<String, Object>> loanConditionListMap = new ArrayList<>();
                if (null != loanConditionList && loanConditionList.size() > 0) {
                    for (ReviewLoanCondition loanCondition : loanConditionList) {
                        Map<String, Object> map = new HashMap<>();
                        recordNo = recordNo + 1;
                        map.put("recordNo", NumberToChnUtil.NumberToChn(recordNo));
                        map.put("currencyEName", currency.getCode());
                        map.put("currencyZName", currency.getName());
                        if (null != loanCondition.getAmount()) {
                            map.put("amountName",
                                    MoneyToCNFormatUtil.formatToCN(loanCondition.getAmount().doubleValue()));
                        }
                        map.put("amount", NumberFormatUtil.convertDecimal(loanCondition.getAmount(),
                                NumberFormatUtil.THOUSAND_SEPARATOR_TWO_DECIMAL));
                        // 固定条件序号
                        String fixedConditionNo = null;
                        // 补充条件序号
                        String supplementaryConditionNo = null;
                        // 付款条件
                        String paymentCondition = null;
                        List<ContractLoanConditionSetting> loanConditionSetList = contractLoanConditionSettingService.list(new QueryWrapper<ContractLoanConditionSetting>()
                                .eq("contract_info_id", contractInfo.getId()).eq("is_checked", true));
                        if (null != loanConditionSetList && loanConditionSetList.size() > 0) {
                            // 固定条件序号
                            List<Integer> fixedConditionList = loanConditionSetList.stream()
                                    .filter(e -> e.getFixedCondition())
                                    .map(ContractLoanConditionSetting::getOrderNumber).collect(Collectors.toList());
                            if (null != fixedConditionList && fixedConditionList.size() > 0) {
                                fixedConditionNo = StringUtil.join(fixedConditionList.toArray(), "、");
                            }
                            // 补充条件序号
                            List<Integer> supplementaryConditionList = loanConditionSetList.stream()
                                    .filter(e -> !e.getFixedCondition())
                                    .map(ContractLoanConditionSetting::getOrderNumber).collect(Collectors.toList());
                            if (null != supplementaryConditionList && supplementaryConditionList.size() > 0) {
                                supplementaryConditionNo = StringUtil.join(supplementaryConditionList.toArray(), "、");
                            }
                            // 付款条件:固定条件和补充条件都存在
                            if (StringUtil.isNotEmpty(fixedConditionNo)
                                    && StringUtil.isNotEmpty(supplementaryConditionNo)) {
                                paymentCondition = fixedConditionNo + "、" + supplementaryConditionNo;
                            }
                            // 付款条件:固定条件存在，补充条件不存在
                            if (StringUtil.isNotEmpty(fixedConditionNo)
                                    && StringUtil.isEmpty(supplementaryConditionNo)) {
                                paymentCondition = fixedConditionNo;
                            }
                            // 付款条件:固定条件不存在，补充条件存在
                            if (StringUtil.isEmpty(fixedConditionNo)
                                    && StringUtil.isNotEmpty(supplementaryConditionNo)) {
                                paymentCondition = supplementaryConditionNo;
                            }
                        }
                        // 金额合计
                        amountTotal = loanConditionList.stream().filter(e -> null != e.getAmount())
                                .map(ReviewLoanCondition::getAmount).reduce(BigDecimal::add)
                                .orElse(new BigDecimal(0));
                        if (null != amountTotal) {
                            amountTotalName = MoneyToCNFormatUtil.formatToCN(amountTotal.doubleValue());
                        }
                        map.put("fixedConditionNo", fixedConditionNo);
                        map.put("supplementaryConditionNo", supplementaryConditionNo);
                        map.put("paymentCondition", paymentCondition);
                        loanConditionListMap.add(map);
                    }
                    dataMap.put("loanConditionListMap", loanConditionListMap);
                }
                loanConditionListLength = loanConditionListMap.size() * 2;

                List<ContractLoanConditionSetting> loanConditionSetList = contractLoanConditionSettingService.list(new QueryWrapper<ContractLoanConditionSetting>()
                        .eq("contract_info_id", contractInfo.getId())
                        .eq("condition_type", ConstantConversionUtil.CONTRACT_LOAN_CONDITION_SETTING_CONDITION));
                if (null != loanConditionSetList && loanConditionSetList.size() > 0) {
                    List<ContractLoanConditionSetting> list2 = loanConditionSetList.stream()
                            .filter(e -> !e.getFixedCondition()).collect(Collectors.toList());
                    String orderNumbers = "";
                    if (null != list2 && list2.size() > 0) {
                        for (ContractLoanConditionSetting setting : list2) {
                            Map<String, Object> map2 = new HashMap<>();
                            map2.put("orderNumber", setting.getOrderNumber());
                            map2.put("condition", setting.getLoanCondition());
                            orderNumbers = orderNumbers + setting.getOrderNumber() + "、";
                            listMap2.add(map2);
                        }
                    }
                    dataMap.put("listMap2", listMap2);
                    dataMap.put("orderNumbers", orderNumbers);
                }
                List<Map<String, Object>> listMap3 = new ArrayList<>();
                BigDecimal receivableAmountTotal = BigDecimal.ZERO;
                BigDecimal receivableNetAmountTotal = BigDecimal.ZERO;
                BigDecimal invoiceAmmountTotal = BigDecimal.ZERO;


                Map<String, Object> map3 = new HashMap<>();
                map3.put("i", 1);
                PurchContractBasicInfo purchContractBasicInfo = getPurchContractBasicInfo(contractInfo.getBusinessNo());
                ReviewQuotaDisburse reviewQuotaDisburse = reviewQuotaDisburseService.getById(contractInfo.getReviewQuotaDisburseId());
                map3.put("contractNo", purchContractBasicInfo.getContractNumber());
                map3.put("contractName", purchContractBasicInfo.getContractName());
                map3.put("debtor", debtor.getCompanyName());
                map3.put("receivableType", "货款");
                //计算应收账款金融
                BigDecimal accountsReceivableAmount = calculateAccountsReceivableAmount(reviewQuotaDisburse.getFinancingBasicInfoId());
                map3.put("receivableAmount", accountsReceivableAmount.toString());
                map3.put("receivableNetAmount", reviewQuotaDisburse.getAccountsReceivableNetAmountTotal().toString());
                if (null != reviewQuotaDisburse.getTerm()) {
                    map3.put("term", reviewQuotaDisburse.getTerm());
                }
                if (null != reviewQuotaDisburse.getEndDate()) {
                    map3.put("expiryDate", DateUtil.formateYMD(reviewQuotaDisburse.getEndDate()));
                }
                dataMap.put("currencyName", "CNY");
                dataMap.put("receivableAmountTotal", receivableAmountTotal.toString());
                dataMap.put("receivableNetAmountTotal", receivableNetAmountTotal.toString());
                dataMap.put("invoiceAmmountTotal", invoiceAmmountTotal);
                listMap3.add(map3);
                dataMap.put("receivableAmountTotal", receivableAmountTotal);
                dataMap.put("receivableNetAmountTotal", receivableNetAmountTotal);
                dataMap.put("invoiceAmmountTotal", invoiceAmmountTotal);

                // 授信金额
                BigDecimal creditLine = null;
                // 授信金额金额中文
                String creditLineName = "";
                //授信余额
                BigDecimal creditBalance = null;
                //授信余额中文
                String creditBalanceName = "";
                // 授信期限
                Integer creditTerm = null;
                // 授信开始年
                String creditStartYearStr = null;
                // 授信开始月
                String creditStartMonthStr = null;
                // 授信开始日
                String creditStartDayStr = null;
                // 授信信息
                ProjectInformationVo projectInformationVo = projectInformationService.getByBusinessNo(contractInfo.getBusinessNo());
                CreditResolution creditResolution = creditResolutionService.getByProjectInformationId(projectInformationVo.getProjectInformationId());
                if (null != creditResolution) {
                    creditLine = creditResolution.getProposedCreditLine();
                    creditBalance = reviewQuotaDisburse.getBusinessCreditBalance();
                    if (null != creditBalance) {
                        if (creditBalance.compareTo(BigDecimal.ZERO) == -1) {
                            creditBalanceName = MoneyToCNFormatUtil.formatToCN(creditBalance.abs().doubleValue());
                            creditBalanceName = "负" + creditBalanceName;
                        } else {
                            creditBalanceName = MoneyToCNFormatUtil.formatToCN(creditBalance.abs().doubleValue());
                        }
                    }
                    // 授信金额中文
                    if (null != creditLine) {
                        creditLineName = MoneyToCNFormatUtil.formatToCN(creditLine.doubleValue());
                    }
                    // 授信期限
                    creditTerm = creditResolution.getProposedCreditTerm();
                    if (null != creditResolution.getCreditStartDate()) {
                        Date startDate = creditResolution.getCreditStartDate();
                        creditStartYearStr = DateUtil.getYear(startDate);
                        creditStartMonthStr = DateUtil.getMonth(startDate);
                        creditStartDayStr = DateUtil.getDay(startDate);
                    }
                }
                // 合同信息
                dataMap.put("quotaDisburseBatch", contractInfo.getQuotaDisburseBatch());
                dataMap.put("contractNo", contractNo);
                dataMap.put("contractName", contractName);
                dataMap.put("factoringContractName", factoringContractName);
                dataMap.put("factoringLegalPersion", factoringLegalPersion);
                dataMap.put("factoringAgentName", factoringAgentName);
                dataMap.put("factoringAgentPhone", factoringAgentPhone);
                dataMap.put("factoringCompanyName", factoringCompanyName);
                dataMap.put("factoringAddress", factoringAddress);
                dataMap.put("factoringLegalPerson", factoringLegalPerson);
                dataMap.put("factoringAgent", factoringAgent);
                dataMap.put("applicantCompanyName", applicantCompanyName);
                dataMap.put("applicantCompanyAddress", applicantCompanyAddress);
                dataMap.put("applicantCompanyLegalPerson", applicantCompanyLegalPerson);
                dataMap.put("applicantContact", master.getApplicantContact());
                dataMap.put("applicantContactNumber", master.getApplicantContactNumber());

                Integer platformNum = master.getDoubleFactoringType();
                dataMap.put("platformNum", platformNum);
                if (contractMasterContract.getSpecialAgreement() != null) {
                    dataMap.put("specialAgreement", contractMasterContract.getSpecialAgreement());
                } else {
                    dataMap.put("specialAgreement", "");

                }
                dataMap.put("debtor", debtor);
                dataMap.put("debtorNum", debtorNum);
                dataMap.put("disclosedUndisclosedFactoringNum", disclosedUndisclosedFactoringNum);
                dataMap.put("serviceScopeId", serviceScopeId);
                // 金额数字处理：千位分隔，并保留两位小数，如192->192.00;0->0.00，下同！
                dataMap.put("financingAmmount", NumberFormatUtil.convertDecimal(financingAmmount,
                        NumberFormatUtil.THOUSAND_SEPARATOR_TWO_DECIMAL));
                dataMap.put("currency", currency);
                dataMap.put("cName", currency.getName());
                dataMap.put("eName", currency.getCode());
                dataMap.put("financingAmmountCname", financingAmmountCname);
//                dataMap.put("creditGuaranteeRiskAmount", creditGuaranteeRiskAmount);
//                dataMap.put("creditGuaranteeRiskAmountName", creditGuaranteeRiskAmountName);
                dataMap.put("receivableTransferRateStr", receivableTransferRateStr);
                dataMap.put("principalCollectionMethod", principalCollectionMethod);
                dataMap.put("financingPeriod", financingPeriod);
                dataMap.put("startingDateTypesNum", startingDateTypesNum);
                dataMap.put("yearStr", yearStr);
                dataMap.put("monthStr", monthStr);
                dataMap.put("dayStr", dayStr);
                dataMap.put("loanConditionList", loanConditionListMap);
                dataMap.put("loanConditionListLength", loanConditionListLength);
                dataMap.put("amountTotal",
                        NumberFormatUtil.convertDecimal(amountTotal, NumberFormatUtil.THOUSAND_SEPARATOR_TWO_DECIMAL));
                dataMap.put("amountTotalName", amountTotalName);
                dataMap.put("financingRateStr", financingRateStr);
                dataMap.put("badDebtGuaranteeRate", badDebtGuaranteeRate);
                dataMap.put("financingInterest", NumberFormatUtil.convertDecimal(financingInterest,
                        NumberFormatUtil.THOUSAND_SEPARATOR_TWO_DECIMAL));
                dataMap.put("financingInterestName", financingInterestName);
                dataMap.put("overdueInterestRateStr", overdueInterestRateStr);
                dataMap.put("paymentMethod", paymentMethod);
                dataMap.put("marginRatioStr", marginRatioStr);
                dataMap.put("marginCollectionMethod", marginCollectionMethod);
                dataMap.put("marginReturnMethod", marginReturnMethod);
                dataMap.put("marginReturnCondition", marginReturnCondition);
                dataMap.put("manageFeeAmount", NumberFormatUtil.convertDecimal(manageFeeAmount,
                        NumberFormatUtil.THOUSAND_SEPARATOR_TWO_DECIMAL));
                dataMap.put("manageFeeAmountName", manageFeeAmountName);
                dataMap.put("manageFeeCollectionMethod", manageFeeCollectionMethod);
                dataMap.put("otherFee",
                        NumberFormatUtil.convertDecimal(otherFee, NumberFormatUtil.THOUSAND_SEPARATOR_TWO_DECIMAL));
                dataMap.put("otherFeeName", otherFeeName);
                dataMap.put("transferNoticeMethodId", transferNoticeMethodId);
                dataMap.put("masterContract", master);
                dataMap.put("list1", listMap1);
                dataMap.put("list3", listMap3);
                dataMap.put("marginLoanLastDateStr", marginLoanLastDateStr);
                dataMap.put("creditBalance", NumberFormatUtil.convertDecimal(creditBalance, NumberFormatUtil.THOUSAND_SEPARATOR_TWO_DECIMAL));
                dataMap.put("creditBalanceName", creditBalanceName);
                dataMap.put("creditEcurrency", currency.getCode());
                dataMap.put("creditCcurrency", currency.getName());
                dataMap.put("creditLine", NumberFormatUtil.convertDecimal(creditLine, NumberFormatUtil.THOUSAND_SEPARATOR_TWO_DECIMAL));
                dataMap.put("creditLineName", creditLineName);
                dataMap.put("creditTerm", creditTerm);
                dataMap.put("creditStartYearStr", creditStartYearStr);
                dataMap.put("creditStartMonthStr", creditStartMonthStr);
                dataMap.put("creditStartDayStr", creditStartDayStr);
                dataMap.put("quotaDisburseBatch", contractInfo.getQuotaDisburseBatch());
                dataMap.put("poolFactoringFinancingConfirmNo", poolFactoringFinancingConfirmNo);
                dataMap.put("poolFactoringFinancingConfirmAgree", poolFactoringFinancingConfirmAgree);
                dataMap.put("specialAgreement", "4、" + specialAgreement);
                dataMap.put("factoringSpecialAgreement", specialAgreement);
//                dataMap.put("specialAgreementStr", specialAgreementStr);
                dataMap.put("factoringAccountName", factoringAccountName);
                dataMap.put("factoringAccount", factoringAccount);
                dataMap.put("factoringAccountBank", factoringAccountBank);
                dataMap.put("factoringAccountName1", factoringAccountName1);
                dataMap.put("factoringAccount1", factoringAccount1);
                dataMap.put("factoringAccountBank1", factoringAccountBank1);
                dataMap.put("factoringAccountName2", factoringAccountName2);
                dataMap.put("factoringAccount2", factoringAccount2);
                dataMap.put("factoringAccountBank2", factoringAccountBank2);
                dataMap.put("applicantDesignatedAccountName", applicantDesignatedAccountName);
                dataMap.put("applicantDesignatedAccount", applicantDesignatedAccount);
                dataMap.put("applicantDesignatedbank", applicantDesignatedbank);
                dataMap.put("ourAccountName", ourAccountName);
                dataMap.put("ourAccount", ourAccount);
                dataMap.put("ourAccountBank", ourAccountBank);
                dataMap.put("contractNum", contractNum);
                dataMap.put("year", year);
                dataMap.put("month", month);
                dataMap.put("day", day);
                dataMap.put("date", "日期：" + year + "年" + month + "月" + day + "日");
                dataMap.put("platform", "-");
                dataMap.put("platformAddress", "-");
                dataMap.put("platformLegal", "-");
                dataMap.put("platformContact", "-");
                dataMap.put("platformContactPhone", "-");
                dataMap.put("managementFeeCollectionMethod", contractFinancingInfo.getManagementFeeCollectionMethod());// 管理费支付方式
                dataMap.put("otherFeeCollectionMethod", otherFeeCollectionMethod);
                //放款条件（新增）
                if (type.equals(ConstantConversionUtil.POOL_FACTORING_FINANCING_CONFIRM)) {
                    LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
                    Configure configure = Configure.builder().bind("listMap2", policy)
                            .bind("mapList", policy)
                            .bind("changeList", policy)
                            .bind("list3", policy)
                            .bind("loanConditionListMap", policy)
                            .build();
                    dataMap.put("doubleFactoringType", false);
                    template = XWPFTemplate.compile(absolutePath, configure).render(dataMap);
                    path = FileUtil.getAbsolutePath("池保理保理融资确认书" + master.getApplicantCompanyName(), ".docx", FileModuleDict.ChildEnum.CONTRACT_FILE_PREVIEW);
                    File file = new File(path);
                    if (!file.exists()) {
                        FileUtils.createParentDirectories(file);
                    }
                    template.writeToFile(path);
                    fileAllList.add(file);
                } else if (type.equals(ConstantConversionUtil.POOL_FACTORING_INFORMATION_DOMESTIC)) {
                    LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
                    Configure configure = Configure.builder().bind("listMap2", policy)
                            .bind("mapList", policy)
                            .bind("loanConditionList", policy)
                            .bind("listMap3", policy)
                            .build();
                    dataMap.put("doubleFactoringType", false);
                    template = XWPFTemplate.compile(absolutePath, configure).render(dataMap);
                    path = FileUtil.getAbsolutePath("池保理保理信息表-国内适用" + master.getApplicantCompanyName(), ".docx", FileModuleDict.ChildEnum.CONTRACT_FILE_PREVIEW);
                    File file = new File(path);
                    if (!file.exists()) {
                        FileUtils.createParentDirectories(file);
                    }
                    template.writeToFile(path);
                    fileAllList.add(file);
                } else if (type.equals(ConstantConversionUtil.FACTORING_SERVICE_CONFIRMATION)) {
                    LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
                    Configure configure = Configure.builder().bind("listMap2", policy)
                            .build();
                    dataMap.put("doubleFactoringType", false);
                    template = XWPFTemplate.compile(absolutePath, configure).render(dataMap);
                    path = FileUtil.getAbsolutePath("保理服务确认书" + master.getApplicantCompanyName(), ".docx", FileModuleDict.ChildEnum.CONTRACT_FILE_PREVIEW);
                    File file = new File(path);
                    if (!file.exists()) {
                        FileUtils.createParentDirectories(file);
                    }
                    template.writeToFile(path);
                    fileAllList.add(file);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(CodeUtil.FAIL, "下载保理信息表出错" + e.getMessage());
        }
    }

    /**
     * 计算应收账款金额
     *
     * @param financingBasicInfoId
     * @return
     */
    private BigDecimal calculateAccountsReceivableAmount(Long financingBasicInfoId) {
        List<CFinancingAccountsReceivableInfo> informationList = financingAccountsReceivableInfoService.list(new QueryWrapper<CFinancingAccountsReceivableInfo>()
                .eq("c_financing_basic_info_id", financingBasicInfoId));
        BigDecimal accountsReceivableAmount = BigDecimal.ZERO;
        if (CollectionUtil.isNotEmpty(informationList)) {
            accountsReceivableAmount = informationList.stream().filter(accountsReceivable -> accountsReceivable.getAccountsReceivableAmount() != null)
                    .map(CFinancingAccountsReceivableInfo::getAccountsReceivableAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        }
        return accountsReceivableAmount;
    }

    /**
     * 获取采购合同信息
     *
     * @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;
    }

    /**
     * 下载应收账款转让通知书
     */
    private void dealNewNoticeDownloadAll(ContractInfo contractInfo, List<File> fileAllList, String absolutePath, String type) {
        String path;
        XWPFTemplate template;
        try {
            Map<String, Object> noticeMap = new HashMap<>();
            // 主合同信息
            ReviewMasterContract masterContract = reviewMasterContractService.getOne(new QueryWrapper<ReviewMasterContract>()
                    .eq("review_quota_disburse_id", contractInfo.getReviewQuotaDisburseId()));
            if (null != masterContract) {
                //主合同信息-债务人
                // 合同名称
                String contractName = masterContract.getContractName();
                // 保理合同编号
                String factoringContractNo = masterContract.getContractNo();
                // 保理商
                String factoringName = masterContract.getFactoringName();
                //保理商联系人
                String factoringAgentName = masterContract.getFactoringAgentName();
                //保理商联系人电话
                String factoringAgentPhone = masterContract.getFactoringAgentPhone();
                //保理商联系人邮箱
                String factoringAgentEmail = masterContract.getFactoringAgentEmail();
                //保理商注册地址
                String factoringAddress = masterContract.getFactoringAddress();
                //保理商法人
                String factoringLegalPersion = masterContract.getFactoringLegalPerson();
                //我司指定账户户名
                String ourAccountName = masterContract.getOurAccountName();
                //我司指定账户开户行
                String ourAccountBank = masterContract.getOurAccountBank();
                //贸易平台公司名称
                String platformCompanyName = masterContract.getPlatformName();
                //贸易平台法人
                String platformLegal = masterContract.getPlatformLegal();
                // 保理申请人公司名称
                String applicantCompanyName = masterContract.getApplicantCompanyName();
                //保理申请人公司法人
                String applicantLegalPerson = masterContract.getApplicantCompanyLegalPerson();
                //保理申请人公司地址
                String applicantCompanyAddress = masterContract.getApplicantCompanyAddress();
                // 保理申请人联系人
                String applicantContact = masterContract.getApplicantContact();
                //保理申请人联系人电话
                String applicantContactNumber = masterContract.getApplicantContactNumber();
                // 保理专户户名
                String factoringAccountName = masterContract.getFactoringAccountName();
                // 保理专户账号
                String factoringAccount = masterContract.getFactoringAccount();
                // 保理专户开户行
                String factoringAccountBank = masterContract.getFactoringAccountBank();
                //融资信息
                ReviewFinancingInfo financingInfo = reviewFinancingInfoService.getOne(new QueryWrapper<ReviewFinancingInfo>()
                        .eq("review_quota_disburse_id", contractInfo.getReviewQuotaDisburseId()));
                //融资利率
                String financingRateStr;
                //融资本金+融资利息
                BigDecimal financingAmountInterest;
                // 应收账款转让通知书编号
                ReviewTransferReceivable transferReceivable = reviewTransferReceivableService
                        .getOne(new QueryWrapper<ReviewTransferReceivable>().eq("review_quota_disburse_id", contractInfo.getReviewQuotaDisburseId()));
                String noticeNo = transferReceivable.getNoticeNo();
                // 币种英文名称
                String currencyName = "CNY";
                List<Map<String, Object>> masterDebtors = new ArrayList<>();
                List<Map<String, Object>> debtors = new ArrayList<>();
                Integer m = 0;

                List<ReviewMasterContractDebtor> debtorList = reviewMasterContractDebtorService.list(new QueryWrapper<ReviewMasterContractDebtor>()
                        .eq("review_master_contract_id", masterContract.getId()));
                if (debtorList != null && debtorList.size() > 0) {
                    for (ReviewMasterContractDebtor masterContractDebtor : debtorList) {
                        //主合同-债务人公司名称
                        m++;
                        Map<String, Object> debtorMap = new HashMap<>();
                        if (debtorList.size() > 1) {
                            debtorMap.put("debtorName", masterContractDebtor.getCompanyName() + "、");
                        } else {
                            debtorMap.put("debtorName", masterContractDebtor.getCompanyName());

                        }
                        debtorMap.put("num", "qz" + m);
                        masterDebtors.add(debtorMap);
                        debtors.add(debtorMap);
                    }
                }
                noticeMap.put("debtors", debtors);
                noticeMap.put("noticeNo", noticeNo);
                noticeMap.put("factoringContractNo", factoringContractNo);
                noticeMap.put("contractName", contractName);
                noticeMap.put("ourAccountName", ourAccountName);
                noticeMap.put("ourAccountBank", ourAccountBank);
                noticeMap.put("applicantContact", applicantContact);
                noticeMap.put("applicantContactNumber", applicantContactNumber);
                noticeMap.put("applicantCompanyName", applicantCompanyName);
                noticeMap.put("factoringName", factoringName);
                noticeMap.put("applicantLegalPerson", applicantLegalPerson);
                noticeMap.put("applicantCompanyAddress", applicantCompanyAddress);
                noticeMap.put("factoringAccountName", factoringAccountName);
                noticeMap.put("factoringAccount", factoringAccount);
                noticeMap.put("factoringAccountBank", factoringAccountBank);
                noticeMap.put("currencyName", currencyName);
                noticeMap.put("factoringAgentName", factoringAgentName);
                noticeMap.put("factoringAgentPhone", factoringAgentPhone);
                noticeMap.put("factoringAgentEmail", factoringAgentEmail);
                noticeMap.put("factoringAddress", ConstantUtil.OUR_COMPANY_ADDRESS_NAME);
                noticeMap.put("factoringLegalPersion", factoringLegalPersion);
                noticeMap.put("financingPeriodInt", financingInfo.getFinancingPeriod());
                Date date = new Date();
                String day = DateUtil.getDay(date);
                String month = DateUtil.getMonth(date);
                String year = DateUtil.getYear(date);
                noticeMap.put("day", day);
                noticeMap.put("month", month);
                noticeMap.put("year", year);
                noticeMap.put("date", "日期：" + year + "年" + month + "月" + day + "日");
                if (masterContract.getDoubleFactoringType().equals(1)) {
                    noticeMap.put("platformCompanyName", "、" + platformCompanyName);
                    noticeMap.put("platformName", "乙方二（保理申请人）" + platformCompanyName);
                    noticeMap.put("platformNameNotice", "乙方二：" + platformCompanyName);//通知书
                    noticeMap.put("platformLegal", platformLegal);
                    String platform = "【乙方二名称】 ";
                    noticeMap.put("two", platform);
                }
                financingRateStr = PercentageUtil.convertPercentage(financingInfo.getFinancingRate().doubleValue());
                if (StringUtil.isNotEmpty(financingRateStr)) {
                    financingRateStr = StringUtil.subZeroAndDot(financingRateStr.split("%")[0]) + "%";
                }
                noticeMap.put("financingRateStr", financingRateStr);
                BigDecimal financingAmmount = financingInfo.getFinancingAmount();
                financingAmountInterest = financingAmmount.add(financingInfo.getFinancingInterest());
                noticeMap.put("financingAmountInterest", financingAmountInterest);
                Map<Long, List<Map<String, Object>>> groupingByMap = new HashMap<>();

                List<Map<String, Object>> changeList = new ArrayList<>();
                BigDecimal invoiceAmmountAll = BigDecimal.ZERO;

                PurchContractBasicInfo purchContractBasicInfo = getPurchContractBasicInfo(contractInfo.getBusinessNo());
                ReviewQuotaDisburse reviewQuotaDisburse = reviewQuotaDisburseService.getById(contractInfo.getReviewQuotaDisburseId());
                Map<String, Object> iMap = new HashMap<>();
                iMap.put("recordNo", 1);
                iMap.put("contractName", purchContractBasicInfo.getContractName());
                iMap.put("contractNo", purchContractBasicInfo.getContractNumber());
                iMap.put("currency", "CNY");
                iMap.put("debtor", debtorList.get(0).getCompanyName());
                iMap.put("accountsReceivableType", "货款");
                //计算应收账款金额
                BigDecimal accountsReceivableAmount = calculateAccountsReceivableAmount(reviewQuotaDisburse.getFinancingBasicInfoId());
                iMap.put("accountsReceivableAmount", accountsReceivableAmount);
                //应收账款净额
                iMap.put("netAmount", reviewQuotaDisburse.getAccountsReceivableNetAmountTotal().toString());
                iMap.put("invoiceAmountTotal", BigDecimal.ZERO);
                iMap.put("financingPeriod", financingInfo.getFinancingPeriod());
                if (null != reviewQuotaDisburse.getEndDate()) {
                    iMap.put("expiryDate", DateUtil.formateYMD(reviewQuotaDisburse.getEndDate()));
                }
                if (null != reviewQuotaDisburse.getTerm()) {
                    iMap.put("term", reviewQuotaDisburse.getTerm());
                }
                iMap.put("invoice", "——");
//                                    if(domesticInvoiceInfoList.size()==0){
//                                        ContractDomesticInvoiceInfo contractDomesticInvoiceInfo = new ContractDomesticInvoiceInfo();
//                                        contractDomesticInvoiceInfo.setInvoiceNo("");
//                                        contractDomesticInvoiceInfo.setInvoiceAmmount(BigDecimal.ZERO);
//                                        Map<String, Object> invoiceMap = new HashMap<>();
//                                        invoiceMap.put("invoiceNo",contractDomesticInvoiceInfo.getInvoiceNo());
//                                        invoiceMap.put("invoiceAmmount",contractDomesticInvoiceInfo.getInvoiceAmmount());
//                                        invoice = invoice + contractDomesticInvoiceInfo.getInvoiceNo()+" "+contractDomesticInvoiceInfo.getInvoiceAmmount()+"\n";
//
//                                        invoiceList.add(invoiceMap);
//                                    }
                changeList.add(iMap);
                noticeMap.put("receivableCurrency", "CNY");

                noticeMap.put("changeList", changeList);
                noticeMap.put("receivableAmountAll", accountsReceivableAmount);
                noticeMap.put("invoiceAmmountAll", invoiceAmmountAll);
                groupingByMap.put(debtorList.get(0).getId(), changeList);

                if (type.equals(ConstantConversionUtil.ACCOUNT_RECEIVABLE_TRANSFER_NOTICE)) {
                    LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
                    Configure configure = Configure.builder().bind("changeList", policy).build();
                    template = XWPFTemplate.compile(absolutePath, configure).render(noticeMap);
                    path = FileUtil.getAbsolutePath("池保理应收账款转让通知书—国内适用—明保理适用" + masterContract.getApplicantCompanyName(), ".docx", FileModuleDict.ChildEnum.CONTRACT_FILE_PREVIEW);
                    File file = new File(path);
                    if (!file.getParentFile().exists()) {
                        file.getParentFile().mkdirs();
                    }
                    template.writeToFile(file.getPath());
                    fileAllList.add(file);
                } else if (type.equals(ConstantConversionUtil.DOMESTIC_ACCOUNT_RECEIVABLE_TRANSFER_NOTICE_BRIGHT)) {
                    LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
                    Configure configure = Configure.builder().bind("changeList", policy).build();
                    template = XWPFTemplate.compile(absolutePath, configure).render(noticeMap);
                    path = FileUtil.getAbsolutePath("国内有追应收账款转让通知书-明保理适用" + masterContract.getApplicantCompanyName(), ".docx", FileModuleDict.ChildEnum.CONTRACT_FILE_PREVIEW);
                    File file = new File(path);
                    if (!file.getParentFile().exists()) {
                        file.getParentFile().mkdirs();
                    }
                    template.writeToFile(file.getPath());
                    fileAllList.add(file);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(CodeUtil.FAIL, "下载保理信息表出错" + e.getMessage());
        }
    }

    /**
     * 下载池保理应收账款入池确认书
     */
    private void dealNewConfirmDownload(ContractInfo contractInfo, List<File> fileAllList, String absolutePath, String type) {
        try {
            // 主合同信息
            ReviewMasterContract masterContract = reviewMasterContractService.getOne(new QueryWrapper<ReviewMasterContract>()
                    .eq("review_quota_disburse_id", contractInfo.getReviewQuotaDisburseId()));
            XWPFTemplate template;
            Map<String, Object> confirmMap = new HashMap<>();
            if (null != masterContract) {
                // 主合同信息
                ReviewFinancingInfo financingInfo = reviewFinancingInfoService.getOne(new QueryWrapper<ReviewFinancingInfo>()
                        .eq("review_quota_disburse_id", contractInfo.getReviewQuotaDisburseId()));
                //管理费率
                String managementFeeRatioStr;
                //逾期利息
                String overdueInterestRateStr = PercentageUtil
                        .convertPercentage(financingInfo.getOverdueInterestRate().doubleValue());
                // 合同名称
                String contractName = masterContract.getContractName();
                //合同编号
                String contractNo = masterContract.getContractNo();
                // 保理合同编号
                String factoringContractNo = masterContract.getContractNo();
                // 应收账款转让确认书编号
                ReviewTransferReceivable transferReceivable = reviewTransferReceivableService
                        .getOne(new QueryWrapper<ReviewTransferReceivable>().eq("review_quota_disburse_id", contractInfo.getReviewQuotaDisburseId()));
                String confirmationNo = transferReceivable.getConfirmationNo();
                //保理商
                String factoringName = masterContract.getFactoringName();
                String factoringLegalPersion = masterContract.getFactoringLegalPerson();
                String factoringAgentName = masterContract.getFactoringAgentName();
                String factoringAgentPhone = masterContract.getFactoringAgentPhone();
                // 保理申请人公司名称
                String applicantCompanyName = masterContract.getApplicantCompanyName();
                String applicantLegalPerson = masterContract.getApplicantCompanyLegalPerson();
                String applicantCompanyAddress = masterContract.getApplicantCompanyAddress();
                String applicantContact = masterContract.getApplicantContact();
                String applicantContactNumber = masterContract.getApplicantContactNumber();
                //我司指定账户户名
                String ourAccountName = masterContract.getOurAccountName();
                //我司指定账户开户行
                String ourAccountBank = masterContract.getOurAccountBank();
                //我司指定账户
                String ourAccount = masterContract.getOurAccount();
                //应收账款金额总计
                String currencyName = "CNY";
                List<ReviewMasterContractDebtor> debtorList = reviewMasterContractDebtorService.list(new QueryWrapper<ReviewMasterContractDebtor>()
                        .eq("review_master_contract_id", masterContract.getId()));
                String debtor = "";
                ReviewQuotaDisburse reviewQuotaDisburse = reviewQuotaDisburseService.getById(contractInfo.getReviewQuotaDisburseId());
                BigDecimal accountsReceivableAmount = calculateAccountsReceivableAmount(reviewQuotaDisburse.getFinancingBasicInfoId());
                confirmMap.put("receivableAmountTotal", accountsReceivableAmount);
                confirmMap.put("factoringContractNo", factoringContractNo);
                confirmMap.put("contractName", contractName);
                confirmMap.put("contractNo", contractNo);
                confirmMap.put("applicantCompanyName", applicantCompanyName);
                confirmMap.put("applicantLegalPerson", applicantLegalPerson);
                confirmMap.put("applicantCompanyAddress", applicantCompanyAddress);
                confirmMap.put("applicantContact", applicantContact);
                confirmMap.put("applicantContactNumber", applicantContactNumber);
                confirmMap.put("factoringName", factoringName);
                confirmMap.put("ourAccountName", ourAccountName);
                confirmMap.put("ourAccountBank", ourAccountBank);
                confirmMap.put("ourAccount", ourAccount);
                confirmMap.put("confirmationNo", confirmationNo);
                confirmMap.put("currencyName", currencyName);
                confirmMap.put("factoringLegalPersion", factoringLegalPersion);
                confirmMap.put("factoringAddress", ConstantUtil.OUR_COMPANY_ADDRESS_NAME);
                confirmMap.put("factoringAgentName", factoringAgentName);
                confirmMap.put("factoringAgentPhone", factoringAgentPhone);
                //融资本金
                BigDecimal financingAmmount = financingInfo.getFinancingAmount() == null ? BigDecimal.ZERO : financingInfo.getFinancingAmount();
                BigDecimal financingDays = new BigDecimal(Integer.parseInt(financingInfo.getFinancingPeriod().toString()));
                //融资本金+ （融资本金✖12%-管理费率➗360✖融资期限）
                BigDecimal balanceLong = financingAmmount.add(financingAmmount.multiply(new BigDecimal(0.12).subtract(financingInfo.getManagementFeeRatio()).divide(new BigDecimal(360), BigDecimal.ROUND_CEILING).multiply(financingDays)));
                //BigDecimal balanceLong = financingAmmount.add(financingAmmount.multiply(new BigDecimal(0.12).subtract(new BigDecimal(financingInfo.getManagementFeeRatio()))));
                confirmMap.put("financingAmountInterest", balanceLong);
                BigDecimal balance = balanceLong.setScale(2, RoundingMode.HALF_UP);
                managementFeeRatioStr = PercentageUtil.convertPercentage(financingInfo.getFinancingRate().add(financingInfo.getManagementFeeRatio()).doubleValue());
                if (StringUtil.isNotEmpty(managementFeeRatioStr)) {
                    managementFeeRatioStr = StringUtil.subZeroAndDot(managementFeeRatioStr.split("%")[0]) + "%";
                }

                if (StringUtil.isNotEmpty(overdueInterestRateStr)) {
                    overdueInterestRateStr = StringUtil.subZeroAndDot(overdueInterestRateStr.split("%")[0]) + "%";
                }
                confirmMap.put("balance", balance);
                confirmMap.put("managementFeeRatioStr", managementFeeRatioStr);
                confirmMap.put("overdueInterestRateStr", overdueInterestRateStr);
                confirmMap.put("financingRateStr", managementFeeRatioStr);
                Date date = new Date();
                confirmMap.put("day", DateUtil.getDay(date));
                confirmMap.put("month", DateUtil.getMonth(date));
                confirmMap.put("year", DateUtil.getYear(date));
                List<Map<String, Object>> changeMapList = new ArrayList<>();
                BigDecimal netAmountTotal = BigDecimal.ZERO;
                CFinancingBasicInfo financingBasicInfo = financingBasicInfoService.getById(reviewQuotaDisburse.getFinancingBasicInfoId());
                Platform platform = platformService.getById(financingBasicInfo.getPlatformId());
                if (platform != null) {
                    debtor = platform.getPlatformName();
                }
                Map<String, Object> changeMap = new HashMap<>();
                changeMap.put("recordNo", 1);
                PurchContractBasicInfo purchContractBasicInfo = getPurchContractBasicInfo(contractInfo.getBusinessNo());
                changeMap.put("contractName", purchContractBasicInfo.getContractName());
                changeMap.put("contractNo", purchContractBasicInfo.getContractNumber());
                changeMap.put("debtor", debtor);
                changeMap.put("accountsReceivableType", "货款");
                changeMap.put("accountsReceivableAmount", accountsReceivableAmount);
                changeMap.put("netAmount", reviewQuotaDisburse.getAccountsReceivableNetAmountTotal());
                if (null != reviewQuotaDisburse.getEndDate()) {
                    changeMap.put("expiryDate", DateUtil.formateYMD(reviewQuotaDisburse.getEndDate()));
                }
                if (null != reviewQuotaDisburse.getTerm()) {
                    changeMap.put("term", reviewQuotaDisburse.getTerm());
                }
                changeMap.put("invoice", "——");
                changeMapList.add(changeMap);
                confirmMap.put("invoiceAmountTotal", BigDecimal.ZERO);
                confirmMap.put("accountsReceivableAmountTotal", accountsReceivableAmount);
                confirmMap.put("netAmountTotal", netAmountTotal);
                if (null != changeMapList && changeMapList.size() > 0) {
                    confirmMap.put("changeList", changeMapList);
                    confirmMap.put("accountsReceivableAmountTotal", accountsReceivableAmount);
                    confirmMap.put("netAmountTotal", reviewQuotaDisburse.getAccountsReceivableNetAmountTotal());
                }
                confirmMap.put("debtor", debtor);
                List<Map<String, Object>> masterDebtors = new ArrayList<>();
                Integer m = 0;
                if (debtorList != null && debtorList.size() > 0) {
                    for (ReviewMasterContractDebtor masterContractDebtor : debtorList) {
                        //主合同-债务人公司名称
                        m++;
                        Map<String, Object> debtorMap = new HashMap<>();
                        if (debtorList.size() > 1) {
                            debtorMap.put("debtorName", masterContractDebtor.getCompanyName() + "、");
                        } else {
                            debtorMap.put("debtorName", masterContractDebtor.getCompanyName());

                        }
                        debtorMap.put("num", "qz" + m);
                        masterDebtors.add(debtorMap);
                    }
                }
                confirmMap.put("debtors", masterDebtors);
                confirmMap.put("doubleFactoringType", false);
                String path = null;
                if (type.equals(ConstantConversionUtil.POOL_FACTORING_ACCOUNT_RECEIVABLE)) {
                    path = FileUtil.getAbsolutePath("池保理应收账款入池确认书" + masterContract.getApplicantCompanyName(), ".docx", FileModuleDict.ChildEnum.CONTRACT_FILE_PREVIEW);
                } else if (type.equals(ConstantConversionUtil.DOMESTIC_ACCOUNT_RECEIVABLE_TRANSFER_CONFIRM)) {
                    //国内有追应收账款转让确认书
                    path = FileUtil.getAbsolutePath("国内有追应收账款转让确认书" + masterContract.getApplicantCompanyName(), ".docx", FileModuleDict.ChildEnum.CONTRACT_FILE_PREVIEW);
                } else if (type.equals(ConstantConversionUtil.ACCOUNTS_RECEIVABLE_ASSIGNMENT_AGREEMENT)) {
                    path = FileUtil.getAbsolutePath("应收账款转让协议" + masterContract.getApplicantCompanyName(), ".docx", FileModuleDict.ChildEnum.CONTRACT_FILE_PREVIEW);
                }

                LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
                Configure configure = Configure.builder().bind("changeList", policy).bind("invoiceMapList", policy).build();
                template = XWPFTemplate.compile(absolutePath, configure).render(confirmMap);
                template.writeToFile(path);
                File file = new File(path);
                if (!file.exists()) {
                    FileUtils.createParentDirectories(file);
                }
                fileAllList.add(file);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(CodeUtil.FAIL, "下载应收账款转让确认书错误" + e.getMessage());
        }
    }

    /**
     * 下载交易信息表
     *
     * @param contractInfo
     * @param list
     */
    private void dealNewTradingInfoDownload(ContractInfo contractInfo, List<File> list, Long basicId, String absolutePath) {
        try {
            // 主合同信息
            ReviewMasterContract masterContract = reviewMasterContractService.getOne(new QueryWrapper<ReviewMasterContract>()
                    .eq("review_quota_disburse_id", contractInfo.getReviewQuotaDisburseId()));
            // 保理合同编号
            String factoringContractNo = masterContract.getContractNo();
            // 池或非池
//            String isPool = contractInfo.getIsPool();
//            String businessType = contractInfo.getBusinessType();
//            String confirmationNo = contractInfo.getConfirmationNo();
//            String noticeNo = contractInfo.getNoticeNo();
//            ContractFinancingInfo financingInfo = contractInfo.getFinancingInfo();
//            Integer financingPeriod = financingInfo.getFinancingPeriod();
            // 国内有追索权（正向、反向）、国内无追索权（正向，目前没有反向业务）、池保理（出口和国内）均有三方协议和交易信息表
            String path;
            XWPFTemplate template;
            ContractBasicContract basic = null;
            List<ContractBasicContract> basicContractList = contractBasicContractService.list(new QueryWrapper<ContractBasicContract>()
                    .eq("contract_info_id", contractInfo.getId()));
            for (ContractBasicContract basicContract : basicContractList) {
                if (basicContract.getId().equals(basicId)) {
                    basic = basicContract;
                }
            }
            if (null != basicContractList && basicContractList.size() > 0) {
                // 表示有三方协议
                Map<String, Object> map = new HashMap<>();
                map.put("creditorName", masterContract.getApplicantCompanyName());// 债权人名称
                map.put("creditorLegalPerson", masterContract.getApplicantCompanyLegalPerson());
                map.put("creditorAddress", masterContract.getApplicantCompanyAddress());// 债权人注册地址
                map.put("factoringContractNo", factoringContractNo);
                map.put("factoringContractName", masterContract.getContractName());
                map.put("factoringName", masterContract.getFactoringName());
                map.put("factoringAddress", masterContract.getFactoringAddress());
                // 基础交易合同
                map.put("tripartiteAgreementNo", basic.getTripartiteAgreementNo());
                if (basic.getSpecialAgreement() != null && !basic.getSpecialAgreement().equals("")) {
                    String specialAgreement = basic.getSpecialAgreement();
                    map.put("specialAgreement", specialAgreement);
                }
                map.put("debtorName", basic.getDebtorCompanyName());// 债务人公司名称
                Enterprise ent = enterpriseService.getById(basic.getDebtorCompanyId());
                if (ent != null) {
                    map.put("entLegalPerson", ent.getLegalRepresentative());
                }
                // 基础交易合同信息
                List<ContractBasicContractChangeContent> changeList = basic.getContractContentList();
                List<Map<String, Object>> changeMapList = new ArrayList<>();
                if (null != changeList && changeList.size() > 0) {
                    for (ContractBasicContractChangeContent change : changeList) {
                        Map<String, Object> changMap = new HashMap<>();
                        changMap.put("contractNo", change.getContractNo());
                        changMap.put("contractName", change.getContractName());
                        changMap.put("originalContractContent", change.getOriginalContractContent());
                        changMap.put("postChangeContent", change.getPostChangeContent());
                        changeMapList.add(changMap);
                    }
                }
                map.put("changeList", changeMapList);
                ReviewTransferReceivable transferReceivable = reviewTransferReceivableService
                        .getOne(new QueryWrapper<ReviewTransferReceivable>().eq("review_quota_disburse_id", contractInfo.getReviewQuotaDisburseId()));
                map.put("confirmationNo", transferReceivable.getConfirmationNo());
                map.put("noticeNo", transferReceivable.getNoticeNo());
                ReviewFinancingInfo financingInfo = reviewFinancingInfoService.getOne(new QueryWrapper<ReviewFinancingInfo>()
                        .eq("review_quota_disburse_id", contractInfo.getReviewQuotaDisburseId()));
                map.put("financingPeriod", financingInfo.getFinancingPeriod());
                Date date = new Date();
                map.put("year", DateUtil.getYear(date));
                map.put("month", DateUtil.getMonth(date));
                map.put("day", DateUtil.getDay(date));
                LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
                Configure configure = Configure.builder().bind("changeList", policy).build();
                template = XWPFTemplate.compile(absolutePath, configure).render(map);
                path = FileUtil.getAbsolutePath("交易信息表" + masterContract.getApplicantCompanyName(), ".docx", FileModuleDict.ChildEnum.CONTRACT_FILE_PREVIEW);
                File file = new File(path);
                if (!file.exists()) {
                    FileUtils.createParentDirectories(file);
                }
                template.writeToFile(path);
                list.add(file);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(CodeUtil.FAIL, "下载交易信息表出错" + e.getMessage());
        }
    }
}
