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

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.inkasso.adapter.bean.AbstractUser;
import com.inkasso.adapter.exception.BusinessException;
import com.inkasso.adapter.exception.ServiceException;
import com.inkasso.adapter.util.CodeUtil;
import com.inkasso.adapter.util.CollectionUtil;
import com.inkasso.adapter.web.LoginUserHolder;
import com.inkasso.factoring.common.constant.ConstantUtil;
import com.inkasso.factoring.common.entity.ResponseJson;
import com.inkasso.factoring.common.service.CommonService;
import com.inkasso.factoring.common.util.ElectronicSignatureUtil;
import com.inkasso.factoring.credit.entity.CreditDetail;
import com.inkasso.factoring.credit.entity.CreditInfo;
import com.inkasso.factoring.credit.service.CreditDetailService;
import com.inkasso.factoring.credit.service.CreditService;
import com.inkasso.factoring.creditmanagement.dao.SupplierInfoMapper;
import com.inkasso.factoring.creditmanagement.entity.*;
import com.inkasso.factoring.creditmanagement.entity.vo.CPartner;
import com.inkasso.factoring.creditmanagement.entity.vo.CRegStock;
import com.inkasso.factoring.creditmanagement.entity.vo.EnterpriseEntry;
import com.inkasso.factoring.creditmanagement.enums.CreditInvestigationTypeEnums;
import com.inkasso.factoring.creditmanagement.enums.SupplierStatusEnums;
import com.inkasso.factoring.creditmanagement.service.*;
import com.inkasso.factoring.dict.entity.Dictionary;
import com.inkasso.factoring.file.entity.FileStorage;
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.file.service.FileStorageService;
import com.inkasso.factoring.system.businessProcessLog.entity.BusinessProcessingLog;
import com.inkasso.factoring.system.businessProcessLog.service.BusinessProcessingLogService;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

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

    private static Logger log = LogManager.getLogger(SupplierInfoServiceImpl.class);

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

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private IEnterpriseService enterpriseService;

    @Autowired
    private CommonService commonService;

    @Autowired
    private ISupplierContactService supplierContactService;

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

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

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

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

    @Value("${sop.addBusinessUrl}")
    private String addBusiness;

    @Value("${trade.supplierStartProcessUrl}")
    private String supplierStartProcess;

    @Value("${sop.twoSearchUrl}")
    private String twoSearch;

    @Value("${sop.sixSearchUrl}")
    private String sixSearch;

    @Autowired
    private FileService fileService;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private ICreditInvestigationInfoService creditInvestigationInfoService;

    @Autowired
    private ICorporateFinanceService corporateFinanceService;

    @Autowired
    private IUpstreamProcurementDocumentsService upstreamProcurementDocumentsService;

    @Autowired
    private ISalesDocumentsInfoService salesDocumentsInfoService;

    @Autowired
    private IAssociatedEnterpriseInfoService associatedEnterpriseInfoService;

    @Autowired
    private ICSupplierInfoHistoryService supplierInfoHistoryService;

    @Autowired
    private ICEnterpriseHistoryService enterpriseHistoryService;

    @Autowired
    private ICSupplierContactHistoryService supplierContactHistoryService;

    @Autowired
    private ICCreditInvestigationInfoHistoryService creditInvestigationInfoHistoryService;

    @Autowired
    private ICCorporateFinanceHistoryService corporateFinanceHistoryService;

    @Autowired
    private ICUpstreamProcurementDocumentsHistoryService upstreamProcurementDocumentsHistoryService;

    @Autowired
    private ICSalesDocumentsInfoHistoryService salesDocumentsInfoHistoryService;

    @Autowired
    private ICAssociatedEnterpriseInfoHistoryService associatedEnterpriseInfoHistoryService;

    @Autowired
    private CreditService creditService;

    @Autowired
    private CreditDetailService creditDetailService;

    @Autowired
    private BusinessProcessingLogService businessProcessingLogService;

    @Autowired
    private ISupplierApprovalFirstService supplierApprovalFirstService;

    @Autowired
    private ISupplierApprovalSecondService supplierApprovalSecondService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SupplierInfo addSupplier(SupplierInfo supplierInfo) {
        AbstractUser abstractUser = LoginUserHolder.get();
        //邮箱  电话校验
        SupplierContact supplierContact = supplierInfo.getSupplierContact();
        String smsCode = supplierContact.getSMSCode();
        String mailCode = supplierContact.getMailCode();
        boolean verifySMSCode = commonService.verifySMSCode(supplierContact.getMobile(), smsCode);
        if (!verifySMSCode) {
            throw new ServiceException(CodeUtil.FAIL, "短信验证码有误，请确认！");
        }
        boolean verifyMailCode = commonService.verifyMailCode(supplierContact.getEmail(), mailCode);
        if (!verifyMailCode) {
            throw new ServiceException(CodeUtil.FAIL, "邮箱验证码有误，请确认！");
        }
        //企业重复性校验 新增供应商
        Enterprise enterprise = supplierInfo.getEnterprise();
        Enterprise existEnterprise = enterpriseService.lambdaQuery().eq(Enterprise::getSocialCreditCode, enterprise.getSocialCreditCode()).one();
        if (existEnterprise != null) {
            SupplierInfo existsSupplier = lambdaQuery().eq(SupplierInfo::getcEnterpriseId, existEnterprise.getId()).one();
            if (existsSupplier != null) {
                throw new ServiceException(CodeUtil.FAIL, "该企业已被绑定，不可重复！");
            }
            supplierInfo.setcEnterpriseId(existEnterprise.getId());
        } else {
            enterpriseService.save(enterprise);
            supplierInfo.setcEnterpriseId(enterprise.getId());
        }
        supplierInfo.setSysUserId(abstractUser.getId());
        save(supplierInfo);
        supplierContact.setSupplierInfoId(supplierInfo.getId());
        supplierContactService.save(supplierContact);
        existEnterprise = enterpriseService.lambdaQuery().eq(Enterprise::getSocialCreditCode, enterprise.getSocialCreditCode()).one();
        String errorsString = qichacha(existEnterprise, supplierInfo, false);
        supplierInfo.setSupplierErrors(errorsString);
        updateById(supplierInfo);
        if (supplierInfo.getConstructionIndustry().equals(0)) {
            //开启流程
            supplierInfo.setHistoryId(supplierInfo.getId());
            ResponseJson responseJson;
            try {
                responseJson = restTemplate.postForObject(supplierStartProcess, supplierInfo, ResponseJson.class);
            } catch (Exception e) {
                throw new ServiceException(CodeUtil.FAIL, "哎呀！网络好像出问题了，请稍后重试！");
            }
            String status = (String) responseJson.getData();
            supplierInfo.setStatus(status);
            updateById(supplierInfo);
        }
        return supplierInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SupplierInfo addBusiness(SupplierInfo supplierInfo) {
        //企业重复性校验 新增担保企业
        Enterprise enterprise = supplierInfo.getGuaranteeEnterprise();
        Enterprise existEnterprise = enterpriseService.lambdaQuery().eq(Enterprise::getSocialCreditCode, enterprise.getSocialCreditCode()).one();
        if (existEnterprise != null) {
            supplierInfo.setGuaranteeEnterpriseId(existEnterprise.getId());
        } else {
            enterpriseService.save(enterprise);
            supplierInfo.setGuaranteeEnterpriseId(enterprise.getId());
        }
        existEnterprise = enterpriseService.lambdaQuery().eq(Enterprise::getSocialCreditCode, enterprise.getSocialCreditCode()).one();
        String errorsString = qichacha(existEnterprise, supplierInfo, true);
        supplierInfo.setGuaranteeEnterpriseErrors(errorsString);
        updateById(supplierInfo);
        return supplierInfo;
    }

    /**
     * sop交互
     *
     * @param existEnterprise     企业信息
     * @param supplierInfo        供应商信息
     * @param guaranteeEnterprise 是否担保企业
     */
    private String qichacha(Enterprise existEnterprise, SupplierInfo supplierInfo, boolean guaranteeEnterprise) {
        List<String> errors = new ArrayList<>();
        if(StringUtils.isEmpty(existEnterprise.getSocialCreditCode())){
            throw new ServiceException(CodeUtil.FAIL,existEnterprise.getCorporateName() + "不存在统一社会信用代码，无法进行后续授信操作！");
        }
        //2006综合风险排查
        String comprehensiveRiskInvestigationUrl = comprehensiveRiskInvestigation + "?socialCreditCode=" + existEnterprise.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");
        existEnterprise.setcComprehensiveRiskInvestigationId(comprehensiveRiskInvestigationId);
        Integer shixin = comprehensiveRiskJsonObject.getInt("shixin");
        Integer zhixing = comprehensiveRiskJsonObject.getInt("zhixing");
        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");
        existEnterprise.setRegisteredCapital(registCapi);
        List<CPartner> partnerList = comprehensiveRiskJsonObject.getBeanList("partnerList", CPartner.class);
        if (CollectionUtil.isEmpty(partnerList)) {
            throw new ServiceException(CodeUtil.FAIL, "综合风险排查未获取到股东信息！");
        }
        if(StringUtils.isEmpty(registCapi)){
            throw new ServiceException(CodeUtil.FAIL,existEnterprise.getCorporateName() + "不存在注册资本，无法进行后续授信操作！");
        }
        registCapi = registCapi.replace("万元人民币", "");
        Double registCapiInt = Double.valueOf(registCapi);
        long betweenYear = DateUtil.betweenYear(startDate, new Date(), false);
        //887-裁判文书核查
        String judgmentDocumentsUrl = judgmentDocuments + "?socialCreditCode=" + existEnterprise.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=" + existEnterprise.getSocialCreditCode() + "&personName=" + existEnterprise.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 sxCount = dongjiangaoRisksObjectData.getInt("sxCount");
        Integer zxCount = dongjiangaoRisksObjectData.getInt("zxCount");
        Integer stCount = dongjiangaoRisksObjectData.getInt("stCount");
        Long dongjiangaoRiskId = dongjiangaoRisksObjectData.getLong("id");
        existEnterprise.setcDongjiangaoRiskId(dongjiangaoRiskId);
        if (CollectionUtil.isEmpty(partnerList)) {
            throw new ServiceException(CodeUtil.FAIL, "无法查询出大股东信息！");
        }
        CPartner cPartner = partnerList.stream().map(r -> {
            String stockPercent = r.getStockPercent();
            stockPercent = stockPercent.replace("%", "");
            if (StringUtils.isNotEmpty(stockPercent)) {
                double percent = Double.valueOf(stockPercent);
                r.setPercent(percent);
            } else {
                r.setPercent(0L);
            }
            return r;
        }).max(Comparator.comparing(CPartner::getPercent)).get();
        Integer sxCountBig;
        Integer zxCountBig;
        Integer stCountBig;
        String stockName = cPartner.getStockName();
        if (stockName.equals(existEnterprise.getLegalRepresentative())) {
            existEnterprise.setMajorShareholders(stockName);
            existEnterprise.setcDongjiangaoRiskBigId(existEnterprise.getcDongjiangaoRiskId());
            sxCountBig = sxCount;
            zxCountBig = zxCount;
            stCountBig = stCount;
        } else {
            //判定没名字超过4个字  就是公司
            if (stockName.length() > 4) {
                //公司循环找出大股东
                findBig(cPartner.getCreditCode(), comprehensiveRiskInvestigationId, existEnterprise);
                sxCountBig = existEnterprise.getSxCountBig();
                zxCountBig = existEnterprise.getZxCountBig();
                stCountBig = existEnterprise.getStCountBig();
            } else {
                existEnterprise.setMajorShareholders(stockName);
                //大股东 763-董监高风险扫描
                String bigDongjiangaoRisksUrl = dongjiangaoRisks + "?socialCreditCode=" + existEnterprise.getSocialCreditCode() + "&personName=" + stockName;
                ResponseJson bigDongjiangaoRisksObject;
                try {
                    bigDongjiangaoRisksObject = restTemplate.getForObject(bigDongjiangaoRisksUrl, ResponseJson.class);
                } catch (Exception e) {
                    throw new ServiceException(CodeUtil.FAIL, "网络异常，请稍后重试！");
                }
                JSONObject bigDongjiangaoRisks = new JSONObject(bigDongjiangaoRisksObject.getData());
                sxCountBig = bigDongjiangaoRisks.getInt("sxCount");
                zxCountBig = bigDongjiangaoRisks.getInt("zxCount");
                stCountBig = bigDongjiangaoRisks.getInt("stCount");
                Long dongjiangaoRiskBigId = bigDongjiangaoRisks.getLong("id");
                existEnterprise.setcDongjiangaoRiskBigId(dongjiangaoRiskBigId);
            }
        }
        if (guaranteeEnterprise) {
            if (registCapiInt < 100) {
                supplierInfo.setStatus(SupplierStatusEnums.VOTE.getCode());
                errors.add("企业注册资本不达标！");
            } else if (betweenYear < 2) {
                supplierInfo.setStatus(SupplierStatusEnums.VOTE.getCode());
                errors.add("企业注册年限不达标！");
            } else {
                supplierInfo.setStatus(SupplierStatusEnums.ADD_INFO.getCode());
            }
        } else {
            if (supplierInfo.getConstructionIndustry().equals(0)) {
                supplierInfo.setStatus(SupplierStatusEnums.DUE_DILIGENCE_ALLOCATION.getCode());
            } else {
                if (registCapiInt < 100 || betweenYear < 2) {
                    supplierInfo.setStatus(SupplierStatusEnums.ADD_BUSINESS.getCode());
                } else {
                    supplierInfo.setStatus(SupplierStatusEnums.ADD_INFO.getCode());
                }
            }
        }
        if (sxCount > 0 || zxCount > 0 || stCount > 0 || sxCountBig > 0 || zxCountBig > 0 || stCountBig > 0 || judgmentDocumentsCount > 0 || shixin > 0 || zhixing > 0 || sumptuary > 0) {
            supplierInfo.setStatus(SupplierStatusEnums.VOTE.getCode());
            errors.add("企业或者法人存在风险信息！");
        }

        if (province.contains("黑龙江") || province.contains("辽宁") || province.contains("吉林")) {
            supplierInfo.setStatus(SupplierStatusEnums.VOTE.getCode());
            errors.add("企业信息不达标！");
        }
        //给sop 推数据   更新企业信息
        EnterpriseEntry enterpriseEntry = new EnterpriseEntry();
        enterpriseEntry.setFlag("0");
        enterpriseEntry.setKeyWord(existEnterprise.getCorporateName());
        Dictionary dictionary = new Dictionary();
        dictionary.setId(197L);
        enterpriseEntry.setInterfaceType(dictionary);
        List list = new ArrayList<>();
        list.add(18L);
        list.add(25L);
        enterpriseEntry.setInterfaceIdList(list);
        ResponseJson entRj;
        try {
            entRj = restTemplate.postForObject(addBusiness, enterpriseEntry, ResponseJson.class);
        } catch (Exception e) {
            throw new ServiceException(CodeUtil.FAIL, "网络异常，请稍后重试！");
        }
        JSONObject jsonObject = new JSONObject(entRj.getData());
        Boolean authStatus = jsonObject.getBool("authStatus");
        String shortAuthUrl = jsonObject.getStr("shortAuthUrl");
        String authUrl = jsonObject.getStr("authUrl");
        Integer certificateSignStatus = jsonObject.getInt("certificateSignStatus");
        String certificateShortSignUrl = jsonObject.getStr("certificateShortSignUrl");
        String certificateSignUrl = jsonObject.getStr("certificateSignUrl");
        Integer autoSignStatus = jsonObject.getInt("autoSignStatus");
        String shortAutoSignUrl = jsonObject.getStr("shortAutoSignUrl");
        String autoSignUrl = jsonObject.getStr("autoSignUrl");
        String fddCustomerId = jsonObject.getStr("fddCustomerId");
        String certificateContractId = jsonObject.getStr("certificateContractId");
        String certificateTransactionId = jsonObject.getStr("certificateTransactionId");
        existEnterprise.setCertificateTransactionId(certificateTransactionId);
        existEnterprise.setAuthStatus(authStatus);
        existEnterprise.setShortAuthUrl(shortAuthUrl);
        existEnterprise.setCertificateSignStatus(certificateSignStatus);
        existEnterprise.setCertificateShortSignUrl(certificateShortSignUrl);
        existEnterprise.setAuthUrl(authUrl);
        existEnterprise.setCertificateSignUrl(certificateSignUrl);
        existEnterprise.setAutoSignStatus(autoSignStatus);
        existEnterprise.setAutoSignUrl(autoSignUrl);
        existEnterprise.setShortAutoSignUrl(shortAutoSignUrl);
        existEnterprise.setFddCustomerId(fddCustomerId);
        existEnterprise.setCertificateContractId(certificateContractId);
        updateById(supplierInfo);
        enterpriseService.updateById(existEnterprise);
        supplierInfo.setErrors(errors);
        if (CollectionUtil.isNotEmpty(errors)) {
            String errorString = existEnterprise.getCorporateName() + "的企业不准入原因:" + errors.stream().collect(Collectors.joining(","));
            log.error(errorString);
            errorString = errors.stream().collect(Collectors.joining(","));
            return errorString;
        }
        return null;
    }

    @Override
    public SupplierInfo findSupplierById(Long id) {
        SupplierInfo supplierInfo = getById(id);
        Enterprise enterprise = enterpriseService.getById(supplierInfo.getcEnterpriseId());
        //sop获取企业省市区
        String getEnterpriseAreaUrl = getEnterpriseArea + "?comprehensiveRiskInvestigationId=" + enterprise.getcComprehensiveRiskInvestigationId();
        ResponseJson areaData = restTemplate.getForObject(getEnterpriseAreaUrl, ResponseJson.class);
        Object data = areaData.getData();
        if (data == null) {
            throw new ServiceException(CodeUtil.FAIL, "获取企业地址信息出错");
        }
        JSONObject areaJS = new JSONObject(data);
        String province = areaJS.getStr("province");
        String city = areaJS.getStr("city");
        String address = "";
        address = enterpriseService.getWebAddress(city);
        if(StringUtils.isEmpty(address)){
            address = enterpriseService.getWebAddress(province);
        }
        setEnterprise(enterprise);
        enterprise.setTaxBureauWebsite(address);
        supplierInfo.setEnterprise(enterprise);
        supplierInfo.setHasGuaranteeEnterprise(false);
        if (supplierInfo.getGuaranteeEnterpriseId() != null) {
            supplierInfo.setHasGuaranteeEnterprise(true);
            Enterprise guarantee = enterpriseService.getById(supplierInfo.getGuaranteeEnterpriseId());
            //sop获取企业省市区
            String getGuaranteeEnterpriseAreaUrl = getEnterpriseArea + "?comprehensiveRiskInvestigationId=" + guarantee.getcComprehensiveRiskInvestigationId();
            ResponseJson guaranteeAreaData = restTemplate.getForObject(getGuaranteeEnterpriseAreaUrl, ResponseJson.class);
            Object guaranteeData = guaranteeAreaData.getData();
            if (guaranteeData == null) {
                throw new ServiceException(CodeUtil.FAIL, "获取企业地址信息出错");
            }
            JSONObject guaranteeAreaJS = new JSONObject(guaranteeData);
            String guaranteeProvince = guaranteeAreaJS.getStr("province");
            String guaranteeCity = areaJS.getStr("city");
            String guaranteeAddress = "";
            guaranteeAddress = enterpriseService.getWebAddress(guaranteeCity);
            if(StringUtils.isEmpty(address)){
                guaranteeAddress = enterpriseService.getWebAddress(guaranteeProvince);
            }
            setEnterprise(guarantee);
            guarantee.setTaxBureauWebsite(guaranteeAddress);
            supplierInfo.setGuaranteeEnterprise(guarantee);
        }
        return supplierInfo;
    }

    private void setEnterprise(Enterprise enterprise) {
        //地点定位图
        List<FileStorageDO> locationMap = fileService.findByBusinessId(enterprise.getId(), FileTypeEnum.ENTERPRISE_LOCATION_MAP.getCode());
        enterprise.setLocationMap(locationMap);
        //租房合同
        List<FileStorageDO> rentalContract = fileService.findByBusinessId(enterprise.getId(), FileTypeEnum.ENTERPRISE_RENTAL_CONTRACT.getCode());
        enterprise.setRentalContract(rentalContract);
        //水电费缴纳流水
        List<FileStorageDO> waterElectricityFees = fileService.findByBusinessId(enterprise.getId(), FileTypeEnum.WATER_ELECTRIICITY_FEES.getCode());
        enterprise.setWaterElectricityFees(waterElectricityFees);
        //办公环境
        List<FileStorageDO> officeEnvironment = fileService.findByBusinessId(enterprise.getId(), FileTypeEnum.ENTERPRISE_OFFICE_ENVIRONMENT.getCode());
        enterprise.setOfficeEnvironment(officeEnvironment);
        //营业执照
        List<FileStorageDO> businessLicense = fileService.findByBusinessId(enterprise.getId(), FileTypeEnum.ENTERPRISE_BUSINESS_LICENSE.getCode());
        enterprise.setBusinessLicense(businessLicense);
        //基本户信息
        List<FileStorageDO> basicAccountInformation = fileService.findByBusinessId(enterprise.getId(), FileTypeEnum.ENTERPRISE_BASIC_ACCOUNT_INFORMATION.getCode());
        enterprise.setBasicAccountInformation(basicAccountInformation);
        //公司章程和修正案
        List<FileStorageDO> articlesAssociation = fileService.findByBusinessId(enterprise.getId(), FileTypeEnum.ENTERPRISE_ARTICLES_ASSOCIATION.getCode());
        enterprise.setArticlesAssociation(articlesAssociation);
        //结案证明或判决书
        List<FileStorageDO> judgment = fileService.findByBusinessId(enterprise.getId(), FileTypeEnum.ENTERPRISE_JUDGMENT.getCode());
        enterprise.setJudgment(judgment);
        //纳税申报表
        List<FileStorageDO> taxReturn = fileService.findByBusinessId(enterprise.getId(), FileTypeEnum.ENTERPRISE_TAX_RETURN.getCode());
        enterprise.setTaxReturn(taxReturn);
        //企业内账报表
        List<FileStorageDO> accountingreport = fileService.findByBusinessId(enterprise.getId(), FileTypeEnum.ENTERPRISE_ACCOUNTING_REPORT.getCode());
        enterprise.setAccountingreport(accountingreport);
        List<CreditInvestigationInfo> creditInvestigationInfoList = creditInvestigationInfoService.lambdaQuery().eq(CreditInvestigationInfo::getcEnterpriseId, enterprise.getId()).list();
        if (CollectionUtil.isNotEmpty(creditInvestigationInfoList)) {
            for (CreditInvestigationInfo creditInvestigationInfo : creditInvestigationInfoList) {
                List<FileStorageDO> files = fileService.findByBusinessId(creditInvestigationInfo.getId(), FileTypeEnum.ENTERPRISE_IDCARD_Files.getCode());
                creditInvestigationInfo.setFiles(files);
                CreditInvestigationTypeEnums typeEnums = CreditInvestigationTypeEnums.getByCode(creditInvestigationInfo.getType());
                creditInvestigationInfo.setTypeStr(typeEnums.getDesc());
            }
        } else {
            creditInvestigationInfoList = new ArrayList<>();
            CreditInvestigationInfo one = new CreditInvestigationInfo();
            one.setcEnterpriseId(enterprise.getId());
            one.setName(enterprise.getLegalRepresentative());
            one.setType(CreditInvestigationTypeEnums.ONE.getCode());
            one.setTypeStr(CreditInvestigationTypeEnums.ONE.getDesc());
            creditInvestigationInfoList.add(one);
            if (enterprise.getMajorShareholders() != null) {
                CreditInvestigationInfo two = new CreditInvestigationInfo();
                two.setcEnterpriseId(enterprise.getId());
                two.setName(enterprise.getMajorShareholders());
                two.setType(CreditInvestigationTypeEnums.TWO.getCode());
                two.setTypeStr(CreditInvestigationTypeEnums.TWO.getDesc());
                creditInvestigationInfoList.add(two);
            } else {
                CreditInvestigationInfo two = new CreditInvestigationInfo();
                two.setcEnterpriseId(enterprise.getId());
                two.setType(CreditInvestigationTypeEnums.TWO.getCode());
                two.setTypeStr(CreditInvestigationTypeEnums.TWO.getDesc());
                creditInvestigationInfoList.add(two);
            }
            CreditInvestigationInfo three = new CreditInvestigationInfo();
            three.setcEnterpriseId(enterprise.getId());
            three.setType(CreditInvestigationTypeEnums.THREE.getCode());
            three.setTypeStr(CreditInvestigationTypeEnums.THREE.getDesc());
            creditInvestigationInfoList.add(three);
        }
        enterprise.setCreditInvestigationInfoList(creditInvestigationInfoList);
        List<CorporateFinance> corporateFinances = corporateFinanceService.lambdaQuery().eq(CorporateFinance::getcEnterpriseId, enterprise.getId()).list();
        if (CollectionUtil.isNotEmpty(corporateFinances)) {
            for (CorporateFinance corporateFinance : corporateFinances) {
                FileStorageDO fileStorageDO = fileService.findOneByBusinessId(corporateFinance.getId(), FileTypeEnum.ENTERPRISE_FINANCIAL_STATEMENTS.getCode());
                corporateFinance.setFileStorage(fileStorageDO);
            }
        }
        enterprise.setCorporateFinances(corporateFinances);
        List<UpstreamProcurementDocuments> upstreamProcurementDocuments = upstreamProcurementDocumentsService.lambdaQuery().eq(UpstreamProcurementDocuments::getcEnterpriseId, enterprise.getId()).list();
        if (CollectionUtil.isNotEmpty(upstreamProcurementDocuments)) {
            for (UpstreamProcurementDocuments upstreamProcurementDocument : upstreamProcurementDocuments) {
                List<FileStorageDO> fileStorageDOS = fileService.findByBusinessId(upstreamProcurementDocument.getId(), FileTypeEnum.ENTERPRISE_UPSTREAM_DOCUMENTS.getCode());
                upstreamProcurementDocument.setFileStorages(fileStorageDOS);
            }
        }
        enterprise.setUpstreamProcurementDocuments(upstreamProcurementDocuments);
        List<SalesDocumentsInfo> salesDocumentsInfos = salesDocumentsInfoService.lambdaQuery().eq(SalesDocumentsInfo::getcEnterpriseId, enterprise.getId()).list();
        if (CollectionUtil.isNotEmpty(salesDocumentsInfos)) {
            for (SalesDocumentsInfo salesDocumentsInfo : salesDocumentsInfos) {
                List<FileStorageDO> fileStorageDOS = fileService.findByBusinessId(salesDocumentsInfo.getId(), FileTypeEnum.ENTERPRISE_SALES_DOCUMENTS.getCode());
                salesDocumentsInfo.setFileStorages(fileStorageDOS);
            }
        }
        enterprise.setSalesDocumentsInfos(salesDocumentsInfos);
        List<AssociatedEnterpriseInfo> associatedEnterpriseInfos = associatedEnterpriseInfoService.lambdaQuery().eq(AssociatedEnterpriseInfo::getcEnterpriseId, enterprise.getId()).list();
        enterprise.setAssociatedEnterpriseInfos(associatedEnterpriseInfos);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SupplierInfo supplement(SupplierInfo supplierInfo) {
        //保存供应商信息
        Enterprise enterprise = supplierInfo.getEnterprise();
        Boolean flag = updateEnterprise(enterprise, supplierInfo);
        if(flag){
            supplierInfo.setStatus(SupplierStatusEnums.VOTE.getCode());
        }
        Enterprise existEnterprise = enterpriseService.getById(enterprise.getId());
        //保存担保企业信息
        Enterprise guaranteeEnterprise = supplierInfo.getGuaranteeEnterprise();
        Enterprise existGuaranteeEnterprise = null;
        if (guaranteeEnterprise != null) {
            existGuaranteeEnterprise = enterpriseService.getById(guaranteeEnterprise.getId());
            Boolean flagGuarantee = updateEnterprise(guaranteeEnterprise, supplierInfo);
            if (supplierInfo.getVisible()) {
                if (flagGuarantee) {
                    supplierInfo.setStatus(SupplierStatusEnums.VOTE.getCode());
                }
                //主企业不存在红否
                if (!flag) {
                    //担保企业不存在红否
                    if (!flagGuarantee) {
                        String sixSearchUrl = sixSearch + "?socialCreditCode=" + existGuaranteeEnterprise.getSocialCreditCode() + "&comprehensiveRiskInvestigationId=" + existGuaranteeEnterprise.getcComprehensiveRiskInvestigationId();
                        String twoSearchUrl = twoSearch + "?socialCreditCode=" + existEnterprise.getSocialCreditCode() + "&comprehensiveRiskInvestigationId=" + existEnterprise.getcComprehensiveRiskInvestigationId();
                        try {
                            restTemplate.getForObject(sixSearchUrl, ResponseJson.class);
                        } catch (Exception e) {
                            throw new ServiceException(CodeUtil.FAIL, "网络异常，请稍后重试！");
                        }
                        try {
                            restTemplate.getForObject(twoSearchUrl, ResponseJson.class);
                        } catch (Exception e) {
                            throw new ServiceException(CodeUtil.FAIL, "网络异常，请稍后重试！");
                        }
                        supplierInfo.setStatus(SupplierStatusEnums.DUE_DILIGENCE_ALLOCATION.getCode());
                    } else {
                        supplierInfo.setStatus(SupplierStatusEnums.VOTE.getCode());
                    }
                }
            }
        } else {
            if (supplierInfo.getVisible()) {
                //主企业不存在红否
                if (!flag) {
                    String sixSearchUrl = sixSearch + "?socialCreditCode=" + existEnterprise.getSocialCreditCode() + "&comprehensiveRiskInvestigationId=" + existEnterprise.getcComprehensiveRiskInvestigationId();
                    try {
                        restTemplate.getForObject(sixSearchUrl, ResponseJson.class);
                    } catch (Exception e) {
                        throw new ServiceException(CodeUtil.FAIL, "网络异常，请稍后重试！");
                    }
                    supplierInfo.setStatus(SupplierStatusEnums.DUE_DILIGENCE_ALLOCATION.getCode());
                } else {
                    supplierInfo.setStatus(SupplierStatusEnums.VOTE.getCode());
                }
            }
        }
        updateById(supplierInfo);
        if (supplierInfo.getVisible()) {
            //下载供应商征信授权书和出证文件
            Long reportId = downloadSignReport(enterprise.getId());
            Long guaranteeEnterpriseReportId = null;
            if (guaranteeEnterprise != null) {
                //下载担保企业征信授权书和出证文件
                guaranteeEnterpriseReportId = downloadSignReport(enterprise.getId());
            }
            Long history = addHistory(supplierInfo, reportId, guaranteeEnterpriseReportId);
            //供应商推征信信息 个人征信 相关 法人、大股东、实控人，姓名和身份证号码推送到B端征信管理板块
            List<CreditInvestigationInfo> creditInvestigationInfos = creditInvestigationInfoService.lambdaQuery().eq(CreditInvestigationInfo::getcEnterpriseId, existEnterprise.getId()).list();
            if (CollectionUtil.isNotEmpty(creditInvestigationInfos)) {
                for (CreditInvestigationInfo creditInvestigationInfo : creditInvestigationInfos) {
                    Long count = creditService.lambdaQuery().eq(CreditInfo::getCardNo, creditInvestigationInfo.getSocialCreditCode()).count();
                    if (count == 0) {
                        CreditInfo creditInfo = new CreditInfo();
                        creditInfo.setName(creditInvestigationInfo.getName());
                        creditInfo.setType(0);
                        creditInfo.setDocumentType(1);
                        creditInfo.setCardNo(creditInvestigationInfo.getSocialCreditCode());
                        creditService.save(creditInfo);
                    }
                }
            }
            //企业名称和统一信用代码推送到B端征信管理板块
            Long count = creditService.lambdaQuery().eq(CreditInfo::getCardNo, existEnterprise.getSocialCreditCode()).count();
            if (count == 0) {
                CreditInfo creditInfo = new CreditInfo();
                creditInfo.setName(existEnterprise.getCorporateName());
                creditInfo.setType(1);
                creditInfo.setCardNo(existEnterprise.getSocialCreditCode());
                creditService.save(creditInfo);
                CreditDetail creditDetail = new CreditDetail();
                creditDetail.setCreditId(creditInfo.getId());
                FileStorageDO byId = fileService.getById(reportId);
                FileStorage fileStorage = new FileStorage();
                fileStorage.setFileType(byId.getType());
                fileStorage.setPath(byId.getPath());
                fileStorage.setAbsolutePath(byId.getAbsolutePath());
                fileStorage.setOriginalName(byId.getOriginalName() + byId.getType());
                fileStorage.setName(byId.getOriginalName() + byId.getType());
                fileStorageService.save(fileStorage);
                creditDetail.setAuthAddress(fileStorage.getId().toString());
                creditDetailService.save(creditDetail);
            }
            //担保企业推征信信息 个人征信 相关 法人、大股东、实控人，姓名和身份证号码推送到B端征信管理板块
            if (guaranteeEnterprise != null) {
                List<CreditInvestigationInfo> creditInvestigationInfoList = creditInvestigationInfoService.lambdaQuery().eq(CreditInvestigationInfo::getcEnterpriseId, existGuaranteeEnterprise.getId()).list();
                if (CollectionUtil.isNotEmpty(creditInvestigationInfoList)) {
                    for (CreditInvestigationInfo creditInvestigationInfo : creditInvestigationInfoList) {
                        Long size = creditService.lambdaQuery().eq(CreditInfo::getCardNo, creditInvestigationInfo.getSocialCreditCode()).count();
                        if (size == 0) {
                            CreditInfo creditInfo = new CreditInfo();
                            creditInfo.setName(creditInvestigationInfo.getName());
                            creditInfo.setType(0);
                            creditInfo.setDocumentType(1);
                            creditInfo.setCardNo(creditInvestigationInfo.getSocialCreditCode());
                            creditService.save(creditInfo);
                        }
                    }
                }
                //企业名称和统一信用代码推送到B端征信管理板块
                Long countGuarantee = creditService.lambdaQuery().eq(CreditInfo::getCardNo, existGuaranteeEnterprise.getSocialCreditCode()).count();
                if (countGuarantee == 0) {
                    CreditInfo creditInfo = new CreditInfo();
                    creditInfo.setName(existGuaranteeEnterprise.getCorporateName());
                    creditInfo.setType(1);
                    creditInfo.setCardNo(existGuaranteeEnterprise.getSocialCreditCode());
                    creditService.save(creditInfo);
                    CreditDetail creditDetail = new CreditDetail();
                    creditDetail.setCreditId(creditInfo.getId());
                    FileStorageDO byId = fileService.getById(guaranteeEnterpriseReportId);
                    FileStorage fileStorage = new FileStorage();
                    fileStorage.setFileType(byId.getType());
                    fileStorage.setPath(byId.getPath());
                    fileStorage.setAbsolutePath(byId.getAbsolutePath());
                    fileStorage.setOriginalName(byId.getOriginalName() + byId.getType());
                    fileStorage.setName(byId.getOriginalName() + byId.getType());
                    fileStorageService.save(fileStorage);
                    creditDetail.setAuthAddress(fileStorage.getId().toString());
                    creditDetailService.save(creditDetail);
                }
            }
            // B端开启流程
            SupplierInfo exist = getById(supplierInfo.getId());
            if(supplierInfo.getStatus().equals(SupplierStatusEnums.DUE_DILIGENCE_ALLOCATION.getCode())){
                exist.setHistoryId(history);
                Enterprise existsEnterprise = enterpriseService.getById(exist.getcEnterpriseId());
                exist.setEnterprise(existsEnterprise);
                ResponseJson responseJson;
                try {
                    responseJson = restTemplate.postForObject(supplierStartProcess, exist, ResponseJson.class);
                } catch (Exception e) {
                    throw new ServiceException(CodeUtil.FAIL, "网络异常，请稍后重试！");
                }
                String status = (String) responseJson.getData();
                exist.setStatus(status);
                updateById(exist);
            }
            return exist;
        }
        return supplierInfo;
    }

    Long downloadSignReport(Long businessId) {
        Enterprise byId = enterpriseService.getById(businessId);
        String contractId = byId.getCertificateContractId();
        //合同下载
        String contDownUrl = ElectronicSignatureUtil.downloadContract(contractId);
        FileStorageDO fileStorageDO = fileService.addFileStorageWithBelongAndName(contractId, FileTypeEnum.ENTERPRISE_CREDIT_AUTHORIZATION_LETTER, contDownUrl);
        fileService.updateBusinessId(fileStorageDO.getId(), businessId);
        //合同归档
        ElectronicSignatureUtil.contractFiled(contractId);
        //电子文件签署线上出证下载
        String reportDownUrl = ElectronicSignatureUtil.complianceContractReport(contractId);
        FileStorageDO report = fileService.addFileStorageWithBelongAndName(contractId, FileTypeEnum.ENTERPRISE_CREDIT_AUTHORIZATION_LETTER_REPORT, reportDownUrl);
        fileService.updateBusinessId(report.getId(), businessId);
        return fileStorageDO.getId();
    }

    @Override
    public List<SupplierInfo> allList() {
        AbstractUser abstractUser = LoginUserHolder.get();
        List<SupplierInfo> supplierInfos = lambdaQuery().eq(SupplierInfo::getSysUserId, abstractUser.getId()).orderByDesc(SupplierInfo::getGmtModified).list();
        for (SupplierInfo supplierInfo : supplierInfos) {
            Enterprise enterprise = enterpriseService.getById(supplierInfo.getcEnterpriseId());
            supplierInfo.setEnterprise(enterprise);
            if (supplierInfo.getStatus().equals(SupplierStatusEnums.VOTE.getCode())) {
                supplierInfo.setStatusStr(SupplierStatusEnums.VOTE.getDesc());
            } else if (supplierInfo.getStatus().equals(SupplierStatusEnums.ADD_BUSINESS.getCode())) {
                supplierInfo.setStatusStr(SupplierStatusEnums.VOTE.getDesc());
            } else if (supplierInfo.getStatus().equals(SupplierStatusEnums.ADD_INFO.getCode())) {
                supplierInfo.setStatusStr(SupplierStatusEnums.ADD_INFO.getDesc());
            } else if (supplierInfo.getStatus().equals(SupplierStatusEnums.DUE_DILIGENCE_ALLOCATION.getCode())) {
                supplierInfo.setStatusStr(SupplierStatusEnums.DUE_DILIGENCE_ALLOCATION.getDesc());
            } else if (supplierInfo.getStatus().equals(SupplierStatusEnums.DUE_DILIGENCE_REVIEW.getCode())) {
                supplierInfo.setStatusStr(SupplierStatusEnums.DUE_DILIGENCE_REVIEW.getDesc());
            } else if (supplierInfo.getStatus().equals(SupplierStatusEnums.VIDEO_DUE_DILIGENCE.getCode())) {
                supplierInfo.setStatusStr(SupplierStatusEnums.VIDEO_DUE_DILIGENCE.getDesc());
            } else if (supplierInfo.getStatus().equals(SupplierStatusEnums.CONFIRM_DUE_DILIGENCE_TIME.getCode())) {
                supplierInfo.setStatusStr(SupplierStatusEnums.CONFIRM_DUE_DILIGENCE_TIME.getDesc());
            } else if (supplierInfo.getStatus().equals(SupplierStatusEnums.WAIT_DUE_DILIGENCE.getCode())) {
                supplierInfo.setStatusStr(SupplierStatusEnums.WAIT_DUE_DILIGENCE.getDesc());
            } else if (supplierInfo.getStatus().equals(SupplierStatusEnums.CREDIT_SUCCESS.getCode())) {
                supplierInfo.setStatusStr(SupplierStatusEnums.CREDIT_SUCCESS.getDesc());
            } else if (supplierInfo.getStatus().equals(SupplierStatusEnums.DUE_DILIGENCE_APPOINTMENT.getCode())) {
                supplierInfo.setStatusStr(SupplierStatusEnums.VOTE.getDesc());
            }
            List<BusinessProcessingLog> list = businessProcessingLogService.lambdaQuery()
                    .eq(BusinessProcessingLog::getBusinessType, ConstantUtil.SUPPLIER_INFO)
                    .eq(BusinessProcessingLog::getBusnessKey, supplierInfo.getId())
                    .isNotNull(BusinessProcessingLog::getEndTime)
                    .orderByDesc(BusinessProcessingLog::getGmtCreate).list();
            if(CollectionUtil.isNotEmpty(list)){
                String reason = null;
                BusinessProcessingLog businessProcessingLog = list.get(0);
                if(ConstantUtil.FIRST_REVIEW.equals(businessProcessingLog.getTaskDefKey())){
                    SupplierApprovalFirst supplierApprovalFirst = supplierApprovalFirstService.getById(businessProcessingLog.getFormBusinessId());
                    reason = supplierApprovalFirst.getApprovalComment();
                }
                if(ConstantUtil.SECOND_REVIEW.equals(businessProcessingLog.getTaskDefKey())){
                    SupplierApprovalSecond supplierApprovalSecond = supplierApprovalSecondService.getById(businessProcessingLog.getFormBusinessId());
                    reason = supplierApprovalSecond.getApprovalComment();
                }
                supplierInfo.setReason(reason);
            }
        }
        return supplierInfos;
    }

    private Long addHistory(SupplierInfo supplierInfo, Long reportId, Long guaranteeEnterpriseReportId) {
        //保存企业信息
        Enterprise enterprise = supplierInfo.getEnterprise();
        Enterprise existEnterprise = enterpriseService.getById(enterprise.getId());
        CEnterpriseHistory cEnterpriseHistory = new CEnterpriseHistory();
        BeanUtils.copyProperties(existEnterprise, cEnterpriseHistory, "id");
        enterpriseHistoryService.save(cEnterpriseHistory);
        supplierInfo.setcEnterpriseId(cEnterpriseHistory.getId());
        //征信授权书
        FileStorageDO fileStorageDO = fileService.getById(reportId);
        fileStorageDO.setId(null);
        fileStorageDO.setBusinessId(cEnterpriseHistory.getId());
        fileStorageDO.setBusinessType(FileTypeEnum.ENTERPRISE_CREDIT_AUTHORIZATION_LETTER_HISTORY.getCode());
        fileService.save(fileStorageDO);
        //担保企业信息
        Enterprise guaranteeEnterprise = supplierInfo.getGuaranteeEnterprise();
        if (guaranteeEnterprise != null) {
            Enterprise existGuaranteeEnterprise = enterpriseService.getById(guaranteeEnterprise.getId());
            CEnterpriseHistory guaranteeEnterpriseHistory = new CEnterpriseHistory();
            BeanUtils.copyProperties(existGuaranteeEnterprise, guaranteeEnterpriseHistory, "id");
            enterpriseHistoryService.save(guaranteeEnterpriseHistory);
            supplierInfo.setGuaranteeEnterpriseId(guaranteeEnterpriseHistory.getId());
            //保存担保企业补充信息
            addHistoryEnterprise(guaranteeEnterprise, guaranteeEnterpriseHistory.getId());
            //征信授权书
            FileStorageDO guaranteeEnterpriseFileStorageDO = fileService.getById(guaranteeEnterpriseReportId);
            guaranteeEnterpriseFileStorageDO.setId(null);
            guaranteeEnterpriseFileStorageDO.setBusinessId(guaranteeEnterpriseHistory.getId());
            guaranteeEnterpriseFileStorageDO.setBusinessType(FileTypeEnum.ENTERPRISE_CREDIT_AUTHORIZATION_LETTER_HISTORY.getCode());
            fileService.save(guaranteeEnterpriseFileStorageDO);
        }
        //供应商信息
        CSupplierInfoHistory cSupplierInfoHistory = new CSupplierInfoHistory();
        SupplierInfo existsSupplierInfo = getById(supplierInfo.getId());
        BeanUtils.copyProperties(existsSupplierInfo, cSupplierInfoHistory, "id");
        cSupplierInfoHistory.setcEnterpriseHistoryId(supplierInfo.getcEnterpriseId());
        cSupplierInfoHistory.setGuaranteeEnterpriseHistoryId(supplierInfo.getGuaranteeEnterpriseId());
        supplierInfoHistoryService.save(cSupplierInfoHistory);
        //供应商联系人信息
        SupplierContact supplierContact = supplierContactService.lambdaQuery().eq(SupplierContact::getSupplierInfoId, supplierInfo.getId()).one();
        CSupplierContactHistory cSupplierContactHistory = new CSupplierContactHistory();
        BeanUtils.copyProperties(supplierContact, cSupplierContactHistory, "id");
        cSupplierContactHistory.setcSupplierInfoHistory(cSupplierInfoHistory.getId());
        supplierContactHistoryService.save(cSupplierContactHistory);
        //保存供应商补充信息历史
        addHistoryEnterprise(enterprise, cEnterpriseHistory.getId());
        return cSupplierInfoHistory.getId();
    }

    private void addHistoryEnterprise(Enterprise enterprise, Long historyId) {
        //保存文件历史
        List<Long> files = enterprise.getAllFileIds();
        if (CollectionUtil.isNotEmpty(files)) {
            for (Long fileId : files) {
                FileStorageDO fileStorageDO = fileService.getById(fileId);
                fileStorageDO.setId(null);
                fileStorageDO.setBusinessId(historyId);
                fileStorageDO.setBusinessType(fileStorageDO.getBusinessType() + "_history");
                fileService.save(fileStorageDO);
            }
        }
        //保存征信信息
        List<CreditInvestigationInfo> creditInvestigationInfoList = enterprise.getCreditInvestigationInfoList();
        if (CollectionUtil.isNotEmpty(creditInvestigationInfoList)) {
            for (CreditInvestigationInfo creditInvestigationInfo : creditInvestigationInfoList) {
                CCreditInvestigationInfoHistory cCreditInvestigationInfoHistory = new CCreditInvestigationInfoHistory();
                BeanUtils.copyProperties(creditInvestigationInfo, cCreditInvestigationInfoHistory, "id");
                cCreditInvestigationInfoHistory.setcEnterpriseHistoryId(historyId);
                creditInvestigationInfoHistoryService.save(cCreditInvestigationInfoHistory);
                List<Long> fileList = creditInvestigationInfo.getFileList();
                if (CollectionUtil.isNotEmpty(fileList)) {
                    for (Long fileId : fileList) {
                        FileStorageDO fileStorageDO = fileService.getById(fileId);
                        fileStorageDO.setId(null);
                        fileStorageDO.setBusinessId(cCreditInvestigationInfoHistory.getId());
                        fileStorageDO.setBusinessType(fileStorageDO.getBusinessType() + "_history");
                        fileService.save(fileStorageDO);
                    }
                }
            }
        }
        //保存近两年财务报表
        List<CorporateFinance> corporateFinances = enterprise.getCorporateFinances();
        if (CollectionUtil.isNotEmpty(corporateFinances)) {
            for (CorporateFinance corporateFinance : corporateFinances) {
                CCorporateFinanceHistory cCorporateFinanceHistory = new CCorporateFinanceHistory();
                BeanUtils.copyProperties(corporateFinance, cCorporateFinanceHistory, "id");
                cCorporateFinanceHistory.setcEnterpriseHistoryId(historyId);
                corporateFinanceHistoryService.save(cCorporateFinanceHistory);
                Long fileId = corporateFinance.getFileId();
                FileStorageDO fileStorageDO = fileService.getById(fileId);
                fileStorageDO.setId(null);
                fileStorageDO.setBusinessId(cCorporateFinanceHistory.getId());
                fileStorageDO.setBusinessType(fileStorageDO.getBusinessType() + "_history");
                fileService.save(fileStorageDO);
            }
        }
        //保存上游采购单据
        List<UpstreamProcurementDocuments> upstreamProcurementDocuments = enterprise.getUpstreamProcurementDocuments();
        if (CollectionUtil.isNotEmpty(upstreamProcurementDocuments)) {
            for (UpstreamProcurementDocuments upstreamProcurementDocument : upstreamProcurementDocuments) {
                CUpstreamProcurementDocumentsHistory cUpstreamProcurementDocumentsHistory = new CUpstreamProcurementDocumentsHistory();
                BeanUtils.copyProperties(upstreamProcurementDocument, cUpstreamProcurementDocumentsHistory, "id");
                cUpstreamProcurementDocumentsHistory.setcEnterpriseHistoryId(historyId);
                upstreamProcurementDocumentsHistoryService.save(cUpstreamProcurementDocumentsHistory);
                List<Long> upstreamProcurementDocumentFiles = upstreamProcurementDocument.getFiles();
                if (CollectionUtil.isNotEmpty(upstreamProcurementDocumentFiles)) {
                    for (Long upstreamProcurementDocumentFile : upstreamProcurementDocumentFiles) {
                        FileStorageDO fileStorageDO = fileService.getById(upstreamProcurementDocumentFile);
                        fileStorageDO.setId(null);
                        fileStorageDO.setBusinessId(cUpstreamProcurementDocumentsHistory.getId());
                        fileStorageDO.setBusinessType(fileStorageDO.getBusinessType() + "_history");
                        fileService.save(fileStorageDO);
                    }
                }
            }
        }
        //保存下游销售单据
        List<SalesDocumentsInfo> salesDocumentsInfos = enterprise.getSalesDocumentsInfos();
        if (CollectionUtil.isNotEmpty(salesDocumentsInfos)) {
            for (SalesDocumentsInfo salesDocumentsInfo : salesDocumentsInfos) {
                CSalesDocumentsInfoHistory salesDocumentsInfoHistory = new CSalesDocumentsInfoHistory();
                BeanUtils.copyProperties(salesDocumentsInfo, salesDocumentsInfoHistory, "id");
                salesDocumentsInfoHistory.setcEnterpriseHistoryId(historyId);
                salesDocumentsInfoHistoryService.save(salesDocumentsInfoHistory);
                List<Long> fileIds = salesDocumentsInfo.getFiles();
                if (CollectionUtil.isNotEmpty(fileIds)) {
                    for (Long fileId : fileIds) {
                        FileStorageDO fileStorageDO = fileService.getById(fileId);
                        fileStorageDO.setId(null);
                        fileStorageDO.setBusinessId(salesDocumentsInfoHistory.getId());
                        fileStorageDO.setBusinessType(fileStorageDO.getBusinessType() + "_history");
                        fileService.save(fileStorageDO);
                    }
                }
            }
        }
        //保存关联企业信息
        List<AssociatedEnterpriseInfo> associatedEnterpriseInfos = enterprise.getAssociatedEnterpriseInfos();
        if (CollectionUtil.isNotEmpty(associatedEnterpriseInfos)) {
            for (AssociatedEnterpriseInfo associatedEnterpriseInfo : associatedEnterpriseInfos) {
                CAssociatedEnterpriseInfoHistory cAssociatedEnterpriseInfoHistory = new CAssociatedEnterpriseInfoHistory();
                BeanUtils.copyProperties(associatedEnterpriseInfo, cAssociatedEnterpriseInfoHistory, "id");
                cAssociatedEnterpriseInfoHistory.setcEnterpriseHistoryId(historyId);
                associatedEnterpriseInfoHistoryService.save(cAssociatedEnterpriseInfoHistory);
            }
        }
    }

    private Boolean updateEnterprise(Enterprise enterprise, SupplierInfo supplierInfo) {
        Enterprise exists = enterpriseService.getById(enterprise.getId());
        Boolean flag = false;
        if (supplierInfo.getVisible()) {
            String businessAddress = enterprise.getBusinessAddress();
            if (businessAddress.contains("黑龙江") || businessAddress.contains("辽宁") || businessAddress.contains("吉林")) {
                supplierInfo.setSupplierErrors("经营地址红否");
                flag = true;
            }
            if (!exists.getAuthStatus() || exists.getCertificateSignStatus() != 1) {
                throw new BusinessException(CodeUtil.FAIL, "请先完成认证和授权书的签署！");
            }
        }
        Enterprise existsEnterprise = enterpriseService.getById(enterprise.getId());
        List files = new ArrayList<>();
        //保存文件
        fileService.lambdaUpdate().eq(FileStorageDO::getBusinessId, enterprise.getId()).eq(FileStorageDO::getBusinessType, FileTypeEnum.ENTERPRISE_LOCATION_MAP.getCode()).set(FileStorageDO::getBusinessId, null).update();
        fileService.lambdaUpdate().eq(FileStorageDO::getBusinessId, enterprise.getId()).eq(FileStorageDO::getBusinessType, FileTypeEnum.ENTERPRISE_RENTAL_CONTRACT.getCode()).set(FileStorageDO::getBusinessId, null).update();
        fileService.lambdaUpdate().eq(FileStorageDO::getBusinessId, enterprise.getId()).eq(FileStorageDO::getBusinessType, FileTypeEnum.WATER_ELECTRIICITY_FEES.getCode()).set(FileStorageDO::getBusinessId, null).update();
        fileService.lambdaUpdate().eq(FileStorageDO::getBusinessId, enterprise.getId()).eq(FileStorageDO::getBusinessType, FileTypeEnum.ENTERPRISE_OFFICE_ENVIRONMENT.getCode()).set(FileStorageDO::getBusinessId, null).update();
        fileService.lambdaUpdate().eq(FileStorageDO::getBusinessId, enterprise.getId()).eq(FileStorageDO::getBusinessType, FileTypeEnum.ENTERPRISE_BUSINESS_LICENSE.getCode()).set(FileStorageDO::getBusinessId, null).update();
        fileService.lambdaUpdate().eq(FileStorageDO::getBusinessId, enterprise.getId()).eq(FileStorageDO::getBusinessType, FileTypeEnum.ENTERPRISE_BASIC_ACCOUNT_INFORMATION.getCode()).set(FileStorageDO::getBusinessId, null).update();
        fileService.lambdaUpdate().eq(FileStorageDO::getBusinessId, enterprise.getId()).eq(FileStorageDO::getBusinessType, FileTypeEnum.ENTERPRISE_ARTICLES_ASSOCIATION.getCode()).set(FileStorageDO::getBusinessId, null).update();
        fileService.lambdaUpdate().eq(FileStorageDO::getBusinessId, enterprise.getId()).eq(FileStorageDO::getBusinessType, FileTypeEnum.ENTERPRISE_JUDGMENT.getCode()).set(FileStorageDO::getBusinessId, null).update();
        fileService.lambdaUpdate().eq(FileStorageDO::getBusinessId, enterprise.getId()).eq(FileStorageDO::getBusinessType, FileTypeEnum.ENTERPRISE_TAX_RETURN.getCode()).set(FileStorageDO::getBusinessId, null).update();
        fileService.lambdaUpdate().eq(FileStorageDO::getBusinessId, enterprise.getId()).eq(FileStorageDO::getBusinessType, FileTypeEnum.ENTERPRISE_ACCOUNTING_REPORT.getCode()).set(FileStorageDO::getBusinessId, null).update();
        List<Long> locationMapIds = enterprise.getLocationMapIds();
        if (CollectionUtil.isNotEmpty(locationMapIds)) {
            files.addAll(locationMapIds);
        }
        fileService.updateBusinessId(locationMapIds, enterprise.getId());
        List<Long> rentalContractIds = enterprise.getRentalContractIds();
        if (CollectionUtil.isNotEmpty(rentalContractIds)) {
            files.addAll(rentalContractIds);
        }
        fileService.updateBusinessId(rentalContractIds, enterprise.getId());
        List<Long> waterElectricityFeesIds = enterprise.getWaterElectricityFeesIds();
        if (CollectionUtil.isNotEmpty(waterElectricityFeesIds)) {
            files.addAll(waterElectricityFeesIds);
        }
        fileService.updateBusinessId(waterElectricityFeesIds, enterprise.getId());
        List<Long> officeEnvironmentIds = enterprise.getOfficeEnvironmentIds();
        if (CollectionUtil.isNotEmpty(officeEnvironmentIds)) {
            files.addAll(officeEnvironmentIds);
        }
        fileService.updateBusinessId(officeEnvironmentIds, enterprise.getId());
        List<Long> businessLicenseIds = enterprise.getBusinessLicenseIds();
        if (CollectionUtil.isNotEmpty(businessLicenseIds)) {
            files.addAll(businessLicenseIds);
        }
        fileService.updateBusinessId(businessLicenseIds, enterprise.getId());
        List<Long> basicAccountInformationIds = enterprise.getBasicAccountInformationIds();
        if (CollectionUtil.isNotEmpty(basicAccountInformationIds)) {
            files.addAll(basicAccountInformationIds);
        }
        fileService.updateBusinessId(basicAccountInformationIds, enterprise.getId());
        List<Long> articlesAssociationIds = enterprise.getArticlesAssociationIds();
        if (CollectionUtil.isNotEmpty(articlesAssociationIds)) {
            files.addAll(articlesAssociationIds);
        }
        fileService.updateBusinessId(articlesAssociationIds, enterprise.getId());
        List<Long> judgmentIds = enterprise.getJudgmentIds();
        if (CollectionUtil.isNotEmpty(judgmentIds)) {
            files.addAll(judgmentIds);
        }
        fileService.updateBusinessId(judgmentIds, enterprise.getId());
        List<Long> taxReturnIds = enterprise.getTaxReturnIds();
        if (CollectionUtil.isNotEmpty(taxReturnIds)) {
            files.addAll(taxReturnIds);
        }
        fileService.updateBusinessId(taxReturnIds, enterprise.getId());
        List<Long> accountingreportIds = enterprise.getAccountingreportIds();
        if (CollectionUtil.isNotEmpty(accountingreportIds)) {
            files.addAll(accountingreportIds);
        }
        fileService.updateBusinessId(accountingreportIds, enterprise.getId());
        enterprise.setAllFileIds(files);
        //保存征信信息
        creditInvestigationInfoService.lambdaUpdate().eq(CreditInvestigationInfo::getcEnterpriseId, enterprise.getId()).remove();
        List<CreditInvestigationInfo> creditInvestigationInfoList = enterprise.getCreditInvestigationInfoList();
        if (CollectionUtil.isNotEmpty(creditInvestigationInfoList)) {
            for (CreditInvestigationInfo creditInvestigationInfo : creditInvestigationInfoList) {
                List<Long> fileList = creditInvestigationInfo.getFileList();
                creditInvestigationInfo.setcEnterpriseId(enterprise.getId());
                creditInvestigationInfo.setName(StringUtils.trimToEmpty(creditInvestigationInfo.getName()));
                creditInvestigationInfoService.save(creditInvestigationInfo);
                fileService.lambdaUpdate().eq(FileStorageDO::getBusinessId,creditInvestigationInfo.getId()).eq(FileStorageDO::getBusinessType,FileTypeEnum.ENTERPRISE_IDCARD_Files.getCode())
                        .set(FileStorageDO::getBusinessId,null).update();
                if(CollectionUtil.isNotEmpty(fileList)){
                    for (Long fileId : fileList) {
                        FileStorageDO fileStorageDO = fileService.getById(fileId);
                        fileStorageDO.setId(null);
                        fileStorageDO.setBusinessId(creditInvestigationInfo.getId());
                        fileService.save(fileStorageDO);
                    }
                }
//                fileService.updateBusinessId(fileList, creditInvestigationInfo.getId());
                if (creditInvestigationInfo.getType().equals(CreditInvestigationTypeEnums.THREE.getCode())) {
                    if (creditInvestigationInfo.getName().equals(existsEnterprise.getLegalRepresentative())) {
                        enterprise.setController(creditInvestigationInfo.getName());
                        enterprise.setcDongjiangaoRiskControllerId(existsEnterprise.getcDongjiangaoRiskId());
                    } else if (creditInvestigationInfo.getName().equals(existsEnterprise.getMajorShareholders())) {
                        enterprise.setController(creditInvestigationInfo.getName());
                        enterprise.setcDongjiangaoRiskControllerId(existsEnterprise.getcDongjiangaoRiskBigId());
//                    } else {
//                        if (StringUtils.isNotEmpty(creditInvestigationInfo.getName())) {
//                            //法人 763-董监高风险扫描
//                            String dongjiangaoRisksUrl = dongjiangaoRisks + "?socialCreditCode=" + existsEnterprise.getSocialCreditCode() + "&personName=" + creditInvestigationInfo.getName();
//                            ResponseJson dongjiangaoRisksObject;
//                            try {
//                                dongjiangaoRisksObject = restTemplate.getForObject(dongjiangaoRisksUrl, ResponseJson.class);
//                            } catch (Exception e) {
//                                throw new ServiceException(CodeUtil.FAIL, "实控人董监高风险扫描出错！请确认实控人为本公司人员！");
//                            }
//                            if (dongjiangaoRisksObject.getCode() != 200) {
//                                throw new ServiceException(CodeUtil.FAIL, "实控人董监高风险扫描出错！请确认实控人为本公司人员！");
//                            }
//                            JSONObject dongjiangaoRisksObjectData = new JSONObject(dongjiangaoRisksObject.getData());
//                            Integer sxCount = dongjiangaoRisksObjectData.getInt("sxCount");
//                            Integer zxCount = dongjiangaoRisksObjectData.getInt("zxCount");
//                            Integer stCount = dongjiangaoRisksObjectData.getInt("stCount");
//                            Long dongjiangaoRiskId = dongjiangaoRisksObjectData.getLong("id");
//                            enterprise.setController(creditInvestigationInfo.getName());
//                            enterprise.setcDongjiangaoRiskControllerId(dongjiangaoRiskId);
//                            if (sxCount > 0 || zxCount > 0 || stCount > 0) {
//                                flag = true;
//                            }
//                        }
                    }
                }
            }
        }
        //保存近两年财务报表
        corporateFinanceService.lambdaUpdate().eq(CorporateFinance::getcEnterpriseId, enterprise.getId()).remove();
        List<CorporateFinance> corporateFinances = enterprise.getCorporateFinances();
        if (CollectionUtil.isNotEmpty(corporateFinances)) {
            for (CorporateFinance corporateFinance : corporateFinances) {
                Long fileId = corporateFinance.getFileId();
                if(fileId == null && supplierInfo.getVisible()){
                    throw new ServiceException(CodeUtil.FAIL,"请上传财务报表附件！");
                }
                corporateFinance.setcEnterpriseId(enterprise.getId());
                corporateFinanceService.save(corporateFinance);
                fileService.updateBusinessId(fileId, corporateFinance.getId());
            }
        }
        //保存上游采购单据
        upstreamProcurementDocumentsService.lambdaUpdate().eq(UpstreamProcurementDocuments::getcEnterpriseId, enterprise.getId()).remove();
        List<UpstreamProcurementDocuments> upstreamProcurementDocuments = enterprise.getUpstreamProcurementDocuments();
        if (CollectionUtil.isNotEmpty(upstreamProcurementDocuments)) {
            for (UpstreamProcurementDocuments upstreamProcurementDocument : upstreamProcurementDocuments) {
                List<Long> upstreamProcurementDocumentFiles = upstreamProcurementDocument.getFiles();
                upstreamProcurementDocument.setcEnterpriseId(enterprise.getId());
                upstreamProcurementDocumentsService.save(upstreamProcurementDocument);
                fileService.updateBusinessId(upstreamProcurementDocumentFiles, upstreamProcurementDocument.getId());
            }
        }
        //保存下游销售单据
        salesDocumentsInfoService.lambdaUpdate().eq(SalesDocumentsInfo::getcEnterpriseId, enterprise.getId()).remove();
        List<SalesDocumentsInfo> salesDocumentsInfos = enterprise.getSalesDocumentsInfos();
        if (CollectionUtil.isNotEmpty(salesDocumentsInfos)) {
            for (SalesDocumentsInfo salesDocumentsInfo : salesDocumentsInfos) {
                List<Long> fileIds = salesDocumentsInfo.getFiles();
                salesDocumentsInfo.setcEnterpriseId(enterprise.getId());
                salesDocumentsInfoService.save(salesDocumentsInfo);
                fileService.updateBusinessId(fileIds, salesDocumentsInfo.getId());
            }
        }
        //保存关联企业信息
        associatedEnterpriseInfoService.lambdaUpdate().eq(AssociatedEnterpriseInfo::getcEnterpriseId, enterprise.getId()).remove();
        List<AssociatedEnterpriseInfo> associatedEnterpriseInfos = enterprise.getAssociatedEnterpriseInfos();
        if (CollectionUtil.isNotEmpty(associatedEnterpriseInfos)) {
            for (AssociatedEnterpriseInfo associatedEnterpriseInfo : associatedEnterpriseInfos) {
                associatedEnterpriseInfo.setcEnterpriseId(enterprise.getId());
                associatedEnterpriseInfoService.save(associatedEnterpriseInfo);
            }
        }
        enterpriseService.updateById(enterprise);
        return flag;
    }

    private void findBig(String creditCode, Long comprehensiveRiskInvestigationId, Enterprise enterprise) {
        // 股东信息 工商登记
        String pubStockUrl = pubStock + "?socialCreditCode=" + creditCode + "&comprehensiveRiskInvestigationId=" + comprehensiveRiskInvestigationId;
        ResponseJson forObject;
        try {
            forObject = restTemplate.getForObject(pubStockUrl, ResponseJson.class);
        } catch (Exception e) {
            throw new ServiceException(CodeUtil.FAIL, "网络异常，请稍后重试！");
        }
        if (forObject != null) {
            JSONObject jsonObject = new JSONObject(forObject.getData());
            List<CRegStock> list = jsonObject.getBeanList("list", CRegStock.class);
            CRegStock cRegStock = list.stream().map(r -> {
                String stockPercent = r.getStockPercent();
                stockPercent = stockPercent.replace("%", "");
                double percent = Double.valueOf(stockPercent);
                r.setPercent(percent);
                return r;
            }).max(Comparator.comparing(CRegStock::getPercent)).get();
            String cRegStockStockName = cRegStock.getStockName();
            if (cRegStockStockName.length() > 4) {
                findBig(cRegStock.getCreditCode(), comprehensiveRiskInvestigationId, enterprise);
            } else {
                //大股东 763-董监高风险扫描
                enterprise.setMajorShareholders(cRegStock.getStockName());
                String bigDongjiangaoRisksUrl = dongjiangaoRisks + "?socialCreditCode=" + creditCode + "&personName=" + cRegStockStockName;
                ResponseJson bigDongjiangaoRisksObject;
                try {
                    bigDongjiangaoRisksObject = restTemplate.getForObject(bigDongjiangaoRisksUrl, ResponseJson.class);
                } catch (Exception e) {
                    throw new ServiceException(CodeUtil.FAIL, "网络异常，请稍后重试！");
                }
                JSONObject bigDongjiangaoRisks = new JSONObject(bigDongjiangaoRisksObject.getData());
                Integer sxCountBig = bigDongjiangaoRisks.getInt("sxCount");
                Integer zxCountBig = bigDongjiangaoRisks.getInt("zxCount");
                Integer stCountBig = bigDongjiangaoRisks.getInt("stCount");
                Long dongjiangaoRiskBigId = bigDongjiangaoRisks.getLong("id");
                enterprise.setcDongjiangaoRiskBigId(dongjiangaoRiskBigId);
                enterprise.setSxCountBig(sxCountBig);
                enterprise.setZxCountBig(zxCountBig);
                enterprise.setStCountBig(stCountBig);
            }
        }
    }
}
