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

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sunxung.factoring.component.exception.BusinessException;
import com.sunxung.factoring.component.exception.ValidatorException;
import com.sunxung.factoring.component.util.*;
import com.sunxung.factoring.dict.impl.ProjectInitiationStatusDict;
import com.sunxung.factoring.entity.GridPage;
import com.sunxung.factoring.entity.creditresolution.*;
import com.sunxung.factoring.entity.entprise.Enterprise;
import com.sunxung.factoring.entity.project.*;
import com.sunxung.factoring.entity.project.vo.SearchBusinessProcessingTask;
import com.sunxung.factoring.entity.supplier.DueDiligenceAllocation;
import com.sunxung.factoring.entity.supplier.SupplierInfo;
import com.sunxung.factoring.entity.supplier.VideoDueDiligence;
import com.sunxung.factoring.entity.supplier.VideoDueDiligenceComprehensiveEvaluation;
import com.sunxung.factoring.entity.sys.*;
import com.sunxung.factoring.mapper.creditresolution.CreditResolutionMapper;
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.IDueDiligenceAllocationService;
import com.sunxung.factoring.service.supplier.ISupplierInfoService;
import com.sunxung.factoring.service.supplier.IVideoDueDiligenceComprehensiveEvaluationService;
import com.sunxung.factoring.service.supplier.IVideoDueDiligenceService;
import com.sunxung.factoring.service.sys.*;
import com.sunxung.factoring.service.sys.flowable.FlowableService;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;

/**
 * <p>
 * 授信决议 服务实现类
 * </p>
 *
 * @author liutao
 * @since 2023-12-21
 */
@Service
public class CreditResolutionServiceImpl extends ServiceImpl<CreditResolutionMapper, CreditResolution> implements ICreditResolutionService {

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

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

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

    @Autowired
    private IProjectAuditService projectAuditService;

    @Autowired
    private IProjectCoreEnterpriseAuditService projectCoreEnterpriseAuditService;

    @Autowired
    private IProjectCoreEnterpriseComprehensiveEvaluationService projectCoreEnterpriseComprehensiveEvaluationService;

    @Autowired
    private IProjectOwnerComprehensiveEvaluationService projectOwnerComprehensiveEvaluationService;

    @Autowired
    private FlowableService flowableService;

    @Autowired
    private IEnterpriseService enterpriseService;

    @Autowired
    private BusinessProcessingLogService businessProcessingLogService;

    @Autowired
    private UserService userService;

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private IBusinessMeetsConditionsService businessMeetsConditionsService;

    @Autowired
    private ILoanConditionsService loanConditionsService;

    @Autowired
    private ICreditConclusionService creditConclusionService;

    @Autowired
    private ICreditResolutionHistoryService creditResolutionHistoryService;

    @Autowired
    private IBusinessMeetsConditionsHistoryService businessMeetsConditionsHistoryService;

    @Autowired
    private ILoanConditionsHistoryService loanConditionsHistoryService;

    @Autowired
    private ICreditConclusionHistoryService creditConclusionHistoryService;

