package com.sunxung.factoring.service.creditresolution.impl;


import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sun.star.awt.AdjustmentType;
import com.sunxung.factoring.component.enums.PrincipalPaymentMethodEnum;
import com.sunxung.factoring.component.util.CollectionUtil;
import com.sunxung.factoring.component.util.ConstantConversionUtil;
import com.sunxung.factoring.component.util.ConstantUtil;
import com.sunxung.factoring.dict.impl.ProjectInitiationStatusDict;
import com.sunxung.factoring.entity.ResponseJson;
import com.sunxung.factoring.entity.creditresolution.*;
import com.sunxung.factoring.entity.entprise.Enterprise;
import com.sunxung.factoring.entity.project.ProjectCoreEnterprise;
import com.sunxung.factoring.entity.project.ProjectInformation;
import com.sunxung.factoring.entity.supplier.SupplierContact;
import com.sunxung.factoring.entity.supplier.SupplierInfo;
import com.sunxung.factoring.entity.sys.Dictionary;
import com.sunxung.factoring.entity.sys.User;
import com.sunxung.factoring.entity.sys.UserDO;
import com.sunxung.factoring.mapper.creditresolution.CreditResolutionApprovalMapper;
import com.sunxung.factoring.service.creditresolution.*;
import com.sunxung.factoring.service.entprise.IEnterpriseService;
import com.sunxung.factoring.service.project.*;
import com.sunxung.factoring.service.supplier.*;
import com.sunxung.factoring.service.sys.CUserService;
import com.sunxung.factoring.service.sys.DictionaryService;
import com.sunxung.factoring.service.sys.UserService;
import com.sunxung.factoring.service.sys.flowable.FlowableService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 授信决议审核结论 服务实现类
 * </p>
 *
 * @author liutao
 * @since 2023-12-21
 */
@Service("credit_resolution_approvalService")
public class CreditResolutionApprovalServiceImpl extends ServiceImpl<CreditResolutionApprovalMapper, CreditResolutionApproval> implements ICreditResolutionApprovalService {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${sop.reviewResolutionReportUrl}")
    private String reviewResolutionReportUrl;

    @Resource(name = "projectInformationService")
    private IProjectInformationService projectInformationService;

    @Resource(name = "projectCoreEnterpriseService")
    private IProjectCoreEnterpriseService projectCoreEnterpriseService;

    @Resource(name = "supplierInfoService")
    private ISupplierInfoService supplierInfoService;

    @Autowired
    private DictionaryService dictionaryService;

    @Autowired
    private ISupplierContactService supplierContactService;

    @Autowired
    private FlowableService flowableService;

    @Autowired
    private IEnterpriseService enterpriseService;

    @Autowired
    private IBusinessMeetsConditionsService businessMeetsConditionsService;

    @Autowired
    private ILoanConditionsService loanConditionsService;

    @Autowired
    private ICreditConclusionService creditConclusionService;

    @Autowired
    private ICreditResolutionHistoryService creditResolutionHistoryService;

    @Resource(name = "creditResolutionService")
    private ICreditResolutionService creditResolutionService;

    @Autowired
    private IBusinessMeetsConditionsHistoryService businessMeetsConditionsHistoryService;

    @Autowired
    private ILoanConditionsHistoryService loanConditionsHistoryService;

    @Autowired
    private ICreditConclusionHistoryService creditConclusionHistoryService;

    @Autowired
    private UserService userService;

    @Autowired
    private CUserService cUserService;

    @Autowired
    private IReconsiderAdjustService reconsiderAdjustService;

