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

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sunxung.factoring.component.constance.SupplierScoringModel;
import com.sunxung.factoring.component.enums.ProjectAndEnterpriseStatusEnums;
import com.sunxung.factoring.component.enums.SupplierStatusEnums;
import com.sunxung.factoring.component.util.CollectionUtil;
import com.sunxung.factoring.component.util.ConstantUtil;
import com.sunxung.factoring.component.util.StringUtil;
import com.sunxung.factoring.dict.impl.FileModuleDict;
import com.sunxung.factoring.entity.ResponseJson;
import com.sunxung.factoring.entity.credit.CreditDetail;
import com.sunxung.factoring.entity.credit.CreditInfo;
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.*;
import com.sunxung.factoring.entity.sys.FileStorage;
import com.sunxung.factoring.entity.sys.FileStorageDO;
import com.sunxung.factoring.mapper.supplier.VideoDueDiligenceMapper;
import com.sunxung.factoring.service.credit.CreditDetailService;
import com.sunxung.factoring.service.credit.CreditService;
import com.sunxung.factoring.service.creditresolution.ICreditResolutionService;
import com.sunxung.factoring.service.entprise.IEnterpriseService;
import com.sunxung.factoring.service.project.IProjectCoreEnterpriseService;
import com.sunxung.factoring.service.project.IProjectInformationService;
import com.sunxung.factoring.service.supplier.*;
import com.sunxung.factoring.service.sys.DictionaryService;
import com.sunxung.factoring.service.sys.FileService;
import com.sunxung.factoring.service.sys.FileStorageService;
import com.sunxung.factoring.service.sys.ISysAttachmentRefService;
import com.sunxung.factoring.service.sys.dto.AttachmentDto;
import com.sunxung.factoring.service.sys.flowable.FlowableService;
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.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 视频尽调 服务实现类
 * </p>
 *
 * @author liutao
 * @since 2023-12-09
 */
@Service("video_due_diligenceService")
public class VideoDueDiligenceServiceImpl extends ServiceImpl<VideoDueDiligenceMapper, VideoDueDiligence> implements IVideoDueDiligenceService {


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

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

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

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

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ISupplierApprovalSecondService supplierApprovalSecondService;

    @Autowired
    private ICCreditInvestigationInfoHistoryService creditInvestigationInfoHistoryService;

    @Autowired
    private ICreditInvestigationInfoService creditInvestigationInfoService;

    @Autowired
    private IEnterpriseService enterpriseService;

    @Autowired
    private FileService fileService;

    @Autowired
    private ISysAttachmentRefService attachmentRefService;

    @Autowired
    private ICSupplierInfoHistoryService supplierInfoHistoryService;

    @Autowired
    private ICEnterpriseHistoryService enterpriseHistoryService;

    @Autowired
    private ICAssociatedEnterpriseInfoHistoryService associatedEnterpriseInfoHistoryService;

    @Autowired
    private ICreditSituationService creditSituationService;

    @Autowired
    private IBlacklistService blacklistService;

    @Autowired
    private ICorporateGoodwillService corporateGoodwillService;

    @Autowired
    private IExceptionDataService exceptionDataService;

    @Autowired
    private INewsService newsService;

    @Autowired
    private IPrivateLendingService privateLendingService;

    @Autowired
    private ISeriousIllegalityService seriousIllegalityService;

    @Autowired
    private ITaxIllegalDataService taxIllegalDataService;

    @Autowired
    private ITaxOweNoticeService taxOweNoticeService;

    @Autowired
    private IUpstreamProcurementDocumentsService upstreamProcurementDocumentsService;

    @Autowired
    private ISalesDocumentsInfoService salesDocumentsInfoService;

    @Autowired
    private IVideoDueDiligenceShareholdersSituationService videoDueDiligenceShareholdersSituationService;

    @Autowired
    private IVideoDueDiligenceCorporateGoodwillService videoDueDiligenceCorporateGoodwillService;

    @Autowired
    private IVideoDueDiligenceFinanceService videoDueDiligenceFinanceService;

    @Autowired
    private IVideoDueDiligenceOperationsService videoDueDiligenceOperationsService;

    @Autowired
    private IVideoDueDiligenceComprehensiveEvaluationService videoDueDiligenceComprehensiveEvaluationService;

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

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

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

    @Autowired
    private FlowableService flowableService;

    @Autowired
    private DictionaryService dictionaryService;

    @Autowired
    private ICCorporateFinanceHistoryService corporateFinanceHistoryService;

    @Autowired
    private CreditService creditService;

    @Autowired
    private CreditDetailService creditDetailService;

    @Autowired
    private FileStorageService fileStorageService;

