package com.inkasso.factoring.creditmanagement.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.inkasso.adapter.exception.ServiceException;
import com.inkasso.adapter.util.CodeUtil;
import com.inkasso.adapter.util.CollectionUtil;
import com.inkasso.adapter.util.StringUtil;
import com.inkasso.adapter.web.LoginUserHolder;
import com.inkasso.auth.exception.ValidatorException;
import com.inkasso.factoring.common.constant.ConstantUtil;
import com.inkasso.factoring.common.entity.ResponseJson;
import com.inkasso.factoring.common.service.SerialNumberGenerator;
import com.inkasso.factoring.creditmanagement.dao.ProjectInformationMapper;
import com.inkasso.factoring.creditmanagement.entity.*;
import com.inkasso.factoring.creditmanagement.entity.vo.UserBiddingProjectsVo;
import com.inkasso.factoring.creditmanagement.enums.ProjectAndEnterpriseStatusEnums;
import com.inkasso.factoring.creditmanagement.enums.ProjectInitiationStatusDict;
import com.inkasso.factoring.creditmanagement.service.*;
import com.inkasso.factoring.dict.entity.Dictionary;
import com.inkasso.factoring.dict.service.DictionaryService;
import com.inkasso.factoring.file.entity.FileStorageDO;
import com.inkasso.factoring.file.enums.FileTypeEnum;
import com.inkasso.factoring.file.service.FileService;
import com.inkasso.factoring.purchManagement.dao.CPurchContractManagementMapper;
import com.inkasso.factoring.purchManagement.entity.vo.PurchContractCompletedVo;
import com.inkasso.factoring.purchManagement.service.ICPurchContractManagementService;
import com.inkasso.factoring.system.user.entity.UserDO;
import com.inkasso.factoring.system.user.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.xpath.operations.Bool;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 项目信息 服务实现类
 * </p>
 *
 * @author liutao
 * @since 2023-11-25
 */
@Service
public class ProjectInformationServiceImpl extends ServiceImpl<ProjectInformationMapper, ProjectInformation> implements IProjectInformationService {

    private static Logger log = LogManager.getLogger(ProjectInformationServiceImpl.class);
    @Autowired
    private SerialNumberGenerator serialNumberGenerator;

    @Autowired
    private IEnterpriseService enterpriseService;

    @Autowired
    private IProjectCoreEnterpriseService projectCoreEnterpriseService;

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

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

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

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

    @Value("${trade.startProjectProcessUrl}")
    private String startProjectProcess;

    @Value("${trade.startProjectCoreEnterpriseProcessUrl}")
    private String startProjectCoreEnterpriseProcess;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private IProjectCoreEnterpriseFileService projectCoreEnterpriseFileService;

    @Autowired
    private FileService fileService;

    @Autowired
    private ICProjectCoreEnterpriseFileHistoryService projectCoreEnterpriseFileHistoryService;

    @Autowired
    private ICProjectCoreEnterpriseHistoryService projectCoreEnterpriseHistoryService;

    @Autowired
    private ICProjectInformationHistoryService projectInformationHistoryService;

    @Autowired
    private ICEnterpriseHistoryService enterpriseHistoryService;

    @Autowired
    private DictionaryService dictionaryService;

    @Autowired
    private UserService userService;

    @Autowired
    private ISupplierInfoService supplierInfoService;

    @Autowired
    private ICreditResolutionService creditResolutionService;

    @Autowired
    private ICreditConclusionService creditConclusionService;

    @Autowired
    private CPurchContractManagementMapper cPurchContractManagementMapper;

