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

import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jfinal.json.Json;
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.exception.ServiceException;
import com.sunxung.factoring.component.exception.ValidatorException;
import com.sunxung.factoring.component.util.*;
import com.sunxung.factoring.dict.impl.FileModuleDict;
import com.sunxung.factoring.entity.ResponseJson;
import com.sunxung.factoring.entity.entprise.Enterprise;
import com.sunxung.factoring.entity.project.BusinessProcessingLog;
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.entity.sys.User;
import com.sunxung.factoring.mapper.supplier.SupplierApprovalSecondMapper;
import com.sunxung.factoring.service.creditresolution.ICreditResolutionService;
import com.sunxung.factoring.service.entprise.IEnterpriseService;
import com.sunxung.factoring.service.project.BusinessProcessingLogService;
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.FileService;
import com.sunxung.factoring.service.sys.ISysAttachmentRefService;
import com.sunxung.factoring.service.sys.UserService;
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.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 供应商审核第二步 服务实现类
 * </p>
 *
 * @author liutao
 * @since 2023-12-05
 */
@Service("second_reviewService")
public class SupplierApprovalSecondServiceImpl extends ServiceImpl<SupplierApprovalSecondMapper, SupplierApprovalSecond> implements ISupplierApprovalSecondService {

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

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

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

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

    @Autowired
    private IDueDiligenceAllocationService dueDiligenceAllocationService;

    @Autowired
    private UserService userService;

    @Autowired
    private BusinessProcessingLogService businessProcessingLogService;

    @Autowired
    private ICSupplierInfoHistoryService supplierInfoHistoryService;

    @Autowired
    private FileService fileService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ICEnterpriseHistoryService enterpriseHistoryService;

    @Autowired
    private ICSalesDocumentsInfoHistoryService cSalesDocumentsInfoHistoryService;

    @Autowired
    private ICUpstreamProcurementDocumentsHistoryService cUpstreamProcurementDocumentsHistoryService;

    @Autowired
    private IUpstreamProcurementDocumentsService upstreamProcurementDocumentsService;

    @Autowired
    private ISalesDocumentsInfoService salesDocumentsInfoService;

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

    @Autowired
    private IEnterpriseService enterpriseService;

    @Autowired
    private FlowableService flowableService;

    @Autowired
    private ICCreditInvestigationInfoHistoryService creditInvestigationInfoHistoryService;

    @Autowired
    private ICreditInvestigationInfoService creditInvestigationInfoService;

    @Autowired
    private ICreditSituationService creditSituationService;

    @Autowired
    private ICorporateGoodwillService corporateGoodwillService;

    @Autowired
    private ISeriousIllegalityService seriousIllegalityService;

    @Autowired
    private ITaxOweNoticeService taxOweNoticeService;

    @Autowired
    private ITaxIllegalDataService taxIllegalDataService;

    @Autowired
    private IBlacklistService blacklistService;

    @Autowired
    private IExceptionDataService exceptionDataService;

    @Autowired
    private INewsService newsService;

    @Autowired
    private ISysAttachmentRefService attachmentRefService;

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

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

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

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

