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

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sunxung.factoring.component.enums.FinancingCurrentStageEnum;
import com.sunxung.factoring.component.exception.BusinessException;
import com.sunxung.factoring.component.exception.ValidatorException;
import com.sunxung.factoring.component.util.*;
import com.sunxung.factoring.component.util.onlineConverter.OfficeConverterUtil;
import com.sunxung.factoring.dict.impl.FileModuleDict;
import com.sunxung.factoring.entity.customerinformation.ElectronicSignaturePersonal;
import com.sunxung.factoring.entity.entprise.Enterprise;
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.sys.Dictionary;
import com.sunxung.factoring.entity.sys.FileStorage;
import com.sunxung.factoring.entity.tradingPlatform.Platform;
import com.sunxung.factoring.service.customerinformation.IElectronicSignaturePersonalService;
import com.sunxung.factoring.service.entprise.IEnterpriseService;
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.BusinessAssigneeService;
import com.sunxung.factoring.service.sys.FileStorageService;
import com.sunxung.factoring.service.sys.flowable.FlowableService;
import com.sunxung.factoring.service.tradingPlatform.PlatformService;
import org.apache.commons.lang3.StringUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.util.PDFTextStripper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description : 合同制作业务层实现类
 * @Author : L.Jia
 * @Date: 2024-01-29 10:57
 */
@Service("contract_makingService")
public class ContractMakingServiceImpl implements ContractMakingService {

    @Autowired
    private ICFinancingBasicInfoService financingBasicInfoService;
    @Autowired
    private IContractInfoService contractInfoService;
    @Autowired
    private ReviewFixedWithdrawalConditionService reviewFixedWithdrawalConditionService;
    @Autowired
    private IContractLoanConditionSettingService contractLoanConditionSettingService;
    @Autowired
    private ReviewIncomeExpenditurePlanService reviewIncomeExpenditurePlanService;
    @Autowired
    private ReviewLoanConditionService reviewLoanConditionService;
    @Autowired
    private ReviewBasicContractService reviewBasicContractService;
    @Autowired
    private ReviewBasicContractChangeContentService reviewBasicContractChangeContentService;
    @Autowired
    private ReviewMasterContractService reviewMasterContractService;
    @Autowired
    private ReviewMasterContractDebtorService reviewMasterContractDebtorService;
    @Autowired
    private IContractMasterContractService contractMasterContractService;
    @Autowired
    private IContractFinancingInfoService contractFinancingInfoService;
    @Autowired
    private IContractBasicContractService contractBasicContractService;
    @Autowired
    private IContractBasicContractChangeContentService contractBasicContractChangeContentService;
    @Autowired
    private IContractBasicContractHisService contractBasicContractHisService;
    @Autowired
    private IContractBasicContractChangeContentHisService contractBasicContractChangeContentHisService;
    @Autowired
    private IContractLoanConditionSettingRelService contractLoanConditionSettingRelService;
    @Autowired
    private PlatformService platformService;
    @Autowired
    private ReviewRltRepayService reviewRltRepayService;
    @Autowired
    private ReviewQuotaDisburseService reviewQuotaDisburseService;
    @Autowired
    private ReviewQuotaMortgageRelService reviewQuotaMortgageRelService;
    @Autowired
    private ReviewMortgageBasicInfoService reviewMortgageBasicInfoService;
    @Autowired
    private IUploadContractInfoService uploadContractInfoService;
    @Autowired
    private IUploadContractSignatoryService uploadContractSignatoryService;
    @Autowired
    private BusinessAssigneeService assigneeService;
    @Autowired
    private FlowableService flowableService;
    @Autowired
    private INewContractMakingService newContractMakingService;
    @Autowired
    private ISysCustomerService sysCustomerService;
    @Autowired
    private IEnterpriseService enterpriseService;
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private IContractElectronicInfoService contractElectronicInfoService;
    @Autowired
    private IContractElectronicCustomerInfoService contractElectronicCustomerInfoService;
    @Autowired
    private IContractTemplateService contractTemplateService;
    @Autowired
    private ReviewFinancingInfoService reviewFinancingInfoService;
    @Autowired
    private IElectronicSignaturePersonalService electronicSignaturePersonalService;

    @Override
    public ContractInfo edit(Long id) {
        ContractInfo contractInfo = getContractInfoByFinancingBasicInfoId(id);
        //新增融资信息
        addContractFinancing(contractInfo);
        //新增主合同信息
        addMasterContract(contractInfo);
        // 新增收支计划信息
        addReviewLoanCondition(contractInfo);
        // 新增放款条件设定
        addFixedLoanConditionSettingList(contractInfo);
        // 新增基础交易合同信息
        addBasicContractList(contractInfo);
        //填充上传合同中可签署方
        autoUploadContract(contractInfo);
        //填充电子签模板集合
        autoElectronicSign(contractInfo);
        return contractInfo;
    }

    @Override
    public List<UploadContractSignatory> getUploadContractList(Long id) {

        ContractInfo contractInfo = getContractInfoByFinancingBasicInfoId(id);

        List<UploadContractSignatory> result = new ArrayList<>();
        if (contractInfo != null) {
            //填充主合同签署人
            ReviewMasterContract masterContract = reviewMasterContractService.getOne(new QueryWrapper<ReviewMasterContract>()
                    .eq("review_quota_disburse_id", contractInfo.getReviewQuotaDisburseId()));
            //填充保理商
            UploadContractSignatory factoring = new UploadContractSignatory();
            factoring.setName(masterContract.getFactoringName());
            factoring.setSocialCreditCode(masterContract.getFactoringSocialCreditCode());
            factoring.setType(true);
            factoring.setContractType(ConstantUtil.contract_type_master);

            UploadContractSignatory factoring1 = new UploadContractSignatory();
            factoring1.setName(masterContract.getFactoringName());
            factoring1.setSocialCreditCode(masterContract.getFactoringSocialCreditCode());
            factoring1.setType(true);
            factoring1.setContractType(ConstantUtil.contract_type_annex);

            result.add(factoring);
            result.add(factoring1);

            //填充保理申请人
            UploadContractSignatory applicant = new UploadContractSignatory();
            applicant.setName(masterContract.getApplicantCompanyName());
            applicant.setSocialCreditCode(masterContract.getApplicantSocialCreditCode());
            applicant.setType(true);
            applicant.setContractType(ConstantUtil.contract_type_master);
            result.add(applicant);
            //填充债务人
            List<ReviewMasterContractDebtor> debtorList = reviewMasterContractDebtorService.list(new QueryWrapper<ReviewMasterContractDebtor>().eq("review_master_contract_id", masterContract.getId()));
            if (CollectionUtil.isNotEmpty(debtorList)) {
                debtorList.forEach(r -> {
                    Platform platform = platformService.getOne(new QueryWrapper<Platform>().eq("platform_name", r.getCompanyName()));
                    if (platform != null) {
                        UploadContractSignatory debtor = new UploadContractSignatory();
                        debtor.setName(platform.getPlatformName());
                        debtor.setSocialCreditCode(platform.getSocialCreditCode());
                        debtor.setType(true);
                        debtor.setContractType(ConstantUtil.contract_type_master);
                        result.add(debtor);
                    }
                });
            }
            //填充附件合同签署人
            //相关还款责任人
            List<ReviewRltRepay> reviewRltRepayList = reviewRltRepayService.list(new QueryWrapper<ReviewRltRepay>()
                    .eq("review_quota_disburse_id", contractInfo.getReviewQuotaDisburseId()));
            if (CollectionUtil.isNotEmpty(reviewRltRepayList)) {
                for (ReviewRltRepay reviewRltRepay : reviewRltRepayList) {
                    UploadContractSignatory guarantee = new UploadContractSignatory();
                    //公司
                    if (reviewRltRepay.getArlpIdType().equals("idType_2")) {
                        guarantee.setName(reviewRltRepay.getArlpName());
                        guarantee.setSocialCreditCode(reviewRltRepay.getArlpCertNum());
                        guarantee.setType(true);
                        guarantee.setContractType(ConstantUtil.contract_type_annex);
                        if (!reviewRltRepay.getArlpCertType().equals("certType_ZYCZR_SJKZR_SJJG_QYGLGX_QTBS_20_idType_2")) {
                            continue;
                        }
                    } else if (reviewRltRepay.getArlpIdType().equals("idType_1")) {
                        //配偶信息
                        if (StringUtil.isNotBlank(reviewRltRepay.getSpouseName()) && StringUtil.isNotBlank(reviewRltRepay.getSpouseIdCard())) {
                            UploadContractSignatory spouse = new UploadContractSignatory();
                            spouse.setName(reviewRltRepay.getSpouseName());
                            spouse.setSocialCreditCode(reviewRltRepay.getSpouseIdCard());
                            spouse.setCardFrontFileStorageId(reviewRltRepay.getSpouseCardFrontFileStorageId());
                            spouse.setCardReverseFileStorageId(reviewRltRepay.getSpouseCardReverseFileStorageId());
                            spouse.setContactNumber(reviewRltRepay.getSpouseContactNumber());
                            spouse.setType(false);
                            spouse.setContractType(ConstantUtil.contract_type_annex);
                            String certTypeId = null;
                            if (reviewRltRepay.getSpouseCardType().equals("certType_ZYZCRY_ZYCZR_SJKZR_10_idType_1")) {
                                certTypeId = "0";
                            } else if (reviewRltRepay.getSpouseCardType().equals("certType_ZYZCRY_ZYCZR_SJKZR_2_idType_1")) {
                                certTypeId = "1";
                            } else if (reviewRltRepay.getSpouseCardType().equals("certType_ZYZCRY_ZYCZR_SJKZR_5_idType_1")) {
                                certTypeId = "B";
                            } else if (reviewRltRepay.getSpouseCardType().equals("certType_ZYZCRY_ZYCZR_SJKZR_6_idType_1")) {
                                certTypeId = "C";
                            }
                            spouse.setCardTypeId(certTypeId);
                            if (StringUtil.isNotEmpty(certTypeId)) {
                                result.add(spouse);
                            }
                        }
                        //个人
                        String certTypeId;
                        if (reviewRltRepay.getArlpCertType().equals("certType_ZYZCRY_ZYCZR_SJKZR_10_idType_1")) {
                            certTypeId = "0";
                        } else if (reviewRltRepay.getArlpCertType().equals("certType_ZYZCRY_ZYCZR_SJKZR_2_idType_1")) {
                            certTypeId = "1";
                        } else if (reviewRltRepay.getArlpCertType().equals("certType_ZYZCRY_ZYCZR_SJKZR_5_idType_1")) {
                            certTypeId = "B";
                        } else if (reviewRltRepay.getArlpCertType().equals("certType_ZYZCRY_ZYCZR_SJKZR_6_idType_1")) {
                            certTypeId = "C";
                        } else {
                            continue;
                        }
                        guarantee.setName(reviewRltRepay.getArlpName());
                        guarantee.setSocialCreditCode(reviewRltRepay.getArlpCertNum());
                        guarantee.setCardTypeId(certTypeId);
                        guarantee.setCardFrontFileStorageId(reviewRltRepay.getGuaranteeCardFrontFileStorageId());
                        guarantee.setCardReverseFileStorageId(reviewRltRepay.getGuaranteeCardReverseFileStorageId());
                        guarantee.setContactNumber(reviewRltRepay.getResponsiblePhone());
                        guarantee.setType(false);
                        guarantee.setContractType(ConstantUtil.contract_type_annex);
                    }
                    result.add(guarantee);
                }
            }
            //抵质押信息
            List<ReviewQuotaMortgageRel> list = reviewQuotaMortgageRelService.list(new QueryWrapper<ReviewQuotaMortgageRel>()
                    .eq("review_quota_disburse_id", contractInfo.getReviewQuotaDisburseId()));
            if (null != list && list.size() > 0) {
                for (ReviewQuotaMortgageRel reviewQuotaMortgageRel : list) {
                    ReviewMortgageBasicInfo reviewMortgageBasicInfo = reviewMortgageBasicInfoService.getById(reviewQuotaMortgageRel.getReviewMortgageBasicId());
                    String certType = reviewMortgageBasicInfo.getMortgagorCertType();
                    UploadContractSignatory uploadContractSignatory = new UploadContractSignatory();
                    if (reviewMortgageBasicInfo.getMortgagorIdType().equals("idType_2")) {
                        uploadContractSignatory.setName(reviewMortgageBasicInfo.getMortgagorName());
                        uploadContractSignatory.setSocialCreditCode(reviewMortgageBasicInfo.getMortgagorCertNum());
                        uploadContractSignatory.setType(true);
                        uploadContractSignatory.setContractType(ConstantUtil.contract_type_annex);
                        if (!certType.equals("certType_ZYCZR_SJKZR_SJJG_QYGLGX_QTBS_20_idType_2")) {
                            continue;
                        }
                    } else if (reviewMortgageBasicInfo.getMortgagorIdType().equals("idType_1")) {
                        String certTypeId;
                        if (certType.equals("certType_ZYZCRY_ZYCZR_SJKZR_10_idType_1")) {
                            certTypeId = "0";
                        } else if (certType.equals("certType_ZYZCRY_ZYCZR_SJKZR_2_idType_1")) {
                            certTypeId = "1";
                        } else if (certType.equals("certType_ZYZCRY_ZYCZR_SJKZR_5_idType_1")) {
                            certTypeId = "B";
                        } else if (certType.equals("certType_ZYZCRY_ZYCZR_SJKZR_6_idType_1")) {
                            certTypeId = "C";
                        } else {
                            continue;
                        }
                        uploadContractSignatory.setName(reviewMortgageBasicInfo.getMortgagorName());
                        uploadContractSignatory.setSocialCreditCode(reviewMortgageBasicInfo.getMortgagorCertNum());
                        uploadContractSignatory.setCardTypeId(certTypeId);
                        uploadContractSignatory.setCardFrontFileStorageId(reviewMortgageBasicInfo.getCardFrontFileStorageId());
                        uploadContractSignatory.setCardReverseFileStorageId(reviewMortgageBasicInfo.getCardReverseFileStorageId());
                        uploadContractSignatory.setContactNumber(reviewMortgageBasicInfo.getContactNumber());
                        uploadContractSignatory.setType(false);
                        uploadContractSignatory.setContractType(ConstantUtil.contract_type_annex);
                    }
                    result.add(uploadContractSignatory);
                }
            }
        }
        List<UploadContractSignatory> distinctResult = result.stream().distinct().collect(Collectors.toList());
        return distinctResult;
    }