    @Autowired
    private CUserService cUserService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private DictionaryService dictionaryService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void startProcess(Long cProjectInformationId) {
        CreditResolution existCredit = baseMapper.getByProjectInfoId(cProjectInformationId);
        if (existCredit == null) {
            //保存基础信息
            ProjectInformation projectInformation = projectInformationService.get(cProjectInformationId);
            ProjectCoreEnterprise projectCoreEnterprise = projectCoreEnterpriseService.getByProjectInfoId(cProjectInformationId);
            SupplierInfo supplierInfo = supplierInfoService.get(projectInformation.getcSupplierInfoId());
            CreditResolution creditResolution = new CreditResolution();
            creditResolution.setcProjectInformationId(cProjectInformationId);
            creditResolution.setCreditType("综合授信");
            creditResolution.setDomesticFactoring("国内保理");
            creditResolution.setImplementingFactoringProducts("贸理通");
            creditResolution.setImplementingFactoringType("池保理 有追索权 明保理 正向保理");
            ProjectAudit projectAudit = projectAuditService.lambdaQuery().eq(ProjectAudit::getcProjectInformationId, projectInformation.getId()).one();
            BigDecimal projectCreditLimit ;
            ProjectCoreEnterpriseAudit projectCoreEnterpriseAudit = projectCoreEnterpriseAuditService.lambdaQuery().eq(ProjectCoreEnterpriseAudit::getcProjectCoreEnterpriseId, projectCoreEnterprise.getId()).one();
            ProjectCoreEnterpriseComprehensiveEvaluation projectCoreEnterpriseComprehensiveEvaluation = projectCoreEnterpriseComprehensiveEvaluationService.lambdaQuery().eq(ProjectCoreEnterpriseComprehensiveEvaluation::getProjectCoreEnterpriseAuditId, projectCoreEnterpriseAudit.getId()).one();
            Enterprise coreEnterprise = enterpriseService.getById(projectCoreEnterprise.getcEnterpriseId());
            Enterprise enterprise = enterpriseService.getById(projectInformation.getcEnterpriseId());
            BigDecimal supplierCreditLimit = supplierInfo.getCreditLimit();
            BigDecimal projectCoreEnterpriseCreditLimit = projectCoreEnterpriseComprehensiveEvaluation.getCreditLimit();
            BigDecimal result ;
            if(projectAudit != null){
                ProjectOwnerComprehensiveEvaluation projectOwnerComprehensiveEvaluation = projectOwnerComprehensiveEvaluationService.lambdaQuery().eq(ProjectOwnerComprehensiveEvaluation::getProjectAuditId, projectAudit.getId()).one();
                projectCreditLimit = projectOwnerComprehensiveEvaluation.getCreditLimit();
                result = supplierCreditLimit.compareTo(projectCreditLimit) > -1 ? projectCreditLimit : supplierCreditLimit;
            }else {
                result = supplierCreditLimit;
            }
            result = result.compareTo(projectCoreEnterpriseCreditLimit) > -1 ? projectCoreEnterpriseCreditLimit : result;
            creditResolution.setProposedCreditLine(result.multiply(new BigDecimal("10000")));
            creditResolution.setCurrency("CNY");
            creditResolution.setProposedCreditTerm(360);
            creditResolution.setStatusStr(ProjectInitiationStatusDict.ChildEnum.PROCESSING.getCode());
            creditResolution.setUpstreamAccountingPeriod(projectInformation.getEstimatedAccountingPeriod() * 30 + 60);
            creditResolution.setFactoringFinancingPeriod(projectInformation.getEstimatedAccountingPeriod() * 30 + 60);
            creditResolution.setCreditReport(1);
            baseMapper.add(creditResolution);
            //开启流程
            Map<String, Object> procVariables = new HashMap<>();
            UserDO userDO = cUserService.getById(supplierInfo.getSysUserId());
            if (userDO.getRiskManager() == null) {
                throw new BusinessException(CodeUtil.FAIL, "请联系客服分配风控经理");
            }
            if (userDO.getProjectManager() == null) {
                throw new BusinessException(CodeUtil.FAIL, "请联系客服分配业务经理");
            }
            procVariables.put(ConstantUtil.CREDIT_RESOLUTION_ADD_ASSIGNEE, userDO.getProjectManager());
            procVariables.put(ConstantUtil.CREDIT_RESOLUTION_APPROVAL_ASSIGNEE, userDO.getRiskManager());
            procVariables.put(ConstantUtil.RECONSIDER_ADJUST_ADD_ASSIGNEE, userDO.getProjectManager());
            procVariables.put(ConstantUtil.RECONSIDER_ADJUST_APPROVAL_ASSIGNEE, userDO.getRiskManager());
            //查询条件：业务编号 项目名称 主企业名称 核心企业名称
            String queryBusiness = projectInformation.getBusinessNumber() + FlowableUtil.splitChar + projectInformation.getProjectName();
            if(enterprise != null){
                queryBusiness = queryBusiness + FlowableUtil.splitChar + enterprise.getCorporateName();
            }
            if(coreEnterprise != null){
                queryBusiness = queryBusiness + FlowableUtil.splitChar + coreEnterprise.getCorporateName();
            }
            ProcessInstance processInst = flowableService.startProcessInstance(creditResolution, procVariables,
                    FlowableUtil.generateBusinessKey(creditResolution, ConstantUtil.CREDIT_RESOLUTION, queryBusiness), null, ConstantUtil.CREDIT_RESOLUTION);
            if (processInst == null) {
                throw new BusinessException(CodeUtil.FAIL, "流程启动失败");
            }
        }
    }