    @Override
    public List<UserBiddingProjectsVo> getUserBiddingProjects() {
        List<UserBiddingProjectsVo> list = baseMapper.getUserBiddingProjects(LoginUserHolder.get().getId());
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ProjectInformation addProject(ProjectInformation projectInformation) {
        //保存项目信息
        String businessNumber = serialNumberGenerator.nextValue(ConstantUtil.BUSINESS_CODE);
        projectInformation.setBusinessNumber(businessNumber);
        //业主方
        Enterprise enterprise = projectInformation.getEnterprise();
        if(enterprise != null){
            Enterprise existEnterprise = enterpriseService.lambdaQuery().eq(Enterprise::getSocialCreditCode, enterprise.getSocialCreditCode()).one();
            if (existEnterprise != null) {
                enterprise = existEnterprise;
                projectInformation.setcEnterpriseId(existEnterprise.getId());
            } else {
                enterpriseService.save(enterprise);
                projectInformation.setcEnterpriseId(enterprise.getId());
            }
        }
        //相同供应商业务名称相同的话  增加 01 02 03
        List<ProjectInformation> list = lambdaQuery().like(ProjectInformation::getProjectName, projectInformation.getProjectName() + "%").list();
        projectInformation.setProjectName(projectInformation.getProjectName() + "_" + list.size() + 1);
        save(projectInformation);
        //核心企业
        ProjectCoreEnterprise projectCore = projectInformation.getProjectCoreEnterprise();
        projectCore.setcProjectInformationId(projectInformation.getId());
        Enterprise coreEnterprise = projectCore.getEnterprise();
        Enterprise existProjectCoreEnterprise = enterpriseService.lambdaQuery().eq(Enterprise::getSocialCreditCode, coreEnterprise.getSocialCreditCode()).one();
        if (existProjectCoreEnterprise != null) {
            coreEnterprise = existProjectCoreEnterprise;
            projectCore.setcEnterpriseId(existProjectCoreEnterprise.getId());
        } else {
            enterpriseService.save(coreEnterprise);
            projectCore.setcEnterpriseId(coreEnterprise.getId());
        }
        projectCoreEnterpriseService.save(projectCore);
        if(enterprise != null){
            //业主方企查查
            List<String> errors = qichacha(projectInformation, enterprise, null);
            if(CollectionUtil.isNotEmpty(errors)){
                String errorsString = errors.stream().collect(Collectors.joining(","));
                projectInformation.setErrorsString(errorsString);
            }
            enterprise.setErrors(errors);
            enterpriseService.updateById(enterprise);
            CEnterpriseHistory cEnterpriseHistory = new CEnterpriseHistory();
            BeanUtils.copyProperties(enterprise, cEnterpriseHistory, "id");
            enterpriseHistoryService.save(cEnterpriseHistory);
            projectInformation.setcEnterpriseHistoryId(cEnterpriseHistory.getId());
            updateById(projectInformation);
        }
        //核心企业企查查
        List<String> coreErrors = qichacha(null, coreEnterprise, projectCore);
        if(CollectionUtil.isNotEmpty(coreErrors)){
            String errorsString = coreErrors.stream().collect(Collectors.joining(","));
            projectCore.setErrorsString(errorsString);
        }
        coreEnterprise.setErrors(coreErrors);
        if(enterprise == null){
            String status = projectCore.getStatus();
            projectInformation.setStatus(status);
            updateById(projectInformation);
        }
        enterpriseService.updateById(coreEnterprise);
        CEnterpriseHistory cCoreEnterpriseHistory = new CEnterpriseHistory();
        BeanUtils.copyProperties(coreEnterprise, cCoreEnterpriseHistory, "id");
        enterpriseHistoryService.save(cCoreEnterpriseHistory);
        projectCore.setcEnterpriseHistoryId(cCoreEnterpriseHistory.getId());
        projectCoreEnterpriseService.updateById(projectCore);
        return projectInformation;
    }

    @Override
    public ProjectInformation getSuppplement(Long id) {
        ProjectInformation projectInformation = getById(id);
        SupplierInfo supplierInfo = supplierInfoService.getById(projectInformation.getcSupplierInfoId());
        //供应商名称
        Enterprise supplierEnterprise = enterpriseService.getById(supplierInfo.getcEnterpriseId());
        projectInformation.setSupplierName(supplierEnterprise.getCorporateName());
        List<FileStorageDO> biddingFiles = fileService.lambdaQuery().eq(FileStorageDO::getBusinessId, projectInformation.getId())
                .eq(FileStorageDO::getBusinessType, FileTypeEnum.PROJECT_BIDDING_FILE.getCode()).list();
        List<FileStorageDO> departmentFiles = fileService.lambdaQuery().eq(FileStorageDO::getBusinessId, projectInformation.getId())
                .eq(FileStorageDO::getBusinessType, FileTypeEnum.PROJECT_DEPARTMENT_FILE.getCode()).list();
        projectInformation.setBiddingFiles(biddingFiles);
        projectInformation.setDepartmentFiles(departmentFiles);
        if(projectInformation.getcEnterpriseId() != null){
            Enterprise ownerEnterprise = enterpriseService.getById(projectInformation.getcEnterpriseId());
            projectInformation.setEnterprise(ownerEnterprise);
        }
        ProjectCoreEnterprise projectCoreEnterprise = projectCoreEnterpriseService.lambdaQuery().eq(ProjectCoreEnterprise::getcProjectInformationId, id).one();
        Enterprise enterprise = enterpriseService.getById(projectCoreEnterprise.getcEnterpriseId());
        List<ProjectCoreEnterpriseFile> projectCoreEnterpriseFiles = projectCoreEnterpriseFileService.lambdaQuery().eq(ProjectCoreEnterpriseFile::getcProjectCoreEnterpriseId, projectCoreEnterprise.getId()).list();
        if(CollectionUtil.isNotEmpty(projectCoreEnterpriseFiles)){
            for (ProjectCoreEnterpriseFile projectCoreEnterpriseFile : projectCoreEnterpriseFiles) {
                List<FileStorageDO> fileStorageDOS = fileService.findByBusinessId(projectCoreEnterpriseFile.getId(), FileTypeEnum.PROJECT_CORE_ENTERPRISE_FILE.getCode());
                projectCoreEnterpriseFile.setFileStorageDOS(fileStorageDOS);
            }
            projectCoreEnterprise.setProjectCoreEnterpriseFiles(projectCoreEnterpriseFiles);
        }
        projectCoreEnterprise.setEnterprise(enterprise);
        projectInformation.setProjectCoreEnterprise(projectCoreEnterprise);
        return projectInformation;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void supplement(ProjectInformation projectInformation) {
        //补充项目信息
        String status = getById(projectInformation.getId()).getStatus();
        if(!status.equals(ProjectAndEnterpriseStatusEnums.VOTE.getCode())){
            updateById(projectInformation);
            fileService.lambdaUpdate().eq(FileStorageDO::getBusinessId,projectInformation.getId())
                    .eq(FileStorageDO::getBusinessType, FileTypeEnum.PROJECT_BIDDING_FILE.getCode())
                    .set(FileStorageDO::getBusinessId,null).update();
            //保存文件
            List<Long> files = projectInformation.getBiddingFileIds();
            fileService.updateBusinessId(files,projectInformation.getId());
            fileService.lambdaUpdate().eq(FileStorageDO::getBusinessId,projectInformation.getId())
                    .eq(FileStorageDO::getBusinessType,FileTypeEnum.PROJECT_DEPARTMENT_FILE.getCode())
                    .set(FileStorageDO::getBusinessId,null).update();
            //保存文件
            List<Long> departmentFileIds = projectInformation.getDepartmentFileIds();
            fileService.updateBusinessId(departmentFileIds,projectInformation.getId());
        }
        //补充核心企业信息
        String coreStatus = null;
        ProjectCoreEnterprise projectCoreEnterprise = projectInformation.getProjectCoreEnterprise();
        if(projectCoreEnterprise != null){
            coreStatus = projectCoreEnterpriseService.getById(projectCoreEnterprise.getId()).getStatus();
            if(!coreStatus.equals(ProjectAndEnterpriseStatusEnums.VOTE.getCode())){
                projectCoreEnterpriseService.updateById(projectCoreEnterprise);
                if(projectCoreEnterprise.getHistoricalCooperation() != null && projectCoreEnterprise.getHistoricalCooperation() == 1){
                    //历史合作资料 先删后增
                    projectCoreEnterpriseFileService.lambdaUpdate().eq(ProjectCoreEnterpriseFile::getcProjectCoreEnterpriseId, projectCoreEnterprise.getId()).remove();
                    List<ProjectCoreEnterpriseFile> projectCoreEnterpriseFiles = projectCoreEnterprise.getProjectCoreEnterpriseFiles();
                    for (ProjectCoreEnterpriseFile projectCoreEnterpriseFile : projectCoreEnterpriseFiles) {
                        projectCoreEnterpriseFile.setcProjectCoreEnterpriseId(projectCoreEnterprise.getId());
                        projectCoreEnterpriseFileService.save(projectCoreEnterpriseFile);
                        //保存文件
                        List<Long> fileIds = projectCoreEnterpriseFile.getFileIds();
                        if(CollectionUtil.isNotEmpty(fileIds)){
                            fileService.updateBusinessId(fileIds,projectCoreEnterpriseFile.getId());
                        }
                    }
                }
            }
        }
        Boolean visible = projectInformation.getVisible();
        if(visible){
            ProjectInformation existsProject = getById(projectInformation.getId());
            SupplierInfo supplierInfo = supplierInfoService.getById(existsProject.getcSupplierInfoId());
            Long sysUserId = supplierInfo.getSysUserId();
            UserDO userDO = userService.getById(sysUserId);
            Long riskManagerId = userDO.getRiskManager();
            if(riskManagerId == null){
                throw new ServiceException(CodeUtil.FAIL,"请联系客服分配风控经理！");
            }
            if(userDO.getProjectManager() == null){
                throw new ServiceException(CodeUtil.FAIL,"请联系客服分配业务经理！");
            }
            existsProject.setRiskManagerId(riskManagerId);
            if(!status.equals(ProjectAndEnterpriseStatusEnums.VOTE.getCode())){
                BigDecimal financialFunds = projectInformation.getFinancialFunds() == null? BigDecimal.ZERO : projectInformation.getFinancialFunds();
                BigDecimal bankLoans = projectInformation.getBankLoans() == null? BigDecimal.ZERO : projectInformation.getBankLoans();
                BigDecimal foreignCapital = projectInformation.getForeignCapital() == null? BigDecimal.ZERO : projectInformation.getForeignCapital();
                BigDecimal raiseIndependently = projectInformation.getRaiseIndependently() == null? BigDecimal.ZERO : projectInformation.getRaiseIndependently();
                BigDecimal specialFund = projectInformation.getSpecialFund() == null? BigDecimal.ZERO : projectInformation.getSpecialFund();
                BigDecimal otherFunds = projectInformation.getOtherFunds() == null? BigDecimal.ZERO : projectInformation.getOtherFunds();
                BigDecimal unknown = projectInformation.getUnknown() == null? BigDecimal.ZERO : projectInformation.getUnknown();
                BigDecimal total = financialFunds.add(bankLoans).add(foreignCapital).add(raiseIndependently).add(specialFund).add(otherFunds).add(unknown);
                if(total.compareTo(new BigDecimal(100)) != 0){
                    throw new ServiceException(CodeUtil.FAIL,"资金来源及占比加和必须等于100");
                }
                //保存项目信息历史
                CProjectInformationHistory cProjectInformationHistory = new CProjectInformationHistory();
                BeanUtils.copyProperties(existsProject,cProjectInformationHistory,"id");
                projectInformationHistoryService.save(cProjectInformationHistory);
                //保存文件历史
                List<Long> files = projectInformation.getBiddingFileIds();
                if(CollectionUtil.isNotEmpty(files)){
                    for (Long file : files) {
                        FileStorageDO fileStorageDO = fileService.getById(file);
                        fileStorageDO.setId(null);
                        fileStorageDO.setBusinessId(cProjectInformationHistory.getId());
                        fileStorageDO.setBusinessType(fileStorageDO.getBusinessType() + "History");
                        fileService.save(fileStorageDO);
                    }
                }
                //保存文件历史
                List<Long> departmentFileIds = projectInformation.getDepartmentFileIds();
                if(CollectionUtil.isNotEmpty(departmentFileIds)){
                    for (Long file : departmentFileIds) {
                        FileStorageDO fileStorageDO = fileService.getById(file);
                        fileStorageDO.setId(null);
                        fileStorageDO.setBusinessId(cProjectInformationHistory.getId());
                        fileStorageDO.setBusinessType(fileStorageDO.getBusinessType() + "History");
                        fileService.save(fileStorageDO);
                    }
                }
                if(existsProject.getcEnterpriseId() != null){
                    //更改项目状态
                    projectInformation.setStatus(ProjectAndEnterpriseStatusEnums.DUE_DILIGENCE_REVIEW.getCode());
                    updateById(projectInformation);
                    //开启B端流程
                    existsProject.setHistoryId(cProjectInformationHistory.getId());
                    if(projectCoreEnterprise != null && projectCoreEnterprise.getId() != null){
                        ProjectCoreEnterprise existsProjectCoreEnterprise = projectCoreEnterpriseService.getById(projectCoreEnterprise.getId());
                        Enterprise existsEnterprise = enterpriseService.getById(existsProjectCoreEnterprise.getcEnterpriseId());
                        existsProjectCoreEnterprise.setEnterprise(existsEnterprise);
                        existsProject.setProjectCoreEnterprise(existsProjectCoreEnterprise);
                    }
                    Enterprise existsProjectEnterprise = enterpriseService.getById(existsProject.getcEnterpriseId());
                    existsProject.setEnterprise(existsProjectEnterprise);
                    try {
                        restTemplate.postForObject(startProjectProcess,existsProject,ResponseJson.class);
                    }catch (Exception e){
                        throw new ServiceException(CodeUtil.FAIL,"网络异常，请稍后重试！");
                    }
                }
            }
            if(coreStatus != null && !coreStatus.equals(ProjectAndEnterpriseStatusEnums.VOTE.getCode())){
                //保存核心企业历史
                CProjectCoreEnterpriseHistory cProjectCoreEnterpriseHistory = new CProjectCoreEnterpriseHistory();
                ProjectCoreEnterprise existsProjectCoreEnterprise = projectCoreEnterpriseService.getById(projectCoreEnterprise.getId());
                BeanUtils.copyProperties(existsProjectCoreEnterprise,cProjectCoreEnterpriseHistory,"id");
                projectCoreEnterpriseHistoryService.save(cProjectCoreEnterpriseHistory);
                if(projectCoreEnterprise.getHistoricalCooperation() == 1){
                    //历史合作资料 历史
                    List<ProjectCoreEnterpriseFile> projectCoreEnterpriseFiles = projectCoreEnterprise.getProjectCoreEnterpriseFiles();
                    for (ProjectCoreEnterpriseFile projectCoreEnterpriseFile : projectCoreEnterpriseFiles) {
                        CProjectCoreEnterpriseFileHistory cProjectCoreEnterpriseFileHistory = new CProjectCoreEnterpriseFileHistory();
                        BeanUtils.copyProperties(projectCoreEnterpriseFile,cProjectCoreEnterpriseFileHistory);
                        cProjectCoreEnterpriseFileHistory.setcProjectCoreEnterpriseId(cProjectCoreEnterpriseHistory.getId());
                        projectCoreEnterpriseFileHistoryService.save(cProjectCoreEnterpriseFileHistory);
                        List<Long> fileIds = projectCoreEnterpriseFile.getFileIds();
                        if(CollectionUtil.isNotEmpty(fileIds)){
                            for (Long fileId : fileIds) {
                                FileStorageDO fileStorageDO = fileService.getById(fileId);
                                FileStorageDO fileStorageDOHistory = new FileStorageDO();
                                BeanUtils.copyProperties(fileStorageDO,fileStorageDOHistory,"id");
                                fileStorageDOHistory.setBusinessType(FileTypeEnum.PROJECT_CORE_ENTERPRISE_FILE_HISTORY.getCode());
                                fileStorageDOHistory.setBusinessId(cProjectCoreEnterpriseFileHistory.getId());
                                fileService.save(fileStorageDOHistory);
                            }
                            fileService.updateBusinessId(fileIds,projectCoreEnterpriseFile.getId());
                        }
                    }
                }
                //更改项目核心企业状态
                projectCoreEnterprise.setStatus(ProjectAndEnterpriseStatusEnums.DUE_DILIGENCE_REVIEW.getCode());
                projectCoreEnterpriseService.updateById(projectCoreEnterprise);
                //判断3个月内是否授信过  如果是就无需再次授信
                List<ProjectCoreEnterprise> list = projectCoreEnterpriseService.lambdaQuery()
                        .eq(ProjectCoreEnterprise::getcEnterpriseId, existsProjectCoreEnterprise.getcEnterpriseId())
                        .eq(ProjectCoreEnterprise::getStatus,ProjectAndEnterpriseStatusEnums.CREDIT_SUCCESS.getCode())
                        .orderByDesc(ProjectCoreEnterprise::getGmtCreate).list();
                Boolean start ;
                if(CollectionUtil.isNotEmpty(list)){
                    ProjectCoreEnterprise old = list.get(0);
                    Date dateTime = DateUtil.offsetMonth(old.getGmtCreate(), 3);
                    if(dateTime.compareTo(new Date()) == 1){
                        start = false;
                        projectCoreEnterprise.setProcess(0);
                        projectCoreEnterprise.setOldCoreEnterpriseId(old.getId());
                        projectCoreEnterprise.setStatus(ProjectAndEnterpriseStatusEnums.CREDIT_SUCCESS.getCode());
                        projectCoreEnterpriseService.updateById(projectCoreEnterprise);
                    }else {
                        start = true;
                    }
                }else {
                    start = true;
                }
                if(start){
                    //开启B端流程
                    Enterprise existsProjectEnterprise = enterpriseService.getById(existsProject.getcEnterpriseId());
                    existsProject.setEnterprise(existsProjectEnterprise);
                    Enterprise existsEnterprise = enterpriseService.getById(existsProjectCoreEnterprise.getcEnterpriseId());
                    existsProjectCoreEnterprise.setEnterprise(existsEnterprise);
                    existsProjectCoreEnterprise.setHistoryId(cProjectCoreEnterpriseHistory.getId());
                    existsProject.setProjectCoreEnterprise(existsProjectCoreEnterprise);
                    try {
                        restTemplate.postForObject(startProjectCoreEnterpriseProcess,existsProject,ResponseJson.class);
                    }catch (Exception e){
                        throw new ServiceException(CodeUtil.FAIL,"网络异常，请稍后重试！");
                    }
                }
            }
        }
    }

    @Override
    public List<ProjectInformation> getLocalPurchCompletedProject() {
        List<ProjectInformation> localPurchCompletedProject = baseMapper.getLocalPurchCompletedProject(
            LoginUserHolder.get().getId());
        if(CollectionUtil.isNotEmpty(localPurchCompletedProject)){
            for(ProjectInformation p:localPurchCompletedProject){
//                PurchContractCompletedVo completedPurchContractByBusinessNumber = purchContractService.getCompletedPurchContractByBusinessNumber(
//                    p.getBusinessNumber());
                PurchContractCompletedVo purchContractCompletedVo = cPurchContractManagementMapper
                    .getCompletedPurchContractByBusinessNumber(LoginUserHolder.get().getId(), p.getBusinessNumber());
                if(purchContractCompletedVo!=null){
                    if (purchContractCompletedVo.getMainEnterpriseId() != null) {
                        Enterprise mainEnterprise = enterpriseService.getById(purchContractCompletedVo.getMainEnterpriseId());
                        if (mainEnterprise != null) {
                            p.setProjectName(p.getProjectName()+"("+mainEnterprise.getCorporateName()+")");
                        }
                    }

                }
            }
        }
        return localPurchCompletedProject;
    }

    @Override
    public List<ProjectInformation> getProjectBySupplierId(Long supplierId) {
        List<ProjectInformation> list = lambdaQuery().eq(ProjectInformation::getcSupplierInfoId, supplierId).orderByDesc(ProjectInformation::getGmtModified).list();
        list.forEach(r->{
            if(r.getcEnterpriseId() != null){
                Enterprise enterprise = enterpriseService.getById(r.getcEnterpriseId());
                r.setOwnerName(enterprise.getCorporateName());
            }
            ProjectCoreEnterprise one = projectCoreEnterpriseService.lambdaQuery().eq(ProjectCoreEnterprise::getcProjectInformationId, r.getId()).one();
            Enterprise coreEnterprise = enterpriseService.getById(one.getcEnterpriseId());
            r.setCoreEnterpriseName(coreEnterprise.getCorporateName());
            Dictionary byCode = dictionaryService.getByCode(r.getStatus());
            Dictionary dictionary = dictionaryService.getByCode(one.getStatus());
            r.setCoreEnterpriseStatusStr(dictionary.getName());
            r.setProjectStatusStr(byCode.getName());
        });
        return list;
    }

    @Override
    public ProjectInformation getDetail(Long id) {
        ProjectInformation projectInformation = getById(id);
        ProjectCoreEnterprise projectCoreEnterprise = projectCoreEnterpriseService.lambdaQuery().eq(ProjectCoreEnterprise::getcProjectInformationId, projectInformation.getId()).one();
        Enterprise enterprise = enterpriseService.getById(projectCoreEnterprise.getcEnterpriseId());
        projectCoreEnterprise.setEnterprise(enterprise);
        projectInformation.setProjectCoreEnterprise(projectCoreEnterprise);
        projectInformation.setCoreEnterpriseName(enterprise.getCorporateName());
        projectInformation.setCoreEnterpriseStatusStr(dictionaryService.getByCode(projectCoreEnterprise.getStatus()).getName());
        projectInformation.setProjectStatusStr(dictionaryService.getByCode(projectInformation.getStatus()).getName());
        CreditResolution creditResolution = creditResolutionService.lambdaQuery().eq(CreditResolution::getcProjectInformationId, projectInformation.getId()).one();
        if(creditResolution != null){
            if(ProjectInitiationStatusDict.COMPLETED.getCode().equals(creditResolution.getStatusStr())){
                List<CreditConclusion> creditConclusions = creditConclusionService.lambdaQuery().eq(CreditConclusion::getCreditResolutionId, creditResolution.getId()).list();
                for (CreditConclusion creditConclusion : creditConclusions) {
                    if(creditConclusion.getContent().startsWith("给予卖方")){
                        creditConclusion.setFx("/给予卖方(.*?)授信金额(.*?)元人民币/g");
                    }
                    if(creditConclusion.getContent().startsWith("授信期限自")){
                        creditConclusion.setFx("/授信期限自(.+)/");
                    }
                    if(creditConclusion.getContent().startsWith("本次合作的买方为")){
                        creditConclusion.setFx("/本次合作的买方为(.*?)，项目为(.+)/");
                    }
                    if(creditConclusion.getContent().startsWith("利息和管理费")){
                        creditConclusion.setFx("/利息和管理费由卖方支付，支付方式为([\\s\\S]*)/");
                    }
                    if(creditConclusion.getContent().startsWith("上游账期为")){
                        creditConclusion.setFx("/上游账期为(.+?)，保理融资期限为(.+?)账期/");
                    }
                    if(creditConclusion.getContent().startsWith("上报卖方")){
                        creditConclusion.setFx("/上报卖方([\\s\\S]+?)征信/g");
                    }
                    if(creditConclusion.getContent().startsWith("卖方法定代表人") || creditConclusion.getContent().startsWith("提供个人连带责任担保") || creditConclusion.getContent().startsWith("提供连带责任担保") ){
                        creditConclusion.setFx("/卖方法定代表人([\\s\\S]*?)提供个人连带责任担保，上报([\\s\\S]*?)征信/g");
                    }
                }
                projectInformation.setCreditConclusions(creditConclusions);
            }
        }
        return projectInformation;
    }

    /**
     * @param projectInformation 项目信息
     * @param enterprise         企业信息
     * @param projectCore        核心企业信息
     */
    private List<String> qichacha(ProjectInformation projectInformation, Enterprise enterprise, ProjectCoreEnterprise projectCore) {
        if(StringUtils.isEmpty(enterprise.getSocialCreditCode())){
            throw new ServiceException(CodeUtil.FAIL,enterprise.getCorporateName() + "不存在统一社会信用代码，无法进行后续授信操作！");
        }
        List<String> error = new ArrayList<>();
        //2006综合风险排查
        String comprehensiveRiskInvestigationUrl = comprehensiveRiskInvestigation + "?socialCreditCode=" + enterprise.getSocialCreditCode();
        ResponseJson comprehensiveRiskInvestigationRj;
        try {
            comprehensiveRiskInvestigationRj = restTemplate.getForObject(comprehensiveRiskInvestigationUrl, ResponseJson.class);
        }catch (Exception e){
            throw new ServiceException(CodeUtil.FAIL,"网络异常，请稍后重试！");
        }
        JSONObject comprehensiveRiskJsonObject = new JSONObject(comprehensiveRiskInvestigationRj.getData());
        Long comprehensiveRiskInvestigationId = comprehensiveRiskJsonObject.getLong("id");
        enterprise.setcComprehensiveRiskInvestigationId(comprehensiveRiskInvestigationId);
        String entType = comprehensiveRiskJsonObject.getStr("entType");
        Integer shixin = comprehensiveRiskJsonObject.getInt("shixin");
        Integer sumptuary = comprehensiveRiskJsonObject.getInt("sumptuary");
        Date startDate = comprehensiveRiskJsonObject.getDate("startDate");
        String address = comprehensiveRiskJsonObject.getStr("address");
        String registCapi = comprehensiveRiskJsonObject.getStr("registCapi");
        String province = comprehensiveRiskJsonObject.getStr("province");
        String city = comprehensiveRiskJsonObject.getStr("city");
        String annualAddress = comprehensiveRiskJsonObject.getStr("annualAddress");
        BigDecimal zhixingAmount = comprehensiveRiskJsonObject.getBigDecimal("zhixingAmount");
        enterprise.setBusinessAddress(annualAddress);
        enterprise.setRegisteredCapital(registCapi);
        if(StringUtils.isEmpty(registCapi)){
            throw new ServiceException(CodeUtil.FAIL,enterprise.getCorporateName() + "不存在注册资本，无法进行后续授信操作！");
        }
        registCapi = registCapi.replace("万元人民币", "");
        Double registCapiInt = Double.valueOf(registCapi);
        long betweenYear = 0L;
        if(startDate != null){
            betweenYear = DateUtil.betweenYear(startDate, new Date(), false);
        }
        //企业基本变动信息
        String getChangesUrl = getChanges + "?comprehensiveRiskInvestigationId=" + enterprise.getcComprehensiveRiskInvestigationId();
        Integer changes;
        try {
            changes = restTemplate.getForObject(getChangesUrl, Integer.class);
        }catch (Exception e){
            throw new ServiceException(CodeUtil.FAIL,"网络异常，请稍后重试！");
        }
        //887-裁判文书核查
        String judgmentDocumentsUrl = judgmentDocuments + "?socialCreditCode=" + enterprise.getSocialCreditCode() + "&comprehensiveRiskInvestigationId=" + comprehensiveRiskInvestigationId;
        ResponseJson judgmentDocumentsObject;
        try {
            judgmentDocumentsObject = restTemplate.getForObject(judgmentDocumentsUrl, ResponseJson.class);
        }catch (Exception e){
            throw new ServiceException(CodeUtil.FAIL,"网络异常，请稍后重试！");
        }
        int judgmentDocumentsCount = (int) judgmentDocumentsObject.getData();
        //法人 763-董监高风险扫描
        String dongjiangaoRisksUrl = dongjiangaoRisks + "?socialCreditCode=" + enterprise.getSocialCreditCode() + "&personName=" + enterprise.getLegalRepresentative();
        ResponseJson dongjiangaoRisksObject;
        try {
            dongjiangaoRisksObject = restTemplate.getForObject(dongjiangaoRisksUrl, ResponseJson.class);
        }catch (Exception e){
            throw new ServiceException(CodeUtil.FAIL,"网络异常，请稍后重试！");
        }
        JSONObject dongjiangaoRisksObjectData = new JSONObject(dongjiangaoRisksObject.getData());
        Integer stCount = dongjiangaoRisksObjectData.getInt("stCount");
        Long dongjiangaoRiskId = dongjiangaoRisksObjectData.getLong("id");
        enterprise.setcDongjiangaoRiskId(dongjiangaoRiskId);
        String status;
        if (enterprise.getBusinessAddress().contains("黑龙江") || enterprise.getBusinessAddress().contains("辽宁") || enterprise.getBusinessAddress().contains("吉林")|| changes >= 2
                || shixin > 0 || sumptuary >0 || zhixingAmount.compareTo(new BigDecimal(registCapi)) == 1 || judgmentDocumentsCount > 0 || stCount > 0) {
            status = ProjectAndEnterpriseStatusEnums.VOTE.getCode();
            if(enterprise.getBusinessAddress().contains("黑龙江") || enterprise.getBusinessAddress().contains("辽宁") || enterprise.getBusinessAddress().contains("吉林")){
                error.add(enterprise.getCorporateName() + "不符合准入条件！");
            }
            if(changes >= 2){
                error.add(enterprise.getCorporateName() + "基本变动信息大于两次");
            }
            if(shixin > 0){
                error.add(enterprise.getCorporateName() + "存在失信执行信息");
            }
            if(sumptuary >0){
                error.add(enterprise.getCorporateName() + "存在限制高消");
            }
            if(zhixingAmount.compareTo(new BigDecimal(registCapi)) == 1){
                error.add(enterprise.getCorporateName() + "当前执行金额大于注册资本");
            }
            if(judgmentDocumentsCount > 0){
                error.add(enterprise.getCorporateName() + "存在涉诉信息");
            }
            if(stCount > 0){
                error.add(enterprise.getCorporateName() + "法人存在限制高消");
            }
        }else {
            status = ProjectAndEnterpriseStatusEnums.ADD_INFO.getCode();
        }
        if(projectInformation != null){
            if(StringUtil.isNotEmpty(entType) && !entType.equals("4") && betweenYear < 2 && projectInformation.getCompanyForProject() == 0){
                error.add(enterprise.getCorporateName() + "不符合企业准入条件！");
                status = ProjectAndEnterpriseStatusEnums.VOTE.getCode();
            }
            if(province.contains("黑龙江") || province.contains("辽宁") || province.contains("吉林")){
                error.add(enterprise.getCorporateName() + "不符合准入条件！");
                status = ProjectAndEnterpriseStatusEnums.VOTE.getCode();
            }
            projectInformation.setStatus(status);
            updateById(projectInformation);
        }
        if(projectCore != null){
            if(betweenYear < 2){
                error.add(enterprise.getCorporateName() + "注册时间少于两年");
                status = ProjectAndEnterpriseStatusEnums.VOTE.getCode();
            }
            if(registCapiInt < 5000){
                error.add(enterprise.getCorporateName() + "注册资本少于5000万");
                status = ProjectAndEnterpriseStatusEnums.VOTE.getCode();
            }
            projectCore.setStatus(status);
            projectCoreEnterpriseService.updateById(projectCore);
        }
        if(CollectionUtil.isNotEmpty(error)){
            log.error(enterprise.getCorporateName() + "的不准入原因:" + error.stream().collect(Collectors.joining(",")));
        }
        return error;
    }
}