    /**
     * 根据融资信息id获取合同信息
     *
     * @param id
     * @return
     */
    private ContractInfo getContractInfoByFinancingBasicInfoId(Long id) {
        CFinancingBasicInfo financingBasicInfo = financingBasicInfoService.getById(id);
        ReviewQuotaDisburse quotaDisburse = reviewQuotaDisburseService.getOne(new QueryWrapper<ReviewQuotaDisburse>()
                .eq("c_financing_basic_info_id", financingBasicInfo.getId()));
        if (quotaDisburse == null) {
            throw new BusinessException(CodeUtil.FAIL, "获取不到对应额度支用信息");
        }
        //取最新一条
        ContractInfo contractInfo = contractInfoService.getOne(new QueryWrapper<ContractInfo>()
                .eq("review_quota_disburse_id", quotaDisburse.getId())
                .orderByDesc("id").last("LIMIT 1"));
        if (null == contractInfo) {
            throw new BusinessException(CodeUtil.FAIL, "通过额度支用Id获取不到对应的合同信息");
        }
        return contractInfo;
    }

    @Override
    public Set<Dictionary> getElectronicSignList(Long contractInfoId) {
        Set<Dictionary> dictionaries = new HashSet<>();
        ContractInfo contractInfo = contractInfoService.getById(contractInfoId);
        ReviewFinancingInfo reviewFinancingInfo = reviewFinancingInfoService.lambdaQuery().eq(ReviewFinancingInfo::getReviewQuotaDisburseId, contractInfo.getReviewQuotaDisburseId()).one();
        List<ReviewRltRepay> reviewRltRepays = reviewRltRepayService.lambdaQuery().eq(ReviewRltRepay::getReviewQuotaDisburseId, contractInfo.getReviewQuotaDisburseId()).list();
        List<ReviewMortgageBasicInfo> reviewMortgageBasicInfos = reviewMortgageBasicInfoService.findByQuotaDisburseId(contractInfo.getReviewQuotaDisburseId());
        List<ContractTemplate> list = contractTemplateService.lambdaQuery().eq(ContractTemplate::getVisible, 1).list();
        for (ContractTemplate contractTemplate : list) {
            if (reviewFinancingInfo.getOccupation().equals(0)) {
                //不占用公司资金
                if (contractTemplate.getTemplateCode().equals(ConstantConversionUtil.GENERAL_GUARANTEE_PERSONAL) ||
                        contractTemplate.getTemplateCode().equals(ConstantConversionUtil.GENERAL_GUARANTEE_COMPANY) ||
                        contractTemplate.getTemplateCode().equals(ConstantConversionUtil.MAXIMUM_GUARANTEE_CULVER_PERSONAL) ||
                        contractTemplate.getTemplateCode().equals(ConstantConversionUtil.MAXIMUM_GUARANTEE_CULVER_COMPANY) ||
                        contractTemplate.getTemplateCode().equals(ConstantConversionUtil.TRIPARTITE_AGREEMENT_FACTORING)) {
                    continue;
                }
                //不占用公司资金 银保通合同模板
                if (contractTemplate.getTemplateCode().equals(ConstantConversionUtil.DOMESTIC_ACCOUNT_RECEIVABLE_TRANSFER_CONFIRM) ||
                        contractTemplate.getTemplateCode().equals(ConstantConversionUtil.DOMESTIC_ACCOUNT_RECEIVABLE_TRANSFER_NOTICE_BRIGHT) ||
                        contractTemplate.getTemplateCode().equals(ConstantConversionUtil.FACTORING_BUSINESS_CONTRACT) ||
                        contractTemplate.getTemplateCode().equals(ConstantConversionUtil.FACTORING_SERVICE_CONFIRMATION) ||
                        contractTemplate.getTemplateCode().equals(ConstantConversionUtil.ACCOUNTS_RECEIVABLE_ASSIGNMENT_AGREEMENT)) {
                    Dictionary dictionaryNew = new Dictionary();
                    dictionaryNew.setCode(contractTemplate.getTemplateCode());
                    dictionaryNew.setName(contractTemplate.getName());
                    dictionaries.add(dictionaryNew);
                }
            } else {
                //占用公司资金 贸理通合同模板
                if (contractTemplate.getTemplateCode().equals(ConstantConversionUtil.MAXIMUM_GUARANTEE_CULVER_PERSONAL_M2) ||
                        contractTemplate.getTemplateCode().equals(ConstantConversionUtil.MAXIMUM_GUARANTEE_CULVER_COMPANY_M2) ||
                        contractTemplate.getTemplateCode().equals(ConstantConversionUtil.GENERAL_GUARANTEE_COMPANY_M2) ||
                        contractTemplate.getTemplateCode().equals(ConstantConversionUtil.GENERAL_GUARANTEE_PERSONAL_M2) ||
                        contractTemplate.getTemplateCode().equals(ConstantConversionUtil.TRIPARTITE_AGREEMENT) ||
                        contractTemplate.getTemplateCode().equals(ConstantConversionUtil.TRADING_INFO)) {
                    continue;
                }
                if (contractTemplate.getTemplateCode().equals(ConstantConversionUtil.POOL_FACTORING_BUSINESS_CONTRACT) ||
                        contractTemplate.getTemplateCode().equals(ConstantConversionUtil.POOL_FACTORING_INFORMATION_DOMESTIC) ||
                        contractTemplate.getTemplateCode().equals(ConstantConversionUtil.POOL_FACTORING_ACCOUNT_RECEIVABLE) ||
                        contractTemplate.getTemplateCode().equals(ConstantConversionUtil.POOL_FACTORING_FINANCING_CONFIRM) ||
                        contractTemplate.getTemplateCode().equals(ConstantConversionUtil.ACCOUNT_RECEIVABLE_TRANSFER_NOTICE)) {
                    Dictionary dictionaryNew = new Dictionary();
                    dictionaryNew.setCode(contractTemplate.getTemplateCode());
                    dictionaryNew.setName(contractTemplate.getName());
                    dictionaries.add(dictionaryNew);
                }
            }
            // 三方协议（贸理通）
            List<ContractBasicContract> basicContractList = contractBasicContractService.lambdaQuery().eq(ContractBasicContract::getContractInfoId, contractInfo.getId()).list();
            if (contractTemplate.getTemplateCode().equals(ConstantConversionUtil.TRIPARTITE_AGREEMENT_FACTORING)) {
                if (basicContractList != null && basicContractList.size() > 0) {
                    for (ContractBasicContract contractBasicContract : basicContractList) {
                        Dictionary dictionary = new Dictionary();
                        dictionary.setCode(contractTemplate.getTemplateCode() + "_" + contractBasicContract.getId());
                        dictionary.setName(contractTemplate.getName() + "_" + contractBasicContract.getDebtorCompanyName());
                        dictionaries.add(dictionary);
                    }
                }
            }
            //三方协议 不可撤销承诺书 交易信息表
            if (contractTemplate.getTemplateCode().equals(ConstantConversionUtil.TRIPARTITE_AGREEMENT)
                    || contractTemplate.getTemplateCode().equals(ConstantConversionUtil.TRADING_INFO)) {
                if (basicContractList != null && basicContractList.size() > 0) {
                    if (basicContractList != null && basicContractList.size() > 0) {
                        for (ContractBasicContract contractBasicContract : basicContractList) {
                            Dictionary dictionaryNew = new Dictionary();
                            dictionaryNew.setCode(contractTemplate.getTemplateCode() + "_" + contractBasicContract.getId());
                            dictionaryNew.setName(contractTemplate.getName() + "_" + contractBasicContract.getDebtorCompanyName());
                            dictionaries.add(dictionaryNew);
                        }
                    }
                }
            }
            if (contractTemplate.getTemplateCode().equals(ConstantConversionUtil.MAXIMUM_GUARANTEE_CULVER_COMPANY)
                    || contractTemplate.getTemplateCode().equals(ConstantConversionUtil.MAXIMUM_GUARANTEE_CULVER_PERSONAL)
                    || contractTemplate.getTemplateCode().equals(ConstantConversionUtil.GENERAL_GUARANTEE_COMPANY)
                    || contractTemplate.getTemplateCode().equals(ConstantConversionUtil.GENERAL_GUARANTEE_PERSONAL)
                    || contractTemplate.getTemplateCode().equals(ConstantConversionUtil.MAXIMUM_GUARANTEE_CULVER_COMPANY_M2)
                    || contractTemplate.getTemplateCode().equals(ConstantConversionUtil.MAXIMUM_GUARANTEE_CULVER_PERSONAL_M2)
                    || contractTemplate.getTemplateCode().equals(ConstantConversionUtil.GENERAL_GUARANTEE_PERSONAL_M2)
                    || contractTemplate.getTemplateCode().equals(ConstantConversionUtil.GENERAL_GUARANTEE_COMPANY_M2)
                    || contractTemplate.getTemplateCode().equals(ConstantConversionUtil.SPOUSE_STATEMENT_GUARANTEE_SPOUSE)
                    || contractTemplate.getTemplateCode().equals(ConstantConversionUtil.FACTORING_CONTRACT_NUMBER_GUARANTEE_PERSON)
                    || contractTemplate.getTemplateCode().equals(ConstantConversionUtil.FACTORING_CONTRACT_NUMBER_GUARANTEE_COMPANY)) {
                if (CollectionUtil.isNotEmpty(reviewRltRepays)) {
                    reviewRltRepays.forEach(c -> {
                        if (c.getArlpType().equals(ConstantConversionUtil.ARLP_TYPE_BZR)) {
                            //最高额公司触发条件：还款责任人类型：保证人，责任人身份类别：自治机构&担保函类型：最高额
                            if (contractTemplate.getTemplateCode().equals(ConstantConversionUtil.MAXIMUM_GUARANTEE_CULVER_COMPANY) ||
                                    contractTemplate.getTemplateCode().equals(ConstantConversionUtil.MAXIMUM_GUARANTEE_CULVER_COMPANY_M2)) {
                                if (c.getArlpIdType() != null && c.getArlpIdType().equals(ConstantConversionUtil.IDENTITY_TYPE2)
                                        && c.getGuaranteeClassify().equals(1)) {
                                    Dictionary dictionaryNew = new Dictionary();
                                    dictionaryNew.setCode(contractTemplate.getTemplateCode() + "_" + c.getId());
                                    dictionaryNew.setName(contractTemplate.getName() + "_" + c.getArlpName());
                                    dictionaries.add(dictionaryNew);
                                }
                            }

                            if (contractTemplate.getTemplateCode().equals(ConstantConversionUtil.MAXIMUM_GUARANTEE_CULVER_PERSONAL) ||
                                    contractTemplate.getTemplateCode().equals(ConstantConversionUtil.MAXIMUM_GUARANTEE_CULVER_PERSONAL_M2)) {
                                //最高额公司M2触发条件：还款责任人类型：保证人，责任人身份类别：自然人&担保函类型：最高额
                                if (c.getArlpIdType() != null && c.getArlpIdType().equals(ConstantConversionUtil.IDENTITY_TYPE1)
                                        && c.getGuaranteeClassify().equals(1)) {
                                    Dictionary dictionaryNew = new Dictionary();
                                    dictionaryNew.setCode(contractTemplate.getTemplateCode() + "_" + c.getId());
                                    dictionaryNew.setName(contractTemplate.getName() + "_" + c.getArlpName());
                                    dictionaries.add(dictionaryNew);

                                }
                            }

                            if (contractTemplate.getTemplateCode().equals(ConstantConversionUtil.GENERAL_GUARANTEE_COMPANY) ||
                                    contractTemplate.getTemplateCode().equals(ConstantConversionUtil.GENERAL_GUARANTEE_COMPANY_M2)) {
                                //常规担保函公司 触发条件：组织机构&担保函类型：常规
                                if (c.getArlpType() != null && c.getArlpIdType().equals(ConstantConversionUtil.IDENTITY_TYPE2)
                                        && c.getGuaranteeClassify().equals(0)) {
                                    Dictionary dictionaryNew = new Dictionary();
                                    dictionaryNew.setCode(contractTemplate.getTemplateCode() + "_" + c.getId());
                                    dictionaryNew.setName(contractTemplate.getName() + "_" + c.getArlpName());
                                    dictionaries.add(dictionaryNew);
                                }
                            }


                            if (contractTemplate.getTemplateCode().equals(ConstantConversionUtil.GENERAL_GUARANTEE_PERSONAL) ||
                                    contractTemplate.getTemplateCode().equals(ConstantConversionUtil.GENERAL_GUARANTEE_PERSONAL_M2)) {
                                //常规担保函个人 触发条件：自然人&担保函类型：常规
                                if (c.getArlpType() != null && c.getArlpIdType().equals(ConstantConversionUtil.IDENTITY_TYPE1)
                                        && c.getGuaranteeClassify().equals(0)) {
                                    Dictionary dictionaryNew = new Dictionary();
                                    dictionaryNew.setCode(contractTemplate.getTemplateCode() + "_" + c.getId());
                                    dictionaryNew.setName(contractTemplate.getName() + "_" + c.getArlpName());
                                    dictionaries.add(dictionaryNew);
                                }
                            }


                            if (contractTemplate.getTemplateCode().equals(ConstantConversionUtil.SPOUSE_STATEMENT_GUARANTEE_SPOUSE)) {
                                // 配偶声明 触发条件：相关还款责任人类型：保证人&身份类别：自然人&担保人配偶不为空
                                if (StringUtil.isNotEmpty(c.getSpouseName())
                                        && StringUtil.isNotEmpty(c.getSpouseIdCard()) &&
                                        c.getArlpIdType().equals(ConstantConversionUtil.IDENTITY_TYPE1)) {
                                    Dictionary dictionaryNew = new Dictionary();
                                    dictionaryNew.setCode(contractTemplate.getTemplateCode() + "_" + c.getId());
                                    dictionaryNew.setName(contractTemplate.getName() + "_" + c.getSpouseName());
                                    dictionaries.add(dictionaryNew);
                                }
                            }

                            if (contractTemplate.getTemplateCode().equals(ConstantConversionUtil.FACTORING_CONTRACT_NUMBER_GUARANTEE_PERSON)) {
                                //财产清单个人 触发条件：相关还款责任人类型：保证人&身份类别：自然人&是否有财产清单 是
                                if (c.getArlpIdType().equals(ConstantConversionUtil.IDENTITY_TYPE1) &&
                                        c.getPropertyList() == 1) {
                                    Dictionary dictionaryNew = new Dictionary();
                                    dictionaryNew.setCode(contractTemplate.getTemplateCode() + "_" + c.getId());
                                    dictionaryNew.setName(contractTemplate.getName() + "_" + c.getArlpName());
                                    dictionaries.add(dictionaryNew);
                                }
                            }

                            if (contractTemplate.getTemplateCode().equals(ConstantConversionUtil.FACTORING_CONTRACT_NUMBER_GUARANTEE_COMPANY)) {
                                if (c.getArlpIdType().equals(ConstantConversionUtil.IDENTITY_TYPE2) &&
                                        c.getPropertyList() == 1) {
                                    Dictionary dictionaryNew = new Dictionary();
                                    dictionaryNew.setCode(contractTemplate.getTemplateCode() + "_" + c.getId());
                                    dictionaryNew.setName(contractTemplate.getName() + "_" + c.getArlpName());
                                    dictionaries.add(dictionaryNew);
                                }
                            }
                        }
                    });
                }
            }
            if (contractTemplate.getTemplateCode().equals(ConstantConversionUtil.MOVABLE_MORTGAGE_CONTRACT_NUMBER_GUARANTEE_COMPANY)) {
                // 动产抵押(公司) 触发条件：抵质押信息-抵押合同-抵押物种类：机械设备&抵押人身份类别：组织机构
                if (CollectionUtil.isNotEmpty(reviewMortgageBasicInfos)) {
                    List<ReviewMortgageBasicInfo> mortgageBasicInfoList = reviewMortgageBasicInfos.stream().filter(c -> c.getGuarType() == 1)
                            .filter(c -> c.getMortgagorIdType().equals(ConstantConversionUtil.IDENTITY_TYPE2) &&
                                    CollectionUtil.isNotEmpty(c.getMortgageCollateralInfoList()))
                            .collect(Collectors.toList());
                    if (CollectionUtil.isNotEmpty(mortgageBasicInfoList)) {
                        mortgageBasicInfoList.forEach(c -> {
                            long count = c.getMortgageCollateralInfoList().stream().filter(m -> m.getCollType()
                                    .equals(ConstantConversionUtil.COLLATERAL_TYPE_JQSB)).count();
                            if (count > 0) {
                                Dictionary dictionaryNew = new Dictionary();
                                dictionaryNew.setCode(contractTemplate.getTemplateCode() + "_" + c.getId());
                                dictionaryNew.setName(contractTemplate.getName().replace("编号", "") + "_" + c.getMortgagorName());
                                dictionaries.add(dictionaryNew);
                            }
                        });
                    }
                }
            }
            if (contractTemplate.getTemplateCode().equals(ConstantConversionUtil.MOVABLE_MORTGAGE_CONTRACT_NUMBER_GUARANTEE_PERSONAL)) {
                // 动产抵押（个人）触发条件：抵质押信息-抵押合同-抵押物种类：机械设备&抵押人身份类别：自然人
                if (CollectionUtil.isNotEmpty(reviewMortgageBasicInfos)) {
                    List<ReviewMortgageBasicInfo> mortgageBasicInfoList = reviewMortgageBasicInfos.stream().filter(c -> c.getGuarType() == 1)
                            .filter(c -> c.getMortgagorIdType().equals(ConstantConversionUtil.IDENTITY_TYPE1) &&
                                    CollectionUtil.isNotEmpty(c.getMortgageCollateralInfoList()))
                            .collect(Collectors.toList());
                    if (CollectionUtil.isNotEmpty(mortgageBasicInfoList)) {
                        mortgageBasicInfoList.forEach(c -> {
                                    long count = c.getMortgageCollateralInfoList().stream().filter(m -> m.getCollType()
                                            .equals(ConstantConversionUtil.COLLATERAL_TYPE_JQSB)).count();
                                    if (count > 0) {
                                        Dictionary dictionaryNew = new Dictionary();
                                        dictionaryNew.setCode(contractTemplate.getTemplateCode() + "_" + c.getId());
                                        dictionaryNew.setName(contractTemplate.getName().replace("编号", "") + "_" + c.getMortgagorName());
                                        dictionaries.add(dictionaryNew);
                                    }
                                }
                        );
                    }
                }
            }
            if (contractTemplate.getTemplateCode().equals(ConstantConversionUtil.STOCK_RIGHT_CONTRACT_NUMBER_PLEDGOR_COMPANY)) {
                // 股权质押(公司) 触发条件：抵质押信息-质押合同-质押物种类：股权&出质人身份类别：组织机构
                if (CollectionUtil.isNotEmpty(reviewMortgageBasicInfos)) {
                    List<ReviewMortgageBasicInfo> mortgageBasicInfoList = reviewMortgageBasicInfos.stream().filter(c -> c.getGuarType() == 2)
                            .filter(c -> c.getMortgagorIdType().equals(ConstantConversionUtil.IDENTITY_TYPE2)
                                    && CollectionUtil.isNotEmpty(c.getMortgagePledgeInfoList()))
                            .collect(Collectors.toList());
                    if (CollectionUtil.isNotEmpty(mortgageBasicInfoList)) {
                        mortgageBasicInfoList.forEach(c -> {
                            long count = c.getMortgagePledgeInfoList().stream().filter(m -> m.getPleType()
                                    .equals(ConstantConversionUtil.PLEDGE_TYPE_EQUITY)).count();
                            if (count > 0) {
                                Dictionary dictionaryNew = new Dictionary();
                                dictionaryNew.setCode(contractTemplate.getTemplateCode() + "_" + c.getId());
                                dictionaryNew.setName(contractTemplate.getName().replace("编号", "") + "_" + c.getMortgagorName());
                                dictionaries.add(dictionaryNew);
                            }

                        });
                    }
                }
            }

            if (contractTemplate.getTemplateCode().equals(ConstantConversionUtil.STOCK_RIGHT_CONTRACT_NUMBER_PLEDGOR_PERSONAL)) {
                // 股权质押(个人) 触发条件：抵质押信息-质押合同-质押物种类：股权&出质人身份类别：自然人
                if (CollectionUtil.isNotEmpty(reviewMortgageBasicInfos)) {
                    List<ReviewMortgageBasicInfo> mortgageBasicInfoList = reviewMortgageBasicInfos.stream().filter(c -> c.getGuarType() == 2)
                            .filter(c -> c.getMortgagorIdType().equals(ConstantConversionUtil.IDENTITY_TYPE1)
                                    && CollectionUtil.isNotEmpty(c.getMortgagePledgeInfoList()))
                            .collect(Collectors.toList());
                    if (CollectionUtil.isNotEmpty(mortgageBasicInfoList)) {
                        mortgageBasicInfoList.forEach(c -> {
                            long count = c.getMortgagePledgeInfoList().stream().filter(m -> m.getPleType()
                                    .equals(ConstantConversionUtil.PLEDGE_TYPE_EQUITY)).count();
                            if (count > 0) {
                                Dictionary dictionaryNew = new Dictionary();
                                dictionaryNew.setCode(contractTemplate.getTemplateCode() + "_" + c.getId());
                                dictionaryNew.setName(contractTemplate.getName().replace("编号", "") + "_" + c.getMortgagorName());
                                dictionaries.add(dictionaryNew);
                            }
                        });
                    }
                }
            }
        }
        return dictionaries;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ContractInfo editContractInfo(ContractInfo contractInfo) {

        ContractInfo oldContractInfo = contractInfoService.getOne(new QueryWrapper<ContractInfo>()
                .eq("review_quota_disburse_id", contractInfo.getReviewQuotaDisburseId())
                .orderByDesc("id").last("LIMIT 1"));
        if (null == oldContractInfo) {
            throw new BusinessException(CodeUtil.FAIL, "通过额度支用Id获取不到对应的合同信息");
        }

        contractInfo.setAssigneeId(ThreadLocalUtil.getUserId());
        if (contractInfo.getElectronicSign() != null) {
            String electronicSignStr = StringUtils.join(contractInfo.getElectronicSign(), ",");
            contractInfo.setElectronicSignFileCode(electronicSignStr);
        }
        contractInfo.setContractNo(oldContractInfo.getContractNo());
        contractInfo.setReviewQuotaDisburseApprovalId(oldContractInfo.getReviewQuotaDisburseApprovalId());
        contractInfo.setQuotaDisburseBatch(oldContractInfo.getQuotaDisburseBatch());
        contractInfoService.save(contractInfo);

        contractFinancingInfoService.remove(new QueryWrapper<ContractFinancingInfo>().eq("contract_info_id", contractInfo.getId()));
        if (contractInfo.getContractFinancingInfo() != null) {
            ContractFinancingInfo contractFinancingInfo = contractInfo.getContractFinancingInfo();
            contractFinancingInfo.setContractInfoId(contractInfo.getId());
            contractFinancingInfoService.save(contractFinancingInfo);
        }

        contractMasterContractService.remove(new QueryWrapper<ContractMasterContract>().eq("contract_info_id", contractInfo.getId()));
        if (contractInfo.getContractMasterContract() != null) {
            ContractMasterContract contractMasterContract = contractInfo.getContractMasterContract();
            contractMasterContract.setContractInfoId(contractInfo.getId());
            contractMasterContractService.save(contractMasterContract);
        }

        ReviewQuotaDisburse quotaDisburse = reviewQuotaDisburseService.getById(contractInfo.getReviewQuotaDisburseId());
        if (quotaDisburse == null) {
            throw new BusinessException(CodeUtil.FAIL, "获取不到对应额度支用信息");
        }

        //删除三方协议变更内容
        List<ContractBasicContract> oldBasicContractList = contractBasicContractService.list(new QueryWrapper<ContractBasicContract>()
                .eq("contract_info_id", contractInfo.getId()));
        if (CollectionUtil.isNotEmpty(oldBasicContractList)) {
            oldBasicContractList.stream().forEach(contractBasicContract -> {

                contractBasicContractChangeContentService.remove(new QueryWrapper<ContractBasicContractChangeContent>()
                        .eq("contract_info_id", contractInfo.getId())
                        .eq("contract_basic_contract_id", contractBasicContract.getId()));
            });
        }
        //生成新的三方协议变更内容
        List<ContractBasicContract> basicContractList = contractInfo.getContractBasicContractList();
        if (CollectionUtil.isNotEmpty(basicContractList)) {
            for (ContractBasicContract basicContract : basicContractList) {
                basicContract.setContractInfoId(contractInfo.getId());
                contractBasicContractService.updateById(basicContract);
                //保存历史
                ContractBasicContractHis basicContractHis = new ContractBasicContractHis();
                BeanUtils.copyProperties(basicContract, basicContractHis, "id");
                contractBasicContractHisService.save(basicContractHis);
                List<ContractBasicContractChangeContent> list = basicContract.getContractContentList();
                if (null != list && list.size() > 0) {
                    for (ContractBasicContractChangeContent changeContent : list) {
                        changeContent.setContractBasicContractId(basicContract.getId());
                        changeContent.setContractInfoId(contractInfo.getId());
                        contractBasicContractChangeContentService.save(changeContent);
                        //保存历史
                        ContractBasicContractChangeContentHis changeContentHis = new ContractBasicContractChangeContentHis();
                        BeanUtils.copyProperties(changeContent, changeContentHis, "id");
                        changeContentHis.setContractBasicContractHisId(basicContractHis.getId());
                        contractBasicContractChangeContentHisService.save(changeContentHis);
                    }
                }
            }
        }

        contractLoanConditionSettingService.remove(new QueryWrapper<ContractLoanConditionSetting>().eq("contract_info_id", contractInfo.getId()));
        List<ContractLoanConditionSetting> conditionSettingList = contractInfo.getConditionSettingList();
        if (CollectionUtil.isNotEmpty(conditionSettingList)) {
            conditionSettingList.stream().forEach(conditionSetting -> {
                if (conditionSetting.getFixedCondition() != null && conditionSetting.getFixedCondition()) {
                    conditionSetting.setContractInfoId(contractInfo.getId());
                    conditionSetting.setConditionType(ConstantConversionUtil.CONTRACT_LOAN_CONDITION_SETTING_CONDITION);
                }
            });
            contractLoanConditionSettingService.saveBatch(conditionSettingList);

            List<ContractLoanConditionSetting> checkedList = conditionSettingList.stream().filter(conditionSetting -> conditionSetting.getChecked() != null && conditionSetting.getChecked())
                    .collect(Collectors.toList());
            List<ReviewLoanCondition> loanConditionList = contractInfo.getLoanConditionList();
            if (CollectionUtil.isNotEmpty(loanConditionList)) {
                loanConditionList.stream().forEach(reviewLoanCondition -> {
                    contractLoanConditionSettingRelService.remove(new QueryWrapper<ContractLoanConditionSettingRel>().eq("review_loan_condition_id", reviewLoanCondition.getId()));
                    checkedList.stream().forEach(contractLoanConditionSetting -> {
                        ContractLoanConditionSettingRel rel = new ContractLoanConditionSettingRel();
                        rel.setReviewLoanConditionId(reviewLoanCondition.getId());
                        rel.setContractLoanConditionSettingId(contractLoanConditionSetting.getId());
                        contractLoanConditionSettingRelService.save(rel);
                    });
                });
            }
        }

        List<UploadContractInfo> oldUploadContractInfoList = uploadContractInfoService.list(new QueryWrapper<UploadContractInfo>()
                .eq("contract_info_id", contractInfo.getId()));
        if (CollectionUtil.isNotEmpty(oldUploadContractInfoList)) {
            for (UploadContractInfo uploadContractInfo : oldUploadContractInfoList) {
                List<UploadContractSignatory> signatoryList = uploadContractSignatoryService.list(new QueryWrapper<UploadContractSignatory>().eq("upload_contract_info_Id", uploadContractInfo.getId()));
                if (CollectionUtil.isNotEmpty(signatoryList)) {
                    List<Long> signatoryIds = signatoryList.stream().map(UploadContractSignatory::getId).collect(Collectors.toList());
                    uploadContractSignatoryService.removeByIds(signatoryIds);
                }
                uploadContractInfoService.removeById(uploadContractInfo.getId());
            }
        }
        List<UploadContractInfo> uploadContractInfoList = contractInfo.getUploadContractInfoList();
        if (CollectionUtil.isNotEmpty(uploadContractInfoList)) {
            for (UploadContractInfo uploadContractInfo : uploadContractInfoList) {
                uploadContractInfo.setContractInfoId(contractInfo.getId());
                uploadContractInfoService.save(uploadContractInfo);
                List<UploadContractSignatory> signatoryList = uploadContractInfo.getUploadContractSignatories();
                if (CollectionUtil.isNotEmpty(signatoryList)) {
                    for (UploadContractSignatory signatory : signatoryList) {
                        signatory.setUploadContractInfoId(uploadContractInfo.getId());
                        uploadContractSignatoryService.save(signatory);
                    }
                }
            }
        }

        if (contractInfo.getVisible()) {
            Map<String, Object> procVariables = new HashMap<>();
            String key = ConstantUtil.FINANCING_APPLY;
            CFinancingBasicInfo financingBasicInfo = financingBasicInfoService.getById(quotaDisburse.getFinancingBasicInfoId());
            Long assigneeId = assigneeService.getIdByBusiness(financingBasicInfo.getId(), key, ConstantUtil.ASSIGNEE_C_SUPPLIER);
            if (contractInfo.getConclusion().equals(ConstantConversionUtil.APPROVAL_RESULT_PASS)) {
                //修改融资申请当前阶段
                financingBasicInfo.setCurrentStage(FinancingCurrentStageEnum.CONTRACT_SIGNING.getCode());
                financingBasicInfoService.updateById(financingBasicInfo);

                procVariables.put(ConstantUtil.CONTRACT_SIGNING_ASSIGNEE, assigneeId);
                if (contractInfo.getContractSignMethod().equals(1)) {
                    List<String> electronicSigns = contractInfo.getElectronicSign();
                    if (electronicSigns != null && electronicSigns.size() > 0) {
                        //制作电子签合同
                        makeElectronicFile(contractInfo, electronicSigns);
                    }
                    //处理上传的合同
                    if (CollectionUtil.isNotEmpty(contractInfo.getUploadContractInfoList())) {
                        doUploadContract(contractInfo);
                    }
                }
            } else if (contractInfo.getConclusion().equals(ConstantConversionUtil.APPROVAL_RESULT_BACK)) {
                //修改融资申请当前阶段
                financingBasicInfo.setCurrentStage(FinancingCurrentStageEnum.REVIEW_QUOTA_DISBURSE.getCode());
                financingBasicInfoService.updateById(financingBasicInfo);
            }
            Map<String, Object> msgVariables = new HashMap<>(2);
            msgVariables.put(ConstantUtil.FLOWABLE_MSG_TITLE, financingBasicInfo.getBusinessNumber());
            msgVariables.put(ConstantUtil.FLOWABLE_MSG_CONTENT,
                    "业务编号为“" + financingBasicInfo.getBusinessNumber() + "”的项目已inOut“"
                            + ConstantConversionUtil.flowBusinessKeyNames.get(key) + "—formBusiness”阶段，");
            String conclusion = ConstantConversionUtil.processApprovalResult.get(contractInfo.getConclusion()).equals("驳回") ?
                    "退回" : ConstantConversionUtil.processApprovalResult.get(contractInfo.getConclusion());
            Boolean result = flowableService.completeMyTask(contractInfo.getTaskId(), financingBasicInfo, procVariables,
                    conclusion, contractInfo.getId(), msgVariables, key);
            if (result == null || !result) {
                throw new ValidatorException(CodeUtil.FAIL, "合同制作提交时出错啦！");
            }
        }

        return contractInfo;
    }

    /**
     * 新增三方协议
     *
     * @param contractBasicContract
     * @return
     */
    public ContractBasicContract addContractBasicContract(ContractBasicContract contractBasicContract) {
        contractBasicContractService.save(contractBasicContract);
        List<ContractBasicContractChangeContent> list = contractBasicContract.getContractContentList();
        if (null != list && list.size() > 0) {
            for (ContractBasicContractChangeContent changeContent : list) {
                changeContent.setContractBasicContractId(contractBasicContract.getId());
                changeContent.setContractInfoId(contractBasicContract.getContractInfoId());
                contractBasicContractChangeContentService.save(changeContent);
            }
        }
        return contractBasicContract;
    }

    @Override
    public ContractInfo getView(Long id) {
        ContractInfo contractInfo = contractInfoService.getById(id);
        if (null == contractInfo) {
            throw new BusinessException(CodeUtil.FAIL, "获取不到对应的合同信息");
        }
        //新增融资信息
        addContractFinancing(contractInfo);
        //新增主合同信息
        addMasterContract(contractInfo);
        // 新增收支计划信息
        addReviewLoanCondition(contractInfo);
        // 新增放款条件设定
        addFixedLoanConditionSettingList(contractInfo);
        // 新增基础交易合同信息
        addBasicContractList(contractInfo);
        //填充上传合同中可签署方
        autoUploadContract(contractInfo);
        //填充电子签模板集合
        autoElectronicSign(contractInfo);
        return contractInfo;
    }

    /**
     * 制作电子签文件
     *
     * @param contractInfo
     * @param electronicSigns
     */
    private void makeElectronicFile(ContractInfo contractInfo, List<String> electronicSigns) {
        String autoSignKeyword = "cyqz";
        for (String electronicSign : electronicSigns) {
            String[] split = electronicSign.split("_");
            String type = split[0];
            Long id = null;
            if (split.length == 2) {
                id = Long.parseLong(split[1]);
            }
            ContractTemplate contractTemplate = contractTemplateService.lambdaQuery().eq(ContractTemplate::getTemplateCode, type).eq(ContractTemplate::getVisible, 1).one();
            String templateName = contractTemplate.getName();

            List<File> list = new ArrayList<>();
            newContractMakingService.createContractDocument(type, id, contractInfo, list);
            List<ContractElectronicCustomerInfo> contractElectronicCustomerInfos = new ArrayList<>();
            //国际的不需要电子签  国内的才电子签
            TAXSignCustomer(electronicSign, contractElectronicCustomerInfos, contractInfo);
            //常规担保函  配偶声明 池保理应收账款转让通知书- 财产清单（个人）不需要长银签章
            if (type.equals(ConstantConversionUtil.GENERAL_GUARANTEE_COMPANY) || type.equals(ConstantConversionUtil.SPOUSE_STATEMENT_GUARANTEE_SPOUSE) ||
                    type.equals(ConstantConversionUtil.GENERAL_GUARANTEE_PERSONAL)
                    || type.equals(ConstantConversionUtil.FACTORING_CONTRACT_NUMBER_GUARANTEE_COMPANY) ||
                    type.equals(ConstantConversionUtil.FACTORING_CONTRACT_NUMBER_GUARANTEE_PERSON) ||
                    type.equals(ConstantConversionUtil.GENERAL_GUARANTEE_COMPANY_M2) || type.equals(ConstantConversionUtil.GENERAL_GUARANTEE_PERSONAL_M2)) {
                doNotAutoSign(contractInfo, templateName, contractElectronicCustomerInfos, list.get(0));
            } else {
                doAutoSign(contractInfo, autoSignKeyword, templateName, contractElectronicCustomerInfos, list.get(0));
            }
        }
    }

    private void doNotAutoSign(ContractInfo contractInfo, String templateName, List<ContractElectronicCustomerInfo> contractElectronicCustomerInfos, File file) {
        //保存上传的PDF合同
        String suffix = FileUtil.getSuffix(file.getName());
        String newPath = file.getAbsolutePath().replace(suffix, ".pdf");
        File pdfFile = OfficeConverterUtil.office2Pdf(file.getAbsolutePath(), newPath);
        String originalName = pdfFile.getName();
        FileStorage fileStorage = new FileStorage(originalName, pdfFile.getAbsolutePath(),
                FileModuleDict.ChildEnum.ELECTRONIC_FILE);
        fileStorageService.add(fileStorage);
        ContractElectronicInfo contractElectronicInfo = new ContractElectronicInfo();
        contractElectronicInfo.setFileId(fileStorage.getId());
        contractElectronicInfo.setContractInfoId(contractInfo.getId());
        contractElectronicInfo.setContractName(templateName);
        //上传合同
        String contractId = UUID.randomUUID().toString().trim().replaceAll("-", "").toUpperCase();
        contractElectronicInfo.setContractId(contractId);
//        ContractInfo contractInfo = contractInfoService.get(contractMaking.getContractInfo().getId());
        String docTitle = "合同制作：" + templateName;
        ElectronicSignatureUtil.uploadContract(contractId, docTitle, pdfFile);
        contractElectronicInfoService.save(contractElectronicInfo);
        for (ContractElectronicCustomerInfo contractElectronicCustomerInfo : contractElectronicCustomerInfos) {
            contractElectronicCustomerInfo.setContractElectronicInfoId(contractElectronicInfo.getId());
            contractElectronicCustomerInfoService.save(contractElectronicCustomerInfo);
        }
    }

    /**
     * 新增基础交易合同信息
     */
    private void addBasicContractList(ContractInfo contractInfo) {
        List<ContractBasicContract> contractBasicContractList = new ArrayList<>();
        if (null != contractInfo && null != contractInfo.getId()) {
            List<ContractBasicContract> list = contractBasicContractService.list(new QueryWrapper<ContractBasicContract>()
                    .eq("contract_info_id", contractInfo.getId()));
            if (CollectionUtil.isNotEmpty(list)) {
                contractBasicContractList = list;
                for (ContractBasicContract contractBasicContract : list) {
                    List<ContractBasicContractChangeContent> contractBasicContractChangeContentList = contractBasicContractChangeContentService.list(new QueryWrapper<ContractBasicContractChangeContent>()
                            .eq("contract_basic_contract_id", contractBasicContract.getId()));
                    contractBasicContract.setContractContentList(contractBasicContractChangeContentList);
                }
            } else {
                List<ReviewBasicContract> reviewBasicContractList = reviewBasicContractService.list(new QueryWrapper<ReviewBasicContract>()
                        .eq("review_quota_disburse_id", contractInfo.getReviewQuotaDisburseId()));
                if (CollectionUtil.isNotEmpty(reviewBasicContractList)) {
                    for (ReviewBasicContract reviewBasicContract : reviewBasicContractList) {
                        ContractBasicContract contractBasicContract = new ContractBasicContract(reviewBasicContract);
                        if (contractInfo.getId() != null) {
                            contractBasicContract.setContractInfoId(contractInfo.getId());
                        }
                        List<ReviewBasicContractChangeContent> changeContentList = reviewBasicContractChangeContentService.list(new QueryWrapper<ReviewBasicContractChangeContent>()
                                .eq("review_basic_contract_id", reviewBasicContract.getId()));
                        if (CollectionUtil.isNotEmpty(changeContentList)) {
                            List<ContractBasicContractChangeContent> contractChangeContentList = changeContentList.stream().map(reviewBasicContractChangeContent -> new ContractBasicContractChangeContent(reviewBasicContractChangeContent))
                                    .collect(Collectors.toList());
                            contractBasicContract.setContractContentList(contractChangeContentList);
                        }
                        contractBasicContractList.add(contractBasicContract);
                    }
                }
            }
        }
        contractInfo.setContractBasicContractList(contractBasicContractList);
    }

    /**
     * 新增融资信息
     *
     * @param contractInfo
     */
    private void addContractFinancing(ContractInfo contractInfo) {
        if (contractInfo != null) {
            ContractFinancingInfo contractFinancingInfo = contractFinancingInfoService.getOne(new QueryWrapper<ContractFinancingInfo>()
                    .eq("contract_info_id", contractInfo.getId()));
            if (contractFinancingInfo != null) {
                contractInfo.setContractFinancingInfo(contractFinancingInfo);
            }
        }
    }

    /**
     * 新增主合同信息
     *
     * @param contractInfo
     */
    private void addMasterContract(ContractInfo contractInfo) {
        if (contractInfo != null) {
            ContractMasterContract contractMasterContract = contractMasterContractService.getOne(new QueryWrapper<ContractMasterContract>()
                    .eq("contract_info_id", contractInfo.getId()));
            if (contractMasterContract != null) {
                contractInfo.setContractMasterContract(contractMasterContract);
            }
        }
    }

    /**
     * 填充上传的合同文件
     *
     * @param contractInfo
     */
    private void autoUploadContract(ContractInfo contractInfo) {
        if (contractInfo != null) {
            List<UploadContractInfo> uploadContractInfoList = uploadContractInfoService.list(new QueryWrapper<UploadContractInfo>()
                    .eq("contract_info_id", contractInfo.getId()));
            if (CollectionUtil.isNotEmpty(uploadContractInfoList)) {
                for (UploadContractInfo uploadContractInfo : uploadContractInfoList) {
                    List<UploadContractSignatory> signatoryList = uploadContractSignatoryService.list(new QueryWrapper<UploadContractSignatory>()
                            .eq("upload_contract_info_Id", uploadContractInfo.getId()));
                    if (CollectionUtil.isNotEmpty(signatoryList)) {
                        List<String> signatoryNameList = signatoryList.stream().map(UploadContractSignatory::getName).collect(Collectors.toList());
                        uploadContractInfo.setUploadContractSignatories(signatoryList);
                        uploadContractInfo.setSignatoryNameList(signatoryNameList);
                    }
                    if (uploadContractInfo.getFileStorageId() != null) {
                        FileStorage fileStorage = fileStorageService.get(uploadContractInfo.getFileStorageId());
                        uploadContractInfo.setFileStorage(fileStorage);
                    }

                }
            }
            contractInfo.setUploadContractInfoList(uploadContractInfoList);
        }
    }

    /**
     * 新增电子签模板code
     *
     * @param contractInfo
     */
    private void autoElectronicSign(ContractInfo contractInfo) {
        List<String> electronicSignList = new ArrayList<>();
        if (contractInfo != null && StringUtils.isNotEmpty(contractInfo.getElectronicSignFileCode())) {
            String electronicSignFileCode = contractInfo.getElectronicSignFileCode();
            electronicSignList = Arrays.asList(electronicSignFileCode.split(","));
        }
        contractInfo.setElectronicSign(electronicSignList);
    }

    /**
     * 新增放款条件
     *
     * @param contractInfo
     */
    private void addReviewLoanCondition(ContractInfo contractInfo) {
        if (contractInfo != null && contractInfo.getReviewQuotaDisburseId() != null) {
            List<ReviewIncomeExpenditurePlan> incomeExpenditurePlans = reviewIncomeExpenditurePlanService.list(new QueryWrapper<ReviewIncomeExpenditurePlan>()
                    .eq("review_quota_disburse_id", contractInfo.getReviewQuotaDisburseId()));

            List<ReviewLoanCondition> loanConditionList = new ArrayList<>();
            if (CollectionUtil.isNotEmpty(incomeExpenditurePlans)) {
                for (ReviewIncomeExpenditurePlan reviewIncomeExpenditurePlan : incomeExpenditurePlans) {
                    // 新增合同放款条件
                    if (null != reviewIncomeExpenditurePlan) {
                        // 根据额度支用收支计划查询对应额度支用审批中的放款条件
                        ReviewLoanCondition reviewLoanCondition = reviewLoanConditionService.getOne(new QueryWrapper<ReviewLoanCondition>()
                                .eq("income_expenditure_plan_id", reviewIncomeExpenditurePlan.getId()));
                        if (null != reviewLoanCondition) {
                            loanConditionList.add(reviewLoanCondition);
                        }
                    }
                }
            }
            contractInfo.setLoanConditionList(loanConditionList);
        }
    }

    /**
     * 新增放款条件（单笔指导性单笔业务满足条件、评审会放款条件、放款条件设定-固定条件）
     */
    private void addFixedLoanConditionSettingList(ContractInfo contractInfo) {

        List<ContractLoanConditionSetting> contractlist = new ArrayList<>();
        if (contractInfo != null && contractInfo.getId() != null) {
            // 放款条件设定-条件
            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) {
                contractlist = loanConditionSetList;
            } else {
                //贸理通默认为国内+池保理
                String conditionType = ConstantConversionUtil.DOMESTIC_POOL;
                // 新增条件设定中-固定提款条件
                int index = 0;
                List<String> list = reviewFixedWithdrawalConditionService.findByConditionType(conditionType);
                if (null != list && list.size() > 0) {
                    for (String str : list) {
                        index++;
                        ContractLoanConditionSetting contractLoanConditionSetting = new ContractLoanConditionSetting();
                        contractLoanConditionSetting.setLoanCondition(str);
                        contractLoanConditionSetting.setOrderNumber(index);
                        contractLoanConditionSetting.setFixedCondition(true);
                        contractLoanConditionSetting.setChecked(true);
                        contractLoanConditionSetting.setConditionType(ConstantConversionUtil.CONTRACT_LOAN_CONDITION_SETTING_CONDITION);
                        if (contractInfo.getId() != null) {
                            contractLoanConditionSetting.setContractInfoId(contractInfo.getId());
                        }
                        contractlist.add(contractLoanConditionSetting);
                    }
                }
            }
        }
        contractInfo.setConditionSettingList(contractlist);
    }