    @Override
    public CreditResolution get(Long id) {
        CreditResolution creditResolution = baseMapper.getById(id);
        creditResolution.setCreditStartDate(new Date());
        Date date = DateUtil.addYears(new Date(), 1);
        creditResolution.setCreditEndDate(date);
        ProjectInformation projectInformation = projectInformationService.get(creditResolution.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());
        creditResolution.setProjectInformation(projectInformation);
        creditResolution.setOwnerEnterprise(ownerEnterprise);
        creditResolution.setCoreEnterprise(coreEnterprise);
        creditResolution.setSupplierEnterprise(supplierInfoEnterprise);
        //担保企业
        if (supplierInfo.getGuaranteeEnterpriseId() != null) {
            Enterprise guaranteeEnterprise = enterpriseService.getById(supplierInfo.getGuaranteeEnterpriseId());
            creditResolution.setGuaranteeEnterprise(guaranteeEnterprise);
        }
        List<BusinessMeetsConditions> businessMeetsConditions = businessMeetsConditionsService.lambdaQuery().eq(BusinessMeetsConditions::getCreditResolutionId, id).list();
        List<LoanConditions> loanConditions = loanConditionsService.lambdaQuery().eq(LoanConditions::getCreditResolutionId, id).list();
        List<CreditConclusion> creditConclusionList = creditConclusionService.lambdaQuery().eq(CreditConclusion::getCreditResolutionId, id).list();
        creditResolution.setBusinessMeetsConditionsList(businessMeetsConditions);
        creditResolution.setLoanConditionsList(loanConditions);
        creditResolution.setCreditConclusionList(creditConclusionList);
        return creditResolution;
    }