    @Override
    public VideoDueDiligence getVideoDueDiligence(Long supplierId) {
        VideoDueDiligence videoDueDiligence = lambdaQuery().eq(VideoDueDiligence::getcSupplierInfoId, supplierId).one();
        if (videoDueDiligence == null) {
            videoDueDiligence = new VideoDueDiligence();
            videoDueDiligence.setcSupplierInfoId(supplierId);
        }
        SupplierInfo supplierInfo = supplierInfoService.get(supplierId);
        Enterprise enterprise = enterpriseService.getById(supplierInfo.getcEnterpriseId());
        if (supplierInfo.getGuaranteeEnterpriseId() != null) {
            enterprise = enterpriseService.getById(supplierInfo.getGuaranteeEnterpriseId());
        }
        videoDueDiligence.setEnterpriseName(enterprise.getCorporateName());
        videoDueDiligence.setSocialCreditCode(enterprise.getSocialCreditCode());
        // 股东信息 工商登记
        String pubStockUrl = pubStock + "?socialCreditCode=" + enterprise.getSocialCreditCode() + "&comprehensiveRiskInvestigationId=" + enterprise.getcComprehensiveRiskInvestigationId();
        ResponseJson forObject = restTemplate.getForObject(pubStockUrl, ResponseJson.class);
        JSONObject jsonObject = new JSONObject(forObject.getData());
        List<CRegStock> list = jsonObject.getBeanList("list", CRegStock.class);
        videoDueDiligence.setRegStocks(list);
        videoDueDiligence.setLegalRepresentative(enterprise.getLegalRepresentative());
        CreditInvestigationInfo creditInvestigationInfo = creditInvestigationInfoService.lambdaQuery()
                .eq(CreditInvestigationInfo::getcEnterpriseId, enterprise.getId())
                .eq(CreditInvestigationInfo::getName, enterprise.getLegalRepresentative())
                .eq(CreditInvestigationInfo::getType, "c_credit_investigation_info_type_1").one();
        int bornYear = Integer.valueOf(creditInvestigationInfo.getSocialCreditCode().substring(6, 10));
        int bornMon = Integer.valueOf(creditInvestigationInfo.getSocialCreditCode().substring(10, 12));
        int bornDay = Integer.valueOf(creditInvestigationInfo.getSocialCreditCode().substring(12, 14));
        Date date = new Date(bornYear-1900, bornMon, bornDay);
        int age = cn.hutool.core.date.DateUtil.age(date,new Date());
        videoDueDiligence.setAge(age);
        SupplierApprovalSecond supplierApprovalSecond = supplierApprovalSecondService.lambdaQuery().eq(SupplierApprovalSecond::getcSupplierInfoId, supplierId).orderByDesc(SupplierApprovalSecond::getGmtCreate).list().get(0);
        videoDueDiligence.setShareholderStandardScore(BigDecimal.ONE);
        videoDueDiligence.setShareholderMeasurementScore(supplierApprovalSecond.getShareholderScore());
        videoDueDiligence.setShareholderQuestion("法人是否为代持？股东是否为亲属？公司实控人是？");
        videoDueDiligence.setStartDate(enterprise.getStartSate());
        long year = DateUtil.betweenYear(enterprise.getStartSate(), new Date(), false);
        videoDueDiligence.setEstablishmentPeriod(year);
        videoDueDiligence.setLifeStandardScore(new BigDecimal("1.5"));
        videoDueDiligence.setLifeMeasurementScore(supplierApprovalSecond.getEstablishmentPeriodScore());
        videoDueDiligence.setLifeQuestion("实际从事该行业的年份？是否存在其他抬头公司进行业务经营？");
        videoDueDiligence.setRegisteredCapital(enterprise.getRegisteredCapital());
        videoDueDiligence.setCapitalStandardScore(new BigDecimal("1.5"));
        videoDueDiligence.setCapitalMeasurementScore(supplierApprovalSecond.getRegisteredCapitalScore());
        videoDueDiligence.setCapitalQuestion("公司实际运营资金多少？投入资金多少？");
        videoDueDiligence.setAddress(enterprise.getAddress());
        videoDueDiligence.setAddressStandardScore(new BigDecimal("1"));
        videoDueDiligence.setAddressMeasurementScore(supplierApprovalSecond.getRegisteredAddressScore());
        videoDueDiligence.setAddressQuestion("注册地址与实际经营地址是否不一致？");
        videoDueDiligence.setBusinessAddress(enterprise.getBusinessAddress());
        videoDueDiligence.setBusinessAddressQuestion("是否存在该项资料？是否可以补充上传？");
        //查询文件
        CSupplierInfoHistory supplierInfoHistory = supplierInfoHistoryService.getById(supplierApprovalSecond.getcSupplierInfoHistoryId());
        CEnterpriseHistory enterpriseHistory;
        if (supplierInfoHistory.getGuaranteeEnterpriseHistoryId() != null) {
            enterpriseHistory = enterpriseHistoryService.getById(supplierInfoHistory.getGuaranteeEnterpriseHistoryId());
        } else {
            enterpriseHistory = enterpriseHistoryService.getById(supplierInfoHistory.getcEnterpriseHistoryId());
        }
        List<FileStorageDO> rentalFiles = fileService.findByBusinessId(enterpriseHistory.getId(), FileModuleDict.ChildEnum.ENTERPRISE_RENTAL_CONTRACT_HISTORY.getCode());
        List<FileStorageDO> waterFiles = fileService.findByBusinessId(enterpriseHistory.getId(), FileModuleDict.ChildEnum.WATER_ELECTRIICITY_FEES_HISTORY.getCode());
        List<FileStorageDO> officeFiles = fileService.findByBusinessId(enterpriseHistory.getId(), FileModuleDict.ChildEnum.ENTERPRISE_OFFICE_ENVIRONMENT_HISTORY.getCode());
        videoDueDiligence.setRentalFiles(rentalFiles);
        videoDueDiligence.setWaterFiles(waterFiles);
        videoDueDiligence.setOfficeFiles(officeFiles);
        videoDueDiligence.setBusinessAddressStandardScore(new BigDecimal("3"));
        videoDueDiligence.setBusinessAddressMeasurementScore(supplierApprovalSecond.getBusinessAddressScore());
        //所属行业
        String getIndustryUrl = getIndustry + "?comprehensiveRiskInvestigationId=" + enterprise.getcComprehensiveRiskInvestigationId();
        String industry = restTemplate.getForObject(getIndustryUrl, String.class);
        videoDueDiligence.setIndustry(industry);
        //经营范围
        videoDueDiligence.setBusinessScope(supplierApprovalSecond.getScope());
        videoDueDiligence.setBusinessScopeStandardScore(new BigDecimal("1"));
        videoDueDiligence.setBusinessScopeMeasurementScore(supplierApprovalSecond.getBusinessScopeScore());
        //近一年股东或法人变更*次
        String getChangesUrl = getChanges + "?comprehensiveRiskInvestigationId=" + enterprise.getcComprehensiveRiskInvestigationId();
        Integer changes = restTemplate.getForObject(getChangesUrl, Integer.class);
        videoDueDiligence.setBasicChangeSize(changes);
        videoDueDiligence.setChangeStandardScore(new BigDecimal("1"));
        videoDueDiligence.setChangeMeasurementScore(supplierApprovalSecond.getBasicChangeScore());
        //关联企业
        List<CAssociatedEnterpriseInfoHistory> enterpriseInfoHistoryList = associatedEnterpriseInfoHistoryService.lambdaQuery().eq(CAssociatedEnterpriseInfoHistory::getcEnterpriseHistoryId, enterpriseHistory.getId()).list();
        videoDueDiligence.setEnterpriseInfoHistoryList(enterpriseInfoHistoryList);
        videoDueDiligence.setAssociatedEnterpriseQuestion("是否还有其他业务关联公司？关联公司业务分别是？");
        //人员信息
        List<CreditSituation> creditSituations = creditSituationService.lambdaQuery().eq(CreditSituation::getcSupplierInfoId, supplierId).list();
        creditSituations = creditSituations.stream().filter(r -> {
            CCreditInvestigationInfoHistory creditInvestigationInfoHistory = creditInvestigationInfoHistoryService.getById(r.getcCreditInvestigationInfoHistoryId());
            CEnterpriseHistory byId = enterpriseHistoryService.getById(creditInvestigationInfoHistory.getcEnterpriseHistoryId());
            CEnterpriseHistory serviceById = enterpriseHistoryService.getById(supplierApprovalSecond.getcEnterpriseHistoryId());
            return byId.getCorporateName().equals(serviceById.getCorporateName());
        }).collect(Collectors.toList());
        for (CreditSituation creditSituation : creditSituations) {
            CCreditInvestigationInfoHistory creditInvestigationInfoHistory = creditInvestigationInfoHistoryService.getById(creditSituation.getcCreditInvestigationInfoHistoryId());
            String name = dictionaryService.getByCode(creditInvestigationInfoHistory.getType()).getName();
            creditInvestigationInfoHistory.setTypeStr(name);
            //todo 填充征信报告
            CreditInfo creditInfo = creditService.lambdaQuery().eq(CreditInfo::getCardNo, creditInvestigationInfoHistory.getSocialCreditCode()).one();
            List<FileStorage> fileList = new ArrayList<>();
            if (creditInfo != null) {
                List<CreditDetail> creditDetails = creditDetailService.lambdaQuery()
                        .eq(CreditDetail::getCreditId,creditInfo.getId())
                        .isNotNull(CreditDetail::getCreditAddress)
                        .orderByDesc(CreditDetail::getGmtCreate).list();
                if (CollectionUtil.isNotEmpty(creditDetails)) {
                    CreditDetail creditDetail = creditDetails.get(0);
                    if(StringUtil.isNotEmpty(creditDetail.getCreditAddress())){
                        FileStorage creditDetailFiles = fileStorageService.get(Long.valueOf(creditDetail.getCreditAddress()));
                        fileList.add(creditDetailFiles);
                    }
                }
            }
            creditInvestigationInfoHistory.setCreditDetailFiles(fileList);
            List<FileStorageDO> cardFiles = fileService.findByBusinessId(creditInvestigationInfoHistory.getId(), FileModuleDict.ChildEnum.ENTERPRISE_IDCARD_FILES_HISTORY.getCode());
            creditInvestigationInfoHistory.setCardFiles(cardFiles);
            creditSituation.setQuestion("逾期详情？提供还款记录说明；逾期详情？提供还款记录说明；查询的原因是？小贷查询次数多少？查询后借到多少金额款项？什么性质的担保？为谁担保？历史失信被执行情况详情？判决书；历史被执行情况详情？判决书；限制高消费情况详情；详细解释诉讼案件以及提供判决书");
            creditSituation.setCreditInvestigationInfoHistory(creditInvestigationInfoHistory);
        }
        videoDueDiligence.setCreditSituations(creditSituations);
        //企业信誉
        CorporateGoodwill corporateGoodwill = corporateGoodwillService.lambdaQuery()
                .eq(CorporateGoodwill::getcSupplierInfoId, supplierId).eq(CorporateGoodwill::getcEnterpriseId, enterprise.getId()).one();
        corporateGoodwill.setShiXin(corporateGoodwill.getShiXin() == 0 ? 0 : 1);
        corporateGoodwill.setHistoryShiXin(corporateGoodwill.getHistoryShiXin() == 0 ? 0 : 1);
        corporateGoodwill.setZhiXing(corporateGoodwill.getZhiXing() == 0 ? 0 : 1);
        corporateGoodwill.setHistoryZhiXing(corporateGoodwill.getHistoryZhiXing() == 0 ? 0 : 1);
        corporateGoodwill.setGaoXiao(corporateGoodwill.getGaoXiao() == 0 ? 0 : 1);
        corporateGoodwill.setHistoryGaoXiao(corporateGoodwill.getHistoryGaoXiao() == 0 ? 0 : 1);
        corporateGoodwill.setDocumnetBeiGao(corporateGoodwill.getDocumnetBeiGao() == 0 ? 0 : 1);
        corporateGoodwill.setDocumnetYuanGao(corporateGoodwill.getDocumnetYuanGao() == 0 ? 0 : 1);
        corporateGoodwill.setDocumentFinance(corporateGoodwill.getDocumentFinance() == 0 ? 0 : 1);
        //todo 填充征信报告
        List<FileStorage> fileList = new ArrayList<>();
        CreditInfo creditInfo = creditService.lambdaQuery().eq(CreditInfo::getCardNo, enterprise.getSocialCreditCode()).one();
        if (creditInfo != null) {
            List<CreditDetail> creditDetails = creditDetailService.lambdaQuery()
                    .eq(CreditDetail::getCreditId,creditInfo.getId())
                    .isNotNull(CreditDetail::getCreditAddress)
                    .orderByDesc(CreditDetail::getGmtCreate).list();
            if (CollectionUtil.isNotEmpty(creditDetails)) {
                CreditDetail creditDetail = creditDetails.get(0);
                if(StringUtil.isNotEmpty(creditDetail.getCreditAddress())){
                    FileStorage creditDetailFiles = fileStorageService.get(Long.valueOf(creditDetail.getCreditAddress()));
                    fileList.add(creditDetailFiles);
                }
            }
        }
        corporateGoodwill.setCreditDetailFiles(fileList);
        corporateGoodwill.setQuestion("有无其他融资渠道？融资缺口有多少？");
        videoDueDiligence.setCorporateGoodwill(corporateGoodwill);
        videoDueDiligence.setNegativeInformationQuestion(" 历史失信被执行情况详情？判决书；历史被执行情况详情？判决书；限制高消费情况详情；行政处罚情况说明；涉诉情况说明");
        List<PrivateLending> privateLendings = privateLendingService.lambdaQuery().eq(PrivateLending::getcSupplierInfoId, supplierId).eq(PrivateLending::getcEnterpriseId, enterprise.getId()).list();
        if(CollectionUtil.isNotEmpty(privateLendings)){
            privateLendings.forEach(r->r.setVideoDueDiligencePrivateLending(0));
        }
        videoDueDiligence.setPrivateLendings(privateLendings);
        List<SeriousIllegality> seriousIllegalities = seriousIllegalityService.lambdaQuery().eq(SeriousIllegality::getcSupplierInfoId, supplierId).eq(SeriousIllegality::getcEnterpriseId, enterprise.getId()).list();
        if(CollectionUtil.isNotEmpty(seriousIllegalities)){
            seriousIllegalities.forEach(r->r.setVideoDueDiligenceSeriousIllegality(0));
        }
        videoDueDiligence.setSeriousIllegalities(seriousIllegalities);
        List<TaxOweNotice> taxOweNotices = taxOweNoticeService.lambdaQuery().eq(TaxOweNotice::getcSupplierInfoId, supplierId).eq(TaxOweNotice::getcEnterpriseId, enterprise.getId()).list();
        if(CollectionUtil.isNotEmpty(taxOweNotices)){
            taxOweNotices.forEach(r->r.setVideoDueDiligenceTaxOweNotice(0));
        }
        videoDueDiligence.setTaxOweNotices(taxOweNotices);
        List<TaxIllegalData> taxIllegalData = taxIllegalDataService.lambdaQuery().eq(TaxIllegalData::getcSupplierInfoId, supplierId).eq(TaxIllegalData::getcEnterpriseId, enterprise.getId()).list();
        if(CollectionUtil.isNotEmpty(taxIllegalData)){
            taxIllegalData.forEach(r->r.setVideoDueDiligenceTaxIllegal(0));
        }
        videoDueDiligence.setTaxIllegalData(taxIllegalData);
        List<Blacklist> blacklists = blacklistService.lambdaQuery().eq(Blacklist::getcSupplierInfoId, supplierId).eq(Blacklist::getcEnterpriseId, enterprise.getId()).list();
        if(CollectionUtil.isNotEmpty(blacklists)){
            blacklists.forEach(r->r.setVideoDueDiligenceBlacklist(0));
        }
        videoDueDiligence.setBlacklists(blacklists);
        List<ExceptionData> exceptionData = exceptionDataService.lambdaQuery().eq(ExceptionData::getcSupplierInfoId, supplierId).eq(ExceptionData::getcEnterpriseId, enterprise.getId()).list();
        if(CollectionUtil.isNotEmpty(exceptionData)){
            exceptionData.forEach(r->r.setVideoDueDiligenceException(0));
        }
        videoDueDiligence.setExceptionData(exceptionData);
        List<News> news = newsService.lambdaQuery().eq(News::getcSupplierInfoId, supplierId).eq(News::getcEnterpriseId, enterprise.getId()).list();
        if(CollectionUtil.isNotEmpty(news)){
            news.forEach(r->r.setVideoDueDiligenceNews(0));
        }
        videoDueDiligence.setNews(news);
        AttachmentDto attachmentDto = AttachmentDto.builder()
                .setEntityId(supplierApprovalSecond.getId())
                .setChildEnum(FileModuleDict.ChildEnum.SUPPLIER_APPROVAL_MOVABLE_PROPERTY_FINANCING_FILE)
                .build();
        List<FileStorage> files = attachmentRefService.getFiles(attachmentDto);
        videoDueDiligence.setFiles(files);
        //企业经营与财务
        List<FileStorageDO> enterpriseTaxReturnFiles = fileService.findByBusinessId(enterpriseHistory.getId(), FileModuleDict.ChildEnum.ENTERPRISE_TAX_RETURN_HISTORY.getCode());
        List<CCorporateFinanceHistory> cCorporateFinanceHistories = corporateFinanceHistoryService.lambdaQuery().eq(CCorporateFinanceHistory::getcEnterpriseHistoryId, enterpriseHistory.getId()).list();
        for (CCorporateFinanceHistory cCorporateFinanceHistory : cCorporateFinanceHistories) {
            List<FileStorageDO> enterpriseFinancialStatementsFiles = fileService.findByBusinessId(cCorporateFinanceHistory.getId(), FileModuleDict.ChildEnum.ENTERPRISE_FINANCIAL_STATEMENTS_HISTORY.getCode());
            cCorporateFinanceHistory.setFileStorageDO(enterpriseFinancialStatementsFiles.get(0));
            cCorporateFinanceHistory.setFileStorage(enterpriseFinancialStatementsFiles.get(0));
        }
        List<FileStorageDO> enterpriseAccountingReportFiles = fileService.findByBusinessId(enterpriseHistory.getId(), FileModuleDict.ChildEnum.ENTERPRISE_ACCOUNTING_REPORT_HISTORY.getCode());
        videoDueDiligence.setEnterpriseTaxReturnFiles(enterpriseTaxReturnFiles);
        videoDueDiligence.setCorporateFinanceList(cCorporateFinanceHistories);
        videoDueDiligence.setEnterpriseAccountingReportFiles(enterpriseAccountingReportFiles);
        //企业财务
        VideoDueDiligenceFinance videoDueDiligenceFinance = new VideoDueDiligenceFinance();
        videoDueDiligence.setMainBusinessIncome(supplierApprovalSecond.getMainBusinessIncome());
        videoDueDiligence.setMainBusinessCost(supplierApprovalSecond.getMainBusinessCost());
        videoDueDiligence.setMainBusinessProfit(supplierApprovalSecond.getMainBusinessProfit());
        videoDueDiligenceFinance.setQuestion("是否有企业内账？企业真实年营业收入有多少？业务收入占比情况如何？毛利率约多少？对客户是如何筛选？");
        videoDueDiligence.setVideoDueDiligenceFinance(videoDueDiligenceFinance);
        //上游采购单据
        List<UpstreamProcurementDocuments> upstreamProcurementDocumentsList = upstreamProcurementDocumentsService.lambdaQuery().eq(UpstreamProcurementDocuments::getSupplierApprovalSecondId, supplierApprovalSecond.getId()).list();
        if (CollectionUtil.isNotEmpty(upstreamProcurementDocumentsList)) {
            for (UpstreamProcurementDocuments upstreamProcurementDocuments : upstreamProcurementDocumentsList) {
                List<FileStorageDO> fileStorageDOS = fileService.findByBusinessId(upstreamProcurementDocuments.getcUpstreamProcurementDocumentsHistoryId(), FileModuleDict.ChildEnum.ENTERPRISE_UPSTREAM_DOCUMENTS_HISTORY.getCode());
                upstreamProcurementDocuments.setFileStorageDOS(fileStorageDOS);
                upstreamProcurementDocuments.setStandardScore(new BigDecimal("2"));
            }
        }
        videoDueDiligence.setUpstreamProcurementDocumentsList(upstreamProcurementDocumentsList);
        //下游销售单据
        List<SalesDocumentsInfo> salesDocumentsInfoList = salesDocumentsInfoService.lambdaQuery().eq(SalesDocumentsInfo::getSupplierApprovalSecondId, supplierApprovalSecond.getId()).list();
        if (CollectionUtil.isNotEmpty(salesDocumentsInfoList)) {
            for (SalesDocumentsInfo salesDocumentsInfo : salesDocumentsInfoList) {
                List<FileStorageDO> fileStorageDOS = fileService.findByBusinessId(salesDocumentsInfo.getcSalesDocumentsInfoHistoryId(), FileModuleDict.ChildEnum.ENTERPRISE_SALES_DOCUMENTS_HISTORY.getCode());
                salesDocumentsInfo.setFileStorageDOS(fileStorageDOS);
                salesDocumentsInfo.setStandardScore(new BigDecimal("1"));
            }
        }
        videoDueDiligence.setSalesDocumentsInfoList(salesDocumentsInfoList);
        VideoDueDiligenceOperations videoDueDiligenceOperations = new VideoDueDiligenceOperations();
        videoDueDiligenceOperations.setQuestion("主营业务是？有无其他业务？合作的客户或者项目有哪些？年供应量大概多少？参与过项目有哪些？合作过的下游国企有哪些？有没有长期合作企业？本年度的项目有哪些？主要销售市场是？其他地区有没有业务如何入行？关系经验有哪些？有没有计划拓展的新领域？销售计划是什么？预计本年度营收收入、销售量多少？\n" +
                "1.上游情况一般是从钢厂采购？供应商有没有区别？是钢厂的代理？上游合作商有哪些？如何选用供应商？还会采购其他货物吗？\n" + "2.下游情况招投标、签合同、下订单、送货、验收、对账、开票、付款流程介绍项目都有招标吗？与国企的往期合作情况 实际账期大概多久？付款方式是？");
        videoDueDiligence.setVideoDueDiligenceOperations(videoDueDiligenceOperations);

        return videoDueDiligence;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void videoDueDiligence(VideoDueDiligence videoDueDiligence) {
        //一键测算
        measurement(videoDueDiligence);
        //保存视频尽调信息
        save(videoDueDiligence);
        //保存文件
        List<Long> addressFileIds = videoDueDiligence.getAddressFileIds();
        if (CollectionUtil.isNotEmpty(addressFileIds)) {
            saveFiles(addressFileIds, videoDueDiligence.getId(), FileModuleDict.ChildEnum.VIDEO_DUE_DILIGENCE_ADDRESS_FILE);
        }
        List<Long> associatedEnterpriseFileIds = videoDueDiligence.getAssociatedEnterpriseFileIds();
        if (CollectionUtil.isNotEmpty(associatedEnterpriseFileIds)) {
            saveFiles(associatedEnterpriseFileIds, videoDueDiligence.getId(), FileModuleDict.ChildEnum.VIDEO_DUE_DILIGENCE_ASSOCIATED_ENTERPRISE_FILE);
        }
        List<Long> businessAddressFileIds = videoDueDiligence.getBusinessAddressFileIds();
        if (CollectionUtil.isNotEmpty(businessAddressFileIds)) {
            saveFiles(businessAddressFileIds, videoDueDiligence.getId(), FileModuleDict.ChildEnum.VIDEO_DUE_DILIGENCE_BUSINESS_ADDRESS_FILE);
        }
        List<Long> businessScopeFileIds = videoDueDiligence.getBusinessScopeFileIds();
        if (CollectionUtil.isNotEmpty(businessScopeFileIds)) {
            saveFiles(businessScopeFileIds, videoDueDiligence.getId(), FileModuleDict.ChildEnum.VIDEO_DUE_DILIGENCE_BUSINESS_SCOPE_FILE);
        }
        List<Long> capitalFileIds = videoDueDiligence.getCapitalFileIds();
        if (CollectionUtil.isNotEmpty(capitalFileIds)) {
            saveFiles(capitalFileIds, videoDueDiligence.getId(), FileModuleDict.ChildEnum.VIDEO_DUE_DILIGENCE_CAPITAL_FILE);
        }
        List<Long> changeFileIds = videoDueDiligence.getChangeFileIds();
        if (CollectionUtil.isNotEmpty(changeFileIds)) {
            saveFiles(changeFileIds, videoDueDiligence.getId(), FileModuleDict.ChildEnum.VIDEO_DUE_DILIGENCE_CHANGE_FILE);
        }
        List<Long> industryFileIds = videoDueDiligence.getIndustryFileIds();
        if (CollectionUtil.isNotEmpty(industryFileIds)) {
            saveFiles(industryFileIds, videoDueDiligence.getId(), FileModuleDict.ChildEnum.VIDEO_DUE_DILIGENCE_INDUSTRY_FILE);
        }
        List<Long> lifeFileIds = videoDueDiligence.getLifeFileIds();
        if (CollectionUtil.isNotEmpty(lifeFileIds)) {
            saveFiles(lifeFileIds, videoDueDiligence.getId(), FileModuleDict.ChildEnum.VIDEO_DUE_DILIGENCE_LIFE_FILE);
        }
        List<Long> negativeInformationFileIds = videoDueDiligence.getNegativeInformationFileIds();
        if (CollectionUtil.isNotEmpty(negativeInformationFileIds)) {
            saveFiles(negativeInformationFileIds, videoDueDiligence.getId(), FileModuleDict.ChildEnum.VIDEO_DUE_DILIGENCE_NEGATIVE_INFORMATION_FILE);
        }
        List<Long> shareholderFileIds = videoDueDiligence.getShareholderFileIds();
        if (CollectionUtil.isNotEmpty(shareholderFileIds)) {
            saveFiles(shareholderFileIds, videoDueDiligence.getId(), FileModuleDict.ChildEnum.VIDEO_DUE_DILIGENCE_SHAREHOLDER_FILE);
        }
        //保存企业负责人情况
        List<VideoDueDiligenceShareholdersSituation> videoDueDiligenceShareholdersSituations = videoDueDiligence.getVideoDueDiligenceShareholdersSituations();
        if (CollectionUtil.isNotEmpty(videoDueDiligenceShareholdersSituations)) {
            for (VideoDueDiligenceShareholdersSituation videoDueDiligenceShareholdersSituation : videoDueDiligenceShareholdersSituations) {
                videoDueDiligenceShareholdersSituation.setcSupplierInfoId(videoDueDiligence.getcSupplierInfoId());
                videoDueDiligenceShareholdersSituation.setVideoDueDiligenceId(videoDueDiligence.getId());
                videoDueDiligenceShareholdersSituationService.save(videoDueDiligenceShareholdersSituation);
                //保存文件
                List<Long> fileIds = videoDueDiligenceShareholdersSituation.getFileIds();
                saveFiles(fileIds, videoDueDiligenceShareholdersSituation.getId(), FileModuleDict.ChildEnum.VIDEO_DUE_DILIGENCE_SHAREHOLDER_SITUATION_FILE);
            }
        }
        //保存企业信誉信息
        VideoDueDiligenceCorporateGoodwill videoDueDiligenceCorporateGoodwill = videoDueDiligence.getVideoDueDiligenceCorporateGoodwill();
        videoDueDiligenceCorporateGoodwill.setcSupplierInfoId(videoDueDiligence.getcSupplierInfoId());
        videoDueDiligenceCorporateGoodwill.setVideoDueDiligenceId(videoDueDiligence.getId());
        videoDueDiligenceCorporateGoodwillService.save(videoDueDiligenceCorporateGoodwill);
        //保存文件
        List<Long> fileIds = videoDueDiligenceCorporateGoodwill.getFileIds();
        saveFiles(fileIds, videoDueDiligenceCorporateGoodwill.getId(), FileModuleDict.ChildEnum.VIDEO_DUE_DILIGENCE_CORPORATE_GOODWILL_FILE);
        List<PrivateLending> privateLendings = videoDueDiligence.getPrivateLendings();
        if (CollectionUtil.isNotEmpty(privateLendings)) {
            for (PrivateLending privateLending : privateLendings) {
                privateLendingService.updateById(privateLending);
            }
        }
        List<SeriousIllegality> seriousIllegalities = videoDueDiligence.getSeriousIllegalities();
        if (CollectionUtil.isNotEmpty(seriousIllegalities)) {
            for (SeriousIllegality seriousIllegality : seriousIllegalities) {
                seriousIllegalityService.updateById(seriousIllegality);
            }
        }
        List<TaxOweNotice> taxOweNotices = videoDueDiligence.getTaxOweNotices();
        if (CollectionUtil.isNotEmpty(taxOweNotices)) {
            for (TaxOweNotice taxOweNotice : taxOweNotices) {
                taxOweNoticeService.updateById(taxOweNotice);
            }
        }
        List<TaxIllegalData> taxIllegalData = videoDueDiligence.getTaxIllegalData();
        if (CollectionUtil.isNotEmpty(taxIllegalData)) {
            for (TaxIllegalData taxIllegalDatum : taxIllegalData) {
                taxIllegalDataService.updateById(taxIllegalDatum);
            }
        }
        List<Blacklist> blacklists = videoDueDiligence.getBlacklists();
        if (CollectionUtil.isNotEmpty(blacklists)) {
            for (Blacklist blacklist : blacklists) {
                blacklistService.updateById(blacklist);
            }
        }
        List<ExceptionData> exceptionData = videoDueDiligence.getExceptionData();
        if (CollectionUtil.isNotEmpty(exceptionData)) {
            for (ExceptionData exceptionDatum : exceptionData) {
                exceptionDataService.updateById(exceptionDatum);
            }
        }
        List<News> news = videoDueDiligence.getNews();
        if (CollectionUtil.isNotEmpty(news)) {
            for (News news1 : news) {
                newsService.updateById(news1);
            }
        }
        //企业经财务
        VideoDueDiligenceFinance videoDueDiligenceFinance = videoDueDiligence.getVideoDueDiligenceFinance();
        videoDueDiligenceFinance.setVideoDueDiligenceId(videoDueDiligence.getId());
        videoDueDiligenceFinanceService.save(videoDueDiligenceFinance);
        //保存文件
        List<Long> videoDueDiligenceFinanceFileIds = videoDueDiligenceFinance.getFileIds();
        saveFiles(videoDueDiligenceFinanceFileIds, videoDueDiligenceFinance.getId(), FileModuleDict.ChildEnum.VIDEO_DUE_DILIGENCE_FINANCE_FILE);
        //上游采购单据
        List<UpstreamProcurementDocuments> upstreamProcurementDocumentsList = videoDueDiligence.getUpstreamProcurementDocumentsList();
        if (CollectionUtil.isNotEmpty(upstreamProcurementDocumentsList)) {
            for (UpstreamProcurementDocuments upstreamProcurementDocuments : upstreamProcurementDocumentsList) {
                upstreamProcurementDocumentsService.updateById(upstreamProcurementDocuments);
            }
        }
        //下游销售单据：
        List<SalesDocumentsInfo> salesDocumentsInfoList = videoDueDiligence.getSalesDocumentsInfoList();
        if (CollectionUtil.isNotEmpty(salesDocumentsInfoList)) {
            for (SalesDocumentsInfo salesDocumentsInfo : salesDocumentsInfoList) {
                salesDocumentsInfoService.updateById(salesDocumentsInfo);
            }
        }
        //企业经营情况
        VideoDueDiligenceOperations videoDueDiligenceOperations = videoDueDiligence.getVideoDueDiligenceOperations();
        videoDueDiligenceOperations.setVideoDueDiligenceId(videoDueDiligence.getId());
        videoDueDiligenceOperationsService.save(videoDueDiligenceOperations);
        //保存文件
        List<Long> videoDueDiligenceOperationsFileIds = videoDueDiligenceOperations.getFileIds();
        saveFiles(videoDueDiligenceOperationsFileIds, videoDueDiligenceOperations.getId(), FileModuleDict.ChildEnum.VIDEO_DUE_DILIGENCE_OPERATIONS_FILE);
        //综合评估
        SupplierInfo supplierInfo = supplierInfoService.get(videoDueDiligence.getcSupplierInfoId());
        VideoDueDiligenceComprehensiveEvaluation videoDueDiligenceComprehensiveEvaluation = videoDueDiligence.getVideoDueDiligenceComprehensiveEvaluation();
        videoDueDiligenceComprehensiveEvaluation.setVideoDueDiligenceId(videoDueDiligence.getId());
        videoDueDiligenceComprehensiveEvaluation.setEvaluationOpinions(videoDueDiligence.getEvaluationOpinions());
        videoDueDiligenceComprehensiveEvaluationService.save(videoDueDiligenceComprehensiveEvaluation);
        supplierInfo.setScore(videoDueDiligenceComprehensiveEvaluation.getScore());
        supplierInfo.setAdmitted(videoDueDiligenceComprehensiveEvaluation.getAdmitted());
        supplierInfo.setCreditLimit(videoDueDiligenceComprehensiveEvaluation.getCreditLimit());
        supplierInfo.setRevenueRating(videoDueDiligenceComprehensiveEvaluation.getRevenueRating());
        if (videoDueDiligenceComprehensiveEvaluation.getAdmitted().equals(SupplierScoringModel.ADMITTED)) {
            supplierInfo.setStatusStr(SupplierStatusEnums.CREDIT_SUCCESS.getCode());
        } else {
            supplierInfo.setStatusStr(SupplierStatusEnums.VOTE.getCode());
        }
        supplierInfoService.updateById(supplierInfo);
        //完成流程
        String taskId = videoDueDiligence.getTaskId();
        Enterprise enterprise = enterpriseService.getById(supplierInfo.getcEnterpriseId());
        Map<String, Object> msgVariables = new HashMap<>();
        msgVariables.put(ConstantUtil.FLOWABLE_MSG_TITLE, "供应商名称：" + enterprise.getCorporateName());
        msgVariables.put(ConstantUtil.FLOWABLE_MSG_CONTENT,
                "供应商名称为“" + enterprise.getCorporateName() + "”的供应商已完成审核！"
                        + ConstantUtil.FLOWABLE_MSG_ASSIGNEE);
        flowableService.completeMyTask(taskId, supplierInfo, null, null, videoDueDiligence.getId(), msgVariables, ConstantUtil.SUPPLIER_INFO);

        //判断是否开启授信决议
        List<ProjectInformation> projectInformations = projectInformationService.lambdaQuery().eq(ProjectInformation::getcSupplierInfoId, videoDueDiligence.getcSupplierInfoId()).list();
        if (CollectionUtil.isNotEmpty(projectInformations)) {
            for (ProjectInformation projectInformation : projectInformations) {
                if (projectInformation.getStatusStr().equals(ProjectAndEnterpriseStatusEnums.CREDIT_SUCCESS.getCode())) {
                    ProjectCoreEnterprise projectCoreEnterprise = projectCoreEnterpriseService.lambdaQuery().eq(ProjectCoreEnterprise::getcProjectInformationId, projectInformation.getId()).one();
                    if (projectCoreEnterprise.getStatusStr().equals(ProjectAndEnterpriseStatusEnums.CREDIT_SUCCESS.getCode())) {
                        if (supplierInfo.getStatusStr().equals(SupplierStatusEnums.CREDIT_SUCCESS.getCode())) {
                            //开启流程
                            creditResolutionService.startProcess(projectInformation.getId());
                        }
                    }
                }
            }
        }
    }

    private void saveFiles(List<Long> fileIds, Long id, FileModuleDict.ChildEnum fileModuleDict) {
        if (CollectionUtil.isNotEmpty(fileIds)) {
            AttachmentDto attachmentDto = AttachmentDto.builder()
                    .setEntityId(id)
                    .setChildEnum(fileModuleDict)
                    .build();
            attachmentRefService.saveRef(fileIds, attachmentDto);
        }
    }

    @Override
    public VideoDueDiligence getView(Long id) {
        VideoDueDiligence byId = getById(id);
        VideoDueDiligence videoDueDiligence = getVideoDueDiligence(byId.getcSupplierInfoId());
        SupplierInfo supplierInfo = supplierInfoService.get(byId.getcSupplierInfoId());
        Enterprise enterprise = enterpriseService.getById(supplierInfo.getcEnterpriseId());
        if (supplierInfo.getGuaranteeEnterpriseId() != null) {
            enterprise = enterpriseService.getById(supplierInfo.getGuaranteeEnterpriseId());
        }
        List<FileStorage> addressFile = getFiles(id, FileModuleDict.ChildEnum.VIDEO_DUE_DILIGENCE_ADDRESS_FILE);
        byId.setAddressFile(addressFile);
        List<FileStorage> associatedEnterpriseFile = getFiles(id, FileModuleDict.ChildEnum.VIDEO_DUE_DILIGENCE_ASSOCIATED_ENTERPRISE_FILE);
        byId.setAssociatedEnterpriseFile(associatedEnterpriseFile);
        List<FileStorage> businessAddressFile = getFiles(id, FileModuleDict.ChildEnum.VIDEO_DUE_DILIGENCE_BUSINESS_ADDRESS_FILE);
        byId.setBusinessAddressFile(businessAddressFile);
        List<FileStorage> businessScopeFile = getFiles(id, FileModuleDict.ChildEnum.VIDEO_DUE_DILIGENCE_BUSINESS_SCOPE_FILE);
        byId.setBusinessScopeFile(businessScopeFile);
        List<FileStorage> capitalFiles = getFiles(id, FileModuleDict.ChildEnum.VIDEO_DUE_DILIGENCE_CAPITAL_FILE);
        byId.setCapitalFile(capitalFiles);
        List<FileStorage> changeFiles = getFiles(id, FileModuleDict.ChildEnum.VIDEO_DUE_DILIGENCE_CHANGE_FILE);
        byId.setChangeFile(changeFiles);
        List<FileStorage> industryFiles = getFiles(id, FileModuleDict.ChildEnum.VIDEO_DUE_DILIGENCE_INDUSTRY_FILE);
        byId.setIndustryFile(industryFiles);
        List<FileStorage> lifeFiles = getFiles(id, FileModuleDict.ChildEnum.VIDEO_DUE_DILIGENCE_LIFE_FILE);
        byId.setLifeFile(lifeFiles);
        List<FileStorage> negativeInformationFile = getFiles(id, FileModuleDict.ChildEnum.VIDEO_DUE_DILIGENCE_NEGATIVE_INFORMATION_FILE);
        byId.setNegativeInformationFile(negativeInformationFile);
        List<FileStorage> shareholderFiles = getFiles(id, FileModuleDict.ChildEnum.VIDEO_DUE_DILIGENCE_SHAREHOLDER_FILE);
        byId.setShareholderFile(shareholderFiles);
        //视频尽调企业人员
        List<CreditSituation> creditSituations = videoDueDiligence.getCreditSituations();
        List<VideoDueDiligenceShareholdersSituation> videoDueDiligenceShareholdersSituations = videoDueDiligenceShareholdersSituationService.lambdaQuery().eq(VideoDueDiligenceShareholdersSituation::getVideoDueDiligenceId, videoDueDiligence.getId()).list();
        for (CreditSituation creditSituation : creditSituations) {
            for (VideoDueDiligenceShareholdersSituation videoDueDiligenceShareholdersSituation : videoDueDiligenceShareholdersSituations) {
                if (creditSituation.getcCreditInvestigationInfoHistoryId() == videoDueDiligenceShareholdersSituation.getcCreditInvestigationInfoHistoryId()) {
                    creditSituation.setOverdueAccounts(videoDueDiligenceShareholdersSituation.getOverdueAccounts());
                    creditSituation.setTotalOverdueAmountFix(videoDueDiligenceShareholdersSituation.getTotalOverdueAmountFix());
                    creditSituation.setOver90DaysOverdue(videoDueDiligenceShareholdersSituation.getOver90DaysOverdue());
                    creditSituation.setOverdueMonths(videoDueDiligenceShareholdersSituation.getOverdueMonths());
                    creditSituation.setNumberOfOverdueRepayments(videoDueDiligenceShareholdersSituation.getNumberOfOverdueRepayments());
                    creditSituation.setNumberOfLoanInquiries(videoDueDiligenceShareholdersSituation.getNumberOfLoanInquiries());
                    creditSituation.setRepaymentGuaranteeAmount(videoDueDiligenceShareholdersSituation.getRepaymentGuaranteeAmount());
                    creditSituation.setBadRecordsFix(videoDueDiligenceShareholdersSituation.getBadRecordsFix());
                    creditSituation.setRecordOfDishonestyExecutionFix(videoDueDiligenceShareholdersSituation.getRecordOfDishonestyExecutionFix());
                    creditSituation.setExecutedRecordFix(videoDueDiligenceShareholdersSituation.getExecutedRecordFix());
                    creditSituation.setStCountFix(videoDueDiligenceShareholdersSituation.getStCountFix());
                }
            }
        }
        videoDueDiligence.setVideoDueDiligenceShareholdersSituations(videoDueDiligenceShareholdersSituations);
        //视频尽调企业信誉信息
        VideoDueDiligenceCorporateGoodwill videoDueDiligenceCorporateGoodwill = videoDueDiligenceCorporateGoodwillService.lambdaQuery().eq(VideoDueDiligenceCorporateGoodwill::getVideoDueDiligenceId, videoDueDiligence.getId()).one();
        CorporateGoodwill corporateGoodwill = videoDueDiligence.getCorporateGoodwill();
        corporateGoodwill.setVideoDueDiligenceCorporateGoodwill(videoDueDiligenceCorporateGoodwill);
        videoDueDiligence.setVideoDueDiligenceCorporateGoodwill(videoDueDiligenceCorporateGoodwill);
        videoDueDiligence.setCorporateGoodwill(corporateGoodwill);
        //企业经营与财务
        VideoDueDiligenceFinance videoDueDiligenceFinance = videoDueDiligenceFinanceService.lambdaQuery().eq(VideoDueDiligenceFinance::getVideoDueDiligenceId, videoDueDiligence.getId()).one();
        videoDueDiligence.setMainBusinessIncomeFix(videoDueDiligenceFinance.getMainBusinessIncomeFix());
        videoDueDiligence.setMainBusinessCostFix(videoDueDiligenceFinance.getMainBusinessCostFix());
        videoDueDiligence.setMainBusinessProfitFix(videoDueDiligenceFinance.getMainBusinessProfitFix());
        videoDueDiligence.setVideoDueDiligenceFinance(videoDueDiligenceFinance);
        //企业经营情况
        VideoDueDiligenceOperations videoDueDiligenceOperations = videoDueDiligenceOperationsService.lambdaQuery().eq(VideoDueDiligenceOperations::getVideoDueDiligenceId, videoDueDiligence.getId()).one();
        videoDueDiligence.setVideoDueDiligenceOperations(videoDueDiligenceOperations);
        //综合评估
        VideoDueDiligenceComprehensiveEvaluation videoDueDiligenceComprehensiveEvaluation = videoDueDiligenceComprehensiveEvaluationService.lambdaQuery().eq(VideoDueDiligenceComprehensiveEvaluation::getVideoDueDiligenceId, videoDueDiligence.getId()).one();
        videoDueDiligence.setVideoDueDiligenceComprehensiveEvaluation(videoDueDiligenceComprehensiveEvaluation);
        return videoDueDiligence;
    }

    private List<FileStorage> getFiles(Long id, FileModuleDict.ChildEnum fileModuleDict) {
        AttachmentDto attachmentDto = AttachmentDto.builder()
                .setEntityId(id)
                .setChildEnum(fileModuleDict)
                .build();
        List<FileStorage> files = attachmentRefService.getFiles(attachmentDto);
        return files;
    }

    @Override
    public VideoDueDiligence measurement(VideoDueDiligence videoDueDiligence) {
        BigDecimal scoreTotal = BigDecimal.ZERO;
        //企业人员情况
        BigDecimal personScore;
        List<VideoDueDiligenceShareholdersSituation> videoDueDiligenceShareholdersSituations = videoDueDiligence.getVideoDueDiligenceShareholdersSituations();
        for (VideoDueDiligenceShareholdersSituation videoDueDiligenceShareholdersSituation : videoDueDiligenceShareholdersSituations) {
            //近两年发生过逾期的账户数得分
            BigDecimal numberOfOverdueAccountsScore = BigDecimal.ZERO;
            if (videoDueDiligenceShareholdersSituation.getOverdueAccounts().equals(0L)) {
                numberOfOverdueAccountsScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.NO_OVERDUE_STANDARD);
            } else if (videoDueDiligenceShareholdersSituation.getOverdueAccounts() < 3L && videoDueDiligenceShareholdersSituation.getTotalOverdueAmountFix().compareTo(new BigDecimal("5000")) == -1) {
                numberOfOverdueAccountsScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.OVERDUE_STANDARD_ONE);
            } else if (videoDueDiligenceShareholdersSituation.getOverdueAccounts() < 3L && videoDueDiligenceShareholdersSituation.getTotalOverdueAmountFix().compareTo(new BigDecimal("5000")) > -1) {
                numberOfOverdueAccountsScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.OVERDUE_STANDARD_TWO);
            } else if (videoDueDiligenceShareholdersSituation.getOverdueAccounts() > 3L && videoDueDiligenceShareholdersSituation.getTotalOverdueAmountFix().compareTo(new BigDecimal("5000")) == -1) {
                numberOfOverdueAccountsScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.OVERDUE_STANDARD_THREE);
            } else if (videoDueDiligenceShareholdersSituation.getOverdueAccounts() > 3L && videoDueDiligenceShareholdersSituation.getTotalOverdueAmountFix().compareTo(new BigDecimal("5000")) > -1) {
                numberOfOverdueAccountsScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.OVERDUE_STANDARD_FORE);
            }
            videoDueDiligenceShareholdersSituation.setNumberOfOverdueAccountsScore(numberOfOverdueAccountsScore);
            //账户是否发生过90天以上逾期得分
            BigDecimal overdueScore;
            if (videoDueDiligenceShareholdersSituation.getOver90DaysOverdue().equals(0)) {
                overdueScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.OVERDUE_90DAYS_STANDARD_ONE);
            } else {
                overdueScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.OVERDUE_90DAYS_STANDARD_TWO);
            }
            videoDueDiligenceShareholdersSituation.setOverdueScore(overdueScore);
            //近两年贷款、信用卡连续逾期的月数
            BigDecimal consecutiveOverdueMonthScore = BigDecimal.ZERO;
            if (videoDueDiligenceShareholdersSituation.getOverdueMonths().equals(0L) && videoDueDiligenceShareholdersSituation.getNumberOfOverdueRepayments().equals(0L)) {
                consecutiveOverdueMonthScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.OVERDUE_THREE_SIX_STANDARD_ONE);
            } else if (videoDueDiligenceShareholdersSituation.getOverdueMonths().equals(0L) && videoDueDiligenceShareholdersSituation.getNumberOfOverdueRepayments() <= 5L) {
                consecutiveOverdueMonthScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.OVERDUE_THREE_SIX_STANDARD_TWO);
            } else if (videoDueDiligenceShareholdersSituation.getOverdueMonths().equals(0L) && videoDueDiligenceShareholdersSituation.getNumberOfOverdueRepayments() > 5L) {
                consecutiveOverdueMonthScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.OVERDUE_THREE_SIX_STANDARD_THREE);
            } else if (videoDueDiligenceShareholdersSituation.getOverdueMonths() <= 2L && videoDueDiligenceShareholdersSituation.getNumberOfOverdueRepayments().equals(0L)) {
                consecutiveOverdueMonthScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.OVERDUE_THREE_SIX_STANDARD_FORE);
            } else if (videoDueDiligenceShareholdersSituation.getOverdueMonths() <= 2L && videoDueDiligenceShareholdersSituation.getNumberOfOverdueRepayments() <= 5L) {
                consecutiveOverdueMonthScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.OVERDUE_THREE_SIX_STANDARD_FIVE);
            } else if (videoDueDiligenceShareholdersSituation.getOverdueMonths() <= 2L && videoDueDiligenceShareholdersSituation.getNumberOfOverdueRepayments() > 5L) {
                consecutiveOverdueMonthScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.OVERDUE_THREE_SIX_STANDARD_SIX);
            } else if (videoDueDiligenceShareholdersSituation.getOverdueMonths() > 2L && videoDueDiligenceShareholdersSituation.getNumberOfOverdueRepayments().equals(0L)) {
                consecutiveOverdueMonthScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.OVERDUE_THREE_SIX_STANDARD_SEVEN);
            } else if (videoDueDiligenceShareholdersSituation.getOverdueMonths() > 2L && videoDueDiligenceShareholdersSituation.getNumberOfOverdueRepayments() <= 5L) {
                consecutiveOverdueMonthScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.OVERDUE_THREE_SIX_STANDARD_EIGHT);
            } else if (videoDueDiligenceShareholdersSituation.getOverdueMonths() > 2L && videoDueDiligenceShareholdersSituation.getNumberOfOverdueRepayments() > 5L) {
                consecutiveOverdueMonthScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.OVERDUE_THREE_SIX_STANDARD_NINE);
            }
            videoDueDiligenceShareholdersSituation.setConsecutiveOverdueMonthScore(consecutiveOverdueMonthScore);
            //近半年来贷款审批查询次数
            BigDecimal numberOfApprovalQueriesScore;
            if (videoDueDiligenceShareholdersSituation.getNumberOfLoanInquiries() <= 6L) {
                numberOfApprovalQueriesScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.CREDIT_INQUIRY_STANDARD_ONE);
            } else {
                numberOfApprovalQueriesScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.CREDIT_INQUIRY_STANDARD_TWO);
            }
            videoDueDiligenceShareholdersSituation.setNumberOfApprovalQueriesScore(numberOfApprovalQueriesScore);
            //相关还款担保责任金额（为非授信主体的担保）
            BigDecimal amountOfGuaranteeLiabilityScore;
            if (videoDueDiligenceShareholdersSituation.getRepaymentGuaranteeAmount().compareTo(new BigDecimal("5000000")) < 1) {
                amountOfGuaranteeLiabilityScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.GUARANTEE_AMOUNT_STANDARD_ONE);
            } else {
                amountOfGuaranteeLiabilityScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.GUARANTEE_AMOUNT_STANDARD_TWO);
            }
            videoDueDiligenceShareholdersSituation.setAmountOfGuaranteeLiabilityScore(amountOfGuaranteeLiabilityScore);
            //关注类和不良类贷款记录 0无 1有
            BigDecimal badRecordsScore;
            if (videoDueDiligenceShareholdersSituation.getBadRecordsFix() == 0) {
                badRecordsScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.NON_PERFORMING_LOANS_STANDARD_NO);
            } else {
                badRecordsScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.NON_PERFORMING_LOANS_STANDARD_YES);
            }
            videoDueDiligenceShareholdersSituation.setBadRecordsScore(badRecordsScore);
            //失信被执行记录 0无 1有
            BigDecimal shiXinScore;
            if (videoDueDiligenceShareholdersSituation.getRecordOfDishonestyExecutionFix() > 0) {
                shiXinScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.SHI_XIN_STANDARD_YES);
            } else {
                shiXinScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.SHI_XIN_STANDARD_NO);
            }
            videoDueDiligenceShareholdersSituation.setShiXinScore(shiXinScore);
            //被执行记录 0无 1有
            BigDecimal zhiXingScore;
            if (videoDueDiligenceShareholdersSituation.getExecutedRecordFix() > 0) {
                zhiXingScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.ZHI_XING_STANDARD_YES);
            } else {
                zhiXingScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.ZHI_XING_STANDARD_NO);
            }
            videoDueDiligenceShareholdersSituation.setZhiXingScore(zhiXingScore);
            BigDecimal stCountScore;
            if (videoDueDiligenceShareholdersSituation.getStCountFix() > 0) {
                stCountScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.ST_STANDARD_YES);
            } else {
                stCountScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.ST_STANDARD_NO);
            }
            videoDueDiligenceShareholdersSituation.setStCountScore(stCountScore);
            personScore = numberOfOverdueAccountsScore.add(overdueScore).add(consecutiveOverdueMonthScore)
                    .add(numberOfApprovalQueriesScore).add(amountOfGuaranteeLiabilityScore).add(badRecordsScore)
                    .add(shiXinScore).add(zhiXingScore).add(stCountScore);
            scoreTotal = scoreTotal.add(personScore.divide(new BigDecimal(videoDueDiligenceShareholdersSituations.size()), 3, RoundingMode.HALF_UP));
        }
        //企业信誉
        VideoDueDiligenceCorporateGoodwill videoDueDiligenceCorporateGoodwill = videoDueDiligence.getVideoDueDiligenceCorporateGoodwill();
        BigDecimal recoveredBalanceScore;
        if (videoDueDiligenceCorporateGoodwill.getRecoveredBalance() == 0) {
            recoveredBalanceScore = SupplierScoringModel.ENTERPRISE_GOODWILL_RATIO.multiply(SupplierScoringModel.BAD_BALANCE_STANDARD_NO);
        } else {
            recoveredBalanceScore = SupplierScoringModel.ENTERPRISE_GOODWILL_RATIO.multiply(SupplierScoringModel.BAD_BALANCE_STANDARD_YES);
        }
        scoreTotal = scoreTotal.add(recoveredBalanceScore);
        videoDueDiligenceCorporateGoodwill.setRecoveredBalanceScore(recoveredBalanceScore);
        BigDecimal concernedAccountsWithOutstandingCreditScore;
        if (videoDueDiligenceCorporateGoodwill.getUnclearFollowUpAccounts() == 0) {
            concernedAccountsWithOutstandingCreditScore = SupplierScoringModel.ENTERPRISE_GOODWILL_RATIO.multiply(SupplierScoringModel.UNCLEARED_FOCUS_STANDARD_NO);
        } else {
            concernedAccountsWithOutstandingCreditScore = SupplierScoringModel.ENTERPRISE_GOODWILL_RATIO.multiply(SupplierScoringModel.UNCLEARED_FOCUS_STANDARD_YES);
        }
        scoreTotal = scoreTotal.add(concernedAccountsWithOutstandingCreditScore);
        videoDueDiligenceCorporateGoodwill.setConcernedAccountsWithOutstandingCreditScore(concernedAccountsWithOutstandingCreditScore);
        BigDecimal outstandingNonPerformingAccountsScore;
        if (videoDueDiligenceCorporateGoodwill.getOutstandingNonPerformingAccounts() == 0) {
            outstandingNonPerformingAccountsScore = SupplierScoringModel.ENTERPRISE_GOODWILL_RATIO.multiply(SupplierScoringModel.UNCLEARED_BAD_STANDARD_NO);
        } else {
            outstandingNonPerformingAccountsScore = SupplierScoringModel.ENTERPRISE_GOODWILL_RATIO.multiply(SupplierScoringModel.UNCLEARED_BAD_STANDARD_YES);
        }
        scoreTotal = scoreTotal.add(outstandingNonPerformingAccountsScore);
        videoDueDiligenceCorporateGoodwill.setOutstandingNonPerformingAccountsScore(outstandingNonPerformingAccountsScore);
        BigDecimal outstandingBalanceScore;
        if (videoDueDiligenceCorporateGoodwill.getOutstandingShortTermLoanBalance().compareTo(new BigDecimal("10000000")) < 1) {
            outstandingBalanceScore = SupplierScoringModel.ENTERPRISE_GOODWILL_RATIO.multiply(SupplierScoringModel.UNCLEARED_LOAN_BALANCE_STANDARD_ONE);
        } else {
            outstandingBalanceScore = SupplierScoringModel.ENTERPRISE_GOODWILL_RATIO.multiply(SupplierScoringModel.UNCLEARED_LOAN_BALANCE_STANDARD_TWO);
        }
        scoreTotal = scoreTotal.add(outstandingBalanceScore);
        videoDueDiligenceCorporateGoodwill.setOutstandingBalanceScore(outstandingBalanceScore);
        SupplierInfo supplierInfo = supplierInfoService.get(videoDueDiligence.getcSupplierInfoId());
        Long enterpriseId = supplierInfo.getcEnterpriseId();
        if (supplierInfo.getGuaranteeEnterpriseId() != null) {
            enterpriseId = supplierInfo.getGuaranteeEnterpriseId();
        }
        CorporateGoodwill corporateGoodwill = corporateGoodwillService.lambdaQuery().eq(CorporateGoodwill::getcSupplierInfoId, supplierInfo.getId()).eq(CorporateGoodwill::getcEnterpriseId, enterpriseId).one();
        scoreTotal = scoreTotal.add(corporateGoodwill.getShiXinScore());
        scoreTotal = scoreTotal.add(corporateGoodwill.getZhiXingScore());
        scoreTotal = scoreTotal.add(corporateGoodwill.getSumptuaryScore());
        scoreTotal = scoreTotal.add(corporateGoodwill.getAdministrativePenaltyScore());
        scoreTotal = scoreTotal.add(corporateGoodwill.getInvolvingLawsuitsScore());
        List<SeriousIllegality> seriousIllegalities = videoDueDiligence.getSeriousIllegalities();
        BigDecimal seriousIllegalitiesMultiply;
        if (CollectionUtil.isEmpty(seriousIllegalities)) {
            long count = seriousIllegalities.stream().filter(r -> r.getVideoDueDiligenceSeriousIllegality() == 1).count();
            if (count > 0) {
                seriousIllegalitiesMultiply = BigDecimal.ZERO;
            } else {
                seriousIllegalitiesMultiply = SupplierScoringModel.ENTERPRISE_GOODWILL_RATIO.multiply(SupplierScoringModel.ENTERPRISE_OPERATING_RISK_STANDARD_ONE);
            }
        } else {
            seriousIllegalitiesMultiply = SupplierScoringModel.ENTERPRISE_GOODWILL_RATIO.multiply(SupplierScoringModel.ENTERPRISE_OPERATING_RISK_STANDARD_ONE);
        }
        scoreTotal = scoreTotal.add(seriousIllegalitiesMultiply);
        List<TaxOweNotice> taxOweNotices = videoDueDiligence.getTaxOweNotices();
        BigDecimal taxOweNoticesScope;
        if (taxOweNotices.isEmpty()) {
            long count = taxOweNotices.stream().filter(r -> r.getVideoDueDiligenceTaxOweNotice() == 1).count();
            if (count > 0) {
                taxOweNoticesScope = BigDecimal.ZERO;
            } else {
                taxOweNoticesScope = SupplierScoringModel.ENTERPRISE_GOODWILL_RATIO.multiply(SupplierScoringModel.ENTERPRISE_OPERATING_RISK_STANDARD_TWO);
            }
        } else {
            taxOweNoticesScope = SupplierScoringModel.ENTERPRISE_GOODWILL_RATIO.multiply(SupplierScoringModel.ENTERPRISE_OPERATING_RISK_STANDARD_TWO);
        }
        scoreTotal = scoreTotal.add(taxOweNoticesScope);
        List<TaxIllegalData> taxIllegalData = videoDueDiligence.getTaxIllegalData();
        BigDecimal taxIllegalDataScope;
        if (CollectionUtil.isEmpty(taxIllegalData)) {
            long count = taxIllegalData.stream().filter(r -> r.getVideoDueDiligenceTaxIllegal() == 1).count();
            if (count > 0) {
                taxIllegalDataScope = BigDecimal.ZERO;
            } else {
                taxIllegalDataScope = SupplierScoringModel.ENTERPRISE_GOODWILL_RATIO.multiply(SupplierScoringModel.ENTERPRISE_OPERATING_RISK_STANDARD_THREE);
            }
        } else {
            taxIllegalDataScope = SupplierScoringModel.ENTERPRISE_GOODWILL_RATIO.multiply(SupplierScoringModel.ENTERPRISE_OPERATING_RISK_STANDARD_THREE);
        }
        scoreTotal = scoreTotal.add(taxIllegalDataScope);
        List<Blacklist> blacklists = videoDueDiligence.getBlacklists();
        BigDecimal blacklistsScope;
        if (CollectionUtil.isEmpty(blacklists)) {
            long count = blacklists.stream().filter(r -> r.getVideoDueDiligenceBlacklist() == 1).count();
            if (count > 0) {
                blacklistsScope = BigDecimal.ZERO;
            } else {
                blacklistsScope = SupplierScoringModel.ENTERPRISE_GOODWILL_RATIO.multiply(SupplierScoringModel.ENTERPRISE_OPERATING_RISK_STANDARD_FORE);
            }
        } else {
            blacklistsScope = SupplierScoringModel.ENTERPRISE_GOODWILL_RATIO.multiply(SupplierScoringModel.ENTERPRISE_OPERATING_RISK_STANDARD_FORE);
        }
        scoreTotal = scoreTotal.add(blacklistsScope);
        List<ExceptionData> exceptionData = videoDueDiligence.getExceptionData();
        BigDecimal exceptionDataScope;
        if (CollectionUtil.isEmpty(exceptionData)) {
            long count = exceptionData.stream().filter(r -> r.getVideoDueDiligenceException() == 1).count();
            if (count > 0) {
                exceptionDataScope = BigDecimal.ZERO;
            } else {
                exceptionDataScope = SupplierScoringModel.ENTERPRISE_GOODWILL_RATIO.multiply(SupplierScoringModel.ENTERPRISE_OPERATING_RISK_STANDARD_FIVE);
            }
        } else {
            exceptionDataScope = SupplierScoringModel.ENTERPRISE_GOODWILL_RATIO.multiply(SupplierScoringModel.ENTERPRISE_OPERATING_RISK_STANDARD_FIVE);
        }
        scoreTotal = scoreTotal.add(exceptionDataScope);
        List<News> news = videoDueDiligence.getNews();
        BigDecimal newsScope;
        if (CollectionUtil.isEmpty(news)) {
            long count = news.stream().filter(r -> r.getVideoDueDiligenceNews() == 1).count();
            if (count > 0) {
                newsScope = BigDecimal.ZERO;
            } else {
                newsScope = SupplierScoringModel.ENTERPRISE_GOODWILL_RATIO.multiply(SupplierScoringModel.ENTERPRISE_OPERATING_RISK_STANDARD_SIX);
            }
        } else {
            newsScope = SupplierScoringModel.ENTERPRISE_GOODWILL_RATIO.multiply(SupplierScoringModel.ENTERPRISE_OPERATING_RISK_STANDARD_SIX);
        }
        scoreTotal = scoreTotal.add(newsScope);
        //企业经营与财务
        VideoDueDiligenceFinance videoDueDiligenceFinance = videoDueDiligence.getVideoDueDiligenceFinance();
        BigDecimal incomeScore;
        if (videoDueDiligenceFinance.getMainBusinessIncomeFix().compareTo(new BigDecimal("100000000")) > -1) {
            incomeScore = SupplierScoringModel.ENTERPRISE_FINANCE_RATIO.multiply(SupplierScoringModel.ENTERPRISE_CORPORATE_FINANCE_STANDARD_ONE);
        } else {
            incomeScore = SupplierScoringModel.ENTERPRISE_FINANCE_RATIO.multiply(SupplierScoringModel.ENTERPRISE_CORPORATE_FINANCE_STANDARD_TWO);
        }
        scoreTotal = scoreTotal.add(incomeScore);
        videoDueDiligenceFinance.setMainBusinessIncomeScore(incomeScore);
        if (videoDueDiligenceFinance.getMainBusinessProfitFix().compareTo(new BigDecimal("3")) > -1) {
            BigDecimal mainBusinessProfitScore = SupplierScoringModel.ENTERPRISE_FINANCE_RATIO.multiply(SupplierScoringModel.ENTERPRISE_CORPORATE_FINANCE_STANDARD_THREE);
            videoDueDiligenceFinance.setMainBusinessProfitScore(mainBusinessProfitScore);
            scoreTotal = scoreTotal.add(mainBusinessProfitScore);
        }
        SupplierApprovalSecond supplierApprovalSecond = supplierApprovalSecondService.lambdaQuery().eq(SupplierApprovalSecond::getcSupplierInfoId, videoDueDiligence.getcSupplierInfoId()).orderByDesc(SupplierApprovalSecond::getGmtCreate).list().get(0);
        scoreTotal = scoreTotal.add(supplierApprovalSecond.getShareholderScore()).add(supplierApprovalSecond.getEstablishmentPeriodScore()).add(supplierApprovalSecond.getRegisteredCapitalScore())
                .add(supplierApprovalSecond.getRegisteredAddressScore()).add(supplierApprovalSecond.getBusinessAddressScore()).add(supplierApprovalSecond.getIndustryScore())
                .add(supplierApprovalSecond.getBusinessScopeScore()).add(supplierApprovalSecond.getBasicChangeScore());
        String incomeLevel;
        if (videoDueDiligenceFinance.getMainBusinessIncomeFix().compareTo(new BigDecimal("50000000")) == -1) {
            incomeLevel = SupplierScoringModel.INCOME_LEVEL_E;
        } else if (videoDueDiligenceFinance.getMainBusinessIncomeFix().compareTo(new BigDecimal("50000000")) == 1 && videoDueDiligenceFinance.getMainBusinessIncomeFix().compareTo(new BigDecimal("100000000")) == -1) {
            incomeLevel = SupplierScoringModel.INCOME_LEVEL_D;
        } else if (videoDueDiligenceFinance.getMainBusinessIncomeFix().compareTo(new BigDecimal("100000000")) == 1 && videoDueDiligenceFinance.getMainBusinessIncomeFix().compareTo(new BigDecimal("500000000")) == -1) {
            incomeLevel = SupplierScoringModel.INCOME_LEVEL_C;
        } else if (videoDueDiligenceFinance.getMainBusinessIncomeFix().compareTo(new BigDecimal("500000000")) == 1 && videoDueDiligenceFinance.getMainBusinessIncomeFix().compareTo(new BigDecimal("1500000000")) == -1) {
            incomeLevel = SupplierScoringModel.INCOME_LEVEL_B;
        } else {
            incomeLevel = SupplierScoringModel.INCOME_LEVEL_A;
        }
        //上游
        List<UpstreamProcurementDocuments> upstreamProcurementDocumentsList = videoDueDiligence.getUpstreamProcurementDocumentsList();
        BigDecimal upstreamScore = BigDecimal.ZERO;
        if (CollectionUtil.isNotEmpty(upstreamProcurementDocumentsList)) {
            for (UpstreamProcurementDocuments upstreamProcurementDocuments : upstreamProcurementDocumentsList) {
                if (upstreamProcurementDocuments.getResult() == 1) {
                    BigDecimal score = SupplierScoringModel.ENTERPRISE_FINANCE_RATIO.multiply(SupplierScoringModel.UPSTREAN_PROCUREMENT_STANDARD_THREE);
                    upstreamProcurementDocuments.setScore(score);
                    upstreamScore = upstreamScore.add(score);
                } else {
                    upstreamProcurementDocuments.setScore(BigDecimal.ZERO);
                }
            }
        }
        BigDecimal upstreamScoreMax = SupplierScoringModel.ENTERPRISE_FINANCE_RATIO.multiply(SupplierScoringModel.UPSTREAN_PROCUREMENT_STANDARD_THREE).multiply(new BigDecimal("2"));
        if (upstreamScore.compareTo(upstreamScoreMax) == 1) {
            scoreTotal = scoreTotal.add(upstreamScoreMax);
        } else {
            scoreTotal = scoreTotal.add(upstreamScore);
        }
        //下游
        List<SalesDocumentsInfo> salesDocumentsInfoList = videoDueDiligence.getSalesDocumentsInfoList();
        BigDecimal salesScore = BigDecimal.ZERO;
        if (CollectionUtil.isNotEmpty(salesDocumentsInfoList)) {
            for (SalesDocumentsInfo salesDocumentsInfo : salesDocumentsInfoList) {
                if (salesDocumentsInfo.getResult() == 1) {
                    BigDecimal score = SupplierScoringModel.ENTERPRISE_FINANCE_RATIO.multiply(SupplierScoringModel.SALES_DOCUMENTS_STANDARD_THREE);
                    salesDocumentsInfo.setScore(score);
                    salesScore = salesScore.add(score);
                } else {
                    salesDocumentsInfo.setScore(BigDecimal.ZERO);
                }
            }
        }
        BigDecimal supplierScoreMax = SupplierScoringModel.ENTERPRISE_FINANCE_RATIO.multiply(SupplierScoringModel.SALES_DOCUMENTS_STANDARD_THREE).multiply(new BigDecimal("2"));
        if (salesScore.compareTo(supplierScoreMax) == 1) {
            scoreTotal = scoreTotal.add(supplierScoreMax);
        } else {
            scoreTotal = scoreTotal.add(salesScore);
        }
        // 综合评估
        VideoDueDiligenceComprehensiveEvaluation videoDueDiligenceComprehensiveEvaluation = videoDueDiligence.getVideoDueDiligenceComprehensiveEvaluation();
        if (videoDueDiligenceComprehensiveEvaluation == null) {
            videoDueDiligenceComprehensiveEvaluation = new VideoDueDiligenceComprehensiveEvaluation();
        }
        videoDueDiligenceComprehensiveEvaluation.setRevenueRating(incomeLevel);
        videoDueDiligenceComprehensiveEvaluation.setScore(scoreTotal);
        BigDecimal fixScore = videoDueDiligence.getFixScore();
        if(fixScore != null){
            scoreTotal = fixScore;
            videoDueDiligenceComprehensiveEvaluation.setFixScore(fixScore);
        }
        BigDecimal creditLimit = BigDecimal.ZERO;
        if (scoreTotal.compareTo(new BigDecimal("90")) >= 0 && scoreTotal.compareTo(new BigDecimal("94")) == -1) {
            if (incomeLevel.equals(SupplierScoringModel.INCOME_LEVEL_E)) {
                creditLimit = new BigDecimal("500");
            } else if (incomeLevel.equals(SupplierScoringModel.INCOME_LEVEL_D)) {
                creditLimit = new BigDecimal("500");
            } else if (incomeLevel.equals(SupplierScoringModel.INCOME_LEVEL_C)) {
                creditLimit = new BigDecimal("500");
            } else if (incomeLevel.equals(SupplierScoringModel.INCOME_LEVEL_B)) {
                creditLimit = new BigDecimal("1000");
            } else if (incomeLevel.equals(SupplierScoringModel.INCOME_LEVEL_A)) {
                creditLimit = new BigDecimal("1000");
            }
        } else if (scoreTotal.compareTo(new BigDecimal("94")) >= 0 && scoreTotal.compareTo(new BigDecimal("96")) == -1) {
            if (incomeLevel.equals(SupplierScoringModel.INCOME_LEVEL_E)) {
                creditLimit = new BigDecimal("1000");
            } else if (incomeLevel.equals(SupplierScoringModel.INCOME_LEVEL_D)) {
                creditLimit = new BigDecimal("1000");
            } else if (incomeLevel.equals(SupplierScoringModel.INCOME_LEVEL_C)) {
                creditLimit = new BigDecimal("1000");
            } else if (incomeLevel.equals(SupplierScoringModel.INCOME_LEVEL_B)) {
                creditLimit = new BigDecimal("1000");
            } else if (incomeLevel.equals(SupplierScoringModel.INCOME_LEVEL_A)) {
                creditLimit = new BigDecimal("2000");
            }
        } else if (scoreTotal.compareTo(new BigDecimal("96")) >= 0 && scoreTotal.compareTo(new BigDecimal("98")) == -1) {
            if (incomeLevel.equals(SupplierScoringModel.INCOME_LEVEL_E)) {
                creditLimit = new BigDecimal("1000");
            } else if (incomeLevel.equals(SupplierScoringModel.INCOME_LEVEL_D)) {
                creditLimit = new BigDecimal("2000");
            } else if (incomeLevel.equals(SupplierScoringModel.INCOME_LEVEL_C)) {
                creditLimit = new BigDecimal("2000");
            } else if (incomeLevel.equals(SupplierScoringModel.INCOME_LEVEL_B)) {
                creditLimit = new BigDecimal("2000");
            } else if (incomeLevel.equals(SupplierScoringModel.INCOME_LEVEL_A)) {
                creditLimit = new BigDecimal("3000");
            }
        } else if (scoreTotal.compareTo(new BigDecimal("98")) >= 0 && scoreTotal.compareTo(new BigDecimal("100")) <= 0) {
            if (incomeLevel.equals(SupplierScoringModel.INCOME_LEVEL_E)) {
                creditLimit = new BigDecimal("2000");
            } else if (incomeLevel.equals(SupplierScoringModel.INCOME_LEVEL_D)) {
                creditLimit = new BigDecimal("2000");
            } else if (incomeLevel.equals(SupplierScoringModel.INCOME_LEVEL_C)) {
                creditLimit = new BigDecimal("2000");
            } else if (incomeLevel.equals(SupplierScoringModel.INCOME_LEVEL_B)) {
                creditLimit = new BigDecimal("2000");
            } else if (incomeLevel.equals(SupplierScoringModel.INCOME_LEVEL_A)) {
                creditLimit = new BigDecimal("3000");
            }
        }
        videoDueDiligenceComprehensiveEvaluation.setCreditLimit(creditLimit);
        if (scoreTotal.compareTo(new BigDecimal("90")) == -1) {
            videoDueDiligenceComprehensiveEvaluation.setAdmitted(SupplierScoringModel.NOT_ADMITTED);
        } else {
            videoDueDiligenceComprehensiveEvaluation.setAdmitted(SupplierScoringModel.ADMITTED);
        }
        videoDueDiligence.setVideoDueDiligenceComprehensiveEvaluation(videoDueDiligenceComprehensiveEvaluation);
        return videoDueDiligence;
    }

}
