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

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sunxung.factoring.component.constance.SupplierScoringModel;
import com.sunxung.factoring.component.exception.ServiceException;
import com.sunxung.factoring.component.util.*;
import com.sunxung.factoring.dict.impl.FileModuleDict;
import com.sunxung.factoring.entity.ResponseJson;
import com.sunxung.factoring.entity.credit.CreditDetail;
import com.sunxung.factoring.entity.credit.CreditInfo;
import com.sunxung.factoring.entity.entprise.Enterprise;
import com.sunxung.factoring.entity.project.BusinessProcessingLog;
import com.sunxung.factoring.entity.supplier.*;
import com.sunxung.factoring.entity.sys.FileStorage;
import com.sunxung.factoring.entity.sys.FileStorageDO;
import com.sunxung.factoring.entity.sys.User;
import com.sunxung.factoring.mapper.supplier.SupplierApprovalFirstMapper;
import com.sunxung.factoring.service.credit.CreditDetailService;
import com.sunxung.factoring.service.credit.CreditService;
import com.sunxung.factoring.service.entprise.IEnterpriseService;
import com.sunxung.factoring.service.project.BusinessProcessingLogService;
import com.sunxung.factoring.service.supplier.*;
import com.sunxung.factoring.service.sys.DictionaryService;
import com.sunxung.factoring.service.sys.FileService;
import com.sunxung.factoring.service.sys.FileStorageService;
import com.sunxung.factoring.service.sys.UserService;
import com.sunxung.factoring.service.sys.flowable.FlowableService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 供应商审核第一步 综合评估 服务实现类
 * </p>
 *
 * @author liutao
 * @since 2023-12-05
 */
@Service("first_reviewService")
public class SupplierApprovalFirstServiceImpl extends ServiceImpl<SupplierApprovalFirstMapper, SupplierApprovalFirst> implements ISupplierApprovalFirstService {

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

    @Autowired
    private BusinessProcessingLogService businessProcessingLogService;

    @Autowired
    private ICSupplierInfoHistoryService supplierInfoHistoryService;

    @Autowired
    private ICEnterpriseHistoryService enterpriseHistoryService;

    @Autowired
    private ICCreditInvestigationInfoHistoryService creditInvestigationInfoHistoryService;

    @Autowired
    private FileService fileService;

    @Autowired
    private ICreditSituationService creditSituationService;

    @Autowired
    private IBlacklistService blacklistService;

    @Autowired
    private ICorporateGoodwillService corporateGoodwillService;

    @Autowired
    private IExceptionDataService exceptionDataService;

    @Autowired
    private INewsService newsService;

    @Autowired
    private IPrivateLendingService privateLendingService;

    @Autowired
    private ISeriousIllegalityService seriousIllegalityService;

    @Autowired
    private ITaxIllegalDataService taxIllegalDataService;

    @Autowired
    private ITaxOweNoticeService taxOweNoticeService;

    @Autowired
    private RestTemplate restTemplate;

    @Value("${sop.findCorporateGoodwillUrl}")
    private String findCorporateGoodwill;

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

    @Autowired
    private IEnterpriseService enterpriseService;

    @Autowired
    private UserService userService;

    @Autowired
    private IDueDiligenceAllocationService dueDiligenceAllocationService;

    @Autowired
    private FlowableService flowableService;

    @Autowired
    private DictionaryService dictionaryService;

    @Autowired
    private CreditService creditService;

    @Autowired
    private CreditDetailService creditDetailService;

    @Autowired
    private FileStorageService fileStorageService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void firstReview(SupplierInfo supplierInfo) {
        //保存第一步审核结论
        SupplierApprovalFirst supplierApprovalFirst = measurement(supplierInfo);
        save(supplierApprovalFirst);
        //保存企业审核信息
        Enterprise enterprise = supplierInfo.getEnterprise();
        saveInfo(enterprise,supplierInfo.getId());
        //保存担保企业审核信息
        Enterprise guaranteeEnterprise = supplierInfo.getGuaranteeEnterprise();
        if(guaranteeEnterprise != null){
            saveInfo(guaranteeEnterprise, supplierInfo.getId());
        }
        //流程处理
//        if(supplierInfo.getVisible()){
            String taskId = supplierInfo.getTaskId();
            String result = "通过";
            Long mainEnterpriseCount = supplierApprovalFirst.getMainEnterpriseCount();
            if(mainEnterpriseCount > 0){
                result = "红否";
            }
            if(guaranteeEnterprise != null){
                Long guaranteeEnterpriseCount = supplierApprovalFirst.getGuaranteeEnterpriseCount();
                if(guaranteeEnterpriseCount > 0){
                    result = "红否";
                }
            }
            Map<String, Object> procVariables = new HashMap<>();
            procVariables.put("result",result);
            Map<String, Object> msgVariables = new HashMap<>();
            msgVariables.put(ConstantUtil.FLOWABLE_MSG_TITLE, "供应商名称：" + enterprise.getCorporateName());
            if(result.equals("通过")){
                msgVariables.put(ConstantUtil.FLOWABLE_MSG_CONTENT,
                        "供应商名称为“" + enterprise.getCorporateName() + "”的供应商已进入“"
                                + ConstantConversionUtil.flowBusinessKeyNames.get(ConstantUtil.SUPPLIER_INFO) + "—供应商审核第二步，"
                                + ConstantUtil.FLOWABLE_MSG_ASSIGNEE);
            }else {
                msgVariables.put(ConstantUtil.FLOWABLE_MSG_CONTENT,
                        "供应商名称为“" + enterprise.getCorporateName() + "”的供应商审核已被否决");
            }
            flowableService.completeMyTask(taskId, supplierInfo, procVariables, null, supplierApprovalFirst.getId(), msgVariables, ConstantUtil.SUPPLIER_INFO);
//        }
    }