    @Override
    public SupplierApprovalSecond getSecondReviewById(Long id) {
        SupplierApprovalSecond supplierApprovalSecond = new SupplierApprovalSecond();
        //获取最后一次供应商C端录入时的log
        BusinessProcessingLog lastLog = businessProcessingLogService.getLastByBusinessKeyBusinessTypeTaskName(id, ConstantUtil.SUPPLIER_INFO, "供应商C端录入");
        CSupplierInfoHistory supplierInfoHistory = supplierInfoHistoryService.getById(lastLog.getFormBusinessId());
        //分配信息
        DueDiligenceAllocation dueDiligenceAllocation = dueDiligenceAllocationService.lambdaQuery().eq(DueDiligenceAllocation::getcSupplierInfoId, id).one();
        User riskManager = userService.get(dueDiligenceAllocation.getRiskManagerId());
        dueDiligenceAllocation.setRiskManager(riskManager);
        supplierApprovalSecond.setDueDiligenceAllocation(dueDiligenceAllocation);

        CEnterpriseHistory enterpriseHistory;
        supplierApprovalSecond.setcSupplierInfoHistoryId(supplierInfoHistory.getId());
        supplierApprovalSecond.setcSupplierInfoId(id);
        SupplierInfo supplierInfo = supplierInfoService.get(id);
        Long enterpriseId;
        if (supplierInfoHistory.getGuaranteeEnterpriseHistoryId() != null) {
            enterpriseId = supplierInfo.getGuaranteeEnterpriseId();
            enterpriseHistory = enterpriseHistoryService.getById(supplierInfoHistory.getGuaranteeEnterpriseHistoryId());
        } else {
            enterpriseId = supplierInfo.getcEnterpriseId();
            enterpriseHistory = enterpriseHistoryService.getById(supplierInfoHistory.getcEnterpriseHistoryId());
        }
        Enterprise enterprise = enterpriseService.getById(enterpriseId);
        CreditInvestigationInfo creditInvestigationInfo = creditInvestigationInfoService.lambdaQuery()
                .eq(CreditInvestigationInfo::getcEnterpriseId, enterpriseId)
                .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());
        supplierApprovalSecond.setAge(age);
        if( age > 55){
            supplierApprovalSecond.setAgeCompliance(0);
        }else {
            supplierApprovalSecond.setAgeCompliance(1);
        }
        //查询文件
        List<FileStorageDO> mapFiles = fileService.findByBusinessId(enterpriseHistory.getId(), FileModuleDict.ChildEnum.ENTERPRISE_LOCATION_MAP_HISTORY.getCode());
        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());
        supplierApprovalSecond.setMapFiles(mapFiles);
        supplierApprovalSecond.setRentalFiles(rentalFiles);
        supplierApprovalSecond.setWaterFiles(waterFiles);
        supplierApprovalSecond.setOfficeFiles(officeFiles);
        supplierApprovalSecond.setcEnterpriseHistoryId(enterpriseHistory.getId());
        supplierApprovalSecond.setBusinessAddress(enterpriseHistory.getBusinessAddress());
        //获取经营范围
        String getScopeUrl = getScope + "?comprehensiveRiskInvestigationId=" + enterpriseHistory.getcComprehensiveRiskInvestigationId();
        String scope = restTemplate.getForObject(getScopeUrl, String.class);
        supplierApprovalSecond.setScope(scope);
        //上游采购单据
        List<CUpstreamProcurementDocumentsHistory> cUpstreamProcurementDocumentsHistories = cUpstreamProcurementDocumentsHistoryService.lambdaQuery().eq(CUpstreamProcurementDocumentsHistory::getcEnterpriseHistoryId, enterpriseHistory.getId()).list();
        if (CollectionUtil.isNotEmpty(cUpstreamProcurementDocumentsHistories)) {
            List<UpstreamProcurementDocuments> upstreamProcurementDocumentsList = cUpstreamProcurementDocumentsHistories.stream().map(r -> {
                List<FileStorageDO> fileStorageDOS = fileService.findByBusinessId(r.getId(), FileModuleDict.ChildEnum.ENTERPRISE_UPSTREAM_DOCUMENTS_HISTORY.getCode());
                UpstreamProcurementDocuments upstreamProcurementDocuments = new UpstreamProcurementDocuments();
                upstreamProcurementDocuments.setFileStorageDOS(fileStorageDOS);
                upstreamProcurementDocuments.setcUpstreamProcurementDocumentsHistoryId(r.getId());
                upstreamProcurementDocuments.setName(r.getName());
                return upstreamProcurementDocuments;
            }).collect(Collectors.toList());
            supplierApprovalSecond.setUpstreamProcurementDocumentsList(upstreamProcurementDocumentsList);
        }
        //下游销售单据
        List<CSalesDocumentsInfoHistory> cSalesDocumentsInfoHistories = cSalesDocumentsInfoHistoryService.lambdaQuery().eq(CSalesDocumentsInfoHistory::getcEnterpriseHistoryId, enterpriseHistory.getId()).list();
        if (CollectionUtil.isNotEmpty(cSalesDocumentsInfoHistories)) {
            List<SalesDocumentsInfo> salesDocumentsInfoList = cSalesDocumentsInfoHistories.stream().map(r -> {
                List<FileStorageDO> fileStorageDOS = fileService.findByBusinessId(r.getId(), FileModuleDict.ChildEnum.ENTERPRISE_SALES_DOCUMENTS_HISTORY.getCode());
                SalesDocumentsInfo salesDocumentsInfo = new SalesDocumentsInfo();
                salesDocumentsInfo.setFileStorageDOS(fileStorageDOS);
                salesDocumentsInfo.setcSalesDocumentsInfoHistoryId(r.getId());
                salesDocumentsInfo.setName(r.getName());
                return salesDocumentsInfo;
            }).collect(Collectors.toList());
            supplierApprovalSecond.setSalesDocumentsInfoList(salesDocumentsInfoList);
        }
        return supplierApprovalSecond;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void secondReview(SupplierApprovalSecond supplierApprovalSecond) {
        String taskId = supplierApprovalSecond.getTaskId();
        SupplierInfo supplierInfo = supplierInfoService.get(supplierApprovalSecond.getcSupplierInfoId());
        Enterprise enterprise = enterpriseService.getById(supplierInfo.getcEnterpriseId());
        //一键测算
        SupplierApprovalSecond measurement = measurement(supplierApprovalSecond);
        supplierInfo.setSupplierErrors(measurement.getSupplierErrors());
        //保存第二次审核信息
        save(supplierApprovalSecond);
        //保存文件
        List<Long> files = supplierApprovalSecond.getFiles();
        if (CollectionUtil.isNotEmpty(files)) {
            AttachmentDto attachmentDto = AttachmentDto.builder()
                    .setEntityId(supplierApprovalSecond.getId())
                    .setChildEnum(FileModuleDict.ChildEnum.SUPPLIER_APPROVAL_MOVABLE_PROPERTY_FINANCING_FILE)
                    .build();
            attachmentRefService.saveRef(files, attachmentDto);
        }
        //保存上游采购单据
        List<UpstreamProcurementDocuments> upstreamProcurementDocumentsList = supplierApprovalSecond.getUpstreamProcurementDocumentsList();
        if (CollectionUtil.isNotEmpty(upstreamProcurementDocumentsList)) {
            for (UpstreamProcurementDocuments upstreamProcurementDocuments : upstreamProcurementDocumentsList) {
                upstreamProcurementDocuments.setSupplierApprovalSecondId(supplierApprovalSecond.getId());
                upstreamProcurementDocumentsService.save(upstreamProcurementDocuments);
            }
        }
        //保存下游销售单据
        List<SalesDocumentsInfo> salesDocumentsInfoList = supplierApprovalSecond.getSalesDocumentsInfoList();
        if (CollectionUtil.isNotEmpty(salesDocumentsInfoList)) {
            for (SalesDocumentsInfo salesDocumentsInfo : salesDocumentsInfoList) {
                salesDocumentsInfo.setSupplierApprovalSecondId(supplierApprovalSecond.getId());
                salesDocumentsInfoService.save(salesDocumentsInfo);
            }
        }
        //完成流程
        String result;
        String approvalConclusion = supplierApprovalSecond.getApprovalConclusion();
        if (approvalConclusion.equals(ConstantConversionUtil.APPROVAL_RESULT_PASS)) {
            BigDecimal score = supplierApprovalSecond.getScore();
            BigDecimal creditLimit = supplierApprovalSecond.getCreditLimit();
            if (score.compareTo(new BigDecimal("90")) > -1 && creditLimit.compareTo(new BigDecimal(10000000)) < 1) {
                result = "授信成功";
                supplierInfo.setStatusStr(SupplierStatusEnums.CREDIT_SUCCESS.getCode());
            } else {
                supplierInfo.setStatusStr(SupplierStatusEnums.DUE_DILIGENCE_APPOINTMENT.getCode());
                result = "待视频尽调";
            }
        } else if (approvalConclusion.equals(ConstantConversionUtil.APPROVAL_RESULT_BACK)) {
            result = "退回";
            supplierInfo.setStatusStr(SupplierStatusEnums.ADD_INFO.getCode());
        } else {
            throw new ValidatorException(CodeUtil.FAIL, "审核结论错误！");
        }
        supplierInfo.setScore(supplierApprovalSecond.getScore());
        supplierInfo.setAdmitted(supplierApprovalSecond.getAdmitted());
        supplierInfo.setCreditLimit(supplierApprovalSecond.getCreditLimit());
        supplierInfo.setRevenueRating(supplierApprovalSecond.getRevenueRating());
        supplierInfoService.updateById(supplierInfo);
        Map<String, Object> procVariables = new HashMap<>();
        procVariables.put("result", result);
        Map<String, Object> msgVariables = new HashMap<>();
        msgVariables.put(ConstantUtil.FLOWABLE_MSG_TITLE, "供应商名称：" + enterprise.getCorporateName());
        if (result.equals("授信成功")) {
            msgVariables.put(ConstantUtil.FLOWABLE_MSG_CONTENT,
                    "供应商名称为“" + enterprise.getCorporateName() + "”的供应商审核已授信成功");
        } else if (result.equals("退回")) {
            msgVariables.put(ConstantUtil.FLOWABLE_MSG_CONTENT,
                    "供应商名称为“" + enterprise.getCorporateName() + "”的供应商已退回进入“"
                            + ConstantConversionUtil.flowBusinessKeyNames.get(ConstantUtil.SUPPLIER_INFO) + "—供应商C端录入，"
                            + ConstantUtil.FLOWABLE_MSG_ASSIGNEE);
        } else if (result.equals("待视频尽调")) {
            msgVariables.put(ConstantUtil.FLOWABLE_MSG_CONTENT,
                    "供应商名称为“" + enterprise.getCorporateName() + "”的供应商已进入“"
                            + ConstantConversionUtil.flowBusinessKeyNames.get(ConstantUtil.SUPPLIER_INFO) + "—供应商审核视频尽调预约，"
                            + ConstantUtil.FLOWABLE_MSG_ASSIGNEE);
        } else {
            throw new ValidatorException(CodeUtil.FAIL, "审核结论错误！");
        }
        flowableService.completeMyTask(taskId, supplierInfo, procVariables, null, supplierApprovalSecond.getId(), msgVariables, ConstantUtil.SUPPLIER_INFO);

        //判断是否开启授信决议
        List<ProjectInformation> projectInformations = projectInformationService.lambdaQuery().eq(ProjectInformation::getcSupplierInfoId, supplierInfo.getId()).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());
                        }
                    }
                }
            }
        }
    }

    @Override
    public SupplierApprovalSecond getView(Long id) {
        SupplierApprovalSecond supplierApprovalSecond = getById(id);
        //分配信息
        DueDiligenceAllocation dueDiligenceAllocation = dueDiligenceAllocationService.lambdaQuery().eq(DueDiligenceAllocation::getcSupplierInfoId, supplierApprovalSecond.getcSupplierInfoId()).one();
        User riskManager = userService.get(dueDiligenceAllocation.getRiskManagerId());
        dueDiligenceAllocation.setRiskManager(riskManager);
        supplierApprovalSecond.setDueDiligenceAllocation(dueDiligenceAllocation);
        //查询文件
        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> mapFiles = fileService.findByBusinessId(enterpriseHistory.getId(), FileModuleDict.ChildEnum.ENTERPRISE_LOCATION_MAP_HISTORY.getCode());
        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());
        supplierApprovalSecond.setMapFiles(mapFiles);
        supplierApprovalSecond.setRentalFiles(rentalFiles);
        supplierApprovalSecond.setWaterFiles(waterFiles);
        supplierApprovalSecond.setOfficeFiles(officeFiles);

        //上游采购单据
        List<UpstreamProcurementDocuments> upstreamProcurementDocumentsList = upstreamProcurementDocumentsService.lambdaQuery().eq(UpstreamProcurementDocuments::getSupplierApprovalSecondId, id).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);
            }
            supplierApprovalSecond.setUpstreamProcurementDocumentsList(upstreamProcurementDocumentsList);
        }
        //下游销售单据
        List<SalesDocumentsInfo> salesDocumentsInfoList = salesDocumentsInfoService.lambdaQuery().eq(SalesDocumentsInfo::getSupplierApprovalSecondId, id).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);
            }
            supplierApprovalSecond.setSalesDocumentsInfoList(salesDocumentsInfoList);
        }
        AttachmentDto attachmentDto = AttachmentDto.builder()
                .setEntityId(supplierApprovalSecond.getId())
                .setChildEnum(FileModuleDict.ChildEnum.SUPPLIER_APPROVAL_MOVABLE_PROPERTY_FINANCING_FILE)
                .build();
        List<FileStorage> files = attachmentRefService.getFiles(attachmentDto);
        supplierApprovalSecond.setFileStorageList(files);
        return supplierApprovalSecond;
    }

    @Override
    public SupplierApprovalSecond measurement(SupplierApprovalSecond supplierApprovalSecond) {
        BigDecimal scoreTotal = BigDecimal.ZERO;
        SupplierInfo supplierInfo = supplierInfoService.get(supplierApprovalSecond.getcSupplierInfoId());
        Long enterPriseId = supplierInfo.getcEnterpriseId();
        if (supplierInfo.getGuaranteeEnterpriseId() != null) {
            enterPriseId = supplierInfo.getGuaranteeEnterpriseId();
        }
        CorporateGoodwill corporateGoodwill = corporateGoodwillService.lambdaQuery()
                .eq(CorporateGoodwill::getcSupplierInfoId, supplierApprovalSecond.getcSupplierInfoId())
                .eq(CorporateGoodwill::getcEnterpriseId, enterPriseId).one();
        Enterprise enterprise = enterpriseService.getById(enterPriseId);
        Integer ageCompliance = supplierApprovalSecond.getAgeCompliance();
        if (supplierApprovalSecond.getShareholderScore() == null) {
            supplierApprovalSecond.setShareholderScore(BigDecimal.ZERO);
            supplierApprovalSecond.setEstablishmentPeriodScore(BigDecimal.ZERO);
            supplierApprovalSecond.setRegisteredCapitalScore(BigDecimal.ZERO);
            supplierApprovalSecond.setRegisteredAddressScore(BigDecimal.ZERO);
            supplierApprovalSecond.setBusinessAddressScore(BigDecimal.ZERO);
            supplierApprovalSecond.setIndustryScore(BigDecimal.ZERO);
            supplierApprovalSecond.setBusinessScopeScore(BigDecimal.ZERO);
            supplierApprovalSecond.setBasicChangeScore(BigDecimal.ZERO);
            String legalRepresentative = enterprise.getLegalRepresentative();
            String majorShareholders = enterprise.getMajorShareholders();
            BigDecimal shareholderScore = BigDecimal.ZERO;
            if (legalRepresentative.equals(majorShareholders)) {
                CreditInvestigationInfo creditInvestigationInfo = creditInvestigationInfoService.lambdaQuery()
                        .eq(CreditInvestigationInfo::getcEnterpriseId, enterPriseId)
                        .eq(CreditInvestigationInfo::getName, legalRepresentative)
                        .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());
                if (age < 55) {
                    shareholderScore = SupplierScoringModel.ENTERPRISE_RATIO.multiply(SupplierScoringModel.SHAREHOLDER_STANDARD);
                    ageCompliance = 1;
                    supplierApprovalSecond.setAgeCompliance(1);
                }
            }else {
                supplierApprovalSecond.setNotice(enterprise.getCorporateName() + ":法人担保且股东担保股份大于67%");
            }
            supplierApprovalSecond.setShareholderScore(shareholderScore);
            Date date = DateUtil.addYears(enterprise.getStartSate(), 2);
            if (date.compareTo(new Date()) < 1) {
                BigDecimal establishmentPeriodScore = SupplierScoringModel.ENTERPRISE_RATIO.multiply(SupplierScoringModel.ESTABLISHMENT_PERIOD_STANDARD);
                supplierApprovalSecond.setEstablishmentPeriodScore(establishmentPeriodScore);
            }
            BigDecimal registeredCapital = new BigDecimal(enterprise.getRegisteredCapital().replace("万元人民币", ""));
            if (registeredCapital.compareTo(new BigDecimal("100")) > -1) {
                BigDecimal registeredCapitalScore = SupplierScoringModel.ENTERPRISE_RATIO.multiply(SupplierScoringModel.REGISTERED_CAPITAL_STANDARD);
                supplierApprovalSecond.setRegisteredCapitalScore(registeredCapitalScore);
            }
            BigDecimal registeredAddressScore = BigDecimal.ZERO;
            //sop获取企业省市区
            String getEnterpriseAreaUrl = getEnterpriseArea + "?comprehensiveRiskInvestigationId=" + enterprise.getcComprehensiveRiskInvestigationId();
            ResponseJson areaData = restTemplate.getForObject(getEnterpriseAreaUrl, ResponseJson.class);
            Object data = areaData.getData();
            if (data == null) {
                throw new ServiceException(CodeUtil.FAIL, "获取企业地址信息出错");
            }
            JSONObject areaJS = new JSONObject(data);
            String province = areaJS.getStr("province");
            String city = areaJS.getStr("city");
            if (province.contains("广东") || province.contains("江苏")) {
                if (city.contains("深圳") || city.contains("广州") || city.contains("佛山") || city.contains("东莞")
                        || city.contains("东莞") || city.contains("东莞") || city.contains("东莞")
                        || city.contains("东莞") || city.contains("东莞") || city.contains("东莞")) {
                    registeredAddressScore = SupplierScoringModel.ENTERPRISE_RATIO.multiply(SupplierScoringModel.REGISTERED_ADDRESS_STANDARD_ONE);
                } else {
                    registeredAddressScore = SupplierScoringModel.ENTERPRISE_RATIO.multiply(SupplierScoringModel.REGISTERED_ADDRESS_STANDARD_TWO);
                }
            } else if (province.contains("山东") || province.contains("浙江")) {
                if (city.contains("青岛") || city.contains("济南") || city.contains("烟台")
                        || city.contains("杭州") || city.contains("宁波") || city.contains("温州")) {
                    registeredAddressScore = SupplierScoringModel.ENTERPRISE_RATIO.multiply(SupplierScoringModel.REGISTERED_ADDRESS_STANDARD_TWO);
                } else {
                    registeredAddressScore = SupplierScoringModel.ENTERPRISE_RATIO.multiply(SupplierScoringModel.REGISTERED_ADDRESS_STANDARD_THREE);
                }
            } else if (province.contains("河南") || province.contains("四川") || province.contains("湖北") || province.contains("福建")
                    || province.contains("湖南") || province.contains("安徽") || province.contains("上海") || province.contains("河北") || province.contains("北京")) {
                if(city.contains("郑州") || city.contains("成都") || city.contains("武汉")
                        || city.contains("福州") || city.contains("泉州") || city.contains("合肥")
                        || city.contains("唐山") || city.contains("长沙") || city.contains("北京") || city.contains("上海")){
                    registeredAddressScore = SupplierScoringModel.ENTERPRISE_RATIO.multiply(SupplierScoringModel.REGISTERED_ADDRESS_STANDARD_THREE);
                }else {
                    registeredAddressScore = SupplierScoringModel.ENTERPRISE_RATIO.multiply(SupplierScoringModel.REGISTERED_ADDRESS_STANDARD_FORE);
                }
            }else if(province.contains("陕西") || province.contains("江西") || province.contains("重庆") ||province.contains("云南")
                    || province.contains("广西") || province.contains("山西") || province.contains("内蒙") || province.contains("贵州")){
                if(city.contains("西安") || city.contains("重庆")){
                    registeredAddressScore = SupplierScoringModel.ENTERPRISE_RATIO.multiply(SupplierScoringModel.REGISTERED_ADDRESS_STANDARD_FORE);
                }else {
                    registeredAddressScore = SupplierScoringModel.ENTERPRISE_RATIO.multiply(SupplierScoringModel.REGISTERED_ADDRESS_STANDARD_FIVE);
                }
            }else if(province.contains("新疆") || province.contains("天津") || province.contains("甘肃") ){
                if(city.contains("甘肃")){
                    registeredAddressScore = SupplierScoringModel.ENTERPRISE_RATIO.multiply(SupplierScoringModel.REGISTERED_ADDRESS_STANDARD_FIVE);
                }else {
                    registeredAddressScore = SupplierScoringModel.ENTERPRISE_RATIO.multiply(SupplierScoringModel.REGISTERED_ADDRESS_STANDARD_SIX);
                }
            }else if(province.contains("海南") || province.contains("宁夏") || province.contains("青海") ||province.contains("西藏")){
                registeredAddressScore = SupplierScoringModel.ENTERPRISE_RATIO.multiply(SupplierScoringModel.REGISTERED_ADDRESS_STANDARD_SEVEN);
            }
            supplierApprovalSecond.setRegisteredAddressScore(registeredAddressScore);
            String getChangesUrl = getChanges + "?comprehensiveRiskInvestigationId=" + enterprise.getcComprehensiveRiskInvestigationId();
            Integer changes = restTemplate.getForObject(getChangesUrl, Integer.class);
            if (changes < 2) {
                BigDecimal basicChangeScore = SupplierScoringModel.ENTERPRISE_RATIO.multiply(SupplierScoringModel.BASIC_CHANGE_STANDARD);
                supplierApprovalSecond.setBasicChangeScore(basicChangeScore);
            }
            //企业负责人情况
            BigDecimal personScore;
            List<CreditSituation> creditSituations = creditSituationService.lambdaQuery()
                    .eq(CreditSituation::getcSupplierInfoId, supplierApprovalSecond.getcSupplierInfoId()).list();
            if (CollectionUtil.isNotEmpty(creditSituations)) {
                creditSituations = creditSituations.stream().filter(r -> {
                    CCreditInvestigationInfoHistory creditInvestigationInfoHistory = creditInvestigationInfoHistoryService.getById(r.getcCreditInvestigationInfoHistoryId());
                    CEnterpriseHistory enterpriseHistoryServiceById = enterpriseHistoryService.getById(creditInvestigationInfoHistory.getcEnterpriseHistoryId());
                    CEnterpriseHistory enterpriseHistory = enterpriseHistoryService.getById(supplierApprovalSecond.getcEnterpriseHistoryId());
                    return enterpriseHistoryServiceById.getCorporateName().equals(enterpriseHistory.getCorporateName());
                }).collect(Collectors.toList());
                for (CreditSituation creditSituation : creditSituations) {
                    CCreditInvestigationInfoHistory creditInvestigationInfoHistory = creditInvestigationInfoHistoryService.getById(creditSituation.getcCreditInvestigationInfoHistoryId());
                    //近两年发生过逾期的账户数得分
                    BigDecimal numberOfOverdueAccountsScore = BigDecimal.ZERO;
                    if (creditSituation.getNumberOfOverdueAccounts().equals(0L)) {
                        numberOfOverdueAccountsScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.NO_OVERDUE_STANDARD);
                    } else if (creditSituation.getNumberOfOverdueAccounts() < 3L && creditSituation.getTotalOverdueAmount().compareTo(new BigDecimal("5000")) == -1) {
                        numberOfOverdueAccountsScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.OVERDUE_STANDARD_ONE);
                    } else if (creditSituation.getNumberOfOverdueAccounts() < 3L && creditSituation.getTotalOverdueAmount().compareTo(new BigDecimal("5000")) > -1) {
                        numberOfOverdueAccountsScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.OVERDUE_STANDARD_TWO);
                    } else if (creditSituation.getNumberOfOverdueAccounts() > 3L && creditSituation.getTotalOverdueAmount().compareTo(new BigDecimal("5000")) == -1) {
                        numberOfOverdueAccountsScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.OVERDUE_STANDARD_THREE);
                    } else if (creditSituation.getNumberOfOverdueAccounts() > 3L && creditSituation.getTotalOverdueAmount().compareTo(new BigDecimal("5000")) > -1) {
                        numberOfOverdueAccountsScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.OVERDUE_STANDARD_FORE);
                    }
                    creditSituation.setNumberOfOverdueAccountsScore(numberOfOverdueAccountsScore);
                    //账户是否发生过90天以上逾期得分
                    BigDecimal overdueScore;
                    if (creditSituation.getOverdue() == 0) {
                        overdueScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.OVERDUE_90DAYS_STANDARD_ONE);
                    } else {
                        overdueScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.OVERDUE_90DAYS_STANDARD_TWO);
                    }
                    creditSituation.setOverdueScore(overdueScore);
                    //近两年贷款、信用卡连续逾期的月数
                    BigDecimal consecutiveOverdueMonthScore = BigDecimal.ZERO;
                    if (creditSituation.getConsecutiveOverdueMonth() == 0 && creditSituation.getAccumulatedOverdueTimes() == 0) {
                        consecutiveOverdueMonthScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.OVERDUE_THREE_SIX_STANDARD_ONE);
                    } else if (creditSituation.getConsecutiveOverdueMonth() == 0 && creditSituation.getAccumulatedOverdueTimes() <= 5L) {
                        consecutiveOverdueMonthScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.OVERDUE_THREE_SIX_STANDARD_TWO);
                    } else if (creditSituation.getConsecutiveOverdueMonth() == 0 && creditSituation.getAccumulatedOverdueTimes() > 5L) {
                        consecutiveOverdueMonthScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.OVERDUE_THREE_SIX_STANDARD_THREE);
                    } else if (creditSituation.getConsecutiveOverdueMonth() <= 2L && creditSituation.getAccumulatedOverdueTimes() == 0L) {
                        consecutiveOverdueMonthScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.OVERDUE_THREE_SIX_STANDARD_FORE);
                    } else if (creditSituation.getConsecutiveOverdueMonth() <= 2L && creditSituation.getAccumulatedOverdueTimes() <= 5L) {
                        consecutiveOverdueMonthScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.OVERDUE_THREE_SIX_STANDARD_FIVE);
                    } else if (creditSituation.getConsecutiveOverdueMonth() <= 2L && creditSituation.getAccumulatedOverdueTimes() > 5L) {
                        consecutiveOverdueMonthScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.OVERDUE_THREE_SIX_STANDARD_SIX);
                    } else if (creditSituation.getConsecutiveOverdueMonth() > 2L && creditSituation.getAccumulatedOverdueTimes() == 0L) {
                        consecutiveOverdueMonthScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.OVERDUE_THREE_SIX_STANDARD_SEVEN);
                    } else if (creditSituation.getConsecutiveOverdueMonth() > 2L && creditSituation.getAccumulatedOverdueTimes() <= 5L) {
                        consecutiveOverdueMonthScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.OVERDUE_THREE_SIX_STANDARD_EIGHT);
                    } else if (creditSituation.getConsecutiveOverdueMonth() > 2L && creditSituation.getAccumulatedOverdueTimes() > 5L) {
                        consecutiveOverdueMonthScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.OVERDUE_THREE_SIX_STANDARD_NINE);
                    }
                    creditSituation.setConsecutiveOverdueMonthScore(consecutiveOverdueMonthScore);
                    //近半年来贷款审批查询次数
                    BigDecimal numberOfApprovalQueriesScore;
                    if (creditSituation.getNumberOfApprovalQueries() <= 6L) {
                        numberOfApprovalQueriesScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.CREDIT_INQUIRY_STANDARD_ONE);
                    } else {
                        numberOfApprovalQueriesScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.CREDIT_INQUIRY_STANDARD_TWO);
                    }
                    creditSituation.setNumberOfApprovalQueriesScore(numberOfApprovalQueriesScore);
                    //相关还款担保责任金额（为非授信主体的担保）
                    BigDecimal amountOfGuaranteeLiabilityScore;
                    if (creditSituation.getAmountOfGuaranteeLiability().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);
                    }
                    creditSituation.setAmountOfGuaranteeLiabilityScore(amountOfGuaranteeLiabilityScore);
                    //关注类和不良类贷款记录 0无 1有
                    BigDecimal badRecordsScore;
                    if (creditSituation.getBadRecords() == 0) {
                        badRecordsScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.NON_PERFORMING_LOANS_STANDARD_NO);
                    } else {
                        badRecordsScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.NON_PERFORMING_LOANS_STANDARD_YES);
                    }
                    creditSituation.setBadRecordsScore(badRecordsScore);