    private void TAXSignCustomer(String templateCode, List<ContractElectronicCustomerInfo> contractElectronicCustomerInfos, ContractInfo contractInfo) {
        String[] strs = templateCode.split("_");
        Long id = null;
        templateCode = strs[0];
        if (strs.length == 2) {
            id = Long.parseLong(strs[1]);
        }
        ReviewQuotaDisburse reviewQuotaDisburse = reviewQuotaDisburseService.getById(contractInfo.getReviewQuotaDisburseId());
        // 主合同信息
        ReviewMasterContract masterContract = reviewMasterContractService.getOne(new QueryWrapper<ReviewMasterContract>()
                .eq("review_quota_disburse_id", reviewQuotaDisburse.getId()));

        if (templateCode.equals(ConstantConversionUtil.MAXIMUM_GUARANTEE_CULVER_COMPANY)
                || templateCode.equals(ConstantConversionUtil.MAXIMUM_GUARANTEE_CULVER_COMPANY_M2)) {
            //最高额担保函公司
            ReviewRltRepay rltRepay = reviewRltRepayService.getById(id);
            if (rltRepay.getArlpCertNum() != null && !rltRepay.getArlpCertNum().equals("")) {
                Enterprise enterprise = enterpriseService.getOne(new QueryWrapper<Enterprise>().eq("social_credit_code", rltRepay.getArlpCertNum()));
                SysCustomer sysCustomer = sysCustomerService.getCustomerIdBySocialCreditCode(rltRepay.getArlpCertNum());
                if (sysCustomer != null && sysCustomer.getFddCustomerId() != null) {
                    ContractElectronicCustomerInfo contractElectronicCustomerInfo = new ContractElectronicCustomerInfo("yf", sysCustomer.getFddCustomerId());
                    contractElectronicCustomerInfo.setSysCustomerId(sysCustomer.getId());
                    contractElectronicCustomerInfos.add(contractElectronicCustomerInfo);
                } else {
                    SysCustomer customer = new SysCustomer();
                    customer.setAccountType("2");
                    customer.setEntBusinessId(enterprise.getId());
                    sysCustomerService.add(customer);
                    ContractElectronicCustomerInfo contractElectronicCustomerInfo = new ContractElectronicCustomerInfo("yf", customer.getFddCustomerId());
                    contractElectronicCustomerInfo.setSysCustomerId(customer.getId());
                    contractElectronicCustomerInfos.add(contractElectronicCustomerInfo);
                }
            }
        } else if (templateCode.equals(ConstantConversionUtil.MAXIMUM_GUARANTEE_CULVER_PERSONAL)
                || templateCode.equals(ConstantConversionUtil.MAXIMUM_GUARANTEE_CULVER_PERSONAL_M2)) {
            //最高额担保函个人
            ReviewRltRepay rltRepay = reviewRltRepayService.getById(id);
            ElectronicSignaturePersonal electronicSignaturePersonal = electronicSignaturePersonalService.getOne(new QueryWrapper<ElectronicSignaturePersonal>()
                    .eq("socialCreditCode", rltRepay.getArlpCertNum()));
            SysCustomer sysCustomer = null;
            if (electronicSignaturePersonal != null) {
                sysCustomer = sysCustomerService.getCustomerPersonBySocialCreditCode(rltRepay.getArlpCertNum());
                electronicSignaturePersonal.setName(rltRepay.getArlpName());
                electronicSignaturePersonal.setSocialCreditCode(rltRepay.getArlpCertNum());
                electronicSignaturePersonal.setCardType("idCard");
                electronicSignaturePersonal.setMobile(rltRepay.getResponsiblePhone());
                sysCustomer.setElectronicSignaturePersonal(electronicSignaturePersonal);
                electronicSignaturePersonalService.updateById(electronicSignaturePersonal);
            }
            if (sysCustomer != null && sysCustomer.getFddCustomerId() != null) {
                ContractElectronicCustomerInfo contractElectronicCustomerInfo = new ContractElectronicCustomerInfo("yf", sysCustomer.getFddCustomerId());
                contractElectronicCustomerInfo.setSysCustomerId(sysCustomer.getId());
                contractElectronicCustomerInfos.add(contractElectronicCustomerInfo);
            } else {
                SysCustomer customer = new SysCustomer();
                if (electronicSignaturePersonal == null) {
                    electronicSignaturePersonal = new ElectronicSignaturePersonal();
                    electronicSignaturePersonal.setName(rltRepay.getArlpName());
                    electronicSignaturePersonal.setSocialCreditCode(rltRepay.getArlpCertNum());
                    electronicSignaturePersonal.setCardType("idCard");
                    electronicSignaturePersonal.setMobile(rltRepay.getResponsiblePhone());
                    customer.setElectronicSignaturePersonal(electronicSignaturePersonal);
                }
                customer.setAccountType("1");
                sysCustomerService.add(customer);
                ContractElectronicCustomerInfo contractElectronicCustomerInfo = new ContractElectronicCustomerInfo("yf", customer.getFddCustomerId());
                contractElectronicCustomerInfo.setSysCustomerId(customer.getId());
                contractElectronicCustomerInfos.add(contractElectronicCustomerInfo);
            }
        } else if (templateCode.equals(ConstantConversionUtil.GENERAL_GUARANTEE_COMPANY)
                || templateCode.equals(ConstantConversionUtil.GENERAL_GUARANTEE_COMPANY_M2)) {
            //常规担保函公司
            ReviewRltRepay rltRepay = reviewRltRepayService.getById(id);
            if (rltRepay.getArlpCertNum() != null && !rltRepay.getArlpCertNum().equals("")) {
                Enterprise enterprise = enterpriseService.getOne(new QueryWrapper<Enterprise>().eq("social_credit_code", rltRepay.getArlpCertNum()));
                SysCustomer sysCustomer = sysCustomerService.getCustomerIdBySocialCreditCode(rltRepay.getArlpCertNum());
                if (sysCustomer != null && sysCustomer.getFddCustomerId() != null) {
                    ContractElectronicCustomerInfo contractElectronicCustomerInfo = new ContractElectronicCustomerInfo("gut", sysCustomer.getFddCustomerId());
                    contractElectronicCustomerInfo.setSysCustomerId(sysCustomer.getId());
                    contractElectronicCustomerInfos.add(contractElectronicCustomerInfo);
                } else {
                    SysCustomer customer = new SysCustomer();
                    customer.setAccountType("2");
                    customer.setEntBusinessId(enterprise.getId());
                    sysCustomerService.add(customer);
                    ContractElectronicCustomerInfo contractElectronicCustomerInfo = new ContractElectronicCustomerInfo("gut", customer.getFddCustomerId());
                    contractElectronicCustomerInfo.setSysCustomerId(customer.getId());
                    contractElectronicCustomerInfos.add(contractElectronicCustomerInfo);
                }
            }
        } else if (templateCode.equals(ConstantConversionUtil.GENERAL_GUARANTEE_PERSONAL)
                || templateCode.equals(ConstantConversionUtil.GENERAL_GUARANTEE_PERSONAL_M2)) {
            //常规担保函个人
            ReviewRltRepay rltRepay = reviewRltRepayService.getById(id);
            ElectronicSignaturePersonal electronicSignaturePersonal = electronicSignaturePersonalService.getOne(new QueryWrapper<ElectronicSignaturePersonal>()
                    .eq("socialCreditCode", rltRepay.getArlpCertNum()));
            SysCustomer sysCustomer = null;
            if (electronicSignaturePersonal != null) {
                sysCustomer = sysCustomerService.getCustomerPersonBySocialCreditCode(rltRepay.getArlpCertNum());
                electronicSignaturePersonal.setName(rltRepay.getArlpName());
                electronicSignaturePersonal.setSocialCreditCode(rltRepay.getArlpCertNum());
                electronicSignaturePersonal.setCardType("idCard");
                electronicSignaturePersonal.setMobile(rltRepay.getResponsiblePhone());
                sysCustomer.setElectronicSignaturePersonal(electronicSignaturePersonal);
                electronicSignaturePersonalService.updateById(electronicSignaturePersonal);
            }
            if (sysCustomer != null && sysCustomer.getFddCustomerId() != null) {
                ContractElectronicCustomerInfo contractElectronicCustomerInfo = new ContractElectronicCustomerInfo("gut", sysCustomer.getFddCustomerId());
                contractElectronicCustomerInfo.setSysCustomerId(sysCustomer.getId());
                contractElectronicCustomerInfos.add(contractElectronicCustomerInfo);
            } else {
                SysCustomer customer = new SysCustomer();
                if (electronicSignaturePersonal == null) {
                    electronicSignaturePersonal = new ElectronicSignaturePersonal();
                    electronicSignaturePersonal.setName(rltRepay.getArlpName());
                    electronicSignaturePersonal.setSocialCreditCode(rltRepay.getArlpCertNum());
                    electronicSignaturePersonal.setCardType("idCard");
                    electronicSignaturePersonal.setMobile(rltRepay.getResponsiblePhone());
                    customer.setElectronicSignaturePersonal(electronicSignaturePersonal);
                }
                customer.setAccountType("1");
                sysCustomerService.add(customer);
                ContractElectronicCustomerInfo contractElectronicCustomerInfo = new ContractElectronicCustomerInfo("gut", customer.getFddCustomerId());
                contractElectronicCustomerInfo.setSysCustomerId(customer.getId());
                contractElectronicCustomerInfos.add(contractElectronicCustomerInfo);
            }
        } else if (templateCode.equals(ConstantConversionUtil.SPOUSE_STATEMENT_GUARANTEE_SPOUSE)) {
            //配偶声明
            ReviewRltRepay rltRepay = reviewRltRepayService.getById(id);
            //电子签个人有无配偶信息
            ElectronicSignaturePersonal electronicSignaturePersonal = electronicSignaturePersonalService.getOne(new QueryWrapper<ElectronicSignaturePersonal>()
                    .eq("socialCreditCode", rltRepay.getSpouseIdCard()));
            SysCustomer sysCustomer = null;
            if (electronicSignaturePersonal != null) {
                sysCustomer = sysCustomerService.getCustomerPersonBySocialCreditCode(rltRepay.getSpouseIdCard());
                electronicSignaturePersonal.setName(rltRepay.getSpouseName());
                electronicSignaturePersonal.setSocialCreditCode(rltRepay.getSpouseIdCard());
                electronicSignaturePersonal.setCardType("idCard");
                electronicSignaturePersonal.setMobile(rltRepay.getResponsiblePhone());
                sysCustomer.setElectronicSignaturePersonal(electronicSignaturePersonal);
                electronicSignaturePersonalService.updateById(electronicSignaturePersonal);
            }
            if (sysCustomer != null && sysCustomer.getFddCustomerId() != null) {
                ContractElectronicCustomerInfo contractElectronicCustomerInfo = new ContractElectronicCustomerInfo("gut", sysCustomer.getFddCustomerId());
                contractElectronicCustomerInfo.setSysCustomerId(sysCustomer.getId());
                contractElectronicCustomerInfos.add(contractElectronicCustomerInfo);
            } else {
                SysCustomer customer = new SysCustomer();
                if (electronicSignaturePersonal == null) {
                    electronicSignaturePersonal = new ElectronicSignaturePersonal();
                    electronicSignaturePersonal.setName(rltRepay.getSpouseName());
                    electronicSignaturePersonal.setSocialCreditCode(rltRepay.getSpouseIdCard());
                    electronicSignaturePersonal.setCardType("idCard");

                    electronicSignaturePersonal.setMobile(rltRepay.getResponsiblePhone());
                    customer.setElectronicSignaturePersonal(electronicSignaturePersonal);
                }
                customer.setAccountType("1");
                sysCustomerService.add(customer);
                ContractElectronicCustomerInfo contractElectronicCustomerInfo = new ContractElectronicCustomerInfo("gut", customer.getFddCustomerId());
                contractElectronicCustomerInfo.setSysCustomerId(customer.getId());
                contractElectronicCustomerInfos.add(contractElectronicCustomerInfo);
            }
        } else if (templateCode.equals(ConstantConversionUtil.FACTORING_CONTRACT_NUMBER_GUARANTEE_COMPANY)) {
            //保理合同 公司(财产清单)
            ReviewRltRepay rltRepay = reviewRltRepayService.getById(id);
            if (rltRepay.getArlpCertNum() != null) {
                Enterprise enterprise = enterpriseService.getOne(new QueryWrapper<Enterprise>().eq("social_credit_code", rltRepay.getArlpCertNum()));
                SysCustomer sysCustomer = sysCustomerService.getCustomerIdBySocialCreditCode(rltRepay.getArlpCertNum());
                if (sysCustomer != null && sysCustomer.getFddCustomerId() != null) {
                    ContractElectronicCustomerInfo contractElectronicCustomerInfo = new ContractElectronicCustomerInfo("gut", sysCustomer.getFddCustomerId());
                    contractElectronicCustomerInfo.setSysCustomerId(sysCustomer.getId());
                    contractElectronicCustomerInfos.add(contractElectronicCustomerInfo);
                } else {
                    SysCustomer customer = new SysCustomer();
                    customer.setAccountType("2");
                    customer.setEntBusinessId(enterprise.getId());
                    sysCustomerService.add(customer);
                    ContractElectronicCustomerInfo contractElectronicCustomerInfo = new ContractElectronicCustomerInfo("gut", customer.getFddCustomerId());
                    contractElectronicCustomerInfo.setSysCustomerId(customer.getId());
                    contractElectronicCustomerInfos.add(contractElectronicCustomerInfo);
                }
            }
        } else if (templateCode.equals(ConstantConversionUtil.FACTORING_CONTRACT_NUMBER_GUARANTEE_PERSON)) {
            //保理合同 个人(财产清单)
            ReviewRltRepay rltRepay = reviewRltRepayService.getById(id);
            ElectronicSignaturePersonal electronicSignaturePersonal = electronicSignaturePersonalService.getOne(new QueryWrapper<ElectronicSignaturePersonal>()
                    .eq("socialCreditCode", rltRepay.getArlpCertNum()));
            SysCustomer sysCustomer = null;
            if (electronicSignaturePersonal != null) {
                sysCustomer = sysCustomerService.getCustomerPersonBySocialCreditCode(rltRepay.getArlpCertNum());
                electronicSignaturePersonal.setName(rltRepay.getArlpName());
                electronicSignaturePersonal.setSocialCreditCode(rltRepay.getArlpCertNum());
                electronicSignaturePersonal.setCardType("idCard");
                electronicSignaturePersonal.setMobile(rltRepay.getResponsiblePhone());
                sysCustomer.setElectronicSignaturePersonal(electronicSignaturePersonal);
                electronicSignaturePersonalService.updateById(electronicSignaturePersonal);
            }
            if (sysCustomer != null && sysCustomer.getFddCustomerId() != null) {
                ContractElectronicCustomerInfo contractElectronicCustomerInfo = new ContractElectronicCustomerInfo("gut", sysCustomer.getFddCustomerId());
                contractElectronicCustomerInfo.setSysCustomerId(sysCustomer.getId());
                contractElectronicCustomerInfos.add(contractElectronicCustomerInfo);
            } else {
                SysCustomer customer = new SysCustomer();
                if (electronicSignaturePersonal == null) {
                    electronicSignaturePersonal = new ElectronicSignaturePersonal();
                    electronicSignaturePersonal.setName(rltRepay.getArlpName());
                    electronicSignaturePersonal.setSocialCreditCode(rltRepay.getArlpCertNum());
                    electronicSignaturePersonal.setCardType("idCard");
                    electronicSignaturePersonal.setMobile(rltRepay.getResponsiblePhone());
                    customer.setElectronicSignaturePersonal(electronicSignaturePersonal);
                }
                customer.setAccountType("1");
                sysCustomerService.add(customer);
                ContractElectronicCustomerInfo contractElectronicCustomerInfo = new ContractElectronicCustomerInfo("gut", customer.getFddCustomerId());
                contractElectronicCustomerInfo.setSysCustomerId(customer.getId());
                contractElectronicCustomerInfos.add(contractElectronicCustomerInfo);
            }
        } else if (templateCode.equals(ConstantConversionUtil.MOVABLE_MORTGAGE_CONTRACT_NUMBER_GUARANTEE_COMPANY)) {
            //动产抵押合同 公司
            ReviewMortgageBasicInfo chattelMortgage = reviewMortgageBasicInfoService.getById(id);
            if (chattelMortgage.getMortgagorCertNum() != null && !chattelMortgage.getMortgagorCertNum().equals("")) {
                Enterprise enterprise = enterpriseService.getOne(new QueryWrapper<Enterprise>().eq("social_credit_code", chattelMortgage.getMortgagorCertNum()));
                SysCustomer sysCustomer = sysCustomerService.getCustomerIdBySocialCreditCode(chattelMortgage.getMortgagorCertNum());
                if (sysCustomer != null && sysCustomer.getFddCustomerId() != null) {
                    ContractElectronicCustomerInfo contractElectronicCustomerInfo = new ContractElectronicCustomerInfo("mtg", sysCustomer.getFddCustomerId());
                    contractElectronicCustomerInfo.setSysCustomerId(sysCustomer.getId());
                    contractElectronicCustomerInfos.add(contractElectronicCustomerInfo);
                } else {
                    SysCustomer customer = new SysCustomer();
                    customer.setAccountType("2");
                    customer.setEntBusinessId(enterprise.getId());
                    sysCustomerService.add(customer);
                    ContractElectronicCustomerInfo contractElectronicCustomerInfo = new ContractElectronicCustomerInfo("mtg", customer.getFddCustomerId());
                    contractElectronicCustomerInfo.setSysCustomerId(customer.getId());
                    contractElectronicCustomerInfos.add(contractElectronicCustomerInfo);
                }
            }
        } else if (templateCode.equals(ConstantConversionUtil.MOVABLE_MORTGAGE_CONTRACT_NUMBER_GUARANTEE_PERSONAL)) {
            //动产抵押合同 个人
            ReviewMortgageBasicInfo chattelMortgage = reviewMortgageBasicInfoService.getById(id);
            ElectronicSignaturePersonal electronicSignaturePersonal = electronicSignaturePersonalService.getOne(new QueryWrapper<ElectronicSignaturePersonal>()
                    .eq("socialCreditCode", chattelMortgage.getMortgagorCertNum()));
            SysCustomer sysCustomer = null;
            if (electronicSignaturePersonal != null) {
                sysCustomer = sysCustomerService.getCustomerPersonBySocialCreditCode(chattelMortgage.getMortgagorCertNum());
                electronicSignaturePersonal.setName(chattelMortgage.getMortgagorName());
                electronicSignaturePersonal.setSocialCreditCode(chattelMortgage.getMortgagorCertNum());
                electronicSignaturePersonal.setCardType("idCard");
                electronicSignaturePersonal.setMobile(chattelMortgage.getContactNumber());
                sysCustomer.setElectronicSignaturePersonal(electronicSignaturePersonal);
                electronicSignaturePersonalService.updateById(electronicSignaturePersonal);
            }
            if (sysCustomer != null && sysCustomer.getFddCustomerId() != null) {
                ContractElectronicCustomerInfo contractElectronicCustomerInfo = new ContractElectronicCustomerInfo("mtg", sysCustomer.getFddCustomerId());
                contractElectronicCustomerInfo.setSysCustomerId(sysCustomer.getId());
                contractElectronicCustomerInfos.add(contractElectronicCustomerInfo);
            } else {
                SysCustomer customer = new SysCustomer();
                if (electronicSignaturePersonal == null) {
                    electronicSignaturePersonal = new ElectronicSignaturePersonal();
                    electronicSignaturePersonal.setName(chattelMortgage.getMortgagorName());
                    electronicSignaturePersonal.setSocialCreditCode(chattelMortgage.getMortgagorCertNum());
                    electronicSignaturePersonal.setCardType("idCard");
                    electronicSignaturePersonal.setMobile(chattelMortgage.getContactNumber());
                    customer.setElectronicSignaturePersonal(electronicSignaturePersonal);
                }
                customer.setAccountType("1");
                sysCustomerService.add(customer);
                ContractElectronicCustomerInfo contractElectronicCustomerInfo = new ContractElectronicCustomerInfo("mtg", customer.getFddCustomerId());
                contractElectronicCustomerInfo.setSysCustomerId(customer.getId());
                contractElectronicCustomerInfos.add(contractElectronicCustomerInfo);
            }
        } else if (templateCode.equals(ConstantConversionUtil.STOCK_RIGHT_CONTRACT_NUMBER_PLEDGOR_COMPANY)) {
            //股权质押 公司
            ReviewMortgageBasicInfo pledgeInfo = reviewMortgageBasicInfoService.getById(id);
            if (pledgeInfo.getMortgagorCertNum() != null && !pledgeInfo.getMortgagorCertNum().equals("")) {
                Enterprise enterprise = enterpriseService.getOne(new QueryWrapper<Enterprise>().eq("social_credit_code", pledgeInfo.getMortgagorCertNum()));
                SysCustomer sysCustomer = sysCustomerService.getCustomerIdBySocialCreditCode(pledgeInfo.getMortgagorCertNum());
                if (sysCustomer != null && sysCustomer.getFddCustomerId() != null) {
                    ContractElectronicCustomerInfo contractElectronicCustomerInfo = new ContractElectronicCustomerInfo("pd", sysCustomer.getFddCustomerId());
                    contractElectronicCustomerInfo.setSysCustomerId(sysCustomer.getId());
                    contractElectronicCustomerInfos.add(contractElectronicCustomerInfo);
                } else {
                    SysCustomer customer = new SysCustomer();
                    customer.setAccountType("2");
                    customer.setEntBusinessId(enterprise.getId());
                    sysCustomerService.add(customer);
                    ContractElectronicCustomerInfo contractElectronicCustomerInfo = new ContractElectronicCustomerInfo("pd", customer.getFddCustomerId());
                    contractElectronicCustomerInfo.setSysCustomerId(customer.getId());
                    contractElectronicCustomerInfos.add(contractElectronicCustomerInfo);
                }
            }
        } else if (templateCode.equals(ConstantConversionUtil.STOCK_RIGHT_CONTRACT_NUMBER_PLEDGOR_PERSONAL)) {
            //股权质押 个人
            ReviewMortgageBasicInfo pledgeInfo = reviewMortgageBasicInfoService.getById(id);
            ElectronicSignaturePersonal electronicSignaturePersonal = electronicSignaturePersonalService.getOne(new QueryWrapper<ElectronicSignaturePersonal>()
                    .eq("socialCreditCode", pledgeInfo.getMortgagorCertNum()));
            SysCustomer sysCustomer = null;
            if (electronicSignaturePersonal != null) {
                sysCustomer = sysCustomerService.getCustomerPersonBySocialCreditCode(pledgeInfo.getMortgagorCertNum());
                electronicSignaturePersonal.setName(pledgeInfo.getMortgagorName());
                electronicSignaturePersonal.setSocialCreditCode(pledgeInfo.getMortgagorCertNum());
                electronicSignaturePersonal.setCardType("idCard");
                electronicSignaturePersonal.setMobile(pledgeInfo.getContactNumber());
                sysCustomer.setElectronicSignaturePersonal(electronicSignaturePersonal);
                electronicSignaturePersonalService.updateById(electronicSignaturePersonal);
            }
            if (sysCustomer != null && sysCustomer.getFddCustomerId() != null) {
                ContractElectronicCustomerInfo contractElectronicCustomerInfo = new ContractElectronicCustomerInfo("pd", sysCustomer.getFddCustomerId());
                contractElectronicCustomerInfo.setSysCustomerId(sysCustomer.getId());
                contractElectronicCustomerInfos.add(contractElectronicCustomerInfo);
            } else {
                SysCustomer customer = new SysCustomer();
                if (electronicSignaturePersonal == null) {
                    electronicSignaturePersonal = new ElectronicSignaturePersonal();
                    electronicSignaturePersonal.setName(pledgeInfo.getMortgagorName());
                    electronicSignaturePersonal.setSocialCreditCode(pledgeInfo.getMortgagorCertNum());
                    electronicSignaturePersonal.setCardType("idCard");
                    electronicSignaturePersonal.setMobile(pledgeInfo.getContactNumber());
                    customer.setElectronicSignaturePersonal(electronicSignaturePersonal);
                }
                customer.setAccountType("1");
                sysCustomerService.add(customer);
                ContractElectronicCustomerInfo contractElectronicCustomerInfo = new ContractElectronicCustomerInfo("pd", customer.getFddCustomerId());
                contractElectronicCustomerInfo.setSysCustomerId(customer.getId());
                contractElectronicCustomerInfos.add(contractElectronicCustomerInfo);
            }
        } else if (templateCode.equals(ConstantConversionUtil.ACCOUNT_RECEIVABLE_TRANSFER_NOTICE) ||
                templateCode.equals(ConstantConversionUtil.DOMESTIC_ACCOUNT_RECEIVABLE_TRANSFER_NOTICE_BRIGHT)) {
            //池保理应收账款转让通知书—国内适用—明保理适用 国内有追应收账款转让通知书明保理
            String socialCreditCode = null;
            String debtorKeywords;
            Integer i = 0;
            //债务人
            List<ReviewMasterContractDebtor> debtors = reviewMasterContractDebtorService.list(new QueryWrapper<ReviewMasterContractDebtor>()
                    .eq("review_master_contract_id", masterContract.getId()));
            if (debtors != null && debtors.size() > 0) {
                for (ReviewMasterContractDebtor debtor : debtors) {
                    i++;
                    if ((socialCreditCode != null && !socialCreditCode.equals("")) || (debtor.getCompanyName() != null && !debtor.getCompanyName().equals(""))) {
                        Enterprise debtorEnterprise = enterpriseService.getOne(new QueryWrapper<Enterprise>().eq("corporate_name", debtor.getCompanyName()));
                        if (debtorEnterprise != null) {
                            SysCustomer sysCustomer = sysCustomerService.getByName(debtor.getCompanyName());
                            debtorKeywords = "qz" + i;
                            if (sysCustomer != null && sysCustomer.getFddCustomerId() != null) {
                                ContractElectronicCustomerInfo contractElectronicCustomerInfo = new ContractElectronicCustomerInfo(debtorKeywords, sysCustomer.getFddCustomerId());
                                contractElectronicCustomerInfo.setSysCustomerId(sysCustomer.getId());
                                contractElectronicCustomerInfos.add(contractElectronicCustomerInfo);
                            } else {
                                SysCustomer customer = new SysCustomer();
                                customer.setAccountType("2");
                                customer.setEntBusinessId(debtorEnterprise.getId());
                                customer = sysCustomerService.add(customer);
                                ContractElectronicCustomerInfo contractElectronicCustomerInfo = new ContractElectronicCustomerInfo(debtorKeywords, customer.getFddCustomerId());
                                contractElectronicCustomerInfo.setSysCustomerId(customer.getId());
                                contractElectronicCustomerInfos.add(contractElectronicCustomerInfo);
                            }
                        }
                    }
                }
            }
            Enterprise enterpriseBusinessInfo = enterpriseService.getOne(new QueryWrapper<Enterprise>().eq("social_credit_code", masterContract.getApplicantSocialCreditCode()));
            SysCustomer sysCustomer = sysCustomerService.getCustomerIdBySocialCreditCode(masterContract.getApplicantSocialCreditCode());
            if (sysCustomer != null && sysCustomer.getFddCustomerId() != null) {
                ContractElectronicCustomerInfo contractElectronicCustomerInfo = new ContractElectronicCustomerInfo("acn", sysCustomer.getFddCustomerId());
                contractElectronicCustomerInfo.setSysCustomerId(sysCustomer.getId());
                contractElectronicCustomerInfos.add(contractElectronicCustomerInfo);
            } else {
                SysCustomer customer = new SysCustomer();
                customer.setAccountType("2");
                customer.setEntBusinessId(enterpriseBusinessInfo.getId());
                customer = sysCustomerService.add(customer);
                ContractElectronicCustomerInfo contractElectronicCustomerInfo = new ContractElectronicCustomerInfo("acn", customer.getFddCustomerId());
                contractElectronicCustomerInfo.setSysCustomerId(customer.getId());
                contractElectronicCustomerInfos.add(contractElectronicCustomerInfo);
            }
        } else if (templateCode.equals(ConstantConversionUtil.TRIPARTITE_AGREEMENT_FACTORING) ||
                templateCode.equals(ConstantConversionUtil.TRIPARTITE_AGREEMENT) ||
                templateCode.equals(ConstantConversionUtil.TRADING_INFO)) {
            /*
             * 三方协议 保理业务合同之三方协议 三方协议(贸理通) 交易信息表
             * */
            //债务人
            ContractBasicContract basic = null;
            List<ContractBasicContract> basicContracts = contractBasicContractService.list(new QueryWrapper<ContractBasicContract>()
                    .eq("contract_info_id", contractInfo.getId()));
            for (ContractBasicContract basicContract : basicContracts) {
                if (basicContract.getId().equals(id)) {
                    basic = basicContract;
                }
            }
            if (basic.getDebtorSocialCreditCode() != null && !basic.getDebtorSocialCreditCode().equals("")) {
                Platform platform = platformService.lambdaQuery().eq(Platform::getSocialCreditCode, basic.getDebtorSocialCreditCode()).one();
                SysCustomer debtorSysCustomer = sysCustomerService.lambdaQuery().eq(SysCustomer::getPlatformId,platform.getId()).one();
                if (debtorSysCustomer != null && debtorSysCustomer.getFddCustomerId() != null) {
                    ContractElectronicCustomerInfo contractElectronicCustomerInfo = new ContractElectronicCustomerInfo("dbqz", debtorSysCustomer.getFddCustomerId());
                    contractElectronicCustomerInfo.setSysCustomerId(debtorSysCustomer.getId());
                    contractElectronicCustomerInfos.add(contractElectronicCustomerInfo);
                } else {
                    SysCustomer customer = new SysCustomer();
                    customer.setAccountType("2");
                    customer.setPlatformId(platform.getId());
                    customer = sysCustomerService.add(customer);
                    ContractElectronicCustomerInfo contractElectronicCustomerInfo = new ContractElectronicCustomerInfo("dbqz", customer.getFddCustomerId());
                    contractElectronicCustomerInfo.setSysCustomerId(customer.getId());
                    contractElectronicCustomerInfos.add(contractElectronicCustomerInfo);
                }
            }
            if (masterContract.getApplicantSocialCreditCode() != null && !masterContract.getApplicantSocialCreditCode().equals("")) {
                Enterprise enterpriseBusinessInfo = enterpriseService.getOne(new QueryWrapper<Enterprise>().eq("social_credit_code", masterContract.getApplicantSocialCreditCode()));
                SysCustomer sysCustomer = sysCustomerService.getCustomerIdBySocialCreditCode(masterContract.getApplicantSocialCreditCode());
                if (sysCustomer != null && sysCustomer.getFddCustomerId() != null) {
                    ContractElectronicCustomerInfo contractElectronicCustomerInfo = new ContractElectronicCustomerInfo("apn", sysCustomer.getFddCustomerId());
                    contractElectronicCustomerInfo.setSysCustomerId(sysCustomer.getId());
                    contractElectronicCustomerInfos.add(contractElectronicCustomerInfo);
                } else {
                    SysCustomer customer = new SysCustomer();
                    customer.setAccountType("2");
                    customer.setEntBusinessId(enterpriseBusinessInfo.getId());
                    customer = sysCustomerService.add(customer);
                    ContractElectronicCustomerInfo contractElectronicCustomerInfo = new ContractElectronicCustomerInfo("apn", customer.getFddCustomerId());
                    contractElectronicCustomerInfo.setSysCustomerId(customer.getId());
                    contractElectronicCustomerInfos.add(contractElectronicCustomerInfo);
                }
            }
        } else if (templateCode.equals(ConstantConversionUtil.POOL_FACTORING_BUSINESS_CONTRACT) ||
                templateCode.equals(ConstantConversionUtil.POOL_FACTORING_INFORMATION_DOMESTIC) ||
                templateCode.equals(ConstantConversionUtil.POOL_FACTORING_ACCOUNT_RECEIVABLE) ||
                templateCode.equals(ConstantConversionUtil.POOL_FACTORING_FINANCING_CONFIRM) ||
                templateCode.equals(ConstantConversionUtil.DOMESTIC_ACCOUNT_RECEIVABLE_TRANSFER_CONFIRM) ||
                templateCode.equals(ConstantConversionUtil.FACTORING_BUSINESS_CONTRACT) ||
                templateCode.equals(ConstantConversionUtil.FACTORING_SERVICE_CONFIRMATION) ||
                templateCode.equals(ConstantConversionUtil.ACCOUNTS_RECEIVABLE_ASSIGNMENT_AGREEMENT)) {
            /**
             * 池保理业务合同
             * 池保理保理信息表-国内适用
             * 池保理应收账款入池确认书
             * 池保理保理融资确认书
             * 池保理应收账款转让通知书—国内适用—暗保理适用
             * 国内有追应收账款转让通知书-暗保理适用
             * 保理业务合同
             * 保理服务确认书
             * 应收账款转让协议
             * 国际有追索权商业保理合同
             * 国际有追保理信息表
             * 保理融资确认书
             * 国际有追应收账款转让确认书
             * 国内有追索权商业保理合同
             * 国内无追索权商业保理合同
             * 国内有追保理信息表
             * 国内无追保理信息表
             * 国内有追应收账款转让确认书
             * 国内无追应收账款转让确认书
             * 国内有追保理信息表（全保理、票理通、租赁保理化）
             * 国内有追索权商业保理合同（税理通）
             * 国内有追应收账款转让确认书（税理通）
             * 国际有追应收账款转让通知书—明保理适用
             */
            String socialCreditCode = null;
            Long dataSourceId = null;
            if (masterContract.getDoubleFactoringType().equals(1)) {
                if ((masterContract.getPlatformName() != null && !masterContract.getPlatformName().equals("")) || (socialCreditCode != null && !socialCreditCode.equals(""))) {
                    Enterprise enterpriseBusinessInfo = enterpriseService.getOne(new QueryWrapper<Enterprise>().eq("corporate_name", masterContract.getPlatformName()));
                    if (enterpriseBusinessInfo != null) {
                        SysCustomer sysCustomer = sysCustomerService.getCustomerIdBySocialCreditCode(enterpriseBusinessInfo.getSocialCreditCode());
                        if (sysCustomer != null && sysCustomer.getFddCustomerId() != null) {
                            ContractElectronicCustomerInfo contractElectronicCustomerInfo = new ContractElectronicCustomerInfo("ptqz", sysCustomer.getFddCustomerId());
                            contractElectronicCustomerInfo.setSysCustomerId(sysCustomer.getId());
                            contractElectronicCustomerInfos.add(contractElectronicCustomerInfo);
                        } else {
                            SysCustomer customer = new SysCustomer();
                            customer.setAccountType("2");
                            customer.setEntBusinessId(enterpriseBusinessInfo.getId());
                            customer = sysCustomerService.add(customer);
                            ContractElectronicCustomerInfo contractElectronicCustomerInfo = new ContractElectronicCustomerInfo("ptqz", customer.getFddCustomerId());
                            contractElectronicCustomerInfo.setSysCustomerId(customer.getId());
                            contractElectronicCustomerInfos.add(contractElectronicCustomerInfo);
                        }
                    }
                }
            }
            if (masterContract.getApplicantSocialCreditCode() != null && !masterContract.getApplicantSocialCreditCode().equals("")) {
                Enterprise enterpriseBusinessInfo = enterpriseService.getOne(new QueryWrapper<Enterprise>().eq("social_credit_code", masterContract.getApplicantSocialCreditCode()));
                SysCustomer sysCustomer = sysCustomerService.getCustomerIdBySocialCreditCode(masterContract.getApplicantSocialCreditCode());
                if (sysCustomer != null && sysCustomer.getFddCustomerId() != null) {
                    ContractElectronicCustomerInfo contractElectronicCustomerInfo = new ContractElectronicCustomerInfo("acn", sysCustomer.getFddCustomerId());
                    contractElectronicCustomerInfo.setSysCustomerId(sysCustomer.getId());
                    contractElectronicCustomerInfos.add(contractElectronicCustomerInfo);
                } else {
                    SysCustomer customer = new SysCustomer();
                    customer.setAccountType("2");
                    customer.setEntBusinessId(enterpriseBusinessInfo.getId());
                    customer = sysCustomerService.add(customer);
                    ContractElectronicCustomerInfo contractElectronicCustomerInfo = new ContractElectronicCustomerInfo("acn", customer.getFddCustomerId());
                    contractElectronicCustomerInfo.setSysCustomerId(customer.getId());
                    contractElectronicCustomerInfos.add(contractElectronicCustomerInfo);
                }
            }
        }
    }