    private void saveInfo(Enterprise enterprise, Long id) {
        List<CreditSituation> creditSituations = enterprise.getCreditSituations();
        if(CollectionUtil.isNotEmpty(creditSituations)){
            for (CreditSituation creditSituation : creditSituations) {
                creditSituationService.lambdaUpdate()
                        .eq(CreditSituation::getcCreditInvestigationInfoHistoryId,creditSituation.getcCreditInvestigationInfoHistoryId())
                        .eq(CreditSituation::getcSupplierInfoId,id).remove();
                creditSituation.setcSupplierInfoId(id);
                creditSituationService.save(creditSituation);
            }
        }
        corporateGoodwillService.lambdaUpdate().eq(CorporateGoodwill::getcSupplierInfoId,id)
                .eq(CorporateGoodwill::getcEnterpriseId,enterprise.getId()).remove();
        CorporateGoodwill corporateGoodwill = enterprise.getCorporateGoodwill();
        corporateGoodwill.setcSupplierInfoId(id);
        corporateGoodwill.setcEnterpriseId(enterprise.getId());
        corporateGoodwillService.save(corporateGoodwill);
        privateLendingService.lambdaUpdate().eq(PrivateLending::getcSupplierInfoId,id)
                .eq(PrivateLending::getcEnterpriseId,enterprise.getId()).remove();
        List<PrivateLending> privateLendings = enterprise.getPrivateLendings();
        if(CollectionUtil.isNotEmpty(privateLendings)){
            for (PrivateLending privateLending : privateLendings) {
                privateLending.setcSupplierInfoId(id);
                privateLending.setcEnterpriseId(enterprise.getId());
                privateLendingService.save(privateLending);
            }
        }
        seriousIllegalityService.lambdaUpdate().eq(SeriousIllegality::getcSupplierInfoId,id)
                .eq(SeriousIllegality::getcEnterpriseId,enterprise.getId()).remove();
        List<SeriousIllegality> seriousIllegalities = enterprise.getSeriousIllegalities();
        if(CollectionUtil.isNotEmpty(seriousIllegalities)){
            for (SeriousIllegality seriousIllegality : seriousIllegalities) {
                seriousIllegality.setcSupplierInfoId(id);
                seriousIllegality.setcEnterpriseId(enterprise.getId());
                seriousIllegalityService.save(seriousIllegality);
            }
        }
        List<TaxOweNotice> taxOweNotices = enterprise.getTaxOweNotices();
        taxOweNoticeService.lambdaUpdate().eq(TaxOweNotice::getcSupplierInfoId,id)
                .eq(TaxOweNotice::getcEnterpriseId,enterprise.getId()).remove();
        if(CollectionUtil.isNotEmpty(taxOweNotices)){
            for (TaxOweNotice taxOweNotice : taxOweNotices) {
                taxOweNotice.setcSupplierInfoId(id);
                taxOweNotice.setcEnterpriseId(enterprise.getId());
                taxOweNoticeService.save(taxOweNotice);
            }
        }
        List<TaxIllegalData> taxIllegalData = enterprise.getTaxIllegalData();
        taxIllegalDataService.lambdaUpdate().eq(TaxIllegalData::getcSupplierInfoId,id)
                .eq(TaxIllegalData::getcEnterpriseId,enterprise.getId()).remove();
        if(CollectionUtil.isNotEmpty(taxIllegalData)){
            for (TaxIllegalData taxIllegalDatum : taxIllegalData) {
                taxIllegalDatum.setcSupplierInfoId(id);
                taxIllegalDatum.setcEnterpriseId(enterprise.getId());
                taxIllegalDataService.save(taxIllegalDatum);
            }
        }
        List<Blacklist> blacklists = enterprise.getBlacklists();
        blacklistService.lambdaUpdate().eq(Blacklist::getcSupplierInfoId,id)
                .eq(Blacklist::getcEnterpriseId,enterprise.getId()).remove();
        if(CollectionUtil.isNotEmpty(blacklists)){
            for (Blacklist blacklist : blacklists) {
                blacklist.setcSupplierInfoId(id);
                blacklist.setcEnterpriseId(enterprise.getId());
                blacklistService.save(blacklist);
            }
        }
        List<ExceptionData> exceptionData = enterprise.getExceptionData();
        exceptionDataService.lambdaUpdate().eq(ExceptionData::getcSupplierInfoId,id)
                .eq(ExceptionData::getcEnterpriseId,enterprise.getId()).remove();
        if(CollectionUtil.isNotEmpty(exceptionData)){
            for (ExceptionData exceptionDatum : exceptionData) {
                exceptionDatum.setcSupplierInfoId(id);
                exceptionDatum.setcEnterpriseId(enterprise.getId());
                exceptionDataService.save(exceptionDatum);
            }
        }
        List<News> news = enterprise.getNews();
        newsService.lambdaUpdate().eq(News::getcSupplierInfoId,id)
                .eq(News::getcEnterpriseId,enterprise.getId()).remove();
        if(CollectionUtil.isNotEmpty(news)){
            for (News news1 : news) {
                news1.setcSupplierInfoId(id);
                news1.setcEnterpriseId(enterprise.getId());
                newsService.save(news1);
            }
        }
    }

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

        SupplierApprovalFirst supplierApprovalFirst = lambdaQuery().eq(SupplierApprovalFirst::getcSupplierInfoId, id).one();
        supplierInfo.setHistoryId(supplierInfoHistory.getId());
        supplierInfo.setSupplierApprovalFirst(supplierApprovalFirst);

