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.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.plugin.table.LoopColumnTableRenderPolicy;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sunxung.factoring.component.constance.SupplierScoringModel;
import com.sunxung.factoring.component.enums.CreditInvestigationTypeEnums;
import com.sunxung.factoring.component.enums.SupplierStatusEnums;
import com.sunxung.factoring.component.exception.BusinessException;
import com.sunxung.factoring.component.exception.ValidatorException;
import com.sunxung.factoring.component.util.*;
import com.sunxung.factoring.component.util.onlineConverter.OfficeConverterUtil;
import com.sunxung.factoring.dict.impl.FileModuleDict;
import com.sunxung.factoring.entity.GridPage;
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.BusinessProcessingLog;
import com.sunxung.factoring.entity.project.vo.BusinessProcessingLogDetailVo;
import com.sunxung.factoring.entity.project.vo.SearchBusinessProcessingTask;
import com.sunxung.factoring.entity.supplier.*;
import com.sunxung.factoring.entity.sys.*;
import com.sunxung.factoring.entity.sys.Dictionary;
import com.sunxung.factoring.mapper.supplier.SupplierInfoMapper;
import com.sunxung.factoring.service.credit.CreditDetailService;
import com.sunxung.factoring.service.credit.CreditService;
import com.sunxung.factoring.service.entprise.IEnterpriseService;
import com.sunxung.factoring.service.project.BusinessProcessingLogService;
import com.sunxung.factoring.service.supplier.*;
import com.sunxung.factoring.service.sys.*;
import com.sunxung.factoring.service.sys.dto.AttachmentDto;
import com.sunxung.factoring.service.sys.flowable.FlowableService;
import org.apache.commons.io.FileUtils;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 供应商企业信息 服务实现类
 * </p>
 *
 * @author liutao
 * @since 2023-11-25
 */
@Service
public class SupplierInfoServiceImpl extends ServiceImpl<SupplierInfoMapper, SupplierInfo> implements ISupplierInfoService {

    @Autowired
    private FlowableService flowableService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private IEnterpriseService enterpriseService;

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private CUserService cUserService;

    @Autowired
    private IDueDiligenceAllocationService dueDiligenceAllocationService;

    @Autowired
    private BusinessProcessingLogService businessProcessingLogService;

    @Autowired
    private ISupplierContactService supplierContactService;

    @Autowired
    private ICSupplierInfoHistoryService supplierInfoHistoryService;

    @Autowired
    private ICEnterpriseHistoryService enterpriseHistoryService;

    @Autowired
    private FileService fileService;

    @Autowired
    private ICCreditInvestigationInfoHistoryService creditInvestigationInfoHistoryService;

    @Autowired
    private ICCorporateFinanceHistoryService corporateFinanceHistoryService;

    @Autowired
    private ICUpstreamProcurementDocumentsHistoryService upstreamProcurementDocumentsHistoryService;

    @Autowired
    private ICSalesDocumentsInfoHistoryService salesDocumentsInfoHistoryService;

    @Autowired
    private ICAssociatedEnterpriseInfoHistoryService associatedEnterpriseInfoHistoryService;

    @Autowired
    private IVideoDueDiligenceService videoDueDiligenceService;

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

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

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

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

    @Autowired
    private ISupplierApprovalSecondService supplierApprovalSecondService;

    @Autowired
    private ICreditSituationService creditSituationService;

    @Autowired
    private IVideoDueDiligenceShareholdersSituationService videoDueDiligenceShareholdersSituationService;

    @Autowired
    private ICreditInvestigationInfoService creditInvestigationInfoService;

    @Autowired
    private ICorporateGoodwillService corporateGoodwillService;

    @Autowired
    private ISysAttachmentRefService attachmentRefService;

    @Autowired
    private IUpstreamProcurementDocumentsService upstreamProcurementDocumentsService;

    @Autowired
    private ISalesDocumentsInfoService salesDocumentsInfoService;

    @Autowired
    private IVideoDueDiligenceComprehensiveEvaluationService videoDueDiligenceComprehensiveEvaluationService;

    @Autowired
    private IVideoDueDiligenceCorporateGoodwillService videoDueDiligenceCorporateGoodwillService;

    @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 IBlacklistService blacklistService;

    @Autowired
    private IVideoDueDiligenceFinanceService videoDueDiligenceFinanceService;

    @Autowired
    private DictionaryService dictionaryService;

    @Autowired
    private ICSupplierContactHistoryService supplierContactHistoryService;

    @Autowired
    private CreditService creditService;

    @Autowired
    private CreditDetailService creditDetailService;

    @Autowired
    private FileStorageService fileStorageService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String startProcess(SupplierInfo supplierInfo) {
        User admin = userService.getByLoginName("admin");
        Long historyId = supplierInfo.getHistoryId();
        ThreadLocalUtil.setUser(admin);
        Enterprise enterprise = supplierInfo.getEnterprise();
        //自动完成流程第一步 businessProcessingLog 有的话说明在后面的节点有过退回  就走审核过的节点
        List<BusinessProcessingLogDetailVo> list = businessProcessingLogService.findByBusiness(supplierInfo.getId(), ConstantUtil.SUPPLIER_INFO);
        Map<String, Object> procVariables = new HashMap<>();
        String statusStr;
        if (CollectionUtil.isEmpty(list)) {
            //3.开启流程实例
            procVariables.put(ConstantUtil.SUPPLIER_ADD_ASSIGNEE, admin.getId());
            //查询条件：供应商企业名称 建工行业
            String queryBusiness = enterprise.getCorporateName() + FlowableUtil.splitChar + supplierInfo.getConstructionIndustry();
            ProcessInstance processInst = flowableService.startProcessInstance(supplierInfo, procVariables,
                    FlowableUtil.generateBusinessKey(supplierInfo, ConstantUtil.SUPPLIER_INFO, queryBusiness), null, ConstantUtil.SUPPLIER_INFO);
            if (processInst == null) {
                throw new BusinessException(CodeUtil.FAIL, "流程启动失败");
            }
            //获取风控负责人
            List<Long> riskControlOwner = userService.findUserIdByRole(ConstantUtil.RISK_CONTROL_OWNER);
            if (riskControlOwner == null || riskControlOwner.size() == 0) {
                throw new ValidatorException(CodeUtil.FAIL, ConstantUtil.OPERATION_SPECIALIST + "角色内无任何用户！");
            }
            Long riskControlOwnerId = riskControlOwner.get(0);
            procVariables.put("result", "未审核过");

            procVariables.put(ConstantUtil.DUE_DILIGENCE_ALLOCATION_ASSIGNEE, riskControlOwnerId);
            String processInstId = processInst.getId();
            Task task = flowableService.findRuntimeTaskByProcessInstId(processInstId).get(0);
            Map<String, Object> msgVariables = new HashMap<>();
            msgVariables.put(ConstantUtil.FLOWABLE_MSG_TITLE, "供应商名称：" + enterprise.getCorporateName());
            msgVariables.put(ConstantUtil.FLOWABLE_MSG_CONTENT,
                    "供应商名称为“" + enterprise.getCorporateName() + "”的供应商已进入“"
                            + ConstantConversionUtil.flowBusinessKeyNames.get(ConstantUtil.SUPPLIER_INFO) + "—供应商审核尽调分配，"
                            + ConstantUtil.FLOWABLE_MSG_ASSIGNEE);
            flowableService.completeMyTask(task.getId(), supplierInfo, procVariables, null, historyId, msgVariables, ConstantUtil.SUPPLIER_INFO);
            statusStr = SupplierStatusEnums.DUE_DILIGENCE_ALLOCATION.getCode();
            //判断第二步是否自动完成
            UserDO userDO = cUserService.get(supplierInfo.getSysUserId());
            if (userDO.getRiskManager() != null) {
                User riskControlOwnerUser = userService.getByLoginName("liuzhuoxuan");
                //设置风控经理
                ThreadLocalUtil.setUser(riskControlOwnerUser);
                Task firstTask = flowableService.findRuntimeTaskByProcessInstId(processInstId).get(0);
                DueDiligenceAllocation dueDiligenceAllocation = new DueDiligenceAllocation();
                dueDiligenceAllocation.setcSupplierInfoId(supplierInfo.getId());
                dueDiligenceAllocation.setAssignDate(new Date());
                dueDiligenceAllocation.setName(enterprise.getCorporateName());
                dueDiligenceAllocation.setSocialCreditCode(enterprise.getSocialCreditCode());
                dueDiligenceAllocation.setRiskManagerId(userDO.getRiskManager());
                dueDiligenceAllocation.setTaskId(firstTask.getId());
                statusStr = dueDiligenceAllocationService.addInfo(dueDiligenceAllocation, supplierInfo);
            }
        } else {
            procVariables.put("result", "审核过");
            BusinessProcessingLog lastLog = businessProcessingLogService.getByBusinessTypeBusinessKey(ConstantUtil.SUPPLIER_INFO, supplierInfo.getId());
            Map<String, Object> msgVariables = new HashMap<>();
            msgVariables.put(ConstantUtil.FLOWABLE_MSG_TITLE, "供应商名称：" + enterprise.getCorporateName());
            msgVariables.put(ConstantUtil.FLOWABLE_MSG_CONTENT,
                    "供应商名称为“" + enterprise.getCorporateName() + "”的供应商已进入“"
                            + ConstantConversionUtil.flowBusinessKeyNames.get(ConstantUtil.SUPPLIER_INFO) + "—供应商审核(第二步))，"
                            + ConstantUtil.FLOWABLE_MSG_ASSIGNEE);
            flowableService.completeMyTask(lastLog.getHistoricTaskId(), supplierInfo, procVariables, null, historyId, msgVariables, ConstantUtil.SUPPLIER_INFO);
            statusStr = SupplierStatusEnums.DUE_DILIGENCE_REVIEW.getCode();
        }
        return statusStr;
    }