    /**
     * 合同电子签
     */
    private void doAutoSign(ContractInfo contractInfo, String autoSignKeyword, String templateName, List<ContractElectronicCustomerInfo> contractElectronicCustomerInfos, File file) {
        //保存上传的PDF合同
        String suffix = FileUtil.getSuffix(file.getName());
        String newPath = file.getAbsolutePath().replace(suffix, ".pdf");
        File pdfFile = OfficeConverterUtil.office2Pdf(file.getAbsolutePath(), newPath);
        String originalName = pdfFile.getName();
        FileStorage fileStorage = new FileStorage(originalName, pdfFile.getAbsolutePath(),
                FileModuleDict.ChildEnum.ELECTRONIC_FILE);
        fileStorageService.add(fileStorage);
        ContractElectronicInfo contractElectronicInfo = new ContractElectronicInfo();
        contractElectronicInfo.setFileId(fileStorage.getId());
        contractElectronicInfo.setContractInfoId(contractInfo.getId());
        contractElectronicInfo.setContractName(templateName);
        //上传合同
        String contractId = UUID.randomUUID().toString().trim().replaceAll("-", "").toUpperCase();
        contractElectronicInfo.setContractId(contractId);
        //生成电子签客户信息
        String docTitle = "合同制作：" + templateName;
        String transactionId = UUID.randomUUID().toString().trim().replaceAll("-", "").toUpperCase();
        ElectronicSignatureUtil.uploadContract(contractId, docTitle, pdfFile);
        //合同自动签署
        String signKeyword = autoSignKeyword;
        //获取长安银科商业保理有限公司的customerid
        Platform platform = platformService.getOne(new QueryWrapper<Platform>().eq("socialCreditCode", "91610132MA6U08HU0L"));
        ElectronicSignatureUtil.autoSign(transactionId, contractId, platform.getFddCustomerId(), docTitle, signKeyword);
        contractElectronicInfo.setAutoSignTransactionId(transactionId);
        contractElectronicInfoService.save(contractElectronicInfo);
        for (ContractElectronicCustomerInfo contractElectronicCustomerInfo : contractElectronicCustomerInfos) {
            contractElectronicCustomerInfo.setContractElectronicInfoId(contractElectronicInfo.getId());
            contractElectronicCustomerInfoService.save(contractElectronicCustomerInfo);
        }
    }