    @Override
    public void test(Long id){
        CreditResolution creditResolution = creditResolutionService.get(id);
        ProjectInformation projectInformation = projectInformationService.get(creditResolution.getcProjectInformationId());
        Map requestParams = new HashMap();
        SupplierInfo supplierInfo = supplierInfoService.get(projectInformation.getcSupplierInfoId());
        SupplierContact supplierContact = supplierContactService.lambdaQuery().eq(SupplierContact::getSupplierInfoId, supplierInfo.getId()).one();
        Enterprise supplierEnterprise = enterpriseService.getById(supplierInfo.getcEnterpriseId());
        UserDO userDO = cUserService.getById(supplierInfo.getSysUserId());
        User projectManager = userService.get(userDO.getProjectManager());
        User riskManager = userService.get(userDO.getRiskManager());
        requestParams.put("businessNo",projectInformation.getBusinessNumber());
        requestParams.put("manager",projectManager.getName());
        requestParams.put("currency","CNY");
        requestParams.put("transCode","sop.resolution.report");
        requestParams.put("creditLine",creditResolution.getProposedCreditLine());
        requestParams.put("creditTerm",creditResolution.getProposedCreditTerm());
        requestParams.put("customerId","factoringTrade");
        requestParams.put("riskManager",riskManager.getName());
        requestParams.put("creditStartDate", DateUtil.formatDate(creditResolution.getCreditStartDate()));
        requestParams.put("financingPeriod",creditResolution.getFactoringFinancingPeriod());
        requestParams.put("enterpriseIdentity",supplierEnterprise.getSocialCreditCode());
        requestParams.put("contactPerson",supplierContact.getContactName());
        requestParams.put("contactPhone",supplierContact.getMobile());
        requestParams.put("financingRatioLow",creditResolution.getFinancingRatioLow());
        requestParams.put("financingRatioHigh",creditResolution.getFinancingRatioHigh());
        requestParams.put("planIrr",creditResolution.getPlanIrr());
        requestParams.put("financingRateLow",creditResolution.getFinancingRateLow());
        requestParams.put("financingRateHigh",creditResolution.getFinancingRateHigh());
        requestParams.put("managementRateLow",creditResolution.getManagementRateLow());
        requestParams.put("managementRateHigh",creditResolution.getManagementRateHigh());
        requestParams.put("marginRatioLow",creditResolution.getMarginRatioLow());
        requestParams.put("marginRatioHigh",creditResolution.getMarginRatioHigh());
        requestParams.put("hasCondition",creditResolution.getHasCondition());
        List<BusinessMeetsConditions> businessMeetsConditionsList = businessMeetsConditionsService.lambdaQuery().eq(BusinessMeetsConditions::getCreditResolutionId, creditResolution.getId()).list();
        requestParams.put("businessMeetsConditionsList",null);
        if(CollectionUtil.isNotEmpty(businessMeetsConditionsList)){
            List<String> collect = businessMeetsConditionsList.stream().map(r -> r.getContent()).collect(Collectors.toList());
            requestParams.put("businessMeetsConditionsList",collect);
        }
        requestParams.put("comprehensiveQuotation",creditResolution.getComprehensiveQuotation());
        requestParams.put("principalPaymentMethod", PrincipalPaymentMethodEnum.getByCode(creditResolution.getPrincipalPaymentMethod()));
        String paymentMethodForInterestManagementFee = creditResolution.getPaymentMethodForInterestManagementFee();
        Dictionary dic = dictionaryService.getByCode(paymentMethodForInterestManagementFee);
        if(paymentMethodForInterestManagementFee.equals("paymentMethodForInterestManagementFee_A")){
            requestParams.put("interestCollectionMethod",dic.getName());
            requestParams.put("managementFeeCollectionMethod",dic.getName());
        }else if(paymentMethodForInterestManagementFee.equals("paymentMethodForInterestManagementFee_B")){
            requestParams.put("interestCollectionMethod",dic.getName());
            requestParams.put("managementFeeCollectionMethod",dic.getName());
        }else if(paymentMethodForInterestManagementFee.equals("paymentMethodForInterestManagementFee_C")){
            requestParams.put("interestCollectionMethod","后收");
            requestParams.put("managementFeeCollectionMethod","前收");
        }else if(paymentMethodForInterestManagementFee.equals("paymentMethodForInterestManagementFee_D")){
            requestParams.put("interestCollectionMethod",creditResolution.getPaymentMethodForInterestManagementFeeDetail());
            requestParams.put("managementFeeCollectionMethod",creditResolution.getPaymentMethodForInterestManagementFeeDetail());
        }
        requestParams.put("marginPaymentMethod",creditResolution.getMarginPaymentMethod());
        requestParams.put("otherFeePaymentMethod",creditResolution.getOtherFeePaymentMethod());
        requestParams.put("creditEnhancementMeasuresOne",creditResolution.getCreditEnhancementMeasuresOne());
        requestParams.put("creditEnhancementMeasuresTwo",creditResolution.getCreditEnhancementMeasuresTwo());
        requestParams.put("creditEnhancementMeasuresThree",creditResolution.getCreditEnhancementMeasuresThree());
        requestParams.put("creditEnhancementMeasuresFore",creditResolution.getCreditEnhancementMeasuresFore());
        requestParams.put("creditEnhancementMeasuresIllustrate",creditResolution.getCreditEnhancementMeasuresIllustrate());
        List<String> strings = creditResolution.getLoanConditionsList().stream().map(r -> r.getContent()).collect(Collectors.toList());
        requestParams.put("loanConditionsList",strings);
        List<ReconsiderAdjust> reconsiderAdjusts = reconsiderAdjustService.lambdaQuery().eq(ReconsiderAdjust::getCreditResolutionId, creditResolution.getId()).orderByDesc(ReconsiderAdjust::getId).list();
        if(CollectionUtil.isNotEmpty(reconsiderAdjusts)){
            ReconsiderAdjust reconsiderAdjust = reconsiderAdjusts.get(0);
            requestParams.put("reason",reconsiderAdjust.getReason());
            requestParams.put("adjustType",reconsiderAdjust.getAdjustType());
        }
        restTemplate.postForObject(reviewResolutionReportUrl,requestParams, ResponseJson.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addInfo(CreditResolution creditResolution) {
        creditResolution.setFinancingRatioLow(creditResolution.getFinancingRatioLow() == null? 0: creditResolution.getFinancingRatioLow() / 100);
        creditResolution.setFinancingRatioHigh(creditResolution.getFinancingRatioHigh() == null? 0: creditResolution.getFinancingRatioHigh() / 100);
        creditResolution.setPlanIrr(creditResolution.getPlanIrr() == null? 0: creditResolution.getPlanIrr() / 100);
        creditResolution.setProposedFinancingRatioTwoLow(creditResolution.getProposedFinancingRatioTwoLow() == null? 0: creditResolution.getProposedFinancingRatioTwoLow() / 100);
        creditResolution.setProposedFinancingRatioTwoHigh(creditResolution.getProposedFinancingRatioTwoHigh() == null? 0: creditResolution.getProposedFinancingRatioTwoHigh() / 100);
        creditResolution.setPlanIrrTwo(creditResolution.getPlanIrrTwo() == null? 0: creditResolution.getPlanIrrTwo() / 100);
        creditResolution.setFinancingRateLow(creditResolution.getFinancingRateLow() == null? 0: creditResolution.getFinancingRateLow() / 100);
        creditResolution.setFinancingRateHigh(creditResolution.getFinancingRateHigh() == null? 0: creditResolution.getFinancingRateHigh() / 100);
        creditResolution.setManagementRateLow(creditResolution.getManagementRateLow() == null? 0: creditResolution.getManagementRateLow() / 100);
        creditResolution.setManagementRateHigh(creditResolution.getManagementRateHigh() == null? 0: creditResolution.getManagementRateHigh() / 100);
        creditResolution.setMarginRatioLow(creditResolution.getMarginRatioLow() == null? 0: creditResolution.getMarginRatioLow() / 100);
        creditResolution.setMarginRatioHigh(creditResolution.getMarginRatioHigh() == null? 0: creditResolution.getMarginRatioHigh() / 100);
        creditResolution.setComprehensiveQuotation(creditResolution.getComprehensiveQuotation() == null? 0: creditResolution.getComprehensiveQuotation() / 100);
        creditResolutionService.updateById(creditResolution);
        List<BusinessMeetsConditions> businessMeetsConditionsList = creditResolution.getBusinessMeetsConditionsList();
        businessMeetsConditionsService.lambdaUpdate().eq(BusinessMeetsConditions::getCreditResolutionId, creditResolution.getId()).remove();
        if(CollectionUtil.isNotEmpty(businessMeetsConditionsList)){
            for (BusinessMeetsConditions businessMeetsConditions : businessMeetsConditionsList) {
                businessMeetsConditions.setCreditResolutionId(creditResolution.getId());
                businessMeetsConditionsService.save(businessMeetsConditions);
            }
        }
        List<LoanConditions> loanConditionsList = creditResolution.getLoanConditionsList();
        loanConditionsService.lambdaUpdate().eq(LoanConditions::getCreditResolutionId,creditResolution.getId()).remove();
        if(CollectionUtil.isNotEmpty(loanConditionsList)){
            for (LoanConditions loanConditions : loanConditionsList) {
                loanConditions.setCreditResolutionId(creditResolution.getId());
                loanConditionsService.save(loanConditions);
            }
        }
        List<CreditConclusion> creditConclusionList = creditResolution.getCreditConclusionList();
        creditConclusionService.lambdaUpdate().eq(CreditConclusion::getCreditResolutionId,creditResolution.getId()).remove();
        if(CollectionUtil.isNotEmpty(creditConclusionList)){
            for (CreditConclusion creditConclusion : creditConclusionList) {
                creditConclusion.setCreditResolutionId(creditResolution.getId());
                creditConclusionService.save(creditConclusion);
            }
        }
        //保存历史
        Long historyId = addHistory(creditResolution);
        //保存结论
        CreditResolutionApproval creditResolutionApproval = creditResolution.getCreditResolutionApproval();
        creditResolutionApproval.setCreditResolutionId(creditResolution.getId());
        creditResolutionApproval.setCreditResolutionHistoryId(historyId);
        save(creditResolutionApproval);
        //流程处理
        String result;
        ProjectInformation projectInformation = projectInformationService.get(creditResolution.getcProjectInformationId());
        Map<String, Object> msgVariables = new HashMap<>();
        if(creditResolutionApproval.getConclusion().equals(ConstantConversionUtil.APPROVAL_RESULT_PASS)){
            creditResolutionService.lambdaUpdate().eq(CreditResolution::getId,creditResolution.getId()).set(CreditResolution::getStatusStr,ProjectInitiationStatusDict.ChildEnum.COMPLETED.getCode()).update();
            result = ConstantConversionUtil.APPROVAL_RESULT_PASS_DISPLAY;
            msgVariables.put(ConstantUtil.FLOWABLE_MSG_TITLE, "项目名称：" + projectInformation.getProjectName());
            msgVariables.put(ConstantUtil.FLOWABLE_MSG_CONTENT,
                    "项目名称“" + projectInformation.getProjectName() + "”的项目已授信决议已完成。“"
                            + ConstantUtil.FLOWABLE_MSG_ASSIGNEE);
        }else {
            msgVariables.put(ConstantUtil.FLOWABLE_MSG_TITLE, "项目名称：" + projectInformation.getProjectName());
            msgVariables.put(ConstantUtil.FLOWABLE_MSG_CONTENT,
                    "项目名称“" + projectInformation.getProjectName() + "”的项目已退回“"
                            + ConstantConversionUtil.flowBusinessKeyNames.get(ConstantUtil.CREDIT_RESOLUTION) + "授信决议，"
                            + ConstantUtil.FLOWABLE_MSG_ASSIGNEE);
            result = "退回";
        }
        flowableService.completeMyTask(creditResolution.getTaskId(), creditResolution, null, result, creditResolutionApproval.getId(), msgVariables, ConstantUtil.CREDIT_RESOLUTION);
        if(creditResolutionApproval.getConclusion().equals(ConstantConversionUtil.APPROVAL_RESULT_PASS)){
            //同步sop
            Map requestParams = new HashMap();
            CreditResolution exists = creditResolutionService.get(creditResolution.getId());
            SupplierInfo supplierInfo = supplierInfoService.get(projectInformation.getcSupplierInfoId());
            SupplierContact supplierContact = supplierContactService.lambdaQuery().eq(SupplierContact::getSupplierInfoId, supplierInfo.getId()).one();
            Enterprise supplierEnterprise = enterpriseService.getById(supplierInfo.getcEnterpriseId());
            UserDO userDO = cUserService.getById(supplierInfo.getSysUserId());
            User projectManager = userService.get(userDO.getProjectManager());
            User riskManager = userService.get(userDO.getRiskManager());
            requestParams.put("businessNo",projectInformation.getBusinessNumber());
            requestParams.put("manager",projectManager.getName());
            requestParams.put("currency","CNY");
            requestParams.put("transCode","sop.resolution.report");
            requestParams.put("creditLine",exists.getProposedCreditLine());
            requestParams.put("creditTerm",exists.getProposedCreditTerm());
            requestParams.put("customerId","factoringTrade");
            requestParams.put("riskManager",riskManager.getName());
            requestParams.put("creditStartDate", DateUtil.formatDate(exists.getCreditStartDate()));
            requestParams.put("financingPeriod",exists.getFactoringFinancingPeriod());
            requestParams.put("enterpriseIdentity",supplierEnterprise.getSocialCreditCode());
            requestParams.put("contactPerson",supplierContact.getContactName());
            requestParams.put("contactPhone",supplierContact.getMobile());
            requestParams.put("financingRatioLow",exists.getFinancingRatioLow());
            requestParams.put("financingRatioHigh",exists.getFinancingRatioHigh());
            requestParams.put("planIrr",exists.getPlanIrr());
            requestParams.put("financingRateLow",exists.getFinancingRateLow());
            requestParams.put("financingRateHigh",exists.getFinancingRateHigh());
            requestParams.put("managementRateLow",exists.getManagementRateLow());
            requestParams.put("managementRateHigh",exists.getManagementRateHigh());
            requestParams.put("marginRatioLow",exists.getMarginRatioLow());
            requestParams.put("marginRatioHigh",exists.getMarginRatioHigh());
            requestParams.put("hasCondition",exists.getHasCondition());
            requestParams.put("businessMeetsConditionsList",null);
            if(CollectionUtil.isNotEmpty(businessMeetsConditionsList)){
                List<String> collect = businessMeetsConditionsList.stream().map(r -> r.getContent()).collect(Collectors.toList());
                requestParams.put("businessMeetsConditionsList",collect);
            }
            requestParams.put("comprehensiveQuotation",exists.getComprehensiveQuotation());
            requestParams.put("principalPaymentMethod",PrincipalPaymentMethodEnum.getByCode(exists.getPrincipalPaymentMethod()));
            String paymentMethodForInterestManagementFee = exists.getPaymentMethodForInterestManagementFee();
            Dictionary dic = dictionaryService.getByCode(paymentMethodForInterestManagementFee);
            if(paymentMethodForInterestManagementFee.equals("paymentMethodForInterestManagementFee_A")){
                requestParams.put("interestCollectionMethod",dic.getName());
                requestParams.put("managementFeeCollectionMethod",dic.getName());
            }else if(paymentMethodForInterestManagementFee.equals("paymentMethodForInterestManagementFee_B")){
                requestParams.put("interestCollectionMethod",dic.getName());
                requestParams.put("managementFeeCollectionMethod",dic.getName());
            }else if(paymentMethodForInterestManagementFee.equals("paymentMethodForInterestManagementFee_C")){
                requestParams.put("interestCollectionMethod","后收");
                requestParams.put("managementFeeCollectionMethod","前收");
            }else if(paymentMethodForInterestManagementFee.equals("paymentMethodForInterestManagementFee_D")){
                requestParams.put("interestCollectionMethod",exists.getPaymentMethodForInterestManagementFeeDetail());
                requestParams.put("managementFeeCollectionMethod",exists.getPaymentMethodForInterestManagementFeeDetail());
            }
            requestParams.put("marginPaymentMethod",exists.getMarginPaymentMethod());
            requestParams.put("otherFeePaymentMethod",exists.getOtherFeePaymentMethod());
            requestParams.put("creditEnhancementMeasuresOne",exists.getCreditEnhancementMeasuresOne());
            requestParams.put("creditEnhancementMeasuresTwo",exists.getCreditEnhancementMeasuresTwo());
            requestParams.put("creditEnhancementMeasuresThree",exists.getCreditEnhancementMeasuresThree());
            requestParams.put("creditEnhancementMeasuresFore",exists.getCreditEnhancementMeasuresFore());
            requestParams.put("creditEnhancementMeasuresIllustrate",exists.getCreditEnhancementMeasuresIllustrate());
            List<String> strings = creditResolution.getLoanConditionsList().stream().map(r -> r.getContent()).collect(Collectors.toList());
            requestParams.put("loanConditionsList",strings);
            List<ReconsiderAdjust> reconsiderAdjusts = reconsiderAdjustService.lambdaQuery().eq(ReconsiderAdjust::getCreditResolutionId, creditResolution.getId()).orderByDesc(ReconsiderAdjust::getId).list();
            if(CollectionUtil.isNotEmpty(reconsiderAdjusts)){
                ReconsiderAdjust reconsiderAdjust = reconsiderAdjusts.get(0);
                requestParams.put("reason",reconsiderAdjust.getReason());
                requestParams.put("adjustType",reconsiderAdjust.getAdjustType());
            }
            restTemplate.postForObject(reviewResolutionReportUrl,requestParams, ResponseJson.class);
        }
    }

    private Float format(Float number){
        if(number != 0){
            DecimalFormat decimalFormat = new DecimalFormat(".00");
            String financingRatioLowStr =decimalFormat.format(number);
            number = Float.parseFloat(financingRatioLowStr);
        }
        return number;
    };

    @Override
    public CreditResolutionHistory getView(Long id) {
        CreditResolutionApproval creditResolutionApproval = getById(id);
        CreditResolutionHistory creditResolutionHistory = creditResolutionHistoryService.getById(creditResolutionApproval.getCreditResolutionHistoryId());
        creditResolutionHistory.setFinancingRatioLow(format(creditResolutionHistory.getFinancingRatioLow() == null? 0: creditResolutionHistory.getFinancingRatioLow() * 100));
        creditResolutionHistory.setFinancingRatioHigh(format(creditResolutionHistory.getFinancingRatioHigh() == null? 0: creditResolutionHistory.getFinancingRatioHigh() * 100));
        creditResolutionHistory.setPlanIrr(format(creditResolutionHistory.getPlanIrr() == null? 0: creditResolutionHistory.getPlanIrr() * 100));
        creditResolutionHistory.setProposedFinancingRatioTwoLow(format(creditResolutionHistory.getProposedFinancingRatioTwoLow() == null? 0: creditResolutionHistory.getProposedFinancingRatioTwoLow() * 100));
        creditResolutionHistory.setProposedFinancingRatioTwoHigh(format(creditResolutionHistory.getProposedFinancingRatioTwoHigh() == null? 0: creditResolutionHistory.getProposedFinancingRatioTwoHigh() * 100));
        creditResolutionHistory.setPlanIrrTwo(format(creditResolutionHistory.getPlanIrrTwo() == null? 0: creditResolutionHistory.getPlanIrrTwo() * 100));
        creditResolutionHistory.setFinancingRateLow(format(creditResolutionHistory.getFinancingRateLow() == null? 0: creditResolutionHistory.getFinancingRateLow() * 100));
        creditResolutionHistory.setFinancingRateHigh(format(creditResolutionHistory.getFinancingRateHigh() == null? 0: creditResolutionHistory.getFinancingRateHigh() * 100));
        creditResolutionHistory.setManagementRateLow(format(creditResolutionHistory.getManagementRateLow() == null? 0: creditResolutionHistory.getManagementRateLow() * 100));
        creditResolutionHistory.setManagementRateHigh(format(creditResolutionHistory.getManagementRateHigh() == null? 0: creditResolutionHistory.getManagementRateHigh() * 100));
        creditResolutionHistory.setMarginRatioLow(format(creditResolutionHistory.getMarginRatioLow() == null? 0: creditResolutionHistory.getMarginRatioLow() * 100));
        creditResolutionHistory.setMarginRatioHigh(format(creditResolutionHistory.getMarginRatioHigh() == null? 0: creditResolutionHistory.getMarginRatioHigh() * 100));
        creditResolutionHistory.setComprehensiveQuotation(format(creditResolutionHistory.getComprehensiveQuotation() == null? 0: creditResolutionHistory.getComprehensiveQuotation() * 100));
        ProjectInformation projectInformation = projectInformationService.get(creditResolutionHistory.getcProjectInformationId());
        ProjectCoreEnterprise projectCoreEnterprise = projectCoreEnterpriseService.getByProjectInfoId(projectInformation.getId());
        //主企业
        Enterprise ownerEnterprise = enterpriseService.getById(projectInformation.getcEnterpriseId());
        //核心企业
        Enterprise coreEnterprise = enterpriseService.getById(projectCoreEnterprise.getcEnterpriseId());
        SupplierInfo supplierInfo = supplierInfoService.get(projectInformation.getcSupplierInfoId());
        //供应商
        Enterprise supplierInfoEnterprise = enterpriseService.getById(supplierInfo.getcEnterpriseId());
        creditResolutionHistory.setProjectInformation(projectInformation);
        creditResolutionHistory.setOwnerEnterprise(ownerEnterprise);
        creditResolutionHistory.setCoreEnterprise(coreEnterprise);
        creditResolutionHistory.setSupplierEnterprise(supplierInfoEnterprise);
        List<BusinessMeetsConditionsHistory> businessMeetsConditionsHistoryList = businessMeetsConditionsHistoryService.lambdaQuery().eq(BusinessMeetsConditionsHistory::getCreditResolutionId, creditResolutionHistory.getId()).list();
        List<LoanConditionsHistory> loanConditionsHistoryList = loanConditionsHistoryService.lambdaQuery().eq(LoanConditionsHistory::getCreditResolutionId, creditResolutionHistory.getId()).list();
        List<CreditConclusionHistory> creditConclusionHistoryList = creditConclusionHistoryService.lambdaQuery().eq(CreditConclusionHistory::getCreditResolutionId, creditResolutionHistory.getId()).list();
        //担保企业
        if (supplierInfo.getGuaranteeEnterpriseId() != null) {
            Enterprise guaranteeEnterprise = enterpriseService.getById(supplierInfo.getGuaranteeEnterpriseId());
            creditResolutionHistory.setGuaranteeEnterprise(guaranteeEnterprise);
        }
        creditResolutionHistory.setBusinessMeetsConditionsHistoryList(businessMeetsConditionsHistoryList);
        creditResolutionHistory.setBusinessMeetsConditionsList(businessMeetsConditionsHistoryList);
        creditResolutionHistory.setLoanConditionsHistoryList(loanConditionsHistoryList);
        creditResolutionHistory.setCreditConclusionHistoryList(creditConclusionHistoryList);
        creditResolutionHistory.setCreditResolutionApproval(creditResolutionApproval);
        return creditResolutionHistory;
    }

    private Long addHistory(CreditResolution creditResolution) {
        CreditResolution exists = creditResolutionService.get(creditResolution.getId());
        exists.setFinancingRatioLow(creditResolution.getFinancingRatioLow() );
        exists.setFinancingRatioHigh(creditResolution.getFinancingRatioHigh() );
        exists.setPlanIrr(creditResolution.getPlanIrr() );
        exists.setProposedFinancingRatioTwoLow(creditResolution.getProposedFinancingRatioTwoLow() );
        exists.setProposedFinancingRatioTwoHigh(creditResolution.getProposedFinancingRatioTwoHigh() );
        exists.setPlanIrrTwo(creditResolution.getPlanIrrTwo() );
        exists.setFinancingRateLow(creditResolution.getFinancingRateLow() );
        exists.setFinancingRateHigh(creditResolution.getFinancingRateHigh() );
        exists.setManagementRateLow(creditResolution.getManagementRateLow());
        exists.setManagementRateHigh(creditResolution.getManagementRateHigh());
        exists.setMarginRatioLow(creditResolution.getMarginRatioLow());
        exists.setMarginRatioHigh(creditResolution.getMarginRatioHigh());
        exists.setComprehensiveQuotation(creditResolution.getComprehensiveQuotation());
        CreditResolutionHistory creditResolutionHistory = new CreditResolutionHistory();
        BeanUtils.copyProperties(exists, creditResolutionHistory, "id");
        creditResolutionHistoryService.save(creditResolutionHistory);
        List<BusinessMeetsConditions> businessMeetsConditionsList = creditResolution.getBusinessMeetsConditionsList();
        if(CollectionUtil.isNotEmpty(businessMeetsConditionsList)){
            for (BusinessMeetsConditions businessMeetsConditions : businessMeetsConditionsList) {
                BusinessMeetsConditionsHistory businessMeetsConditionsHistory = new BusinessMeetsConditionsHistory();
                BeanUtils.copyProperties(businessMeetsConditions,businessMeetsConditionsHistory,"id");
                businessMeetsConditionsHistory.setCreditResolutionId(creditResolutionHistory.getId());
                businessMeetsConditionsHistoryService.save(businessMeetsConditionsHistory);
            }
        }
        List<LoanConditions> loanConditionsList = creditResolution.getLoanConditionsList();
        if(CollectionUtil.isNotEmpty(loanConditionsList)){
            for (LoanConditions loanConditions : loanConditionsList) {
                LoanConditionsHistory loanConditionsHistory = new LoanConditionsHistory();
                BeanUtils.copyProperties(loanConditions,loanConditionsHistory,"id");
                loanConditionsHistory.setCreditResolutionId(creditResolutionHistory.getId());
                loanConditionsHistoryService.save(loanConditionsHistory);
            }
        }
        List<CreditConclusion> creditConclusionList = creditResolution.getCreditConclusionList();
        if(CollectionUtil.isNotEmpty(creditConclusionList)){
            for (CreditConclusion creditConclusion : creditConclusionList) {
                CreditConclusionHistory creditConclusionHistory = new CreditConclusionHistory();
                BeanUtils.copyProperties(creditConclusion,creditConclusionHistory,"id");
                creditConclusionHistory.setCreditResolutionId(creditResolutionHistory.getId());
                creditConclusionHistoryService.save(creditConclusionHistory);
            }
        }
        return creditResolutionHistory.getId();
    }
}