        CEnterpriseHistory enterpriseHistory = enterpriseHistoryService.getById(supplierInfoHistory.getcEnterpriseHistoryId());
        Enterprise enterprise = enterpriseService.getById(supplierInfo.getcEnterpriseId());
        autoFirstReview(id,enterprise,enterpriseHistory);
        supplierInfo.setEnterprise(enterprise);
        supplierInfo.setHasGuaranteeEnterprise(false);
        if(supplierInfo.getGuaranteeEnterpriseId() != null){
            supplierInfo.setHasGuaranteeEnterprise(true);
            CEnterpriseHistory enteguaranteeHistory = enterpriseHistoryService.getById(supplierInfoHistory.getGuaranteeEnterpriseHistoryId());
            Enterprise guaranteeEnterprise = enterpriseService.getById(supplierInfo.getGuaranteeEnterpriseId());
            autoFirstReview(id,guaranteeEnterprise, enteguaranteeHistory);
            supplierInfo.setGuaranteeEnterprise(guaranteeEnterprise);
        }
        return supplierInfo;
    }

    private void autoFirstReview(Long id,Enterprise enterprise, CEnterpriseHistory enterpriseHistory) {
        //企业负责人征信情况
        List<CreditSituation> creditSituations = creditSituationService.lambdaQuery().eq(CreditSituation::getcSupplierInfoId, id).list();
        List<CreditSituation> creditSituationsResult = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(creditSituations)){
            for (CreditSituation creditSituation : creditSituations) {
                CCreditInvestigationInfoHistory creditInvestigationInfoHistory = creditInvestigationInfoHistoryService.getById(creditSituation.getcCreditInvestigationInfoHistoryId());
                creditInvestigationInfoHistory.setTypeStr(dictionaryService.getByCode(creditInvestigationInfoHistory.getType()).getName());
                CEnterpriseHistory byId = enterpriseHistoryService.getById(creditInvestigationInfoHistory.getcEnterpriseHistoryId());
                CEnterpriseHistory historyServiceById = enterpriseHistoryService.getById(enterpriseHistory.getId());
                List<FileStorage> list = new ArrayList<>();
                if(byId.getCorporateName().equals(historyServiceById.getCorporateName())){
                    //todo 填充征信报告
                    CreditInfo creditInfo = creditService.lambdaQuery().eq(CreditInfo::getCardNo, creditInvestigationInfoHistory.getSocialCreditCode()).one();
                    if(creditInfo != null){
                        List<CreditDetail> creditDetails = creditDetailService.lambdaQuery()
                                .eq(CreditDetail::getCreditId,creditInfo.getId())
                                .isNotNull(CreditDetail::getCreditAddress)
                                .orderByDesc(CreditDetail::getGmtCreate).list();
                        if(CollectionUtil.isNotEmpty(creditDetails)){
                            CreditDetail creditDetail = creditDetails.get(0);
                            if(StringUtil.isNotEmpty(creditDetail.getCreditAddress())){
                                FileStorage creditDetailFiles = fileStorageService.get(Long.valueOf(creditDetail.getCreditAddress()));
                                list.add(creditDetailFiles);
                            }
                        }
                    }
                    creditInvestigationInfoHistory.setCreditDetailFiles(list);
                    List<FileStorageDO> cardFiles = fileService.findByBusinessId(creditInvestigationInfoHistory.getId(), FileModuleDict.ChildEnum.ENTERPRISE_IDCARD_FILES_HISTORY.getCode());
                    creditInvestigationInfoHistory.setCardFiles(cardFiles);
                    creditSituation.setCreditInvestigationInfoHistory(creditInvestigationInfoHistory);
                    creditSituationsResult.add(creditSituation);
                }
            }
        }
        if(CollectionUtil.isEmpty(creditSituationsResult)){
            List<CCreditInvestigationInfoHistory> creditInvestigationInfoHistories = creditInvestigationInfoHistoryService.lambdaQuery().eq(CCreditInvestigationInfoHistory::getcEnterpriseHistoryId, enterpriseHistory.getId()).list();
            if(CollectionUtil.isNotEmpty(creditInvestigationInfoHistories)){
                //去重
                List<CCreditInvestigationInfoHistory> filterResult = creditInvestigationInfoHistories.stream()
                        .collect(Collectors.toMap(CCreditInvestigationInfoHistory::getName, user -> user, (u1, u2) -> u1))
                        .values().stream().collect(Collectors.toList());
                for (CCreditInvestigationInfoHistory creditInvestigationInfoHistory : filterResult) {
                    List<FileStorage> list = new ArrayList<>();
                    if(creditInvestigationInfoHistory.getcEnterpriseHistoryId().equals(enterpriseHistory.getId())){
                        List<FileStorageDO> cardFiles = fileService.findByBusinessId(creditInvestigationInfoHistory.getId(), FileModuleDict.ChildEnum.ENTERPRISE_IDCARD_FILES_HISTORY.getCode());
                        creditInvestigationInfoHistory.setTypeStr(dictionaryService.getByCode(creditInvestigationInfoHistory.getType()).getName());
                        creditInvestigationInfoHistory.setCardFiles(cardFiles);
                        CreditSituation creditSituation = new CreditSituation();
                        creditSituation.setcSupplierInfoId(id);
                        creditSituation.setcCreditInvestigationInfoHistoryId(creditInvestigationInfoHistory.getId());
                        //todo 填充征信报告
                        CreditInfo creditInfo = creditService.lambdaQuery().eq(CreditInfo::getCardNo, creditInvestigationInfoHistory.getSocialCreditCode()).one();
                        if(creditInfo != null){
                            List<CreditDetail> creditDetails = creditDetailService.lambdaQuery()
                                    .eq(CreditDetail::getCreditId,creditInfo.getId())
                                    .isNotNull(CreditDetail::getCreditAddress)
                                    .orderByDesc(CreditDetail::getGmtCreate).list();
                            if(CollectionUtil.isNotEmpty(creditDetails)){
                                CreditDetail creditDetail = creditDetails.get(0);
                                FileStorage creditDetailFiles = fileStorageService.get(Long.valueOf(creditDetail.getCreditAddress()));
                                list.add(creditDetailFiles);
                            }
                        }
                        creditInvestigationInfoHistory.setCreditDetailFiles(list);
                        creditSituation.setCreditInvestigationInfoHistory(creditInvestigationInfoHistory);
                        Long dongjiangaoRiskId = null;
                        if (creditInvestigationInfoHistory.getType().equals("c_credit_investigation_info_type_1")) {
                            dongjiangaoRiskId = enterprise.getcDongjiangaoRiskId();
                        } else if (creditInvestigationInfoHistory.getType().equals("c_credit_investigation_info_type_2")) {
                            dongjiangaoRiskId = enterprise.getcDongjiangaoRiskBigId();
                        }else {
                            dongjiangaoRiskId = enterprise.getcDongjiangaoRiskControllerId();
                        }
                        if(dongjiangaoRiskId != null){
                            String dongjiangaoRisksUrl = dongjiangaoRisks + "?id=" + dongjiangaoRiskId;
                            ResponseJson dongjiangaoRisksObject = restTemplate.getForObject(dongjiangaoRisksUrl, ResponseJson.class);
                            if (dongjiangaoRisksObject == null) {
                                throw new ServiceException(CodeUtil.FAIL, "董监高风险扫描出错！");
                            }
                            JSONObject dongjiangaoRisksObjectData = new JSONObject(dongjiangaoRisksObject.getData());
                            Integer sxCount = dongjiangaoRisksObjectData.getInt("sxCount");
                            Integer zxCount = dongjiangaoRisksObjectData.getInt("zxCount");
                            Integer stCount = dongjiangaoRisksObjectData.getInt("stCount");
                            if (sxCount > 0) {
                                creditSituation.setRecordOfDishonestyExecution(1);
                            } else {
                                creditSituation.setRecordOfDishonestyExecution(0);
                            }
                            if (zxCount > 0) {
                                creditSituation.setExecutedRecord(1);
                            } else {
                                creditSituation.setExecutedRecord(0);
                            }
                            if (stCount > 0) {
                                creditSituation.setStCount(1);
                            } else {
                                creditSituation.setStCount(0);
                            }
                        }
                        creditSituationsResult.add(creditSituation);
                    }
                }
            }
        }
        enterprise.setCreditSituations(creditSituationsResult);
        //企业信誉
        CorporateGoodwill corporateGoodwill = corporateGoodwillService.lambdaQuery().eq(CorporateGoodwill::getcSupplierInfoId, id).eq(CorporateGoodwill::getcEnterpriseId, enterprise.getId()).one();
        if(corporateGoodwill == null){
            corporateGoodwill = new CorporateGoodwill();
            corporateGoodwill.setcSupplierInfoId(id);
            corporateGoodwill.setcEnterpriseId(enterprise.getId());
        }
        //todo 填充征信报告
        CreditInfo creditInfo = creditService.lambdaQuery().eq(CreditInfo::getCardNo, enterprise.getSocialCreditCode()).one();
        List<FileStorage> list = new ArrayList<>();
        if(creditInfo != null){
            List<CreditDetail> creditDetails = creditDetailService.lambdaQuery()
                    .eq(CreditDetail::getCreditId,creditInfo.getId())
                    .isNotNull(CreditDetail::getCreditAddress)
                    .orderByDesc(CreditDetail::getGmtCreate).list();
            if(CollectionUtil.isNotEmpty(creditDetails)){
                CreditDetail creditDetail = creditDetails.get(0);
                if(StringUtil.isNotEmpty(creditDetail.getCreditAddress())){
                    FileStorage creditDetailFiles = fileStorageService.get(Long.valueOf(creditDetail.getCreditAddress()));
                    list.add(creditDetailFiles);
                }
            }
        }
        corporateGoodwill.setCreditDetailFiles(list);
        enterprise.setCorporateGoodwill(corporateGoodwill);
        List<PrivateLending> privateLendings = privateLendingService.lambdaQuery().eq(PrivateLending::getcSupplierInfoId, id).eq(PrivateLending::getcEnterpriseId, enterprise.getId()).list();
        if(CollectionUtil.isNotEmpty(privateLendings)){
            privateLendings.forEach(r->r.setPrivateLending(0));
        }
        enterprise.setPrivateLendings(privateLendings);
        List<SeriousIllegality> seriousIllegalities = seriousIllegalityService.lambdaQuery().eq(SeriousIllegality::getcSupplierInfoId, id).eq(SeriousIllegality::getcEnterpriseId, enterprise.getId()).list();
        if(CollectionUtil.isNotEmpty(seriousIllegalities)){
            seriousIllegalities.forEach(r->r.setSeriousIllegality(0));
        }
        enterprise.setSeriousIllegalities(seriousIllegalities);
        List<TaxOweNotice> taxOweNotices = taxOweNoticeService.lambdaQuery().eq(TaxOweNotice::getcSupplierInfoId, id).eq(TaxOweNotice::getcEnterpriseId, enterprise.getId()).list();
        if(CollectionUtil.isNotEmpty(taxOweNotices)){
            taxOweNotices.forEach(r->r.setTaxOweNotice(0));
        }
        enterprise.setTaxOweNotices(taxOweNotices);
        List<TaxIllegalData> taxIllegalData = taxIllegalDataService.lambdaQuery().eq(TaxIllegalData::getcSupplierInfoId, id).eq(TaxIllegalData::getcEnterpriseId, enterprise.getId()).list();
        if(CollectionUtil.isNotEmpty(taxIllegalData)){
            taxIllegalData.forEach(r->r.setTaxIllegal(0));
        }
        enterprise.setTaxIllegalData(taxIllegalData);
        List<Blacklist> blacklists = blacklistService.lambdaQuery().eq(Blacklist::getcSupplierInfoId, id).eq(Blacklist::getcEnterpriseId, enterprise.getId()).list();
        if(CollectionUtil.isNotEmpty(blacklists)){
            blacklists.forEach(r->r.setBlacklist(0));
        }
        enterprise.setBlacklists(blacklists);
        List<ExceptionData> exceptionData = exceptionDataService.lambdaQuery().eq(ExceptionData::getcSupplierInfoId, id).eq(ExceptionData::getcEnterpriseId, enterprise.getId()).list();
        if(CollectionUtil.isNotEmpty(exceptionData)){
            exceptionData.forEach(r->r.setException(0));
        }
        enterprise.setExceptionData(exceptionData);
        List<News> news = newsService.lambdaQuery().eq(News::getcSupplierInfoId, id).eq(News::getcEnterpriseId, enterprise.getId()).list();
        if(CollectionUtil.isNotEmpty(news)){
            news.forEach(r->r.setNews(0));
        }
        enterprise.setNews(news);
        if(CollectionUtil.isEmpty(privateLendings) || CollectionUtil.isEmpty(seriousIllegalities) || CollectionUtil.isEmpty(taxOweNotices) || CollectionUtil.isEmpty(taxIllegalData)
                || CollectionUtil.isEmpty(blacklists)|| CollectionUtil.isEmpty(exceptionData)|| CollectionUtil.isEmpty(news)){
            //sop 获取企业信誉数据
            String findCorporateGoodwillUrl = findCorporateGoodwill + "?comprehensiveRiskInvestigationId=" + enterprise.getcComprehensiveRiskInvestigationId();
            ResponseJson responseJson = restTemplate.getForObject(findCorporateGoodwillUrl, ResponseJson.class);
            if(responseJson != null && responseJson.getCode().equals("200")){
                JSONObject jsonObject = new JSONObject(responseJson.getData()) ;
                JSONArray judgmentDocuments = jsonObject.getJSONArray("judgmentDocuments");
                JSONArray seriousIllegalData = jsonObject.getJSONArray("seriousIllegalData");
                JSONArray taxOweNoticeData = jsonObject.getJSONArray("taxOweNoticeData");
                JSONArray blacklistsRj = jsonObject.getJSONArray("blacklists");
                JSONArray exceptionDataRj = jsonObject.getJSONArray("exceptionData");
                JSONArray newsRj = jsonObject.getJSONArray("news");
                JSONArray taxIllegalDataRj = jsonObject.getJSONArray("taxIllegalData");
                List<PrivateLending> judgmentDocumentList = new ArrayList();
                if(CollectionUtil.isNotEmpty(judgmentDocuments)){
                    for (Object judgmentDocument : judgmentDocuments) {
                        JSONObject object = (JSONObject) judgmentDocument;
                        PrivateLending privateLending = new PrivateLending();
                        privateLending.setcSupplierInfoId(id);
                        privateLending.setcEnterpriseId(enterprise.getId());
                        privateLending.setcJudgmentDocumentsId(object.getLong("id"));
                        privateLending.setCaseName(object.getStr("caseName"));
                        privateLending.setCaseReason(object.getStr("caseReason"));
                        privateLending.setCaseNo(object.getStr("caseNo"));
                        privateLending.setAmount(object.getStr("amount"));
                        privateLending.setJudgeResult(object.getStr("judgeResult"));
                        privateLending.setJudgeDate(object.getStr("judgeDate"));
                        privateLending.setPersonName(object.getStr("name"));
                        privateLending.setPublishDate(object.getStr("publishDate"));
                        judgmentDocumentList.add(privateLending);
                    }
                }
                enterprise.setPrivateLendings(judgmentDocumentList);
                List<SeriousIllegality> seriousIllegalitieList = new ArrayList<>();
                if(CollectionUtil.isNotEmpty(seriousIllegalData)){
                    for (Object seriousIllegalDatum : seriousIllegalData) {
                        JSONObject object = (JSONObject) seriousIllegalDatum;
                        SeriousIllegality seriousIllegality = new SeriousIllegality();
                        seriousIllegality.setcSupplierInfoId(id);
                        seriousIllegality.setcEnterpriseId(enterprise.getId());
                        seriousIllegality.setcSeriousIllegalDataId(object.getLong("id"));
                        seriousIllegality.setAddDate(object.getStr("addDate"));
                        seriousIllegality.setAddOffice(object.getStr("addOffice"));
                        seriousIllegality.setAddReason(object.getStr("addReason"));
                        seriousIllegalitieList.add(seriousIllegality);
                    }
                }
                enterprise.setSeriousIllegalities(seriousIllegalitieList);
                List<TaxOweNotice> taxOweNoticeList = new ArrayList<>();
                if(CollectionUtil.isNotEmpty(taxOweNoticeData)){
                    for (Object taxOweNoticeDatum : taxOweNoticeData) {
                        JSONObject object = (JSONObject) taxOweNoticeDatum;
                        TaxOweNotice taxOweNotice = new TaxOweNotice();
                        taxOweNotice.setcSupplierInfoId(id);
                        taxOweNotice.setcEnterpriseId(enterprise.getId());
                        taxOweNotice.setcTaxOweNoticeDataId(object.getLong("id"));
                        taxOweNotice.setTitle(object.getStr("title"));
                        taxOweNotice.setAmount(object.getStr("amount"));
                        taxOweNotice.setNewAmount(object.getStr("newAmount"));
                        taxOweNotice.setPunishOffice(object.getStr("punishOffice"));
                        taxOweNotice.setPunishDate(object.getStr("punishDate"));
                        taxOweNoticeList.add(taxOweNotice);
                    }
                }
                enterprise.setTaxOweNotices(taxOweNoticeList);
                List<TaxIllegalData> taxIllegalDataList = new ArrayList<>();
                if(CollectionUtil.isNotEmpty(taxIllegalDataRj)){
                    for (Object taxIllegal : taxIllegalDataRj) {
                        JSONObject object = (JSONObject) taxIllegal;
                        TaxIllegalData taxIllegalData1 = new TaxIllegalData();
                        taxIllegalData1.setcSupplierInfoId(id);
                        taxIllegalData1.setcEnterpriseId(enterprise.getId());
                        taxIllegalData1.setcTaxIllegalDataId(object.getLong("id"));
                        taxIllegalData1.setPunishDate(object.getStr("punishDate"));
                        taxIllegalData1.setCaseNature(object.getStr("caseNature"));
                        taxIllegalData1.setTaxGov(object.getStr("taxGov"));
                        taxIllegalData1.setIllegalContent(object.getStr("illegalContent"));
                        taxIllegalData1.setPunishContent(object.getStr("punishContent"));
                        taxIllegalDataList.add(taxIllegalData1);
                    }
                }
                enterprise.setTaxIllegalData(taxIllegalDataList);
                List<Blacklist> blacklist = new ArrayList<>();
                if(CollectionUtil.isNotEmpty(blacklistsRj)){
                    for (Object black : blacklistsRj) {
                        JSONObject object = (JSONObject) black;
                        Blacklist blacks = new Blacklist();
                        blacks.setcSupplierInfoId(id);
                        blacks.setcEnterpriseId(enterprise.getId());
                        blacks.setcBlacklistId(object.getLong("id"));
                        blacks.setPunishType(object.getStr("punishType"));
                        blacks.setCaseReason(object.getStr("caseReason"));
                        blacks.setDecisionOffice(object.getStr("decisionOffice"));
                        blacks.setDecisionDate(object.getStr("decisionDate"));
                        blacks.setRemovedDate(object.getStr("removedDate"));
                        blacklist.add(blacks);
                    }
                }
                enterprise.setBlacklists(blacklist);
                List<ExceptionData> exceptionDataList = new ArrayList<>();
                if(CollectionUtil.isNotEmpty(exceptionDataRj)){
                    for (Object exception : exceptionDataRj) {
                        JSONObject object = (JSONObject) exception;
                        ExceptionData exceptionData1 = new ExceptionData();
                        exceptionData1.setcSupplierInfoId(id);
                        exceptionData1.setcEnterpriseId(enterprise.getId());
                        exceptionData1.setcExceptionDataId(object.getLong("id"));
                        exceptionData1.setAddDate(object.getStr("addDate"));
                        exceptionData1.setAddOffice(object.getStr("addOffice"));
                        exceptionData1.setAddReason(object.getStr("addReason"));
                        exceptionDataList.add(exceptionData1);
                    }
                }
                enterprise.setExceptionData(exceptionDataList);
                List<News> newsList = new ArrayList<>();
                if(CollectionUtil.isNotEmpty(newsRj)){
                    for (Object newsObj : newsRj) {
                        JSONObject object = (JSONObject) newsObj;
                        News newsData = new News();
                        newsData.setcSupplierInfoId(id);
                        newsData.setcEnterpriseId(enterprise.getId());
                        newsData.setcNewsId(object.getLong("id"));
                        newsData.setTitle(object.getStr("title"));
                        newsData.setPublishTime(object.getStr("publishTime"));
                        newsList.add(newsData);
                    }
                }
                enterprise.setNews(newsList);
            }
        }
    }

    @Override
    public SupplierInfo getView(Long id) {
        SupplierApprovalFirst supplierApprovalFirst = getById(id);
        SupplierInfo supplierInfo = supplierInfoService.get(supplierApprovalFirst.getcSupplierInfoId());
        DueDiligenceAllocation dueDiligenceAllocation = dueDiligenceAllocationService.lambdaQuery().eq(DueDiligenceAllocation::getcSupplierInfoId, supplierInfo.getId()).one();
        User user = userService.get(dueDiligenceAllocation.getRiskManagerId());
        dueDiligenceAllocation.setRiskManager(user);
        supplierInfo.setDueDiligenceAllocation(dueDiligenceAllocation);
        CSupplierInfoHistory supplierInfoHistory = supplierInfoHistoryService.getById(supplierApprovalFirst.getcSupplierInfoHistoryId());
        supplierInfo.setSupplierApprovalFirst(supplierApprovalFirst);
        CEnterpriseHistory enterpriseHistory = enterpriseHistoryService.getById(supplierInfoHistory.getcEnterpriseHistoryId());
        Enterprise enterprise = enterpriseService.getById(supplierInfo.getcEnterpriseId());
        autoView(supplierInfo.getId(),enterprise,enterpriseHistory);
        supplierInfo.setEnterprise(enterprise);
        supplierInfo.setHasGuaranteeEnterprise(false);
        if(supplierInfo.getGuaranteeEnterpriseId() != null){
            supplierInfo.setHasGuaranteeEnterprise(true);
            CEnterpriseHistory guaranteeHistory = enterpriseHistoryService.getById(supplierInfoHistory.getGuaranteeEnterpriseHistoryId());
            Enterprise guarantee = enterpriseService.getById(supplierInfo.getGuaranteeEnterpriseId());
            autoView(supplierInfo.getId(),guarantee,guaranteeHistory);
            supplierInfo.setGuaranteeEnterprise(guarantee);
        }
        return supplierInfo;
    }

    @Override
    public SupplierApprovalFirst measurement(SupplierInfo supplierInfo) {
        SupplierApprovalFirst supplierApprovalFirst = new SupplierApprovalFirst();
        supplierApprovalFirst.setcSupplierInfoId(supplierInfo.getId());
        supplierApprovalFirst.setcSupplierInfoHistoryId(supplierInfo.getHistoryId());
        //企业审核信息
        Enterprise enterprise = supplierInfo.getEnterprise();
        measurementCount(enterprise,supplierApprovalFirst,true);
        //担保企业审核信息
        Enterprise guaranteeEnterprise = supplierInfo.getGuaranteeEnterprise();
        if(guaranteeEnterprise != null){
            measurementCount(guaranteeEnterprise,supplierApprovalFirst,false);
        }
        return supplierApprovalFirst;
    }

    private void measurementCount(Enterprise enterprise, SupplierApprovalFirst supplierApprovalFirst, boolean flag) {
        long count = 0L;
        List<CreditSituation> creditSituations = enterprise.getCreditSituations();
        if(CollectionUtil.isNotEmpty(creditSituations)){
            for (CreditSituation creditSituation : creditSituations) {
                creditSituation.setcSupplierInfoId(supplierApprovalFirst.getcSupplierInfoId());
                creditSituationService.lambdaUpdate()
                        .eq(CreditSituation::getcCreditInvestigationInfoHistoryId,creditSituation.getcCreditInvestigationInfoHistoryId())
                        .eq(CreditSituation::getcSupplierInfoId,supplierApprovalFirst.getcSupplierInfoId()).remove();
                creditSituationService.save(creditSituation);
                if(creditSituation.getNumberOfOverdueAccounts() > 0){
                    count ++;
                }
                if(creditSituation.getTotalOverdueAmount().compareTo(BigDecimal.ZERO) == 1){
                    count ++;
                }
                if(creditSituation.getOverdue().equals(1)){
                    count ++;
                }
                if(creditSituation.getConsecutiveOverdueMonth() > 0){
                    count ++;
                }
                if(creditSituation.getAccumulatedOverdueTimes() > 0){
                    count ++;
                }
                if(creditSituation.getBadRecords().equals(1)){
                    count ++;
                }
            }
        }
        CorporateGoodwill corporateGoodwill = enterprise.getCorporateGoodwill();
        corporateGoodwill.setcEnterpriseId(enterprise.getId());
        corporateGoodwill.setcSupplierInfoId(supplierApprovalFirst.getcSupplierInfoId());
        if(corporateGoodwill.getRecoveredBalance().equals(1)){
            count ++;
        }
        if(corporateGoodwill.getConcernedAccountsWithOutstandingCredit().equals(1)){
            count ++;
        }
        if(corporateGoodwill.getOutstandingNonPerformingAccounts().equals(1)){
            count ++;
        }
        corporateGoodwillService.lambdaUpdate().eq(CorporateGoodwill::getcSupplierInfoId,supplierApprovalFirst.getcSupplierInfoId())
                        .eq(CorporateGoodwill::getcEnterpriseId,enterprise.getId()).remove();
        corporateGoodwillService.save(corporateGoodwill);
        privateLendingService.lambdaUpdate().eq(PrivateLending::getcSupplierInfoId,supplierApprovalFirst.getcSupplierInfoId())
                .eq(PrivateLending::getcEnterpriseId,enterprise.getId()).remove();
        List<PrivateLending> privateLendings = enterprise.getPrivateLendings();
        if(CollectionUtil.isNotEmpty(privateLendings)){
            for (PrivateLending privateLending : privateLendings) {
                privateLending.setcSupplierInfoId(supplierApprovalFirst.getcSupplierInfoId());
                privateLending.setcEnterpriseId(enterprise.getId());
                privateLendingService.save(privateLending);
                if(privateLending.getPrivateLending().equals(1)){
                    count ++;
                }
            }
        }
        seriousIllegalityService.lambdaUpdate().eq(SeriousIllegality::getcSupplierInfoId,supplierApprovalFirst.getcSupplierInfoId())
                .eq(SeriousIllegality::getcEnterpriseId,enterprise.getId()).remove();
        List<SeriousIllegality> seriousIllegalities = enterprise.getSeriousIllegalities();
        if(CollectionUtil.isNotEmpty(seriousIllegalities)){
            for (SeriousIllegality seriousIllegality : seriousIllegalities) {
                seriousIllegality.setcSupplierInfoId(supplierApprovalFirst.getcSupplierInfoId());
                seriousIllegality.setcEnterpriseId(enterprise.getId());
                seriousIllegalityService.save(seriousIllegality);
                if(seriousIllegality.getSeriousIllegality().equals(1)){
                    count ++;
                }
            }
        }
        taxOweNoticeService.lambdaUpdate().eq(TaxOweNotice::getcSupplierInfoId,supplierApprovalFirst.getcSupplierInfoId())
                .eq(TaxOweNotice::getcEnterpriseId,enterprise.getId()).remove();
        List<TaxOweNotice> taxOweNotices = enterprise.getTaxOweNotices();
        if(CollectionUtil.isNotEmpty(taxOweNotices)){
            for (TaxOweNotice taxOweNotice : taxOweNotices) {
                taxOweNotice.setcSupplierInfoId(supplierApprovalFirst.getcSupplierInfoId());
                taxOweNotice.setcEnterpriseId(enterprise.getId());
                taxOweNoticeService.save(taxOweNotice);
                if(taxOweNotice.getTaxOweNotice().equals(1)){
                    count ++;
                }
            }
        }
        taxIllegalDataService.lambdaUpdate().eq(TaxIllegalData::getcSupplierInfoId,supplierApprovalFirst.getcSupplierInfoId())
                .eq(TaxIllegalData::getcEnterpriseId,enterprise.getId()).remove();
        List<TaxIllegalData> taxIllegalData = enterprise.getTaxIllegalData();
        if(CollectionUtil.isNotEmpty(taxIllegalData)){
            for (TaxIllegalData taxIllegalDatum : taxIllegalData) {
                taxIllegalDatum.setcSupplierInfoId(supplierApprovalFirst.getcSupplierInfoId());
                taxIllegalDatum.setcEnterpriseId(enterprise.getId());
                taxIllegalDataService.save(taxIllegalDatum);
                if(taxIllegalDatum.getTaxIllegal().equals(1)){
                    count ++;
                }
            }
        }
        blacklistService.lambdaUpdate().eq(Blacklist::getcSupplierInfoId,supplierApprovalFirst.getcSupplierInfoId())
                .eq(Blacklist::getcEnterpriseId,enterprise.getId()).remove();
        List<Blacklist> blacklists = enterprise.getBlacklists();
        if(CollectionUtil.isNotEmpty(blacklists)){
            for (Blacklist blacklist : blacklists) {
                blacklist.setcSupplierInfoId(supplierApprovalFirst.getcSupplierInfoId());
                blacklist.setcEnterpriseId(enterprise.getId());
                blacklistService.save(blacklist);
                if(blacklist.getBlacklist().equals(1)){
                    count ++;
                }
            }
        }
        exceptionDataService.lambdaUpdate().eq(ExceptionData::getcSupplierInfoId,supplierApprovalFirst.getcSupplierInfoId())
                .eq(ExceptionData::getcEnterpriseId,enterprise.getId()).remove();
        List<ExceptionData> exceptionData = enterprise.getExceptionData();
        if(CollectionUtil.isNotEmpty(exceptionData)){
            for (ExceptionData exceptionDatum : exceptionData) {
                exceptionDatum.setcSupplierInfoId(supplierApprovalFirst.getcSupplierInfoId());
                exceptionDatum.setcEnterpriseId(enterprise.getId());
                exceptionDataService.save(exceptionDatum);
                if(exceptionDatum.getException().equals(1)){
                    count ++;
                }
            }
        }
        newsService.lambdaUpdate().eq(News::getcSupplierInfoId,supplierApprovalFirst.getcSupplierInfoId())
                .eq(News::getcEnterpriseId,enterprise.getId()).remove();
        List<News> news = enterprise.getNews();
        if(CollectionUtil.isNotEmpty(news)){
            for (News news1 : news) {
                news1.setcSupplierInfoId(supplierApprovalFirst.getcSupplierInfoId());
                news1.setcEnterpriseId(enterprise.getId());
                newsService.save(news1);
                if(news1.getNews().equals(1)){
                    count ++;
                }
            }
        }
        if(flag){
            supplierApprovalFirst.setMainEnterpriseCount(count);
            if(count > 0 ){
                supplierApprovalFirst.setMainEnterpriseResult("未通过");
            }else {
                supplierApprovalFirst.setMainEnterpriseResult("通过");
            }
        }else {
            supplierApprovalFirst.setGuaranteeEnterpriseCount(count);
            if(count > 0 ){
                supplierApprovalFirst.setGuaranteeEnterpriseResult("未通过");
            }else {
                supplierApprovalFirst.setGuaranteeEnterpriseResult("通过");
            }
        }
    }

    private void autoView(Long id, Enterprise enterprise,CEnterpriseHistory enterpriseHistory) {
        //企业负责人征信情况
        List<CreditSituation> creditSituations = creditSituationService.lambdaQuery().eq(CreditSituation::getcSupplierInfoId, id).list();
        List<CreditSituation> creditSituationsResult = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(creditSituations)){
            for (CreditSituation creditSituation : creditSituations) {
                CCreditInvestigationInfoHistory creditInvestigationInfoHistory = creditInvestigationInfoHistoryService.getById(creditSituation.getcCreditInvestigationInfoHistoryId());
                List<FileStorage> list = new ArrayList<>();
                if(creditInvestigationInfoHistory.getcEnterpriseHistoryId().equals(enterpriseHistory.getId())){
                    //todo 填充征信报告
                    CreditInfo creditInfo = creditService.lambdaQuery().eq(CreditInfo::getCardNo, creditInvestigationInfoHistory.getSocialCreditCode()).one();
                    if(creditInfo != null){
                        List<CreditDetail> creditDetails = creditDetailService.lambdaQuery()
                                .eq(CreditDetail::getCreditId,creditInfo.getId())
                                .isNotNull(CreditDetail::getCreditAddress)
                                .orderByDesc(CreditDetail::getGmtCreate).list();
                        if(CollectionUtil.isNotEmpty(creditDetails)){
                            CreditDetail creditDetail = creditDetails.get(0);
                            if(StringUtil.isNotEmpty(creditDetail.getCreditAddress())){
                                FileStorage creditDetailFiles = fileStorageService.get(Long.valueOf(creditDetail.getCreditAddress()));
                                list.add(creditDetailFiles);
                            }
                        }
                    }
                    creditInvestigationInfoHistory.setCreditDetailFiles(list);
                    List<FileStorageDO> cardFiles = fileService.findByBusinessId(creditInvestigationInfoHistory.getId(), FileModuleDict.ChildEnum.ENTERPRISE_IDCARD_FILES_HISTORY.getCode());
                    creditInvestigationInfoHistory.setTypeStr(dictionaryService.getByCode(creditInvestigationInfoHistory.getType()).getName());
                    creditInvestigationInfoHistory.setCardFiles(cardFiles);
                    creditSituation.setCreditInvestigationInfoHistory(creditInvestigationInfoHistory);
                    creditSituationsResult.add(creditSituation);
                }
            }
        }
        enterprise.setCreditSituations(creditSituationsResult);
        //企业信誉
        CorporateGoodwill corporateGoodwill = corporateGoodwillService.lambdaQuery().eq(CorporateGoodwill::getcSupplierInfoId, id).eq(CorporateGoodwill::getcEnterpriseId, enterprise.getId()).one();
        //todo 填充征信报告
        CreditInfo creditInfo = creditService.lambdaQuery().eq(CreditInfo::getCardNo, enterprise.getSocialCreditCode()).one();
        List<FileStorage> list = new ArrayList<>();
        if(creditInfo != null){
            List<CreditDetail> creditDetails = creditDetailService.lambdaQuery()
                    .eq(CreditDetail::getCreditId,creditInfo.getId())
                    .isNotNull(CreditDetail::getCreditAddress)
                    .orderByDesc(CreditDetail::getGmtCreate).list();
            if(CollectionUtil.isNotEmpty(creditDetails)){
                CreditDetail creditDetail = creditDetails.get(0);
                if(StringUtil.isNotEmpty(creditDetail.getCreditAddress())){
                    FileStorage creditDetailFiles = fileStorageService.get(Long.valueOf(creditDetail.getCreditAddress()));
                    list.add(creditDetailFiles);
                }
            }
        }
        corporateGoodwill.setCreditDetailFiles(list);
        enterprise.setCorporateGoodwill(corporateGoodwill);
        List<PrivateLending> privateLendings = privateLendingService.lambdaQuery().eq(PrivateLending::getcSupplierInfoId, id).eq(PrivateLending::getcEnterpriseId, enterprise.getId()).list();
        enterprise.setPrivateLendings(privateLendings);
        List<SeriousIllegality> seriousIllegalities = seriousIllegalityService.lambdaQuery().eq(SeriousIllegality::getcSupplierInfoId, id).eq(SeriousIllegality::getcEnterpriseId, enterprise.getId()).list();
        enterprise.setSeriousIllegalities(seriousIllegalities);
        List<TaxOweNotice> taxOweNotices = taxOweNoticeService.lambdaQuery().eq(TaxOweNotice::getcSupplierInfoId, id).eq(TaxOweNotice::getcEnterpriseId, enterprise.getId()).list();
        enterprise.setTaxOweNotices(taxOweNotices);
        List<TaxIllegalData> taxIllegalData = taxIllegalDataService.lambdaQuery().eq(TaxIllegalData::getcSupplierInfoId, id).eq(TaxIllegalData::getcEnterpriseId, enterprise.getId()).list();
        enterprise.setTaxIllegalData(taxIllegalData);
        List<Blacklist> blacklists = blacklistService.lambdaQuery().eq(Blacklist::getcSupplierInfoId, id).eq(Blacklist::getcEnterpriseId, enterprise.getId()).list();
        enterprise.setBlacklists(blacklists);
        List<ExceptionData> exceptionData = exceptionDataService.lambdaQuery().eq(ExceptionData::getcSupplierInfoId, id).eq(ExceptionData::getcEnterpriseId, enterprise.getId()).list();
        enterprise.setExceptionData(exceptionData);
        List<News> news = newsService.lambdaQuery().eq(News::getcSupplierInfoId, id).eq(News::getcEnterpriseId, enterprise.getId()).list();
        enterprise.setNews(news);
    }

}