    @Override
    public SupplierInfo get(Long id) {
        return baseMapper.getById(id);
    }

    @Override
    public CSupplierInfoHistory getView(Long id) {
        CSupplierInfoHistory supplierInfoHistory = supplierInfoHistoryService.getById(id);
        CEnterpriseHistory enterpriseHistory = enterpriseHistoryService.getById(supplierInfoHistory.getcEnterpriseHistoryId());
        Enterprise enterprise = new Enterprise();
        BeanUtils.copyProperties(enterpriseHistory,enterprise);
        CSupplierContactHistory supplierContactHistory = supplierContactHistoryService.lambdaQuery().eq(CSupplierContactHistory::getcSupplierInfoHistory, id).one();
        SupplierContact supplierContact = new SupplierContact();
        BeanUtils.copyProperties(supplierContactHistory,supplierContact);
        supplierInfoHistory.setSupplierContact(supplierContact);
        setEnterprise(enterpriseHistory,enterprise);
        supplierInfoHistory.setEnterprise(enterprise);
        supplierInfoHistory.setHasGuaranteeEnterprise(false);
        if (supplierInfoHistory.getGuaranteeEnterpriseHistoryId() != null) {
            supplierInfoHistory.setHasGuaranteeEnterprise(true);
            CEnterpriseHistory enterpriseHistoryServiceById = enterpriseHistoryService.getById(supplierInfoHistory.getGuaranteeEnterpriseHistoryId());
            Enterprise guaranteeEnterprise = new Enterprise();
            BeanUtils.copyProperties(enterpriseHistoryServiceById,guaranteeEnterprise);
            setEnterprise(enterpriseHistoryServiceById,guaranteeEnterprise);
            supplierInfoHistory.setGuaranteeEnterprise(guaranteeEnterprise);
        }
        return supplierInfoHistory;
    }