    private void doUploadContract(ContractInfo contractInfo) {
        //处理上传的合同
        List<UploadContractInfo> uploadContractInfoList = contractInfo.getUploadContractInfoList();
        uploadContractInfoList.forEach(uploadContractInfo -> {
            List<UploadContractSignatory> uploadContractSignatories = uploadContractInfo.getUploadContractSignatories();
            List<ContractElectronicCustomerInfo> contractElectronicCustomerInfos = new ArrayList<>();
            int keyword = 1;
            FileStorage fileStorage = fileStorageService.get(uploadContractInfo.getFileStorageId());
            String text;
            try {
                // 创建PDF文档对象
                PDDocument document = PDDocument.load(new File(fileStorage.getAbsolutePath()));
                // 获取PDF文档中的文本内容
                text = new PDFTextStripper().getText(document);
                // 关闭PDF文档
                document.close();
            } catch (IOException e) {
                throw new ValidatorException(CodeUtil.FAIL, "pdf解析失败！");
            }
            for (UploadContractSignatory uploadContractSignatory : uploadContractSignatories) {
                //长安银科商业保理有限公司不需要生成信息  因为后面是自动签
                if (uploadContractSignatory.getSocialCreditCode().equals("91610132MA6U08HU0L")) {
                    if (!text.contains("cyqz")) {
                        throw new ValidatorException(CodeUtil.FAIL, "上传的《" + fileStorage.getOriginalName() + "》中客户 长安银科商业保理有限公司 的签章位置上缺少关键字：cyqz");
                    }
                    continue;
                }
                //公司
                if (uploadContractSignatory.getType()) {
                    Enterprise enterpriseBusinessInfo = enterpriseService.getOne(new QueryWrapper<Enterprise>().eq("social_credit_code", uploadContractSignatory.getSocialCreditCode()));
                    SysCustomer sysCustomer = sysCustomerService.getCustomerIdBySocialCreditCode(uploadContractSignatory.getSocialCreditCode());
                    if (sysCustomer != null && sysCustomer.getFddCustomerId() != null) {
                        ContractElectronicCustomerInfo contractElectronicCustomerInfo = new ContractElectronicCustomerInfo("khqz" + keyword, sysCustomer.getFddCustomerId());
                        contractElectronicCustomerInfo.setSysCustomerId(sysCustomer.getId());
                        contractElectronicCustomerInfos.add(contractElectronicCustomerInfo);
                    } else {
                        SysCustomer customer = new SysCustomer();
                        customer.setAccountType("2");
                        if (enterpriseBusinessInfo != null) {
                            customer.setEntBusinessId(enterpriseBusinessInfo.getId());
                        } else {
                            Platform platform = platformService.getOne(new QueryWrapper<Platform>().eq("socialCreditCode", uploadContractSignatory.getSocialCreditCode()));
                            if (platform != null) {
                                customer.setPlatformId(platform.getId());
                            } else {
                                throw new BusinessException(CodeUtil.FAIL, "未查到企业信息！");
                            }
                        }
                        customer = sysCustomerService.add(customer);
                        ContractElectronicCustomerInfo contractElectronicCustomerInfo = new ContractElectronicCustomerInfo("khqz" + keyword, customer.getFddCustomerId());
                        contractElectronicCustomerInfo.setSysCustomerId(customer.getId());
                        contractElectronicCustomerInfos.add(contractElectronicCustomerInfo);
                    }
                    //个人
                } else {
//                    ElectronicPersonInfo electronicPersonInfo = electronicPersonInfoService.getBySocialCreditCode(uploadContractSignatory.getSocialCreditCode());
                    ElectronicSignaturePersonal electronicSignaturePersonal = electronicSignaturePersonalService.getOne(new QueryWrapper<ElectronicSignaturePersonal>()
                            .eq("socialCreditCode", uploadContractSignatory.getSocialCreditCode()));

                    SysCustomer sysCustomer = null;
//                    if (electronicPersonInfo != null) {
//                        sysCustomer = sysCustomerService.getCustomerPersonBySocialCreditCode(uploadContractSignatory.getSocialCreditCode());
//                        electronicPersonInfo.setName(uploadContractSignatory.getName());
//                        electronicPersonInfo.setSocialCreditCode(uploadContractSignatory.getSocialCreditCode());
//                        electronicPersonInfo.setCardTypeId(uploadContractSignatory.getCardTypeId());
//                        electronicPersonInfo.setMobile(uploadContractSignatory.getContactNumber());
//                        electronicPersonInfo.setCardFrontFileStorageId(uploadContractSignatory.getCardFrontFileStorageId());
//                        electronicPersonInfo.setCardReverseFileStorageId(uploadContractSignatory.getCardReverseFileStorageId());
//                        sysCustomer.setElectronicPersonInfo(electronicPersonInfo);
//                        ElectronicPersonInfo personInfo = electronicPersonInfoService.getById(electronicPersonInfo.getId());
//                        if (personInfo.getCardTypeId() == null || personInfo.getCardTypeId().equals("")) {
//                            electronicPersonInfoService.updateById(electronicPersonInfo);
//                        }
//                    }
                    if (electronicSignaturePersonal != null) {
                        sysCustomer = sysCustomerService.getCustomerPersonBySocialCreditCode(uploadContractSignatory.getSocialCreditCode());
                        electronicSignaturePersonal.setName(uploadContractSignatory.getName());
                        electronicSignaturePersonal.setSocialCreditCode(uploadContractSignatory.getSocialCreditCode());
                        electronicSignaturePersonal.setCardType("idCard");
                        electronicSignaturePersonal.setMobile(uploadContractSignatory.getContactNumber());
                        sysCustomer.setElectronicSignaturePersonal(electronicSignaturePersonal);
                        electronicSignaturePersonalService.updateById(electronicSignaturePersonal);
                    }
                    if (sysCustomer != null && sysCustomer.getFddCustomerId() != null) {
                        ContractElectronicCustomerInfo contractElectronicCustomerInfo = new ContractElectronicCustomerInfo("khqz" + keyword, sysCustomer.getFddCustomerId());
                        contractElectronicCustomerInfo.setSysCustomerId(sysCustomer.getId());
                        contractElectronicCustomerInfos.add(contractElectronicCustomerInfo);
                    } else {
                        SysCustomer customer = new SysCustomer();
                        if (electronicSignaturePersonal == null) {
                            electronicSignaturePersonal = new ElectronicSignaturePersonal();
                            electronicSignaturePersonal.setName(uploadContractSignatory.getName());
                            electronicSignaturePersonal.setSocialCreditCode(uploadContractSignatory.getSocialCreditCode());
                            electronicSignaturePersonal.setCardType("idCard");
                            electronicSignaturePersonal.setMobile(uploadContractSignatory.getContactNumber());
                            customer.setElectronicSignaturePersonal(electronicSignaturePersonal);
                        }
                        customer.setAccountType("1");
                        customer = sysCustomerService.add(customer);

                        ContractElectronicCustomerInfo contractElectronicCustomerInfo = new ContractElectronicCustomerInfo("khqz" + keyword, customer.getFddCustomerId());
                        contractElectronicCustomerInfo.setSysCustomerId(customer.getId());
                        contractElectronicCustomerInfos.add(contractElectronicCustomerInfo);
                    }
                }
                keyword++;
            }
            contractElectronicCustomerInfos.forEach(r -> {
                if (!text.contains(r.getKeyword())) {
                    SysCustomer sysCustomer = sysCustomerService.getById(r.getSysCustomerId());
                    Enterprise enterprise = enterpriseService.getById(sysCustomer.getEntBusinessId());
                    throw new ValidatorException(CodeUtil.FAIL, "上传的《" + fileStorage.getOriginalName() + "》中客户 " + enterprise.getCorporateName() + " 的签章位置上缺少关键字：" + r.getKeyword());
                }
            });
            doUploadAutoSign(contractInfo, "cyqz", uploadContractInfo.getContractName(), contractElectronicCustomerInfos, fileStorage);
        });
    }