//                    Long dongjiangaoRiskId;
//                    if (creditInvestigationInfoHistory.getType().equals("c_credit_investigation_info_type_1")) {
//                        dongjiangaoRiskId = enterprise.getcDongjiangaoRiskId();
//                    } else if (creditInvestigationInfoHistory.getType().equals("c_credit_investigation_info_type_2")) {
//                        dongjiangaoRiskId = enterprise.getcDongjiangaoRiskBigId();
//                    } else {
//                        dongjiangaoRiskId = enterprise.getcDongjiangaoRiskControllerId();
//                    }
//                    String dongjiangaoRisksUrl = dongjiangaoRisks + "?id=" + dongjiangaoRiskId;
//                    ResponseJson dongjiangaoRisksObject = restTemplate.getForObject(dongjiangaoRisksUrl, ResponseJson.class);
//                    if (dongjiangaoRisksObject == null) {
//                        throw new ServiceException(CodeUtil.FAIL, "董监高风险扫描出错！");
//                    }
//                    JSONObject dongjiangaoRisksObjectData = new JSONObject(dongjiangaoRisksObject.getData());
//                    Integer sxCount = dongjiangaoRisksObjectData.getInt("sxCount");
//                    Integer zxCount = dongjiangaoRisksObjectData.getInt("zxCount");
//                    Integer stCount = dongjiangaoRisksObjectData.getInt("stCount");
                    Integer stCount = creditSituation.getStCount();
                    Integer recordOfDishonestyExecution = creditSituation.getRecordOfDishonestyExecution();
                    Integer executedRecord = creditSituation.getExecutedRecord();
                    BigDecimal shiXinScore;
                    if (recordOfDishonestyExecution == 1) {
                        shiXinScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.SHI_XIN_STANDARD_YES);
                    } else {
                        shiXinScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.SHI_XIN_STANDARD_NO);
                    }
                    creditSituation.setShiXinScore(shiXinScore);
                    BigDecimal zhiXingScore;
                    if (executedRecord == 1) {
                        zhiXingScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.ZHI_XING_STANDARD_YES);
                    } else {
                        zhiXingScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.ZHI_XING_STANDARD_NO);
                    }
                    creditSituation.setZhiXingScore(zhiXingScore);
                    BigDecimal stCountScore;
                    if (stCount == 1) {
                        stCountScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.ST_STANDARD_YES);
                    } else {
                        stCountScore = SupplierScoringModel.PERSON_RATIO.multiply(SupplierScoringModel.ST_STANDARD_NO);
                    }
                    creditSituation.setStCountScore(stCountScore);
                    personScore = numberOfOverdueAccountsScore.add(overdueScore).add(consecutiveOverdueMonthScore)
                            .add(numberOfApprovalQueriesScore).add(amountOfGuaranteeLiabilityScore).add(badRecordsScore)
                            .add(shiXinScore).add(zhiXingScore).add(stCountScore);
                    creditSituationService.updateById(creditSituation);
                    scoreTotal = scoreTotal.add(personScore.divide(new BigDecimal(creditSituations.size()), 3, RoundingMode.HALF_UP));
                }
            }
            //企业商誉
            BigDecimal recoveredBalanceScore;
            if (corporateGoodwill.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);
            }
            corporateGoodwill.setRecoveredBalanceScore(recoveredBalanceScore);
            BigDecimal concernedAccountsWithOutstandingCreditScore;
            if (corporateGoodwill.getConcernedAccountsWithOutstandingCredit() == 0) {
                concernedAccountsWithOutstandingCreditScore = SupplierScoringModel.ENTERPRISE_GOODWILL_RATIO.multiply(SupplierScoringModel.UNCLEARED_FOCUS_STANDARD_NO);
            } else {
                concernedAccountsWithOutstandingCreditScore = SupplierScoringModel.ENTERPRISE_GOODWILL_RATIO.multiply(SupplierScoringModel.UNCLEARED_FOCUS_STANDARD_YES);
            }
            corporateGoodwill.setConcernedAccountsWithOutstandingCreditScore(concernedAccountsWithOutstandingCreditScore);
            BigDecimal outstandingNonPerformingAccountsScore;
            if (corporateGoodwill.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);
            }
            corporateGoodwill.setOutstandingNonPerformingAccountsScore(outstandingNonPerformingAccountsScore);
            BigDecimal outstandingBalanceScore;
            if (corporateGoodwill.getOutstandingBalance().compareTo(new BigDecimal("1000")) < 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);
            }
            corporateGoodwill.setOutstandingBalanceScore(outstandingBalanceScore);
            String getBusinesssScoreUrl = getBusinesssScore + "?comprehensiveRiskInvestigationId=" + enterprise.getcComprehensiveRiskInvestigationId();
            ResponseJson forObject = restTemplate.getForObject(getBusinesssScoreUrl, ResponseJson.class);
            if (forObject == null) {
                throw new ServiceException(CodeUtil.FAIL, "sop接口出错！");
            }
            JSONObject jsonObject = new JSONObject(forObject.getData());
            Integer shiXin = jsonObject.getInt("shiXin");
            Integer historyShiXin = jsonObject.getInt("historyShiXin");
            Integer zhiXing = jsonObject.getInt("zhiXing");
            Integer historyZhiXing = jsonObject.getInt("historyZhiXing");
            Integer gaoXiao = jsonObject.getInt("gaoXiao");
            Integer historyGaoXiao = jsonObject.getInt("historyGaoXiao");
            Integer punish = jsonObject.getInt("punish");
            BigDecimal punishAmount = jsonObject.getBigDecimal("punishAmount");
            Integer documentTotal = jsonObject.getInt("documentTotal");
            Integer documnetBeiGao = jsonObject.getInt("documnetBeiGao");
            Integer documnetYuanGao = jsonObject.getInt("documnetYuanGao");
            Integer documentFinance = jsonObject.getInt("documentFinance");
            corporateGoodwill.setShiXin(shiXin);
            corporateGoodwill.setHistoryShiXin(historyShiXin);
            corporateGoodwill.setZhiXing(zhiXing);
            corporateGoodwill.setHistoryZhiXing(historyZhiXing);
            corporateGoodwill.setGaoXiao(gaoXiao);
            corporateGoodwill.setHistoryGaoXiao(historyGaoXiao);
            corporateGoodwill.setPunish(punish);
            corporateGoodwill.setPunishAmount(punishAmount);
            corporateGoodwill.setDocumentTotal(documentTotal);
            corporateGoodwill.setDocumnetBeiGao(documnetBeiGao);
            corporateGoodwill.setDocumnetYuanGao(documnetYuanGao);
            corporateGoodwill.setDocumentFinance(documentFinance);

            BigDecimal shiXinScore = BigDecimal.ZERO;
            if (shiXin == 0 && historyShiXin == 0) {
                shiXinScore = SupplierScoringModel.ENTERPRISE_GOODWILL_RATIO.multiply(SupplierScoringModel.ENTERPRISE_NO_SHI_XIN_STANDARD);
            } else if (shiXin == 0 && historyShiXin > 0) {
                shiXinScore = SupplierScoringModel.ENTERPRISE_GOODWILL_RATIO.multiply(SupplierScoringModel.ENTERPRISE_HISTORY_SHI_XIN_STANDARD);
            } else if (shiXin > 0 && historyShiXin == 0) {
                shiXinScore = SupplierScoringModel.ENTERPRISE_GOODWILL_RATIO.multiply(SupplierScoringModel.ENTERPRISE_SHI_XIN_STANDARD);
            }
            corporateGoodwill.setShiXinScore(shiXinScore);
            BigDecimal zhiXingScore = BigDecimal.ZERO;
            if (zhiXing == 0 && historyZhiXing == 0) {
                zhiXingScore = SupplierScoringModel.ENTERPRISE_GOODWILL_RATIO.multiply(SupplierScoringModel.ENTERPRISE_NO_ZHI_XING_STANDARD);
            } else if (zhiXing == 0 && historyZhiXing > 0) {
                zhiXingScore = SupplierScoringModel.ENTERPRISE_GOODWILL_RATIO.multiply(SupplierScoringModel.ENTERPRISE_HISTORY_ZHI_XING_STANDARD);
            } else if (zhiXing > 0 && historyZhiXing == 0) {
                zhiXingScore = SupplierScoringModel.ENTERPRISE_GOODWILL_RATIO.multiply(SupplierScoringModel.ENTERPRISE_ZHI_XING_STANDARD);
            }
            corporateGoodwill.setZhiXingScore(zhiXingScore);
            BigDecimal sumptuaryScore = BigDecimal.ZERO;
            if (gaoXiao == 0 && historyGaoXiao == 0) {
                sumptuaryScore = SupplierScoringModel.ENTERPRISE_GOODWILL_RATIO.multiply(SupplierScoringModel.ENTERPRISE_NO_ST_STANDARD);
            } else if (gaoXiao == 0 && historyGaoXiao > 0) {
                sumptuaryScore = SupplierScoringModel.ENTERPRISE_GOODWILL_RATIO.multiply(SupplierScoringModel.ENTERPRISE_HISTORY_ST_STANDARD);
            } else if (gaoXiao > 0 && historyGaoXiao == 0) {
                sumptuaryScore = SupplierScoringModel.ENTERPRISE_GOODWILL_RATIO.multiply(SupplierScoringModel.ENTERPRISE_ST_STANDARD);
            }
            corporateGoodwill.setSumptuaryScore(sumptuaryScore);
            BigDecimal administrativePenaltyScore = BigDecimal.ZERO;
            if (punish == 0) {
                administrativePenaltyScore = SupplierScoringModel.ENTERPRISE_GOODWILL_RATIO.multiply(SupplierScoringModel.ENTERPRISE_ADMINISTRATIVE_PENALTY_STANDARD_ONE);
            } else if (punish <= 2 && punishAmount.compareTo(new BigDecimal("50000")) < 1) {
                administrativePenaltyScore = SupplierScoringModel.ENTERPRISE_GOODWILL_RATIO.multiply(SupplierScoringModel.ENTERPRISE_ADMINISTRATIVE_PENALTY_STANDARD_TWO);
            } else if (punish > 2 && punishAmount.compareTo(new BigDecimal("50000")) < 1) {
                administrativePenaltyScore = SupplierScoringModel.ENTERPRISE_GOODWILL_RATIO.multiply(SupplierScoringModel.ENTERPRISE_ADMINISTRATIVE_PENALTY_STANDARD_THREE);
            } else if (punish <= 2 && punishAmount.compareTo(new BigDecimal("50000")) == 1) {
                administrativePenaltyScore = SupplierScoringModel.ENTERPRISE_GOODWILL_RATIO.multiply(SupplierScoringModel.ENTERPRISE_ADMINISTRATIVE_PENALTY_STANDARD_FORE);
            } else if (punish > 2 && punishAmount.compareTo(new BigDecimal("50000")) == 1) {
                administrativePenaltyScore = SupplierScoringModel.ENTERPRISE_GOODWILL_RATIO.multiply(SupplierScoringModel.ENTERPRISE_ADMINISTRATIVE_PENALTY_STANDARD_FIVE);
            }
            corporateGoodwill.setAdministrativePenaltyScore(administrativePenaltyScore);
            BigDecimal involvingLawsuitsScore;
            if (documentTotal == 0) {
                involvingLawsuitsScore = SupplierScoringModel.ENTERPRISE_GOODWILL_RATIO.multiply(SupplierScoringModel.ENTERPRISE_INVOLVING_LAWSUITS_STANDARD_ONE);
            } else {
                if (documentFinance > 0) {
                    involvingLawsuitsScore = SupplierScoringModel.ENTERPRISE_GOODWILL_RATIO.multiply(SupplierScoringModel.ENTERPRISE_INVOLVING_LAWSUITS_STANDARD_FORE);
                } else {
                    if (documnetBeiGao > 0) {
                        involvingLawsuitsScore = SupplierScoringModel.ENTERPRISE_GOODWILL_RATIO.multiply(SupplierScoringModel.ENTERPRISE_INVOLVING_LAWSUITS_STANDARD_THREE);
                    } else {
                        involvingLawsuitsScore = SupplierScoringModel.ENTERPRISE_GOODWILL_RATIO.multiply(SupplierScoringModel.ENTERPRISE_INVOLVING_LAWSUITS_STANDARD_TWO);
                    }
                }
            }
            corporateGoodwill.setInvolvingLawsuitsScore(involvingLawsuitsScore);
            List<SeriousIllegality> seriousIllegalities = seriousIllegalityService.lambdaQuery().eq(SeriousIllegality::getcSupplierInfoId, supplierApprovalSecond.getcSupplierInfoId())
                    .eq(SeriousIllegality::getcEnterpriseId, enterprise.getId()).eq(SeriousIllegality::getSeriousIllegality, 1).list();
            if (CollectionUtil.isEmpty(seriousIllegalities)) {
                BigDecimal multiply = SupplierScoringModel.ENTERPRISE_GOODWILL_RATIO.multiply(SupplierScoringModel.ENTERPRISE_OPERATING_RISK_STANDARD_ONE);
                corporateGoodwill.setSeriousIllegalityScore(multiply);
            } else {
                corporateGoodwill.setSeriousIllegalityScore(BigDecimal.ZERO);
            }
            List<TaxOweNotice> taxOweNotices = taxOweNoticeService.lambdaQuery().eq(TaxOweNotice::getcSupplierInfoId, supplierApprovalSecond.getcSupplierInfoId())
                    .eq(TaxOweNotice::getcEnterpriseId, enterprise.getId()).eq(TaxOweNotice::getTaxOweNotice, 1).list();
            if (CollectionUtil.isEmpty(taxOweNotices)) {
                BigDecimal multiply = SupplierScoringModel.ENTERPRISE_GOODWILL_RATIO.multiply(SupplierScoringModel.ENTERPRISE_OPERATING_RISK_STANDARD_TWO);
                corporateGoodwill.setTaxOweNoticeScore(multiply);
            } else {
                corporateGoodwill.setTaxOweNoticeScore(BigDecimal.ZERO);
            }
            List<TaxIllegalData> taxIllegalData = taxIllegalDataService.lambdaQuery().eq(TaxIllegalData::getcSupplierInfoId, supplierApprovalSecond.getcSupplierInfoId())
                    .eq(TaxIllegalData::getcEnterpriseId, enterprise.getId()).eq(TaxIllegalData::getTaxIllegal, 1).list();
            if (CollectionUtil.isEmpty(taxIllegalData)) {
                BigDecimal multiply = SupplierScoringModel.ENTERPRISE_GOODWILL_RATIO.multiply(SupplierScoringModel.ENTERPRISE_OPERATING_RISK_STANDARD_THREE);
                corporateGoodwill.setTaxIllegalDataScore(multiply);
            } else {
                corporateGoodwill.setTaxIllegalDataScore(BigDecimal.ZERO);
            }
            List<Blacklist> blacklists = blacklistService.lambdaQuery().eq(Blacklist::getcSupplierInfoId, supplierApprovalSecond.getcSupplierInfoId())
                    .eq(Blacklist::getcEnterpriseId, enterprise.getId()).eq(Blacklist::getBlacklist, 1).list();
            if (CollectionUtil.isEmpty(blacklists)) {
                BigDecimal multiply = SupplierScoringModel.ENTERPRISE_GOODWILL_RATIO.multiply(SupplierScoringModel.ENTERPRISE_OPERATING_RISK_STANDARD_FORE);
                corporateGoodwill.setBlacklistScore(multiply);
            } else {
                corporateGoodwill.setBlacklistScore(BigDecimal.ZERO);
            }
            List<ExceptionData> exceptionData = exceptionDataService.lambdaQuery().eq(ExceptionData::getcSupplierInfoId, supplierApprovalSecond.getcSupplierInfoId())
                    .eq(ExceptionData::getcEnterpriseId, enterprise.getId()).eq(ExceptionData::getException, 1).list();
            if (CollectionUtil.isEmpty(exceptionData)) {
                BigDecimal multiply = SupplierScoringModel.ENTERPRISE_GOODWILL_RATIO.multiply(SupplierScoringModel.ENTERPRISE_OPERATING_RISK_STANDARD_FIVE);
                corporateGoodwill.setExceptionDataScore(multiply);
            } else {
                corporateGoodwill.setExceptionDataScore(BigDecimal.ZERO);
            }
            List<News> news = newsService.lambdaQuery().eq(News::getcSupplierInfoId, supplierApprovalSecond.getcSupplierInfoId())
                    .eq(News::getcEnterpriseId, enterprise.getId()).eq(News::getNews, 1).list();
            if (CollectionUtil.isEmpty(news)) {
                BigDecimal multiply = SupplierScoringModel.ENTERPRISE_GOODWILL_RATIO.multiply(SupplierScoringModel.ENTERPRISE_OPERATING_RISK_STANDARD_SIX);
                corporateGoodwill.setNewsScore(multiply);
            } else {
                corporateGoodwill.setNewsScore(BigDecimal.ZERO);
            }
            corporateGoodwillService.updateById(corporateGoodwill);
        }
        //企业经营与财务
        BigDecimal incomeScore;
        if (supplierApprovalSecond.getMainBusinessIncome().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);
        }
        supplierApprovalSecond.setMainBusinessIncomeScore(incomeScore);
        if (supplierApprovalSecond.getMainBusinessProfit().compareTo(new BigDecimal("3")) > -1) {
            BigDecimal mainBusinessProfitScore = SupplierScoringModel.ENTERPRISE_FINANCE_RATIO.multiply(SupplierScoringModel.ENTERPRISE_CORPORATE_FINANCE_STANDARD_THREE);
            supplierApprovalSecond.setMainBusinessProfitScore(mainBusinessProfitScore);
        }
        String incomeLevel;
        if (supplierApprovalSecond.getMainBusinessIncome().compareTo(new BigDecimal("50000000")) == -1) {
            incomeLevel = SupplierScoringModel.INCOME_LEVEL_E;
        } else if (supplierApprovalSecond.getMainBusinessIncome().compareTo(new BigDecimal("50000000")) == 1 && supplierApprovalSecond.getMainBusinessIncome().compareTo(new BigDecimal("100000000")) == -1) {
            incomeLevel = SupplierScoringModel.INCOME_LEVEL_D;
        } else if (supplierApprovalSecond.getMainBusinessIncome().compareTo(new BigDecimal("100000000")) == 1 && supplierApprovalSecond.getMainBusinessIncome().compareTo(new BigDecimal("500000000")) == -1) {
            incomeLevel = SupplierScoringModel.INCOME_LEVEL_C;
        } else if (supplierApprovalSecond.getMainBusinessIncome().compareTo(new BigDecimal("500000000")) == 1 && supplierApprovalSecond.getMainBusinessIncome().compareTo(new BigDecimal("1500000000")) == -1) {
            incomeLevel = SupplierScoringModel.INCOME_LEVEL_B;
        } else {
            incomeLevel = SupplierScoringModel.INCOME_LEVEL_A;
        }
        supplierApprovalSecond.setRevenueRating(incomeLevel);
        List<UpstreamProcurementDocuments> upstreamProcurementDocumentsList = supplierApprovalSecond.getUpstreamProcurementDocumentsList();
        BigDecimal upstreamScore = BigDecimal.ZERO;
        if (CollectionUtil.isNotEmpty(upstreamProcurementDocumentsList)) {
            for (UpstreamProcurementDocuments upstreamProcurementDocuments : upstreamProcurementDocumentsList) {
                if (upstreamProcurementDocuments.getCompliance() == 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 = supplierApprovalSecond.getSalesDocumentsInfoList();
        BigDecimal salesScore = BigDecimal.ZERO;
        if (CollectionUtil.isNotEmpty(salesDocumentsInfoList)) {
            for (SalesDocumentsInfo salesDocumentsInfo : salesDocumentsInfoList) {
                if (salesDocumentsInfo.getCompliance() == 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);
        if (salesScore.compareTo(supplierScoreMax) == 1) {
            scoreTotal = scoreTotal.add(supplierScoreMax);
        } else {
            scoreTotal = scoreTotal.add(salesScore);
        }
        String businessAddress = supplierApprovalSecond.getBusinessAddress();
        BigDecimal businessAddressScore = BigDecimal.ZERO;
        if (businessAddress.contains("广东") || businessAddress.contains("江苏")) {
            if (businessAddress.contains("深圳") || businessAddress.contains("广州") || businessAddress.contains("佛山") || businessAddress.contains("东莞")
                    || businessAddress.contains("东莞") || businessAddress.contains("东莞") || businessAddress.contains("东莞")
                    || businessAddress.contains("东莞") || businessAddress.contains("东莞") || businessAddress.contains("东莞")) {
                businessAddressScore = SupplierScoringModel.ENTERPRISE_RATIO.multiply(SupplierScoringModel.REGISTERED_ADDRESS_STANDARD_ONE);
            } else {
                businessAddressScore = SupplierScoringModel.ENTERPRISE_RATIO.multiply(SupplierScoringModel.REGISTERED_ADDRESS_STANDARD_TWO);
            }
        } else if (businessAddress.contains("山东") || businessAddress.contains("浙江")) {
            if (businessAddress.contains("青岛") || businessAddress.contains("济南") || businessAddress.contains("烟台")
                    || businessAddress.contains("杭州") || businessAddress.contains("宁波") || businessAddress.contains("温州")) {
                businessAddressScore = SupplierScoringModel.ENTERPRISE_RATIO.multiply(SupplierScoringModel.REGISTERED_ADDRESS_STANDARD_TWO);
            } else {
                businessAddressScore = SupplierScoringModel.ENTERPRISE_RATIO.multiply(SupplierScoringModel.REGISTERED_ADDRESS_STANDARD_THREE);
            }
        } else if (businessAddress.contains("河南") || businessAddress.contains("四川") || businessAddress.contains("湖北") || businessAddress.contains("福建")
                || businessAddress.contains("湖南") || businessAddress.contains("安徽") || businessAddress.contains("上海") || businessAddress.contains("河北") || businessAddress.contains("北京")) {
            if(businessAddress.contains("郑州") || businessAddress.contains("成都") || businessAddress.contains("武汉")
                    || businessAddress.contains("福州") || businessAddress.contains("泉州") || businessAddress.contains("合肥")
                    || businessAddress.contains("唐山") || businessAddress.contains("长沙") || businessAddress.contains("北京") || businessAddress.contains("上海")){
                businessAddressScore = SupplierScoringModel.ENTERPRISE_RATIO.multiply(SupplierScoringModel.REGISTERED_ADDRESS_STANDARD_THREE);
            }else {
                businessAddressScore = SupplierScoringModel.ENTERPRISE_RATIO.multiply(SupplierScoringModel.REGISTERED_ADDRESS_STANDARD_FORE);
            }
        }else if(businessAddress.contains("陕西") || businessAddress.contains("江西") || businessAddress.contains("重庆") ||businessAddress.contains("云南")
                || businessAddress.contains("广西") || businessAddress.contains("山西") || businessAddress.contains("内蒙") || businessAddress.contains("贵州")){
            if(businessAddress.contains("西安") || businessAddress.contains("重庆")){
                businessAddressScore = SupplierScoringModel.ENTERPRISE_RATIO.multiply(SupplierScoringModel.REGISTERED_ADDRESS_STANDARD_FORE);
            }else {
                businessAddressScore = SupplierScoringModel.ENTERPRISE_RATIO.multiply(SupplierScoringModel.REGISTERED_ADDRESS_STANDARD_FIVE);
            }
        }else if(businessAddress.contains("新疆") || businessAddress.contains("天津") || businessAddress.contains("甘肃") ){
            if(businessAddress.contains("甘肃")){
                businessAddressScore = SupplierScoringModel.ENTERPRISE_RATIO.multiply(SupplierScoringModel.REGISTERED_ADDRESS_STANDARD_FIVE);
            }else {
                businessAddressScore = SupplierScoringModel.ENTERPRISE_RATIO.multiply(SupplierScoringModel.REGISTERED_ADDRESS_STANDARD_SIX);
            }
        }else if(businessAddress.contains("海南") || businessAddress.contains("宁夏") || businessAddress.contains("青海") ||businessAddress.contains("西藏")){
            businessAddressScore = SupplierScoringModel.ENTERPRISE_RATIO.multiply(SupplierScoringModel.REGISTERED_ADDRESS_STANDARD_SEVEN);
        }
        BigDecimal pictureScore = BigDecimal.ZERO;
        if(supplierApprovalSecond.getMapFilesCompliance() == 1 && supplierApprovalSecond.getRentalFilesCompliance() == 1
                && supplierApprovalSecond.getWaterFilesCompliance() == 1 && supplierApprovalSecond.getOfficeFilesCompliance() == 1){
            pictureScore = SupplierScoringModel.ENTERPRISE_RATIO.multiply(SupplierScoringModel.PICTURES_STANDARD);
        }
        businessAddressScore = businessAddressScore.add(pictureScore);
        supplierApprovalSecond.setBusinessAddressScore(businessAddressScore);
        if (supplierApprovalSecond.getScopeCompliance() == 1 ) {
            BigDecimal businessScopeScore = SupplierScoringModel.ENTERPRISE_RATIO.multiply(SupplierScoringModel.BUSINESS_SCOPE_STANDARD);
            supplierApprovalSecond.setBusinessScopeScore(businessScopeScore);
        }
        scoreTotal = scoreTotal.add(supplierApprovalSecond.getShareholderScore()).add(supplierApprovalSecond.getEstablishmentPeriodScore())
                .add(supplierApprovalSecond.getRegisteredCapitalScore()).add(supplierApprovalSecond.getRegisteredAddressScore())
                .add(supplierApprovalSecond.getBusinessAddressScore())
                .add(supplierApprovalSecond.getBusinessScopeScore()).add(supplierApprovalSecond.getBasicChangeScore())
                .add(supplierApprovalSecond.getMainBusinessIncomeScore()).add(supplierApprovalSecond.getMainBusinessProfitScore());
        scoreTotal = scoreTotal.add(corporateGoodwill.getRecoveredBalanceScore()).add(corporateGoodwill.getConcernedAccountsWithOutstandingCreditScore())
                .add(corporateGoodwill.getOutstandingNonPerformingAccountsScore()).add(corporateGoodwill.getOutstandingBalanceScore())
                .add(corporateGoodwill.getShiXinScore()).add(corporateGoodwill.getZhiXingScore())
                .add(corporateGoodwill.getSumptuaryScore()).add(corporateGoodwill.getAdministrativePenaltyScore())
                .add(corporateGoodwill.getInvolvingLawsuitsScore()).add(corporateGoodwill.getSeriousIllegalityScore())
                .add(corporateGoodwill.getTaxOweNoticeScore()).add(corporateGoodwill.getTaxIllegalDataScore())
                .add(corporateGoodwill.getBlacklistScore()).add(corporateGoodwill.getExceptionDataScore())
                .add(corporateGoodwill.getNewsScore());
        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");
            }
        }
        if (scoreTotal.compareTo(new BigDecimal("90")) == -1) {
            supplierApprovalSecond.setAdmitted(SupplierScoringModel.NOT_ADMITTED);
        } else {
            supplierApprovalSecond.setAdmitted(SupplierScoringModel.ADMITTED);
        }
        //法人年龄红否
        if(ageCompliance == 0){
            supplierApprovalSecond.setAdmitted(SupplierScoringModel.NOT_ADMITTED);
            supplierApprovalSecond.setSupplierErrors("法人年龄红否");
        }
        if (businessAddress.contains("黑龙江") || businessAddress.contains("辽宁") || businessAddress.contains("吉林")) {
            supplierApprovalSecond.setAdmitted(SupplierScoringModel.NOT_ADMITTED);
            supplierApprovalSecond.setSupplierErrors("经营地址红否");
        }
        supplierApprovalSecond.setCreditLimit(creditLimit);
        supplierApprovalSecond.setScore(scoreTotal);
        return supplierApprovalSecond;
    }
}