    private void setEnterprise(CEnterpriseHistory enterpriseHistory,Enterprise enterprise) {
        //地点定位图
        List<FileStorageDO> locationMap = fileService.findByBusinessId(enterpriseHistory.getId(), FileModuleDict.ChildEnum.ENTERPRISE_LOCATION_MAP_HISTORY.getCode());
        enterprise.setLocationMap(locationMap);
        //租房合同
        List<FileStorageDO> rentalContract = fileService.findByBusinessId(enterpriseHistory.getId(), FileModuleDict.ChildEnum.ENTERPRISE_RENTAL_CONTRACT_HISTORY.getCode());
        enterprise.setRentalContract(rentalContract);
        //水电费缴纳流水
        List<FileStorageDO> waterElectricityFees = fileService.findByBusinessId(enterpriseHistory.getId(), FileModuleDict.ChildEnum.WATER_ELECTRIICITY_FEES_HISTORY.getCode());
        enterprise.setWaterElectricityFees(waterElectricityFees);
        //办公环境
        List<FileStorageDO> officeEnvironment = fileService.findByBusinessId(enterpriseHistory.getId(), FileModuleDict.ChildEnum.ENTERPRISE_OFFICE_ENVIRONMENT_HISTORY.getCode());
        enterprise.setOfficeEnvironment(officeEnvironment);
        //营业执照
        List<FileStorageDO> businessLicense = fileService.findByBusinessId(enterpriseHistory.getId(), FileModuleDict.ChildEnum.ENTERPRISE_BUSINESS_LICENSE_HISTORY.getCode());
        enterprise.setBusinessLicense(businessLicense);
        //基本户信息
        List<FileStorageDO> basicAccountInformation = fileService.findByBusinessId(enterpriseHistory.getId(), FileModuleDict.ChildEnum.ENTERPRISE_BASIC_ACCOUNT_INFORMATION_HISTORY.getCode());
        enterprise.setBasicAccountInformation(basicAccountInformation);
        //公司章程和修正案
        List<FileStorageDO> articlesAssociation = fileService.findByBusinessId(enterpriseHistory.getId(), FileModuleDict.ChildEnum.ENTERPRISE_ARTICLES_ASSOCIATION_HISTORY.getCode());
        enterprise.setArticlesAssociation(articlesAssociation);
        //结案证明或判决书
        List<FileStorageDO> judgment = fileService.findByBusinessId(enterpriseHistory.getId(), FileModuleDict.ChildEnum.ENTERPRISE_JUDGMENT_HISTORY.getCode());
        enterprise.setJudgment(judgment);
        //纳税申报表
        List<FileStorageDO> taxReturn = fileService.findByBusinessId(enterpriseHistory.getId(), FileModuleDict.ChildEnum.ENTERPRISE_TAX_RETURN_HISTORY.getCode());
        enterprise.setTaxReturn(taxReturn);
        //企业内账报表
        List<FileStorageDO> accountingreport = fileService.findByBusinessId(enterpriseHistory.getId(), FileModuleDict.ChildEnum.ENTERPRISE_ACCOUNTING_REPORT_HISTORY.getCode());
        enterprise.setAccountingreport(accountingreport);
        List<CCreditInvestigationInfoHistory> cCreditInvestigationInfoHistories = creditInvestigationInfoHistoryService.lambdaQuery().eq(CCreditInvestigationInfoHistory::getcEnterpriseHistoryId, enterpriseHistory.getId()).list();
        if (CollectionUtil.isNotEmpty(cCreditInvestigationInfoHistories)) {
            for (CCreditInvestigationInfoHistory creditInvestigationInfoHistory : cCreditInvestigationInfoHistories) {
                List<FileStorageDO> files = fileService.findByBusinessId(creditInvestigationInfoHistory.getId(), FileModuleDict.ChildEnum.ENTERPRISE_IDCARD_FILES_HISTORY.getCode());
                creditInvestigationInfoHistory.setFiles(files);
                CreditInvestigationTypeEnums typeEnums = CreditInvestigationTypeEnums.getByCode(creditInvestigationInfoHistory.getType());
                creditInvestigationInfoHistory.setTypeStr(typeEnums.getDesc());
            }
        }
        enterprise.setCreditInvestigationInfoList(cCreditInvestigationInfoHistories);
        List<CCorporateFinanceHistory> cCorporateFinanceHistories = corporateFinanceHistoryService.lambdaQuery().eq(CCorporateFinanceHistory::getcEnterpriseHistoryId, enterpriseHistory.getId()).list();
        if (CollectionUtil.isNotEmpty(cCorporateFinanceHistories)) {
            for (CCorporateFinanceHistory corporateFinanceHistory : cCorporateFinanceHistories) {
                FileStorageDO fileStorageDO = fileService.findOneByBusinessId(corporateFinanceHistory.getId(), FileModuleDict.ChildEnum.ENTERPRISE_FINANCIAL_STATEMENTS_HISTORY.getCode());
                corporateFinanceHistory.setFileStorage(fileStorageDO);
            }
        }
        enterprise.setCorporateFinances(cCorporateFinanceHistories);
        List<CUpstreamProcurementDocumentsHistory> cUpstreamProcurementDocumentsHistories = upstreamProcurementDocumentsHistoryService.lambdaQuery().eq(CUpstreamProcurementDocumentsHistory::getcEnterpriseHistoryId, enterpriseHistory.getId()).list();
        if (CollectionUtil.isNotEmpty(cUpstreamProcurementDocumentsHistories)) {
            for (CUpstreamProcurementDocumentsHistory upstreamProcurementDocumentsHistory : cUpstreamProcurementDocumentsHistories) {
                List<FileStorageDO> fileStorageDOS = fileService.findByBusinessId(upstreamProcurementDocumentsHistory.getId(), FileModuleDict.ChildEnum.ENTERPRISE_UPSTREAM_DOCUMENTS_HISTORY.getCode());
                upstreamProcurementDocumentsHistory.setFileStorages(fileStorageDOS);
            }
        }
        enterprise.setUpstreamProcurementDocuments(cUpstreamProcurementDocumentsHistories);
        List<CSalesDocumentsInfoHistory> cSalesDocumentsInfoHistories = salesDocumentsInfoHistoryService.lambdaQuery().eq(CSalesDocumentsInfoHistory::getcEnterpriseHistoryId, enterpriseHistory.getId()).list();
        if (CollectionUtil.isNotEmpty(cSalesDocumentsInfoHistories)) {
            for (CSalesDocumentsInfoHistory salesDocumentsInfoHistory : cSalesDocumentsInfoHistories) {
                List<FileStorageDO> fileStorageDOS = fileService.findByBusinessId(salesDocumentsInfoHistory.getId(), FileModuleDict.ChildEnum.ENTERPRISE_SALES_DOCUMENTS_HISTORY.getCode());
                salesDocumentsInfoHistory.setFileStorages(fileStorageDOS);
            }
        }
        enterprise.setSalesDocumentsInfos(cSalesDocumentsInfoHistories);
        List<CAssociatedEnterpriseInfoHistory> cAssociatedEnterpriseInfoHistories = associatedEnterpriseInfoHistoryService.lambdaQuery().eq(CAssociatedEnterpriseInfoHistory::getcEnterpriseHistoryId, enterpriseHistory.getId()).list();
        enterprise.setAssociatedEnterpriseInfos(cAssociatedEnterpriseInfoHistories);
        //征信授权书
        List<FileStorageDO> fileStorageDOS = fileService.findByBusinessId(enterpriseHistory.getId(), FileModuleDict.ChildEnum.ENTERPRISE_CREDIT_AUTHORIZATION_LETTER_HISTORY.getCode());
        if(CollectionUtil.isNotEmpty(fileStorageDOS)){
            FileStorageDO fileStorageDO = fileStorageDOS.get(0);
            fileStorageDO.setOriginalName(fileStorageDO.getOriginalName() + ".pdf");
            enterprise.setFileStorageDO(fileStorageDOS.get(0));
        }
    }

    @Override
    public SupplierInfo getViewNew(Long id) {
        SupplierInfo supplierInfo = get(id);
        Enterprise byId = enterpriseService.getById(supplierInfo.getcEnterpriseId());
        supplierInfo.setEnterprise(byId);
        SupplierContact supplierContact = supplierContactService.lambdaQuery().eq(SupplierContact::getSupplierInfoId, id).one();
        supplierInfo.setSupplierContact(supplierContact);
        return supplierInfo;
    }

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