    /**
     * 上传合同的电子签
     */
    private void doUploadAutoSign(ContractInfo contractInfo, String autoSignKeyword, String contractName,
                                  List<ContractElectronicCustomerInfo> contractElectronicCustomerInfos, FileStorage fileStorage) {
        File pdfFile = new File(fileStorage.getAbsolutePath());
        ContractElectronicInfo contractElectronicInfo = new ContractElectronicInfo();
        contractElectronicInfo.setFileId(fileStorage.getId());
        contractElectronicInfo.setContractInfoId(contractInfo.getId());
        contractElectronicInfo.setContractName(contractName);
        //上传合同
        String contractId = UUID.randomUUID().toString().trim().replaceAll("-", "").toUpperCase();
        contractElectronicInfo.setContractId(contractId);
        //生成电子签客户信息
        String docTitle = "合同制作：" + contractInfo.getContractNo();
        String transactionId = UUID.randomUUID().toString().trim().replaceAll("-", "").toUpperCase();
        ElectronicSignatureUtil.uploadContract(contractId, docTitle, pdfFile);
        //合同自动签署
        String signKeyword = autoSignKeyword;
        //获取长安银科商业保理有限公司的customerid
        Platform platform = platformService.getOne(new QueryWrapper<Platform>().eq("socialCreditCode", "91610132MA6U08HU0L"));
        ElectronicSignatureUtil.autoSign(transactionId, contractId, platform.getFddCustomerId(), docTitle, signKeyword);
        contractElectronicInfo.setAutoSignTransactionId(transactionId);
        contractElectronicInfoService.save(contractElectronicInfo);
        for (ContractElectronicCustomerInfo contractElectronicCustomerInfo : contractElectronicCustomerInfos) {
            contractElectronicCustomerInfo.setContractElectronicInfoId(contractElectronicInfo.getId());
            contractElectronicCustomerInfoService.save(contractElectronicCustomerInfo);
        }
    }
}