    @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);
        creditResolution.setCreditStartDate(new Date());
        Date date = DateUtil.addYears(new Date(), 1);
        creditResolution.setCreditEndDate(date);
        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);
            }
        }
        if(creditResolution.getVisible() == 1){
            //保存历史
            Long historyId = addHistory(creditResolution);
            //流程处理
            ProjectInformation projectInformation = projectInformationService.get(creditResolution.getcProjectInformationId());
            Map<String, Object> msgVariables = new HashMap<>();
            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);
            flowableService.completeMyTask(creditResolution.getTaskId(), creditResolution, null, null, historyId, msgVariables, ConstantUtil.CREDIT_RESOLUTION);
        }
    }

    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) {
        CreditResolutionHistory creditResolutionHistory = creditResolutionHistoryService.getById(id);
        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());
        //担保企业
        if (supplierInfo.getGuaranteeEnterpriseId() != null) {
            Enterprise guaranteeEnterprise = enterpriseService.getById(supplierInfo.getGuaranteeEnterpriseId());
            creditResolutionHistory.setGuaranteeEnterprise(guaranteeEnterprise);
        }
        creditResolutionHistory.setProjectInformation(projectInformation);
        creditResolutionHistory.setOwnerEnterprise(ownerEnterprise);
        creditResolutionHistory.setCoreEnterprise(coreEnterprise);
        creditResolutionHistory.setSupplierEnterprise(supplierInfoEnterprise);
        List<BusinessMeetsConditionsHistory> businessMeetsConditionsHistoryList = businessMeetsConditionsHistoryService.lambdaQuery().eq(BusinessMeetsConditionsHistory::getCreditResolutionId, id).list();
        List<LoanConditionsHistory> loanConditionsHistoryList = loanConditionsHistoryService.lambdaQuery().eq(LoanConditionsHistory::getCreditResolutionId, id).list();
        List<CreditConclusionHistory> creditConclusionHistoryList = creditConclusionHistoryService.lambdaQuery().eq(CreditConclusionHistory::getCreditResolutionId, id).list();
        creditResolutionHistory.setBusinessMeetsConditionsHistoryList(businessMeetsConditionsHistoryList);
        creditResolutionHistory.setBusinessMeetsConditionsList(businessMeetsConditionsHistoryList);
        creditResolutionHistory.setLoanConditionsHistoryList(loanConditionsHistoryList);
        creditResolutionHistory.setCreditConclusionHistoryList(creditConclusionHistoryList);
        return creditResolutionHistory;
    }

    @Override
    public GridPage<CreditResolution> allList(SearchBusinessProcessingTask search) {
        Long currentUserId = ThreadLocalUtil.getUserId();
        List<UserOrgRel> userOrgRelList = userService.findOrgRelByUserId(currentUserId);
        List<Long> userIdList;
        List<UserRoleRel> userRoleRels = roleService.getUserRoleByUserId(ThreadLocalUtil.getUserId());
        List<Long> pers = permissionService.getPermissionIdByUserId(ThreadLocalUtil.getUserId());
        Permission per = permissionService.getByEname(ConstantConversionUtil.VIEW_ALL_CREDIT_RESOLUTION);
        if (per == null) {
            throw new ValidatorException(CodeUtil.FAIL, "数据可见-查看全员权限不能为空");
        }
        if (pers.contains(per.getId())
                || ThreadLocalUtil.getUser().getLoginName().equals(ConstantConversionUtil.ADMINISTORIES)) {
            userIdList = null;
        } else {
            userIdList = new ArrayList<>();
            if (CollectionUtil.isNotEmpty(userRoleRels)) {
                for (UserOrgRel userOrgRel : userOrgRelList) {
                    if (userOrgRel.isUserIdentity()) {
                        // 如果是部门负责人，获取部门下所有人员Id
                        List<Long> userIds = userService.findUserIdByOrgId(userOrgRel.getOrgId());
                        userIdList.addAll(userIds);
                    } else {
                        userIdList.add(currentUserId);
                    }
                }
            }
        }
        search.setUserIds(userIdList);
        Page page = PageHelper.startPage(search.getPage(), search.getRows());
        List<CreditResolution> list = baseMapper.allList(search);
        for (CreditResolution creditResolution : list) {
            BusinessProcessingLog businessProcessingLog = businessProcessingLogService.getByBusinessTypeBusinessKey(ConstantUtil.CREDIT_RESOLUTION, creditResolution.getId());
            if (businessProcessingLog.getAssignee().getId() != null) {
                String name = userService.get(businessProcessingLog.getAssignee().getId()).getName();
                creditResolution.setAssigner(name);
            }
            creditResolution.setStatusStr(dictionaryService.getByCode(creditResolution.getStatusStr()).getName());
        }
        return new GridPage<>(page.getPageSize(), page.getPageNum(), page.getTotal(), list);
    }

    @Override
    public CreditResolution getByProjectInformationId(Long projectInformationId) {
        return baseMapper.getByProjectInfoId(projectInformationId);
    }

    @Override
    public CreditResolution getDetail(Long id) {
        CreditResolution creditResolution = get(id);
        List<BusinessMeetsConditions> businessMeetsConditions = businessMeetsConditionsService.lambdaQuery().eq(BusinessMeetsConditions::getCreditResolutionId, id).list();
        List<LoanConditions> loanConditions = loanConditionsService.lambdaQuery().eq(LoanConditions::getCreditResolutionId, id).list();
        List<CreditConclusion> creditConclusions = creditConclusionService.lambdaQuery().eq(CreditConclusion::getCreditResolutionId, id).list();
        creditResolution.setBusinessMeetsConditionsList(businessMeetsConditions);
        creditResolution.setLoanConditionsList(loanConditions);
        creditResolution.setCreditConclusionList(creditConclusions);
        return creditResolution;
    }

    private Long addHistory(CreditResolution creditResolution) {
        CreditResolution exists = 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();
    }
}