    @Override
    public VideoDueDiligence report(Long supplierId) {
        VideoDueDiligence videoDueDiligence = videoDueDiligenceService.lambdaQuery().eq(VideoDueDiligence::getcSupplierInfoId, supplierId).one();
        SupplierInfo supplierInfo = supplierInfoService.get(supplierId);
        Enterprise enterprise = enterpriseService.getById(supplierInfo.getcEnterpriseId());
        if (supplierInfo.getGuaranteeEnterpriseId() != null) {
            enterprise = enterpriseService.getById(supplierInfo.getGuaranteeEnterpriseId());
        }
        SupplierApprovalSecond supplierApprovalSecond = supplierApprovalSecondService.lambdaQuery().eq(SupplierApprovalSecond::getcSupplierInfoId, supplierId).orderByDesc(SupplierApprovalSecond::getGmtCreate).list().get(0);
        CSupplierInfoHistory supplierInfoHistory = supplierInfoHistoryService.getById(supplierApprovalSecond.getcSupplierInfoHistoryId());
        CEnterpriseHistory enterpriseHistory;
        if (supplierInfoHistory.getGuaranteeEnterpriseHistoryId() != null) {
            enterpriseHistory = enterpriseHistoryService.getById(supplierInfoHistory.getGuaranteeEnterpriseHistoryId());
        } else {
            enterpriseHistory = enterpriseHistoryService.getById(supplierInfoHistory.getcEnterpriseHistoryId());
        }
        List<PrivateLending> privateLendings = privateLendingService.lambdaQuery().eq(PrivateLending::getcSupplierInfoId, supplierId).eq(PrivateLending::getcEnterpriseId, enterprise.getId()).list();
        //上游采购单据
        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);
            }
        }
        //下游销售单据
        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);
            }
        }
        //判断有无视频尽调 根据结果从不同地方取值
        if (videoDueDiligence != null) {
            //企业信誉
            CorporateGoodwill corporateGoodwill = corporateGoodwillService.lambdaQuery()
                    .eq(CorporateGoodwill::getcSupplierInfoId, supplierId).eq(CorporateGoodwill::getcEnterpriseId, enterprise.getId()).one();
            //todo 填充征信报告
            CreditInfo creditInfo = creditService.lambdaQuery().eq(CreditInfo::getCardNo, enterprise.getSocialCreditCode()).one();
            List<FileStorage> list = 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()));
                        list.add(creditDetailFiles);
                    }
                }
            }
            corporateGoodwill.setCreditDetailFiles(list);
            //视频尽调的企业信誉
            VideoDueDiligenceCorporateGoodwill videoDueDiligenceCorporateGoodwill = videoDueDiligenceCorporateGoodwillService.lambdaQuery()
                    .eq(VideoDueDiligenceCorporateGoodwill::getVideoDueDiligenceId, videoDueDiligence.getId()).one();
            corporateGoodwill.setRecoveredBalance(videoDueDiligenceCorporateGoodwill.getRecoveredBalance());
            corporateGoodwill.setConcernedAccountsWithOutstandingCredit(videoDueDiligenceCorporateGoodwill.getUnclearFollowUpAccounts());
            corporateGoodwill.setOutstandingNonPerformingAccounts(videoDueDiligenceCorporateGoodwill.getOutstandingNonPerformingAccounts());
            corporateGoodwill.setOutstandingBalance(videoDueDiligenceCorporateGoodwill.getOutstandingShortTermLoanBalance());
            //人员信息
            List<VideoDueDiligenceShareholdersSituation> videoDueDiligenceShareholdersSituations = videoDueDiligenceShareholdersSituationService.lambdaQuery().eq(VideoDueDiligenceShareholdersSituation::getVideoDueDiligenceId, videoDueDiligence.getId()).list();
            List<CreditSituation> creditSituations = new ArrayList<>();
            for (VideoDueDiligenceShareholdersSituation videoDueDiligenceShareholdersSituation : videoDueDiligenceShareholdersSituations) {
                CreditSituation creditSituation = new CreditSituation();
                autoCreditSituation(videoDueDiligenceShareholdersSituation, creditSituation);
                CCreditInvestigationInfoHistory creditInvestigationInfoHistory = creditInvestigationInfoHistoryService.getById(videoDueDiligenceShareholdersSituation.getcCreditInvestigationInfoHistoryId());
                //todo 填充征信报告
                CreditInfo creditInfo1 = creditService.lambdaQuery().eq(CreditInfo::getCardNo, creditInvestigationInfoHistory.getSocialCreditCode()).one();
                List<FileStorage> fileList = new ArrayList<>();
                if(creditInfo1 != 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.setCreditInvestigationInfoHistory(creditInvestigationInfoHistory);
                creditSituations.add(creditSituation);
            }
            videoDueDiligence.setCreditSituations(creditSituations);
            //
            if (CollectionUtil.isEmpty(privateLendings)) {
                long count = privateLendings.stream().filter(r -> r.getVideoDueDiligencePrivateLending() == 1).count();
                if (count > 0) {
                    corporateGoodwill.setPrivateLendings(1);
                } else {
                    corporateGoodwill.setPrivateLendings(0);
                }
            } else {
                corporateGoodwill.setPrivateLendings(1);
            }
            List<SeriousIllegality> seriousIllegalities = seriousIllegalityService.lambdaQuery().eq(SeriousIllegality::getcSupplierInfoId, supplierApprovalSecond.getcSupplierInfoId())
                    .eq(SeriousIllegality::getcEnterpriseId, enterprise.getId()).eq(SeriousIllegality::getVideoDueDiligenceSeriousIllegality, 1).list();
            if (CollectionUtil.isEmpty(seriousIllegalities)) {
                corporateGoodwill.setSeriousIllegalities(0);
                BigDecimal seriousIllegalitiesMultiply = SupplierScoringModel.ENTERPRISE_GOODWILL_RATIO.multiply(SupplierScoringModel.ENTERPRISE_OPERATING_RISK_STANDARD_ONE);
                corporateGoodwill.setSeriousIllegalityScore(seriousIllegalitiesMultiply);
            } else {
                corporateGoodwill.setSeriousIllegalities(1);
                corporateGoodwill.setSeriousIllegalityScore(BigDecimal.ZERO);
            }
            List<TaxOweNotice> taxOweNotices = taxOweNoticeService.lambdaQuery().eq(TaxOweNotice::getcSupplierInfoId, supplierApprovalSecond.getcSupplierInfoId())
                    .eq(TaxOweNotice::getcEnterpriseId, enterprise.getId()).eq(TaxOweNotice::getVideoDueDiligenceTaxOweNotice, 1).list();
            if (CollectionUtil.isEmpty(taxOweNotices)) {
                corporateGoodwill.setTaxOweNotices(0);
                BigDecimal taxOweNoticesScope = SupplierScoringModel.ENTERPRISE_GOODWILL_RATIO.multiply(SupplierScoringModel.ENTERPRISE_OPERATING_RISK_STANDARD_TWO);
                corporateGoodwill.setTaxOweNoticeScore(taxOweNoticesScope);
            } else {
                corporateGoodwill.setTaxOweNotices(1);
                corporateGoodwill.setTaxOweNoticeScore(BigDecimal.ZERO);
            }
            List<TaxIllegalData> taxIllegalData = taxIllegalDataService.lambdaQuery().eq(TaxIllegalData::getcSupplierInfoId, supplierApprovalSecond.getcSupplierInfoId())
                    .eq(TaxIllegalData::getcEnterpriseId, enterprise.getId()).eq(TaxIllegalData::getVideoDueDiligenceTaxIllegal, 1).list();
            if (CollectionUtil.isEmpty(taxIllegalData)) {
                corporateGoodwill.setTaxIllegalData(0);
                BigDecimal taxIllegalDataScope = SupplierScoringModel.ENTERPRISE_GOODWILL_RATIO.multiply(SupplierScoringModel.ENTERPRISE_OPERATING_RISK_STANDARD_THREE);
                corporateGoodwill.setTaxIllegalDataScore(taxIllegalDataScope);
            } else {
                corporateGoodwill.setTaxIllegalData(1);
                corporateGoodwill.setTaxIllegalDataScore(BigDecimal.ZERO);
            }
            List<Blacklist> blacklists = blacklistService.lambdaQuery().eq(Blacklist::getcSupplierInfoId, supplierApprovalSecond.getcSupplierInfoId())
                    .eq(Blacklist::getcEnterpriseId, enterprise.getId()).eq(Blacklist::getVideoDueDiligenceBlacklist, 1).list();
            if (CollectionUtil.isEmpty(blacklists)) {
                corporateGoodwill.setBlacklists(0);
                BigDecimal blacklistsScope = SupplierScoringModel.ENTERPRISE_GOODWILL_RATIO.multiply(SupplierScoringModel.ENTERPRISE_OPERATING_RISK_STANDARD_FORE);
                corporateGoodwill.setBlacklistScore(blacklistsScope);
            } else {
                corporateGoodwill.setBlacklists(1);
                corporateGoodwill.setBlacklistScore(BigDecimal.ZERO);
            }
            List<ExceptionData> exceptionData = exceptionDataService.lambdaQuery().eq(ExceptionData::getcSupplierInfoId, supplierApprovalSecond.getcSupplierInfoId())
                    .eq(ExceptionData::getcEnterpriseId, enterprise.getId()).eq(ExceptionData::getVideoDueDiligenceException, 1).list();
            if (CollectionUtil.isEmpty(exceptionData)) {
                corporateGoodwill.setExceptionData(0);
                BigDecimal exceptionDataScope = SupplierScoringModel.ENTERPRISE_GOODWILL_RATIO.multiply(SupplierScoringModel.ENTERPRISE_OPERATING_RISK_STANDARD_FIVE);
                corporateGoodwill.setExceptionDataScore(exceptionDataScope);
            } else {
                corporateGoodwill.setExceptionData(1);
                corporateGoodwill.setExceptionDataScore(BigDecimal.ZERO);
            }
            List<News> news = newsService.lambdaQuery().eq(News::getcSupplierInfoId, supplierApprovalSecond.getcSupplierInfoId())
                    .eq(News::getcEnterpriseId, enterprise.getId()).eq(News::getVideoDueDiligenceNews, 1).list();
            if (CollectionUtil.isEmpty(news)) {
                corporateGoodwill.setNews(0);
                BigDecimal newsScope = SupplierScoringModel.ENTERPRISE_GOODWILL_RATIO.multiply(SupplierScoringModel.ENTERPRISE_OPERATING_RISK_STANDARD_SIX);
                corporateGoodwill.setNewsScore(newsScope);
            } else {
                corporateGoodwill.setNews(1);
                corporateGoodwill.setNewsScore(BigDecimal.ZERO);
            }
            videoDueDiligence.setCorporateGoodwill(corporateGoodwill);
            //上游采购单据
            if (CollectionUtil.isNotEmpty(upstreamProcurementDocumentsList)) {
                for (UpstreamProcurementDocuments upstreamProcurementDocuments : upstreamProcurementDocumentsList) {
                    if (upstreamProcurementDocuments.getResult() == 1) {
                        upstreamProcurementDocuments.setScore(BigDecimal.ZERO);
                    } else {
                        BigDecimal score = SupplierScoringModel.ENTERPRISE_FINANCE_RATIO.multiply(SupplierScoringModel.UPSTREAN_PROCUREMENT_STANDARD_THREE);
                        upstreamProcurementDocuments.setScore(score);
                    }
                }
            }

            //下游销售单据
            if (CollectionUtil.isNotEmpty(salesDocumentsInfoList)) {
                for (SalesDocumentsInfo salesDocumentsInfo : salesDocumentsInfoList) {
                    if (salesDocumentsInfo.getResult() == 1) {
                        salesDocumentsInfo.setScore(BigDecimal.ZERO);
                    } else {
                        BigDecimal score = SupplierScoringModel.ENTERPRISE_FINANCE_RATIO.multiply(SupplierScoringModel.SALES_DOCUMENTS_STANDARD_THREE);
                        salesDocumentsInfo.setScore(score);
                    }
                }
            }
            //企业财务
            VideoDueDiligenceFinance videoDueDiligenceFinance = videoDueDiligenceFinanceService.lambdaQuery().eq(VideoDueDiligenceFinance::getVideoDueDiligenceId, videoDueDiligence.getId()).one();
            videoDueDiligence.setVideoDueDiligenceFinance(videoDueDiligenceFinance);
            //综合评估
            VideoDueDiligenceComprehensiveEvaluation videoDueDiligenceComprehensiveEvaluation = videoDueDiligenceComprehensiveEvaluationService.lambdaQuery().eq(VideoDueDiligenceComprehensiveEvaluation::getVideoDueDiligenceId, videoDueDiligence.getId()).one();
            videoDueDiligence.setVideoDueDiligenceComprehensiveEvaluation(videoDueDiligenceComprehensiveEvaluation);
        } else {
            videoDueDiligence = new VideoDueDiligence();
            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);
            videoDueDiligence.setShareholderMeasurementScore(supplierApprovalSecond.getShareholderScore());
            videoDueDiligence.setStartDate(enterprise.getStartSate());
            long year = DateUtil.betweenYear(enterprise.getStartSate(), new Date(), false);
            videoDueDiligence.setEstablishmentPeriod(year);
            videoDueDiligence.setLifeMeasurementScore(supplierApprovalSecond.getEstablishmentPeriodScore());
            videoDueDiligence.setRegisteredCapital(enterprise.getRegisteredCapital());
            videoDueDiligence.setCapitalMeasurementScore(supplierApprovalSecond.getRegisteredCapitalScore());
            videoDueDiligence.setAddress(enterprise.getAddress());
            videoDueDiligence.setAddressMeasurementScore(supplierApprovalSecond.getRegisteredAddressScore());
            videoDueDiligence.setBusinessAddress(enterprise.getBusinessAddress());
            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.setBusinessScopeMeasurementScore(supplierApprovalSecond.getBusinessScopeScore());
            //近一年股东或法人变更*次
            String getChangesUrl = getChanges + "?comprehensiveRiskInvestigationId=" + enterprise.getcComprehensiveRiskInvestigationId();
            Integer changes = restTemplate.getForObject(getChangesUrl, Integer.class);
            videoDueDiligence.setBasicChangeSize(changes);
            videoDueDiligence.setChangeMeasurementScore(supplierApprovalSecond.getBasicChangeScore());
            //人员信息
            List<CreditSituation> creditSituations = creditSituationService.lambdaQuery().eq(CreditSituation::getcSupplierInfoId, supplierId).list();
            creditSituations = creditSituations.stream().filter(r -> {
                CCreditInvestigationInfoHistory creditInvestigationInfoHistory = creditInvestigationInfoHistoryService.getById(r.getcCreditInvestigationInfoHistoryId());
                CEnterpriseHistory enterpriseHistoryServiceById = enterpriseHistoryService.getById(creditInvestigationInfoHistory.getcEnterpriseHistoryId());
                CEnterpriseHistory enterpriseHistoryTwo = enterpriseHistoryService.getById(supplierApprovalSecond.getcEnterpriseHistoryId());
                return enterpriseHistoryServiceById.getCorporateName().equals(enterpriseHistoryTwo.getCorporateName());
            }).collect(Collectors.toList());
            for (CreditSituation creditSituation : creditSituations) {
                CCreditInvestigationInfoHistory creditInvestigationInfoHistory = creditInvestigationInfoHistoryService.getById(creditSituation.getcCreditInvestigationInfoHistoryId());
                //todo 填充征信报告
                CreditInfo creditInfo = creditService.lambdaQuery().eq(CreditInfo::getCardNo, creditInvestigationInfoHistory.getSocialCreditCode()).one();
                List<FileStorage> list = 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()));
                            list.add(creditDetailFiles);
                        }
                    }
                }
                creditInvestigationInfoHistory.setCreditDetailFiles(list);
                List<FileStorageDO> cardFiles = fileService.findByBusinessId(creditInvestigationInfoHistory.getId(), FileModuleDict.ChildEnum.ENTERPRISE_IDCARD_FILES_HISTORY.getCode());
                creditInvestigationInfoHistory.setCardFiles(cardFiles);
                creditSituation.setCreditInvestigationInfoHistory(creditInvestigationInfoHistory);
            }
            videoDueDiligence.setCreditSituations(creditSituations);
            //企业信誉
            CorporateGoodwill corporateGoodwill = corporateGoodwillService.lambdaQuery()
                    .eq(CorporateGoodwill::getcSupplierInfoId, supplierId).eq(CorporateGoodwill::getcEnterpriseId, enterprise.getId()).one();
            //todo 填充征信报告
            CreditInfo creditInfo = creditService.lambdaQuery().eq(CreditInfo::getCardNo, enterprise.getSocialCreditCode()).one();
            List<FileStorage> list = 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()));
                        list.add(creditDetailFiles);
                    }
                }
            }
            corporateGoodwill.setCreditDetailFiles(list);
            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);
            //
            if (CollectionUtil.isEmpty(privateLendings)) {
                long count = privateLendings.stream().filter(r -> r.getPrivateLending() == 1).count();
                if (count > 0) {
                    corporateGoodwill.setPrivateLendings(1);
                } else {
                    corporateGoodwill.setPrivateLendings(0);
                }
            } else {
                corporateGoodwill.setPrivateLendings(1);
            }
            List<SeriousIllegality> seriousIllegalities = seriousIllegalityService.lambdaQuery().eq(SeriousIllegality::getcSupplierInfoId, supplierApprovalSecond.getcSupplierInfoId())
                    .eq(SeriousIllegality::getcEnterpriseId, enterprise.getId()).eq(SeriousIllegality::getSeriousIllegality, 1).list();
            if (CollectionUtil.isEmpty(seriousIllegalities)) {
                corporateGoodwill.setSeriousIllegalities(0);
            } else {
                corporateGoodwill.setSeriousIllegalities(1);
            }
            List<TaxOweNotice> taxOweNotices = taxOweNoticeService.lambdaQuery().eq(TaxOweNotice::getcSupplierInfoId, supplierApprovalSecond.getcSupplierInfoId())
                    .eq(TaxOweNotice::getcEnterpriseId, enterprise.getId()).eq(TaxOweNotice::getTaxOweNotice, 1).list();
            if (CollectionUtil.isEmpty(taxOweNotices)) {
                corporateGoodwill.setTaxOweNotices(0);
            } else {
                corporateGoodwill.setTaxOweNotices(1);
            }
            List<TaxIllegalData> taxIllegalData = taxIllegalDataService.lambdaQuery().eq(TaxIllegalData::getcSupplierInfoId, supplierApprovalSecond.getcSupplierInfoId())
                    .eq(TaxIllegalData::getcEnterpriseId, enterprise.getId()).eq(TaxIllegalData::getTaxIllegal, 1).list();
            if (CollectionUtil.isEmpty(taxIllegalData)) {
                corporateGoodwill.setTaxIllegalData(0);
            } else {
                corporateGoodwill.setTaxIllegalData(1);
            }
            List<Blacklist> blacklists = blacklistService.lambdaQuery().eq(Blacklist::getcSupplierInfoId, supplierApprovalSecond.getcSupplierInfoId())
                    .eq(Blacklist::getcEnterpriseId, enterprise.getId()).eq(Blacklist::getBlacklist, 1).list();
            if (CollectionUtil.isEmpty(blacklists)) {
                corporateGoodwill.setBlacklists(0);
            } else {
                corporateGoodwill.setBlacklists(1);
            }
            List<ExceptionData> exceptionData = exceptionDataService.lambdaQuery().eq(ExceptionData::getcSupplierInfoId, supplierApprovalSecond.getcSupplierInfoId())
                    .eq(ExceptionData::getcEnterpriseId, enterprise.getId()).eq(ExceptionData::getException, 1).list();
            if (CollectionUtil.isEmpty(exceptionData)) {
                corporateGoodwill.setExceptionData(0);
            } else {
                corporateGoodwill.setExceptionData(1);
            }
            List<News> news = newsService.lambdaQuery().eq(News::getcSupplierInfoId, supplierApprovalSecond.getcSupplierInfoId())
                    .eq(News::getcEnterpriseId, enterprise.getId()).eq(News::getNews, 1).list();
            if (CollectionUtil.isEmpty(news)) {
                corporateGoodwill.setNews(0);
            } else {
                corporateGoodwill.setNews(1);
            }
            videoDueDiligence.setCorporateGoodwill(corporateGoodwill);
            //企业财务
            VideoDueDiligenceFinance videoDueDiligenceFinance = new VideoDueDiligenceFinance();
            videoDueDiligenceFinance.setMainBusinessIncomeFix(supplierApprovalSecond.getMainBusinessIncome());
            videoDueDiligenceFinance.setMainBusinessIncomeScore(supplierApprovalSecond.getMainBusinessIncomeScore());
            videoDueDiligenceFinance.setMainBusinessCostFix(supplierApprovalSecond.getMainBusinessCost());
            videoDueDiligenceFinance.setMainBusinessProfitFix(supplierApprovalSecond.getMainBusinessProfit());
            videoDueDiligenceFinance.setMainBusinessProfitScore(supplierApprovalSecond.getMainBusinessProfitScore());
            videoDueDiligence.setVideoDueDiligenceFinance(videoDueDiligenceFinance);
            //综合评估
            VideoDueDiligenceComprehensiveEvaluation videoDueDiligenceComprehensiveEvaluation = new VideoDueDiligenceComprehensiveEvaluation();
            videoDueDiligenceComprehensiveEvaluation.setAdmitted(supplierApprovalSecond.getAdmitted());
//            videoDueDiligenceComprehensiveEvaluation.setEvaluationOpinions(supplierApprovalSecond.getEvaluationOpinions());
            videoDueDiligenceComprehensiveEvaluation.setScore(supplierApprovalSecond.getScore());
            videoDueDiligenceComprehensiveEvaluation.setCreditLimit(supplierApprovalSecond.getCreditLimit());
            videoDueDiligenceComprehensiveEvaluation.setRevenueRating(supplierApprovalSecond.getRevenueRating());
            videoDueDiligence.setVideoDueDiligenceComprehensiveEvaluation(videoDueDiligenceComprehensiveEvaluation);
        }
        videoDueDiligence.setUpstreamProcurementDocumentsList(upstreamProcurementDocumentsList);
        videoDueDiligence.setSalesDocumentsInfoList(salesDocumentsInfoList);
        videoDueDiligence.setEnterpriseName(enterprise.getCorporateName());
        videoDueDiligence.setSocialCreditCode(enterprise.getSocialCreditCode());
        //企业经营与财务
        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));
        }
        List<FileStorageDO> enterpriseAccountingReportFiles = fileService.findByBusinessId(enterpriseHistory.getId(), FileModuleDict.ChildEnum.ENTERPRISE_ACCOUNTING_REPORT_HISTORY.getCode());
        videoDueDiligence.setEnterpriseTaxReturnFiles(enterpriseTaxReturnFiles);
        videoDueDiligence.setCorporateFinanceList(cCorporateFinanceHistories);
        videoDueDiligence.setEnterpriseAccountingReportFiles(enterpriseAccountingReportFiles);
        // 股东信息 工商登记
        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);
        //查询文件
        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);
        //关联企业
        List<CAssociatedEnterpriseInfoHistory> enterpriseInfoHistoryList = associatedEnterpriseInfoHistoryService.lambdaQuery().eq(CAssociatedEnterpriseInfoHistory::getcEnterpriseHistoryId, enterpriseHistory.getId()).list();
        videoDueDiligence.setEnterpriseInfoHistoryList(enterpriseInfoHistoryList);
        videoDueDiligence.setSupplierInfo(supplierInfo);
        return videoDueDiligence;
    }

    @Override
    public void downloadReport(Long supplierId, HttpServletResponse response) throws IOException {
        VideoDueDiligence report = report(supplierId);
        List<CAssociatedEnterpriseInfoHistory> enterpriseInfoHistoryList = report.getEnterpriseInfoHistoryList();
        SupplierInfo supplierInfo = report.getSupplierInfo();
        DecimalFormat b = new DecimalFormat("0.00");
        Map params = new HashMap();
        params.put("enterpriseName", report.getEnterpriseName());
        params.put("socialCreditCode", report.getSocialCreditCode());
        List<CRegStock> regStocks = report.getRegStocks();
        List regList = new ArrayList();
        if (CollectionUtil.isNotEmpty(regStocks)) {
            int regNumber = 1;
            for (CRegStock regStock : regStocks) {
                Map map = new HashMap();
                map.put("number", regNumber);
                map.put("stockName", regStock.getStockName());
                map.put("stockPercent", regStock.getStockPercent());
                regList.add(map);
                regNumber = regNumber + 1;
            }
        }
        params.put("regStocks", regList);
        params.put("legalRepresentative", report.getLegalRepresentative());
        params.put("age", report.getAge());
        params.put("shareholderMeasurementScore", b.format(report.getShareholderMeasurementScore()));
        params.put("startDate", DateUtil.formatDate(report.getStartDate()));
        params.put("establishmentPeriod", report.getEstablishmentPeriod());
        params.put("lifeMeasurementScore", b.format(report.getLifeMeasurementScore()));
        params.put("registeredCapital", report.getRegisteredCapital());
        params.put("capitalMeasurementScore", b.format(report.getCapitalMeasurementScore()));
        params.put("address", report.getAddress());
        params.put("addressMeasurementScore", b.format(report.getAddressMeasurementScore()));
        params.put("businessAddress", report.getBusinessAddress());
        params.put("businessAddressMeasurementScore", b.format(report.getBusinessAddressMeasurementScore()));
        params.put("industry", report.getIndustry());
        params.put("constructionIndustry", supplierInfo.getConstructionIndustry() == 1 ? "是" : "否");
        params.put("businessScope", report.getBusinessScope());
        params.put("businessScopeMeasurementScore", b.format(report.getBusinessScopeMeasurementScore()));
        params.put("basicChangeSize", report.getBasicChangeSize());
        params.put("changeMeasurementScore", b.format(report.getChangeMeasurementScore()));
        List enterpriseList = new ArrayList<>();
        int enterpriseNumber = 1;
        if (CollectionUtil.isNotEmpty(enterpriseInfoHistoryList)) {
            for (CAssociatedEnterpriseInfoHistory cAssociatedEnterpriseInfoHistory : enterpriseInfoHistoryList) {
                Map map = new HashMap();
                map.put("number", enterpriseNumber);
                map.put("name", cAssociatedEnterpriseInfoHistory.getName());
                map.put("status", cAssociatedEnterpriseInfoHistory.getStatus());
                map.put("legalRepresentative", cAssociatedEnterpriseInfoHistory.getLegalRepresentative());
                map.put("stockPercent", cAssociatedEnterpriseInfoHistory.getStockPercent() + "%");
                map.put("mainBusiness", cAssociatedEnterpriseInfoHistory.getMainBusiness());
                enterpriseList.add(map);
                enterpriseNumber++;
            }
        }
        params.put("enterpriseInfoHistoryList", enterpriseList);
        List<CreditSituation> creditSituations = report.getCreditSituations();
        int personNumber = 1;
        for (CreditSituation creditSituation : creditSituations) {
            CCreditInvestigationInfoHistory creditInvestigationInfoHistory = creditSituation.getCreditInvestigationInfoHistory();
            Map map = new HashMap();
            map.put("number", personNumber);
            map.put("type", dictionaryService.getByCode(creditInvestigationInfoHistory.getType()).getName());
            map.put("name", creditInvestigationInfoHistory.getName());
            map.put("socialCreditCode", creditInvestigationInfoHistory.getSocialCreditCode());
            map.put("numberOfOverdueAccounts", creditSituation.getNumberOfOverdueAccounts());
            map.put("totalOverdueAmount", creditSituation.getTotalOverdueAmount().setScale(2, RoundingMode.HALF_UP));
            map.put("numberOfOverdueAccountsScore", b.format(creditSituation.getNumberOfOverdueAccountsScore()));
            map.put("overdue", creditSituation.getOverdue() == 1 ? "存在" : "不存在");
            map.put("overdueScore", b.format(creditSituation.getOverdueScore()));
            map.put("consecutiveOverdueMonth", creditSituation.getConsecutiveOverdueMonth());
            map.put("consecutiveOverdueMonthScore", b.format(creditSituation.getConsecutiveOverdueMonthScore()));
            map.put("accumulatedOverdueTimes", creditSituation.getAccumulatedOverdueTimes());
            map.put("numberOfApprovalQueries", creditSituation.getNumberOfApprovalQueries());
            map.put("numberOfApprovalQueriesScore", b.format(creditSituation.getNumberOfApprovalQueriesScore()));
            map.put("amountOfGuaranteeLiability", creditSituation.getAmountOfGuaranteeLiability().setScale(2,RoundingMode.HALF_UP));
            map.put("amountOfGuaranteeLiabilityScore", b.format(creditSituation.getAmountOfGuaranteeLiabilityScore()));
            map.put("badRecords", creditSituation.getBadRecords() == 1 ? "存在" : "不存在");
            map.put("badRecordsScore", b.format(creditSituation.getBadRecordsScore()));
            map.put("recordOfDishonestyExecution", creditSituation.getRecordOfDishonestyExecution() == 1 ? "存在" : "不存在");
            map.put("shiXinScore", b.format(creditSituation.getShiXinScore()));
            map.put("executedRecord", creditSituation.getExecutedRecord() == 1 ? "存在" : "不存在");
            map.put("zhiXingScore", b.format(creditSituation.getZhiXingScore()));
            map.put("stCount", creditSituation.getStCount() == 1 ? "存在" : "不存在");
            map.put("stCountScore", b.format(creditSituation.getStCountScore()));
            if (personNumber == 1) {
                params.put("personOne", map);
            } else if (personNumber == 2) {
                params.put("personTwo", map);
            } else if (personNumber == 3) {
                params.put("personThree", map);
            }
            personNumber++;
        }
        if (creditSituations.size() == 1) {
            params.put("personTwo", false);
            params.put("personThree", false);
        } else if (creditSituations.size() == 2) {
            params.put("personThree", false);
        }
        CorporateGoodwill corporateGoodwill = report.getCorporateGoodwill();
        params.put("recoveredBalance", corporateGoodwill.getRecoveredBalance() == 1 ? "存在" : "不存在");
        params.put("recoveredBalanceScore", b.format(corporateGoodwill.getRecoveredBalanceScore()));
        params.put("concernedAccountsWithOutstandingCredit", corporateGoodwill.getConcernedAccountsWithOutstandingCredit() == 1 ? "存在" : "不存在");
        params.put("concernedAccountsWithOutstandingCreditScore", b.format(corporateGoodwill.getConcernedAccountsWithOutstandingCreditScore()));
        params.put("outstandingNonPerformingAccounts", corporateGoodwill.getOutstandingNonPerformingAccounts() == 1 ? "存在" : "不存在");
        params.put("outstandingNonPerformingAccountsScore", b.format(corporateGoodwill.getOutstandingNonPerformingAccountsScore()));
        params.put("outstandingBalance", corporateGoodwill.getOutstandingBalance().setScale(2,RoundingMode.HALF_UP) + "万元");
        params.put("outstandingBalanceScore", b.format(corporateGoodwill.getOutstandingBalanceScore()));
        params.put("shiXin", corporateGoodwill.getShiXin() == 1 ? "存在" : "不存在");
        params.put("historyShiXin", corporateGoodwill.getHistoryShiXin() == 1 ? "存在" : "不存在");
        params.put("shiXinScore", b.format(corporateGoodwill.getShiXinScore()));
        params.put("zhiXing", corporateGoodwill.getZhiXing() == 1 ? "存在" : "不存在");
        params.put("historyZhiXing", corporateGoodwill.getHistoryZhiXing() == 1 ? "存在" : "不存在");
        params.put("zhiXingScore", b.format(corporateGoodwill.getZhiXingScore()));
        params.put("gaoXiao", corporateGoodwill.getGaoXiao() == 1 ? "存在" : "不存在");
        params.put("historyGaoXiao", corporateGoodwill.getHistoryGaoXiao() == 1 ? "存在" : "不存在");
        params.put("sumptuaryScore", b.format(corporateGoodwill.getSumptuaryScore()));
        params.put("punish", corporateGoodwill.getPunish() == 1 ? "存在" : "不存在");
        params.put("punishAmount", corporateGoodwill.getPunishAmount().setScale(2, RoundingMode.HALF_UP));
        params.put("administrativePenaltyScore", b.format(corporateGoodwill.getAdministrativePenaltyScore()));
        params.put("documnetYuanGao", corporateGoodwill.getDocumnetYuanGao() == 1 ? "存在" : "不存在");
        params.put("documnetBeiGao", corporateGoodwill.getDocumnetBeiGao() == 1 ? "存在" : "不存在");
        params.put("documentFinance", corporateGoodwill.getDocumentFinance() == 1 ? "存在" : "不存在");
        params.put("involvingLawsuitsScore", b.format(corporateGoodwill.getInvolvingLawsuitsScore()));
        params.put("privateLendings", corporateGoodwill.getPrivateLendings() == 1 ? "存在" : "不存在");
        params.put("seriousIllegalities", corporateGoodwill.getSeriousIllegalities() == 1 ? "存在" : "不存在");
        params.put("seriousIllegalityScore", b.format(corporateGoodwill.getSeriousIllegalityScore()));
        params.put("taxOweNotices", corporateGoodwill.getTaxOweNotices() == 1 ? "存在" : "不存在");
        params.put("taxOweNoticeScore", b.format(corporateGoodwill.getTaxOweNoticeScore()));
        params.put("taxIllegalData", corporateGoodwill.getTaxIllegalData() == 1 ? "存在" : "不存在");
        params.put("taxIllegalDataScore", b.format(corporateGoodwill.getTaxIllegalDataScore()));
        params.put("blacklists", corporateGoodwill.getBlacklists() == 1 ? "存在" : "不存在");
        params.put("blacklistScore", b.format(corporateGoodwill.getBlacklistScore()));
        params.put("exceptionData", corporateGoodwill.getExceptionData() == 1 ? "存在" : "不存在");
        params.put("exceptionDataScore", b.format(corporateGoodwill.getExceptionDataScore()));
        params.put("news", corporateGoodwill.getNews() == 1 ? "存在" : "不存在");
        params.put("newsScore", b.format(corporateGoodwill.getNewsScore()));
        VideoDueDiligenceFinance videoDueDiligenceFinance = report.getVideoDueDiligenceFinance();
        params.put("mainBusinessIncomeFix", videoDueDiligenceFinance.getMainBusinessIncomeFix().setScale(2, RoundingMode.HALF_UP));
        params.put("mainBusinessIncomeScore", videoDueDiligenceFinance.getMainBusinessIncomeScore().setScale(2,RoundingMode.HALF_UP));
        params.put("mainBusinessCostFix", videoDueDiligenceFinance.getMainBusinessCostFix().setScale(2, RoundingMode.HALF_UP));
        params.put("mainBusinessProfitFix", videoDueDiligenceFinance.getMainBusinessProfitFix().setScale(2, RoundingMode.HALF_UP));
        params.put("mainBusinessProfitScore", videoDueDiligenceFinance.getMainBusinessProfitScore().setScale(2, RoundingMode.HALF_UP));
        List<UpstreamProcurementDocuments> upstreamProcurementDocumentsList = report.getUpstreamProcurementDocumentsList();
        List upstreamProcurementDocuments = new ArrayList();
        if (CollectionUtil.isNotEmpty(upstreamProcurementDocumentsList)) {
            for (UpstreamProcurementDocuments upstreamProcurementDocument : upstreamProcurementDocumentsList) {
                Map map = new HashMap();
                map.put("name", upstreamProcurementDocument.getName());
                map.put("score", b.format(upstreamProcurementDocument.getScore()));
                upstreamProcurementDocuments.add(map);
            }
        }
        params.put("upstreamProcurementDocumentsList", upstreamProcurementDocuments);
        List<SalesDocumentsInfo> salesDocumentsInfoList = report.getSalesDocumentsInfoList();
        List salesDocumentsInfoListList = new ArrayList();
        if (CollectionUtil.isNotEmpty(salesDocumentsInfoList)) {
            for (SalesDocumentsInfo salesDocumentsInfo : salesDocumentsInfoList) {
                Map map = new HashMap();
                map.put("name", salesDocumentsInfo.getName());
                map.put("score", b.format(salesDocumentsInfo.getScore()));
                salesDocumentsInfoListList.add(map);
            }
        }
        params.put("salesDocumentsInfoList", salesDocumentsInfoListList);
        VideoDueDiligenceComprehensiveEvaluation videoDueDiligenceComprehensiveEvaluation = report.getVideoDueDiligenceComprehensiveEvaluation();
        params.put("revenueRating", videoDueDiligenceComprehensiveEvaluation.getRevenueRating());
        params.put("evaluationOpinions", videoDueDiligenceComprehensiveEvaluation.getEvaluationOpinions());
        params.put("admitted", videoDueDiligenceComprehensiveEvaluation.getAdmitted());
        params.put("score", b.format(videoDueDiligenceComprehensiveEvaluation.getScore()));
        params.put("creditLimit", videoDueDiligenceComprehensiveEvaluation.getCreditLimit().setScale(2, RoundingMode.HALF_UP));
        //模板地址
        ClassPathResource classPathResource = new ClassPathResource("ftl/supplier/supplierReport.docx");
        LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();

        Configure config = Configure.builder()
                .bind("regStocks", policy)
                .bind("enterpriseInfoHistoryList", policy)
                .bind("salesDocumentsInfoList", policy)
                .bind("upstreamProcurementDocumentsList", policy)
                .build();

        XWPFTemplate template = XWPFTemplate.compile(classPathResource.getInputStream(), config).render(params);
        String path = FileUtil.getAbsolutePath(UUID.randomUUID().toString(), ".docx", FileModuleDict.ChildEnum.SUPPLIER_REPORT);
        File docxFile = new File(path);
        if (!docxFile.exists()) {
            FileUtils.createParentDirectories(docxFile);
        }
        template.writeToFile(path);
        //将docx转为pdf
        String suffix = FileUtil.getSuffix(docxFile.getName());
        String newPath = docxFile.getAbsolutePath().replace(suffix, ".pdf");
        File pdfFile = OfficeConverterUtil.office2Pdf(docxFile.getAbsolutePath(), newPath);
        docxFile.deleteOnExit();
        FileUtil.downloadPdfFile(response, pdfFile);
    }

    @Override
    public List<SupplierInfo> getByClientUserId(Long cUserId) {
        return   this.baseMapper.findByCUserId(cUserId);
    }

    @Override
    public SupplierInfo getByEnterpriseId(Long enterpriseId) {
        return baseMapper.getByEnterpriseId(enterpriseId);
    }

    private void autoCreditSituation(VideoDueDiligenceShareholdersSituation videoDueDiligenceShareholdersSituation, CreditSituation creditSituation) {
        creditSituation.setNumberOfOverdueAccounts(videoDueDiligenceShareholdersSituation.getOverdueAccounts());
        creditSituation.setTotalOverdueAmount(videoDueDiligenceShareholdersSituation.getTotalOverdueAmountFix());
        creditSituation.setNumberOfOverdueAccountsScore(videoDueDiligenceShareholdersSituation.getNumberOfOverdueAccountsScore());
        creditSituation.setOverdue(videoDueDiligenceShareholdersSituation.getOver90DaysOverdue());
        creditSituation.setOverdueScore(videoDueDiligenceShareholdersSituation.getOverdueScore());
        creditSituation.setConsecutiveOverdueMonth(videoDueDiligenceShareholdersSituation.getOverdueMonths());
        creditSituation.setAccumulatedOverdueTimes(videoDueDiligenceShareholdersSituation.getNumberOfOverdueRepayments());
        creditSituation.setConsecutiveOverdueMonthScore(videoDueDiligenceShareholdersSituation.getConsecutiveOverdueMonthScore());
        creditSituation.setNumberOfApprovalQueries(videoDueDiligenceShareholdersSituation.getNumberOfLoanInquiries());
        creditSituation.setNumberOfApprovalQueriesScore(videoDueDiligenceShareholdersSituation.getNumberOfApprovalQueriesScore());
        creditSituation.setAmountOfGuaranteeLiability(videoDueDiligenceShareholdersSituation.getRepaymentGuaranteeAmount());
        creditSituation.setAmountOfGuaranteeLiabilityScore(videoDueDiligenceShareholdersSituation.getAmountOfGuaranteeLiabilityScore());
        creditSituation.setBadRecords(videoDueDiligenceShareholdersSituation.getBadRecordsFix());
        creditSituation.setBadRecordsScore(videoDueDiligenceShareholdersSituation.getBadRecordsScore());
        creditSituation.setRecordOfDishonestyExecution(videoDueDiligenceShareholdersSituation.getRecordOfDishonestyExecutionFix());
        creditSituation.setShiXinScore(videoDueDiligenceShareholdersSituation.getShiXinScore());
        creditSituation.setExecutedRecord(videoDueDiligenceShareholdersSituation.getExecutedRecordFix());
        creditSituation.setZhiXingScore(videoDueDiligenceShareholdersSituation.getZhiXingScore());
        creditSituation.setStCount(videoDueDiligenceShareholdersSituation.getStCountFix());
        creditSituation.setStCountScore(videoDueDiligenceShareholdersSituation.getStCountScore());
    }


}
