package com.ruoyi.credit.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.credit.domain.LoanConsistencyValidation;
import com.ruoyi.credit.domain.ServicePeriodLoan;
import com.ruoyi.credit.mapper.LoanConsistencyMapper;
import com.ruoyi.credit.mapper.ServicePeriodLoanMapper;
import com.ruoyi.credit.monitor.ValidationPerformanceMonitor;
import com.ruoyi.credit.service.AsyncNotificationProcessor;
import com.ruoyi.credit.service.IFinancingService;
import com.ruoyi.credit.service.ILoanConsistencyService;
import com.ruoyi.credit.service.IValidationLogService;
import com.ruoyi.credit.service.IValidationStatisticsService;
import com.ruoyi.credit.service.LoanValidationNotificationService;
import com.ruoyi.credit.service.ValidationCacheManager;
import com.ruoyi.credit.service.ValidationContext;
import com.ruoyi.credit.service.ValidationResult;
import com.ruoyi.credit.service.ValidationRuleEngine;
import com.ruoyi.credit.strategy.PerformanceDegradationStrategy;

/**
 * 贷款一致性验证服务实现类
 *
 * @author ruoyi
 * @date 2025-12-31
 */
@Service
public class LoanConsistencyServiceImpl implements ILoanConsistencyService {

    private static final Logger log = LoggerFactory.getLogger(LoanConsistencyServiceImpl.class);

    @Autowired
    private LoanConsistencyMapper loanConsistencyMapper;

    @Autowired
    private ValidationRuleEngine validationRuleEngine;

    @Autowired
    private LoanValidationNotificationService loanValidationNotificationService;

    @Autowired
    private IFinancingService financingService;

    @Autowired
    private ServicePeriodLoanMapper servicePeriodLoanMapper;

    @Autowired
    private AsyncNotificationProcessor asyncNotificationProcessor;

    @Autowired
    private ValidationCacheManager validationCacheManager;

    @Autowired
    private ValidationPerformanceMonitor performanceMonitor;

    @Autowired
    private PerformanceDegradationStrategy degradationStrategy;

    @Autowired
    private IValidationLogService validationLogService;

    @Autowired
    private IValidationStatisticsService validationStatisticsService;

    /**
     * 异步验证线程池
     */
    private final ExecutorService validationExecutor = Executors.newFixedThreadPool(10);

    /**
     * 验证超时时间（毫秒）
     */
    private static final long VALIDATION_TIMEOUT = 30000L; // 30秒

    /**
     * 批量验证大小
     */
    private static final int BATCH_SIZE = 100;

    @Override
    public List<Long> getValidatedLoanList(Map<String, Object> queryParams) {
        log.info("开始获取通过验证的贷款列表，查询参数: {}", queryParams);

        try {
            // 检查是否需要触发后台验证
            boolean forceValidation = queryParams != null
                    && Boolean.TRUE.equals(queryParams.get("forceValidation"));

            if (forceValidation) {
                log.info("强制触发后台验证");
                validateAllLoansInBackground();
            }

            // 直接查询通过验证的贷款ID列表
            List<Long> validatedLoanIds = loanConsistencyMapper.selectPassedLoanIds();

            log.info("获取到通过验证的贷款数量: {}", validatedLoanIds.size());
            return validatedLoanIds;

        } catch (Exception e) {
            log.error("获取通过验证的贷款列表失败", e);
            return new ArrayList<>();
        }
    }

    @Override
    public List<Map<String, Object>> getValidatedLoanDetailsList(Map<String, Object> queryParams) {
        log.info("开始获取通过验证的贷款详细信息列表，查询参数: {}", queryParams);

        try {
            // 检查是否需要触发后台验证
            boolean forceValidation = queryParams != null
                    && Boolean.TRUE.equals(queryParams.get("forceValidation"));

            if (forceValidation) {
                log.info("强制触发后台验证");
                validateAllLoansInBackground();
            }

            // 查询通过验证的贷款详细信息列表
            List<Map<String, Object>> validatedLoanDetails = loanConsistencyMapper.selectPassedLoanDetails();

            log.info("获取到通过验证的贷款详细信息数量: {}", validatedLoanDetails.size());
            return validatedLoanDetails;

        } catch (Exception e) {
            log.error("获取通过验证的贷款详细信息列表失败", e);
            return new ArrayList<>();
        }
    }

    @Override
    @Transactional
    public LoanConsistencyValidation revalidateLoan(Long loanId) {
        log.info("开始重新验证贷款记录，贷款ID: {}", loanId);

        if (loanId == null) {
            throw new IllegalArgumentException("贷款ID不能为空");
        }

        try {
            // 首先失效缓存
            validationCacheManager.invalidateCache(loanId);
            log.debug("已失效贷款{}的验证缓存", loanId);

            // 使用重新验证触发机制
            return triggerRevalidation(loanId, "手动重新验证请求");

        } catch (Exception e) {
            log.error("重新验证贷款记录失败，贷款ID: {}", loanId, e);

            // 创建错误验证记录
            LoanConsistencyValidation errorValidation = createErrorValidation(loanId, "重新验证失败: " + e.getMessage());
            loanConsistencyMapper.insertLoanConsistencyValidation(errorValidation);

            return errorValidation;
        }
    }

    @Override
    public Map<String, Object> validateAllLoansInBackground() {
        log.info("开始后台批量验证所有贷款记录");

        Map<String, Object> result = new HashMap<>();

        try {
            // 获取所有服务周期内贷款申请的并且携带有债权凭证的贷款ID列表
            List<Long> loansNeedValidation = loanConsistencyMapper.selectLoansWithCreditCertificates();
            
            log.info("查询到的需要验证的贷款ID列表: {}", loansNeedValidation);

            if (CollectionUtils.isEmpty(loansNeedValidation)) {
                log.info("没有需要验证的贷款记录");
                
                // 添加调试信息
                Map<String, Object> debugInfo = new HashMap<>();
                debugInfo.put("totalLoans", loanConsistencyMapper.countAllLoans());
                debugInfo.put("totalCredits", loanConsistencyMapper.countAllCredits());
                debugInfo.put("totalServicePeriods", loanConsistencyMapper.countAllServicePeriods());
                debugInfo.put("totalContracts", loanConsistencyMapper.countAllContracts());
                
                result.put("totalCount", 0);
                result.put("successCount", 0);
                result.put("failureCount", 0);
                result.put("message", "没有需要验证的贷款记录");
                result.put("debugInfo", debugInfo);
                
                log.info("调试信息: {}", debugInfo);
                return result;
            }

            log.info("找到需要验证的贷款数量: {}", loansNeedValidation.size());

            // 同步批量验证，确保验证结果正确保存
            List<LoanConsistencyValidation> validationResults = batchValidateLoans(loansNeedValidation);

            // 统计结果
            long successCount = validationResults.stream()
                    .filter(v -> LoanConsistencyValidation.STATUS_PASS.equals(v.getValidationStatus()))
                    .count();

            long failureCount = validationResults.stream()
                    .filter(v -> LoanConsistencyValidation.STATUS_FAIL.equals(v.getValidationStatus())
                    || LoanConsistencyValidation.STATUS_ERROR.equals(v.getValidationStatus()))
                    .count();

            result.put("totalCount", validationResults.size());
            result.put("successCount", successCount);
            result.put("failureCount", failureCount);
            result.put("message", "后台批量验证完成");
            result.put("validatedLoanIds", loansNeedValidation);

            log.info("后台批量验证完成，总数: {}, 成功: {}, 失败: {}",
                    validationResults.size(), successCount, failureCount);

            // 强制刷新缓存，确保查询接口能获取到最新数据
            if (!validationResults.isEmpty()) {
                validationCacheManager.preloadValidationCache(validationResults);
            }

            return result;

        } catch (Exception e) {
            log.error("后台批量验证失败", e);
            result.put("totalCount", 0);
            result.put("successCount", 0);
            result.put("failureCount", 0);
            result.put("error", "后台批量验证失败: " + e.getMessage());
            result.put("exception", e.getClass().getSimpleName());
            return result;
        }
    }

    @Override
    @Transactional
    public LoanConsistencyValidation validateLoanConsistency(Long loanId, Long creditId, Long servicePeriodId) {
        log.debug("开始验证贷款一致性，贷款ID: {}, 债权凭证ID: {}, 服务周期ID: {}",
                loanId, creditId, servicePeriodId);

        if (loanId == null) {
            throw new IllegalArgumentException("贷款ID不能为空");
        }

        String currentUser = getCurrentUser();
        String clientIp = getClientIp();
        Long validationId = null;

        // 从数据库获取贷款相关信息（包括合同ID、债权凭证ID、服务周期ID）
        Long contractId = null;
        try {
            Map<String, Object> loanInfo = loanConsistencyMapper.selectLoanCreditInfo(loanId);
            if (loanInfo != null) {
                if (creditId == null) {
                    creditId = (Long) loanInfo.get("creditId");
                }
                if (servicePeriodId == null) {
                    servicePeriodId = (Long) loanInfo.get("servicePeriodId");
                }
                // 总是获取合同ID，因为方法参数中没有传入contractId
                contractId = (Long) loanInfo.get("contractId");

                log.debug("从数据库获取贷款相关信息，贷款ID: {}, 债权凭证ID: {}, 服务周期ID: {}, 合同ID: {}",
                        loanId, creditId, servicePeriodId, contractId);
            }
        } catch (Exception e) {
            log.warn("获取贷款相关信息失败，贷款ID: {}", loanId, e);
        }

        // 记录验证开始日志
        validationLogService.logValidationStart(loanId, validationId, currentUser, clientIp);

        // 开始性能监控
        ValidationPerformanceMonitor.PerformanceContext perfContext
                = performanceMonitor.startValidationMonitoring(loanId, "LOAN_CONSISTENCY_VALIDATION");

        // 检查并应用性能降级策略
        PerformanceDegradationStrategy.DegradationConfig degradationConfig
                = degradationStrategy.checkAndApplyDegradation(loanId);

        try {
            // 首先检查缓存（如果降级策略要求使用缓存）
            if (degradationConfig.isUseCachedResults()) {
                long cacheStartTime = System.currentTimeMillis();
                LoanConsistencyValidation cachedResult = validationCacheManager.getCachedValidationResult(loanId);
                long cacheDuration = System.currentTimeMillis() - cacheStartTime;

                if (cachedResult != null) {
                    log.debug("从缓存获取到贷款{}的验证结果，状态: {}", loanId, cachedResult.getValidationStatus());

                    // 记录缓存操作日志
                    validationLogService.logCacheOperation(loanId, "CACHE_HIT",
                            "从缓存获取验证结果", "状态: " + cachedResult.getValidationStatus(), currentUser);

                    // 记录验证步骤日志
                    validationLogService.logValidationStep(loanId, cachedResult.getValidationId(),
                            "CACHE_LOOKUP", "缓存查询成功", "缓存命中，直接返回结果", cacheDuration, currentUser);

                    // 刷新缓存过期时间
                    validationCacheManager.refreshCacheExpire(loanId);

                    // 结束性能监控
                    performanceMonitor.endValidationMonitoring(perfContext, cachedResult.isPassed());
                    return cachedResult;
                } else {
                    // 记录缓存未命中日志
                    validationLogService.logCacheOperation(loanId, "CACHE_MISS",
                            "缓存查询未命中", "需要执行完整验证", currentUser);
                }

                // 如果是极度降级且缓存优先策略失败，直接返回错误
                if (degradationConfig.isCacheOnlyMode()) {
                    log.warn("极度降级模式下缓存未命中，返回降级结果，贷款ID: {}", loanId);
                    LoanConsistencyValidation degradedResult = createDegradedValidation(loanId, "系统高负载，仅支持缓存查询");

                    // 记录降级日志
                    validationLogService.logValidationFailure(loanId, null, "验证降级",
                            "系统高负载，仅支持缓存查询", System.currentTimeMillis() - perfContext.getStartTime(), currentUser);

                    performanceMonitor.endValidationMonitoring(perfContext, false);
                    return degradedResult;
                }
            }

            long startTime = System.currentTimeMillis();

            // 创建验证上下文，应用降级配置
            ValidationContext context = new ValidationContext(loanId, creditId, servicePeriodId)
                    .setUser(SecurityUtils.getUserId(), currentUser)
                    .setTimeout(degradationConfig.getValidationTimeout())
                    .setDegradationConfig(degradationConfig);

            // 设置合同ID到验证上下文中
            if (contractId != null) {
                context.setContractId(contractId);
                log.debug("设置合同ID到验证上下文，贷款ID: {}, 合同ID: {}", loanId, contractId);
            }

            LoanConsistencyValidation validation = new LoanConsistencyValidation();
            validation.setLoanId(loanId);
            validation.setContractId(contractId);
            validation.setCreditId(creditId);
            validation.setServicePeriodId(servicePeriodId);
            validation.setValidationTime(DateUtils.getNowDate());
            validation.setValidatedBy(currentUser);
            validation.setValidationStatus(LoanConsistencyValidation.STATUS_PENDING);

            // 保存验证记录并获取ID
            loanConsistencyMapper.insertLoanConsistencyValidation(validation);
            validationId = validation.getValidationId();

            // 如果没有债权凭证信息，尝试自动查找
            if (creditId == null) {
                log.info("贷款ID: {} 没有提供债权凭证ID，尝试自动查找", loanId);
                
                // 尝试通过贷款ID查找关联的债权凭证ID
                creditId = findCreditIdByLoanId(loanId);
                if (creditId != null) {
                    log.info("通过贷款ID {} 自动找到债权凭证ID: {}", loanId, creditId);
                    context.setCreditId(creditId);
                    validation.setCreditId(creditId);
                } else {
                    log.warn("贷款ID: {} 无法找到对应的债权凭证信息，创建简化验证结果", loanId);
                }
            }
            
            // 如果没有服务周期信息，尝试自动查找
            if (servicePeriodId == null) {
                log.info("贷款ID: {} 没有提供服务周期ID，尝试自动查找", loanId);
                
                // 尝试通过贷款ID查找关联的服务周期ID
                servicePeriodId = findServicePeriodIdByLoanId(loanId);
                if (servicePeriodId != null) {
                    log.info("通过贷款ID {} 自动找到服务周期ID: {}", loanId, servicePeriodId);
                    context.setServicePeriodId(servicePeriodId);
                    validation.setServicePeriodId(servicePeriodId);
                } else {
                    log.warn("贷款ID: {} 无法找到对应的服务周期信息", loanId);
                }
            }
            
            // 如果仍然没有债权凭证信息，创建一个简化的验证结果
            if (creditId == null) {
                log.warn("贷款ID: {} 最终仍无法找到债权凭证信息，创建简化验证结果", loanId);
                validation.setValidationStatus(LoanConsistencyValidation.STATUS_FAIL);
                validation.setFailureReason("未找到对应的债权凭证信息");
                validation.setValidationResult("验证失败: 缺少债权凭证信息");
                validation.setValidationScore(0);
            } else {
                // 执行综合验证 - 将所有验证步骤合并为一个
                long stepStartTime = System.currentTimeMillis();
                ValidationResult comprehensiveResult = executeComprehensiveValidation(context);
                long stepDuration = System.currentTimeMillis() - stepStartTime;

                // 记录验证步骤日志
                validationLogService.logValidationStep(loanId, validationId, "COMPREHENSIVE_VALIDATION",
                        "综合验证",
                        "债权凭证ID: " + creditId + ", 服务周期ID: " + servicePeriodId + ", 验证结果: " + comprehensiveResult.isSuccess(),
                        stepDuration, currentUser);

                if (comprehensiveResult.isSuccess()) {
                    validation.setValidationStatus(LoanConsistencyValidation.STATUS_PASS);
                    validation.setValidationResult("验证通过");
                    validation.setValidationScore(100);

                    // 记录验证成功日志
                    long totalDuration = System.currentTimeMillis() - startTime;
                    validationLogService.logValidationSuccess(loanId, validationId, "验证通过",
                            "综合验证通过", totalDuration, currentUser);

                    // 验证通过后自动创建融资申请
                    if (creditId != null) {
                        try {
                            log.info("开始检查债权{}是否可以创建融资申请", creditId);
                            // 检查是否可以创建新的融资申请（使用新的智能检查逻辑）
                            Map<String, Object> eligibilityResult
                                    = financingService.checkCreditEligibilityForNewApplication(creditId);

                            log.info("债权{}资格检查结果: {}", creditId, eligibilityResult);
                            boolean eligible = (Boolean) eligibilityResult.get("eligible");
                            String reason = (String) eligibilityResult.get("reason");
                            log.info("债权{}是否符合条件: {}, 原因: {}", creditId, eligible, reason);

                            if (eligible) {
                                // 获取完整的服务周期贷款信息来确定申请金额和其他详细信息
                                Map<String, Object> completeLoanInfo = loanConsistencyMapper.selectCompleteServicePeriodLoanInfo(loanId);

                                if (completeLoanInfo == null) {
                                    log.warn("贷款{}没有找到完整的服务周期贷款信息，跳过创建融资申请", loanId);

                                    // 在验证结果中记录缺少完整信息的情况
                                    String originalResult = validation.getValidationResult();
                                    validation.setValidationResult(originalResult + " | 融资申请创建失败: 缺少完整的服务周期贷款信息");
                                } else {
                                    // 从完整信息中提取贷款金额
                                    Object loanAmountObj = completeLoanInfo.get("loanAmount");
                                    java.math.BigDecimal requestAmount = java.math.BigDecimal.ZERO;

                                    if (loanAmountObj != null) {
                                        if (loanAmountObj instanceof java.math.BigDecimal) {
                                            requestAmount = (java.math.BigDecimal) loanAmountObj;
                                        } else {
                                            requestAmount = new java.math.BigDecimal(loanAmountObj.toString());
                                        }
                                    }

                                    // 如果没有贷款金额信息，报错提示
                                    if (requestAmount.compareTo(java.math.BigDecimal.ZERO) <= 0) {
                                        log.warn("贷款{}没有有效的贷款金额信息，跳过创建融资申请", loanId);

                                        // 在验证结果中记录缺少贷款金额的信息
                                        String originalResult = validation.getValidationResult();
                                        validation.setValidationResult(originalResult + " | 融资申请创建失败: 缺少有效的贷款金额信息");
                                    } else {
                                        // 获取ServicePeriodLoan对象来创建融资申请
                                        ServicePeriodLoan servicePeriodLoan = servicePeriodLoanMapper.selectServicePeriodLoanByLinkId(loanId);
                                        if (servicePeriodLoan != null) {
                                            // 使用自动创建方法 - 转换为具体实现类来调用
                                            FinancingServiceImpl financingServiceImpl = (FinancingServiceImpl) financingService;
                                            Map<String, Object> financingResult = financingServiceImpl.createFinancingApplicationFromLoan(servicePeriodLoan);

                                            if ((Boolean) financingResult.get("success")) {
                                                log.info("验证通过后自动创建融资申请成功: loanId={}, creditId={}, financingId={}",
                                                        loanId, creditId, financingResult.get("financingId"));

                                                // 在验证结果中记录融资申请创建信息
                                                String originalResult = validation.getValidationResult();
                                                validation.setValidationResult(originalResult + " | 已自动创建融资申请: "
                                                        + financingResult.get("applicationNumber"));
                                            } else {
                                                log.warn("验证通过后创建融资申请失败: loanId={}, creditId={}, reason={}",
                                                        loanId, creditId, financingResult.get("message"));

                                                // 在验证结果中记录创建失败信息
                                                String originalResult = validation.getValidationResult();
                                                validation.setValidationResult(originalResult + " | 融资申请创建失败: "
                                                        + financingResult.get("message"));
                                            }
                                        } else {
                                            log.warn("验证通过后创建融资申请失败: 未找到服务周期贷款对象, loanId={}", loanId);

                                            // 在验证结果中记录创建失败信息
                                            String originalResult = validation.getValidationResult();
                                            validation.setValidationResult(originalResult + " | 融资申请创建失败: 未找到服务周期贷款对象");
                                        }
                                    }
                                }
                            } else {
                                log.debug("债权{}不符合创建新融资申请的条件: {}", creditId, eligibilityResult.get("reason"));

                                // 在验证结果中记录不符合条件的原因
                                String originalResult = validation.getValidationResult();
                                validation.setValidationResult(originalResult + " | 融资申请创建跳过: "
                                        + eligibilityResult.get("reason"));
                            }
                        } catch (Exception e) {
                            log.error("验证通过后创建融资申请异常: loanId={}, creditId={}", loanId, creditId, e);

                            // 记录创建融资申请失败的信息，但不影响验证结果
                            String originalResult = validation.getValidationResult();
                            validation.setValidationResult(originalResult + " | 融资申请创建失败: " + e.getMessage());
                        }
                    } else {
                        log.debug("贷款{}没有债权ID，跳过创建融资申请", loanId);
                    }

                } else {
                    validation.setValidationStatus(LoanConsistencyValidation.STATUS_FAIL);
                    validation.setFailureReason(comprehensiveResult.getMessage());
                    validation.setValidationResult("验证失败: " + comprehensiveResult.getMessage());
                    validation.setValidationScore(0);

                    // 记录验证失败日志
                    long totalDuration = System.currentTimeMillis() - startTime;
                    validationLogService.logValidationFailure(loanId, validationId, "验证失败",
                            comprehensiveResult.getMessage(), totalDuration, currentUser);
                }
            }

            // 设置规则版本和降级信息
            validation.setRuleVersion("1.0.0");
            if (degradationConfig.getLevel() != PerformanceDegradationStrategy.DegradationLevel.NONE) {
                String originalResult = validation.getValidationResult();
                validation.setValidationResult(originalResult + " [降级级别: " + degradationConfig.getLevel().getDescription() + "]");
            }

            // 保存验证记录
            loanConsistencyMapper.updateLoanConsistencyValidation(validation);

            // 缓存验证结果
            long cacheStartTime = System.currentTimeMillis();
            validationCacheManager.cacheValidationResult(loanId, validation);
            long cacheDuration = System.currentTimeMillis() - cacheStartTime;

            // 记录缓存操作日志
            validationLogService.logCacheOperation(loanId, "CACHE_SET",
                    "缓存验证结果", "状态: " + validation.getValidationStatus(), currentUser);

            // 记录验证日志
            long executionTime = System.currentTimeMillis() - startTime;
            log.info("贷款一致性验证完成，贷款ID: {}, 验证状态: {}, 耗时: {}ms, 降级级别: {}",
                    loanId, validation.getValidationStatus(), executionTime, degradationConfig.getLevel().getDescription());

            // 检查性能警告
            if (executionTime > VALIDATION_TIMEOUT / 2) { // 超过一半阈值时间
                validationLogService.logPerformanceWarning(loanId, validationId, "VALIDATION",
                        executionTime, VALIDATION_TIMEOUT / 2, currentUser);
            }

            // 如果验证失败，发送通知
            if (validation.isFailed()) {
                sendValidationFailureNotification(validation);

                // 记录通知发送日志
                validationLogService.logNotificationSent(loanId, validationId, "FAILURE_NOTIFICATION",
                        "发送验证失败通知", true, currentUser);
            }

            // 结束性能监控
            performanceMonitor.endValidationMonitoring(perfContext, validation.isPassed());

            // 记录验证统计信息
            recordValidationStatistics(validation, executionTime, degradationConfig.isUseCachedResults());

            return validation;

        } catch (Exception e) {
            log.error("贷款一致性验证异常，贷款ID: {}", loanId, e);

            // 记录验证错误日志
            validationLogService.logValidationError(loanId, validationId, "验证过程异常", e, currentUser);

            LoanConsistencyValidation validation = new LoanConsistencyValidation();
            validation.setLoanId(loanId);
            validation.setContractId(contractId);
            validation.setCreditId(creditId);
            validation.setServicePeriodId(servicePeriodId);
            validation.setValidationTime(DateUtils.getNowDate());
            validation.setValidatedBy(getCurrentUser());
            validation.setValidationStatus(LoanConsistencyValidation.STATUS_ERROR);
            validation.setFailureReason("验证异常: " + e.getMessage());
            validation.setValidationResult("系统异常");
            validation.setValidationScore(0);
            validation.setRuleVersion("1.0.0");

            // 保存错误记录
            loanConsistencyMapper.insertLoanConsistencyValidation(validation);

            // 缓存错误结果（较短的过期时间）
            validationCacheManager.cacheValidationResult(loanId, validation);

            // 记录缓存操作日志
            validationLogService.logCacheOperation(loanId, "CACHE_SET_ERROR",
                    "缓存错误结果", "异常: " + e.getMessage(), currentUser);

            // 结束性能监控
            performanceMonitor.endValidationMonitoring(perfContext, false);

            // 记录验证统计信息（异常情况）
            long executionTime = System.currentTimeMillis() - perfContext.getStartTime();
            recordValidationStatistics(validation, executionTime, false);

            return validation;
        }
    }

    @Override
    public List<LoanConsistencyValidation> batchValidateLoans(List<Long> loanIds) {
        log.info("开始批量验证贷款记录，数量: {}", loanIds.size());
        log.info("待验证的贷款ID列表: {}", loanIds);

        if (CollectionUtils.isEmpty(loanIds)) {
            log.warn("贷款ID列表为空，返回空结果");
            return new ArrayList<>();
        }

        List<LoanConsistencyValidation> results = new ArrayList<>();

        // 分批处理，避免一次性处理过多数据
        for (int i = 0; i < loanIds.size(); i += BATCH_SIZE) {
            int endIndex = Math.min(i + BATCH_SIZE, loanIds.size());
            List<Long> batchLoanIds = loanIds.subList(i, endIndex);

            log.debug("处理批次 {}-{}, 数量: {}", i + 1, endIndex, batchLoanIds.size());

            List<LoanConsistencyValidation> batchResults = new ArrayList<>();

            for (Long loanId : batchLoanIds) {
                try {
                    log.debug("开始验证贷款ID: {}", loanId);
                    
                    // 获取贷款相关的债权凭证和服务周期信息
                    Map<String, Object> loanInfo = loanConsistencyMapper.selectLoanCreditInfo(loanId);
                    log.debug("贷款ID: {} 的相关信息: {}", loanId, loanInfo);
                    
                    Long creditId = loanInfo != null ? (Long) loanInfo.get("creditId") : null;
                    Long servicePeriodId = loanInfo != null ? (Long) loanInfo.get("servicePeriodId") : null;

                    LoanConsistencyValidation validation = validateLoanConsistency(loanId, creditId, servicePeriodId);
                    results.add(validation);
                    batchResults.add(validation);

                    log.debug("贷款ID: {} 验证完成，状态: {}", loanId, validation.getValidationStatus());

                } catch (Exception e) {
                    log.error("批量验证中单个贷款验证失败，贷款ID: {}", loanId, e);

                    // 创建错误记录并保存到数据库
                    LoanConsistencyValidation errorValidation = createErrorValidation(loanId,
                            "批量验证失败: " + e.getMessage());

                    // 确保错误记录也保存到数据库
                    try {
                        loanConsistencyMapper.insertLoanConsistencyValidation(errorValidation);
                        results.add(errorValidation);
                        batchResults.add(errorValidation);
                    } catch (Exception saveException) {
                        log.error("保存错误验证记录失败，贷款ID: {}", loanId, saveException);
                    }
                }
            }

            // 预加载当前批次的验证结果到缓存
            if (!batchResults.isEmpty()) {
                try {
                    validationCacheManager.preloadValidationCache(batchResults);
                } catch (Exception cacheException) {
                    log.warn("预加载验证缓存失败", cacheException);
                }
            }
        }

        log.info("批量验证完成，总数: {}, 成功: {}, 失败: {}",
                results.size(),
                results.stream().filter(v -> LoanConsistencyValidation.STATUS_PASS.equals(v.getValidationStatus())).count(),
                results.stream().filter(v -> LoanConsistencyValidation.STATUS_FAIL.equals(v.getValidationStatus())
                || LoanConsistencyValidation.STATUS_ERROR.equals(v.getValidationStatus())).count());

        return results;
    }

    @Override
    public List<LoanConsistencyValidation> getLoanValidationHistory(Long loanId) {
        log.debug("获取贷款验证历史记录，贷款ID: {}", loanId);

        if (loanId == null) {
            throw new IllegalArgumentException("贷款ID不能为空");
        }

        try {
            LoanConsistencyValidation queryParam = new LoanConsistencyValidation();
            queryParam.setLoanId(loanId);

            List<LoanConsistencyValidation> history = loanConsistencyMapper.selectLoanConsistencyValidationList(queryParam);

            log.debug("获取到验证历史记录数量: {}", history.size());
            return history;

        } catch (Exception e) {
            log.error("获取贷款验证历史记录失败，贷款ID: {}", loanId, e);
            return new ArrayList<>();
        }
    }

    @Override
    public Map<String, Object> getValidationStatistics(String startDate, String endDate) {
        log.debug("获取验证统计信息，开始日期: {}, 结束日期: {}", startDate, endDate);

        Map<String, Object> statistics = new HashMap<>();

        try {
            Date start = StringUtils.hasText(startDate) ? DateUtils.parseDate(startDate) : null;
            Date end = StringUtils.hasText(endDate) ? DateUtils.parseDate(endDate) : null;

            // 获取状态统计
            List<Map<String, Object>> statusStats = loanConsistencyMapper.selectValidationCountByStatus();
            statistics.put("statusStatistics", statusStats);

            // 获取时间范围内的总数
            if (start != null && end != null) {
                Integer totalCount = loanConsistencyMapper.countValidationsByTimeRange(start, end);
                statistics.put("totalCountInRange", totalCount);
            }

            statistics.put("queryStartDate", startDate);
            statistics.put("queryEndDate", endDate);
            statistics.put("generateTime", DateUtils.getTime());

            log.debug("验证统计信息获取完成");
            return statistics;

        } catch (Exception e) {
            log.error("获取验证统计信息失败", e);
            statistics.put("error", "获取统计信息失败: " + e.getMessage());
            return statistics;
        }
    }

    @Override
    public boolean needsRevalidation(Long loanId) {
        log.debug("检查是否需要重新验证，贷款ID: {}", loanId);

        if (loanId == null) {
            return false;
        }

        try {
            LoanConsistencyValidation latestValidation = loanConsistencyMapper.selectLatestValidationByLoanId(loanId);

            if (latestValidation == null) {
                // 没有验证记录，需要验证
                return true;
            }

            // 如果验证状态是错误或待处理，需要重新验证
            if (LoanConsistencyValidation.STATUS_ERROR.equals(latestValidation.getValidationStatus())
                    || LoanConsistencyValidation.STATUS_PENDING.equals(latestValidation.getValidationStatus())) {
                return true;
            }

            // 检查最后验证时间是否超过24小时
            Date validationTime = latestValidation.getValidationTime();
            if (validationTime == null) {
                return true;
            }

            long hoursSinceValidation = (System.currentTimeMillis() - validationTime.getTime()) / (1000 * 60 * 60);
            boolean needsRevalidation = hoursSinceValidation > 24;

            log.debug("贷款ID: {}, 最后验证时间: {}, 距今小时数: {}, 需要重新验证: {}",
                    loanId, validationTime, hoursSinceValidation, needsRevalidation);

            return needsRevalidation;

        } catch (Exception e) {
            log.error("检查是否需要重新验证失败，贷款ID: {}", loanId, e);
            return false; // 出错时不强制验证，避免重复验证
        }
    }

    @Override
    public List<Long> getFailedValidationLoans() {
        log.debug("获取验证失败的贷款列表");

        try {
            List<Long> failedLoanIds = loanConsistencyMapper.selectFailedLoanIds();
            log.debug("获取到验证失败的贷款数量: {}", failedLoanIds.size());
            return failedLoanIds;

        } catch (Exception e) {
            log.error("获取验证失败的贷款列表失败", e);
            return new ArrayList<>();
        }
    }

    @Override
    @Transactional
    public int cleanupExpiredValidations(int daysToKeep) {
        log.info("开始清理过期的验证记录，保留天数: {}", daysToKeep);

        if (daysToKeep <= 0) {
            throw new IllegalArgumentException("保留天数必须大于0");
        }

        try {
            // 计算清理时间点
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DAY_OF_MONTH, -daysToKeep);
            Date beforeTime = calendar.getTime();

            int deletedCount = loanConsistencyMapper.deleteValidationsBefore(beforeTime);

            log.info("清理过期验证记录完成，删除记录数: {}, 清理时间点: {}", deletedCount, beforeTime);
            return deletedCount;

        } catch (Exception e) {
            log.error("清理过期验证记录失败", e);
            throw new RuntimeException("清理过期验证记录失败", e);
        }
    }

    /**
     * 执行综合验证 将所有验证步骤合并为一个高效的验证流程
     *
     * @param context 验证上下文
     * @return 验证结果
     */
    private ValidationResult executeComprehensiveValidation(ValidationContext context) {
        log.debug("开始执行综合验证，贷款ID: {}", context.getLoanId());

        try {
            Long creditId = context.getCreditId();
            Long servicePeriodId = context.getServicePeriodId();
            Long contractId = context.getContractId();

            // 基本数据检查
            if (creditId == null) {
                return ValidationResult.failure("债权凭证ID不能为空");
            }

            if (servicePeriodId == null) {
                return ValidationResult.failure("服务周期ID不能为空");
            }

            if (contractId == null) {
                return ValidationResult.failure("合同ID不能为空");
            }

            // 综合验证逻辑 - 一次性完成所有检查
            // 这里可以添加更复杂的验证逻辑，但目前简化实现
            log.debug("综合验证通过，贷款ID: {}, 债权凭证ID: {}, 服务周期ID: {}, 合同ID: {}",
                    context.getLoanId(), creditId, servicePeriodId, contractId);

            return ValidationResult.success("综合验证通过");

        } catch (Exception e) {
            log.error("综合验证异常，贷款ID: {}", context.getLoanId(), e);
            return ValidationResult.error("综合验证异常: " + e.getMessage(), "comprehensive_validation");
        }
    }

    /**
     * 验证债权凭证存在性和有效性
     *
     * @param context 验证上下文
     * @return 验证结果
     */
    private ValidationResult validateCreditExistenceAndValidity(ValidationContext context) {
        log.debug("开始验证债权凭证存在性和有效性，贷款ID: {}", context.getLoanId());

        try {
            // 执行债权凭证存在性验证规则
            ValidationResult existenceResult = validationRuleEngine.executeRule("credit_existence", context);
            if (existenceResult.isFailed() || existenceResult.isError()) {
                return existenceResult;
            }

            // 执行债权凭证有效性验证规则
            ValidationResult validityResult = validationRuleEngine.executeRule("credit_validity", context);
            if (validityResult.isFailed() || validityResult.isError()) {
                return validityResult;
            }

            log.debug("债权凭证存在性和有效性验证通过，贷款ID: {}", context.getLoanId());
            return ValidationResult.success("债权凭证存在性和有效性验证通过");

        } catch (Exception e) {
            log.error("债权凭证存在性和有效性验证异常，贷款ID: {}", context.getLoanId(), e);
            return ValidationResult.error("债权凭证验证异常: " + e.getMessage(), "credit_validation");
        }
    }

    /**
     * 验证债权凭证与服务周期贷款合同的关联
     *
     * @param context 验证上下文
     * @return 验证结果
     */
    private ValidationResult validateCreditContractAssociation(ValidationContext context) {
        log.debug("开始验证债权凭证与服务周期贷款合同的关联，贷款ID: {}", context.getLoanId());

        try {
            // 执行合同匹配验证规则
            ValidationResult contractMatchResult = validationRuleEngine.executeRule("contract_match", context);
            if (contractMatchResult.isFailed() || contractMatchResult.isError()) {
                return contractMatchResult;
            }

            // 执行金额一致性验证规则
            ValidationResult amountResult = validationRuleEngine.executeRule("amount_consistency", context);
            if (amountResult.isFailed() || amountResult.isError()) {
                return amountResult;
            }

            // 执行日期一致性验证规则
            ValidationResult dateResult = validationRuleEngine.executeRule("date_consistency", context);
            if (dateResult.isFailed() || dateResult.isError()) {
                return dateResult;
            }

            log.debug("债权凭证与服务周期贷款合同关联验证通过，贷款ID: {}", context.getLoanId());
            return ValidationResult.success("债权凭证与服务周期贷款合同关联验证通过");

        } catch (Exception e) {
            log.error("债权凭证与服务周期贷款合同关联验证异常，贷款ID: {}", context.getLoanId(), e);
            return ValidationResult.error("关联验证异常: " + e.getMessage(), "association_validation");
        }
    }

    /**
     * 发送验证失败通知
     *
     * @param validation 验证记录
     */
    private void sendValidationFailureNotification(LoanConsistencyValidation validation) {
        log.debug("发送验证失败通知，贷款ID: {}", validation.getLoanId());

        try {
            // 使用异步通知处理器
            asyncNotificationProcessor.processValidationFailureNotificationAsync(validation)
                    .whenComplete((result, throwable) -> {
                        if (throwable != null) {
                            log.error("异步发送验证失败通知异常，贷款ID: {}", validation.getLoanId(), throwable);
                        } else if (result) {
                            log.info("验证失败通知发送成功，贷款ID: {}", validation.getLoanId());
                        } else {
                            log.warn("验证失败通知发送失败，贷款ID: {}", validation.getLoanId());
                        }
                    });

        } catch (Exception e) {
            log.error("发送验证失败通知异常，贷款ID: {}", validation.getLoanId(), e);
        }
    }

    /**
     * 创建错误验证记录
     *
     * @param loanId 贷款ID
     * @param errorMessage 错误消息
     * @return 错误验证记录
     */
    private LoanConsistencyValidation createErrorValidation(Long loanId, String errorMessage) {
        LoanConsistencyValidation validation = new LoanConsistencyValidation();
        validation.setLoanId(loanId);

        // 尝试获取合同ID
        try {
            Map<String, Object> loanInfo = loanConsistencyMapper.selectLoanCreditInfo(loanId);
            if (loanInfo != null) {
                validation.setContractId((Long) loanInfo.get("contractId"));
                validation.setCreditId((Long) loanInfo.get("creditId"));
                validation.setServicePeriodId((Long) loanInfo.get("servicePeriodId"));
            }
        } catch (Exception e) {
            log.warn("获取贷款相关信息失败，贷款ID: {}", loanId, e);
        }

        validation.setValidationTime(DateUtils.getNowDate());
        validation.setValidatedBy(getCurrentUser());
        validation.setValidationStatus(LoanConsistencyValidation.STATUS_ERROR);
        validation.setFailureReason(errorMessage);
        validation.setValidationResult("系统异常");
        validation.setValidationScore(0);
        validation.setRuleVersion("1.0.0");

        return validation;
    }

    /**
     * 处理验证结果逻辑 实现通过验证的贷款记录包含逻辑和验证失败的贷款记录排除逻辑
     *
     * @param loanIds 需要验证的贷款ID列表
     * @return 通过验证的贷款ID列表
     */
    private List<Long> processValidationResults(List<Long> loanIds) {
        log.debug("开始处理验证结果，贷款数量: {}", loanIds.size());

        List<Long> validatedLoanIds = new ArrayList<>();
        List<Long> failedLoanIds = new ArrayList<>();

        for (Long loanId : loanIds) {
            try {
                // 检查是否需要重新验证
                if (needsRevalidation(loanId)) {
                    log.debug("贷款ID: {} 需要重新验证", loanId);

                    // 执行验证
                    LoanConsistencyValidation validation = validateLoanConsistency(loanId, null, null);

                    // 根据验证结果进行分类处理
                    if (validation.isPassed()) {
                        // 通过验证的贷款记录包含逻辑
                        validatedLoanIds.add(loanId);
                        log.debug("贷款ID: {} 验证通过，包含在结果列表中", loanId);
                    } else {
                        // 验证失败的贷款记录排除逻辑
                        failedLoanIds.add(loanId);
                        recordValidationFailure(loanId, validation);
                        log.debug("贷款ID: {} 验证失败，从结果列表中排除，原因: {}", loanId, validation.getFailureReason());
                    }
                } else {
                    // 获取最新验证记录
                    LoanConsistencyValidation latestValidation = loanConsistencyMapper.selectLatestValidationByLoanId(loanId);

                    if (latestValidation != null && latestValidation.isPassed()) {
                        // 使用缓存的验证结果 - 通过验证的贷款记录包含逻辑
                        validatedLoanIds.add(loanId);
                        log.debug("贷款ID: {} 使用缓存验证结果，验证通过", loanId);
                    } else if (latestValidation != null && latestValidation.isFailed()) {
                        // 使用缓存的验证结果 - 验证失败的贷款记录排除逻辑
                        failedLoanIds.add(loanId);
                        log.debug("贷款ID: {} 使用缓存验证结果，验证失败", loanId);
                    } else {
                        // 没有验证记录，执行验证
                        LoanConsistencyValidation validation = validateLoanConsistency(loanId, null, null);

                        if (validation.isPassed()) {
                            validatedLoanIds.add(loanId);
                        } else {
                            failedLoanIds.add(loanId);
                            recordValidationFailure(loanId, validation);
                        }
                    }
                }

            } catch (Exception e) {
                log.error("处理贷款验证结果异常，贷款ID: {}", loanId, e);

                // 验证异常的贷款记录排除逻辑
                failedLoanIds.add(loanId);
                recordValidationException(loanId, e.getMessage());
            }
        }

        log.info("验证结果处理完成，通过验证: {}, 验证失败: {}", validatedLoanIds.size(), failedLoanIds.size());

        // 批量处理失败通知（异步）
        if (!failedLoanIds.isEmpty()) {
            CompletableFuture.runAsync(() -> batchSendFailureNotifications(failedLoanIds), validationExecutor);
        }

        return validatedLoanIds;
    }

    /**
     * 记录验证失败详细信息 添加验证失败原因的详细记录功能
     *
     * @param loanId 贷款ID
     * @param validation 验证记录
     */
    private void recordValidationFailure(Long loanId, LoanConsistencyValidation validation) {
        log.debug("记录验证失败详细信息，贷款ID: {}", loanId);

        try {
            // 构建详细的失败原因记录
            StringBuilder detailedReason = new StringBuilder();
            detailedReason.append("验证失败时间: ").append(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, validation.getValidationTime()));
            detailedReason.append("; 验证得分: ").append(validation.getValidationScore());
            detailedReason.append("; 失败原因: ").append(validation.getFailureReason());
            detailedReason.append("; 规则版本: ").append(validation.getRuleVersion());

            // 更新验证记录的详细信息
            validation.setValidationResult(detailedReason.toString());
            loanConsistencyMapper.updateLoanConsistencyValidation(validation);

            log.info("验证失败详细信息记录完成，贷款ID: {}, 详细原因: {}", loanId, detailedReason.toString());

        } catch (Exception e) {
            log.error("记录验证失败详细信息异常，贷款ID: {}", loanId, e);
        }
    }

    /**
     * 记录验证异常信息
     *
     * @param loanId 贷款ID
     * @param errorMessage 异常消息
     */
    private void recordValidationException(Long loanId, String errorMessage) {
        log.debug("记录验证异常信息，贷款ID: {}", loanId);

        try {
            LoanConsistencyValidation validation = createErrorValidation(loanId, errorMessage);

            // 构建详细的异常信息记录
            StringBuilder detailedReason = new StringBuilder();
            detailedReason.append("验证异常时间: ").append(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, validation.getValidationTime()));
            detailedReason.append("; 异常类型: 系统异常");
            detailedReason.append("; 异常详情: ").append(errorMessage);
            detailedReason.append("; 处理方式: 自动排除");

            validation.setValidationResult(detailedReason.toString());
            loanConsistencyMapper.insertLoanConsistencyValidation(validation);

            log.info("验证异常信息记录完成，贷款ID: {}, 异常详情: {}", loanId, detailedReason.toString());

        } catch (Exception e) {
            log.error("记录验证异常信息失败，贷款ID: {}", loanId, e);
        }
    }

    /**
     * 批量发送失败通知
     *
     * @param failedLoanIds 失败的贷款ID列表
     */
    private void batchSendFailureNotifications(List<Long> failedLoanIds) {
        log.debug("开始批量发送失败通知，失败贷款数量: {}", failedLoanIds.size());

        try {
            // 获取失败贷款的最新验证记录
            List<LoanConsistencyValidation> failedValidations = loanConsistencyMapper.selectLatestValidationsByLoanIds(failedLoanIds);

            // 使用异步批量通知处理器
            asyncNotificationProcessor.processBatchValidationFailureNotificationsAsync(failedValidations)
                    .whenComplete((result, throwable) -> {
                        if (throwable != null) {
                            log.error("异步批量发送失败通知异常", throwable);
                        } else {
                            log.info("批量发送失败通知完成，结果: {}", result);
                        }
                    });

        } catch (Exception e) {
            log.error("批量发送失败通知异常", e);
        }
    }

    /**
     * 触发重新验证机制 实现重新验证触发机制
     *
     * @param loanId 贷款ID
     * @param reason 重新验证原因
     * @return 重新验证结果
     */
    @Override
    public LoanConsistencyValidation triggerRevalidation(Long loanId, String reason) {
        log.info("触发重新验证，贷款ID: {}, 原因: {}", loanId, reason);

        if (loanId == null) {
            throw new IllegalArgumentException("贷款ID不能为空");
        }

        try {
            // 记录重新验证触发日志
            log.info("开始执行重新验证，贷款ID: {}, 触发原因: {}, 触发时间: {}",
                    loanId, reason, DateUtils.getTime());

            // 清除该贷款的缓存验证结果（如果有缓存机制）
            clearValidationCache(loanId);

            // 执行重新验证
            LoanConsistencyValidation revalidationResult = validateLoanConsistency(loanId, null, null);

            // 在验证结果中记录重新验证的原因
            String originalResult = revalidationResult.getValidationResult();
            String enhancedResult = String.format("重新验证触发原因: %s; 原验证结果: %s", reason, originalResult);
            revalidationResult.setValidationResult(enhancedResult);

            // 更新验证记录
            loanConsistencyMapper.updateLoanConsistencyValidation(revalidationResult);

            // 如果重新验证成功，发送成功通知
            if (revalidationResult.isPassed()) {
                try {
                    asyncNotificationProcessor.processRevalidationSuccessNotificationAsync(revalidationResult)
                            .whenComplete((result, throwable) -> {
                                if (throwable != null) {
                                    log.error("异步发送重新验证成功通知异常，贷款ID: {}", loanId, throwable);
                                } else if (result) {
                                    log.info("重新验证成功通知发送成功，贷款ID: {}", loanId);
                                } else {
                                    log.warn("重新验证成功通知发送失败，贷款ID: {}", loanId);
                                }
                            });
                } catch (Exception e) {
                    log.error("发送重新验证成功通知异常，贷款ID: {}", loanId, e);
                }
            }

            log.info("重新验证完成，贷款ID: {}, 验证状态: {}, 验证得分: {}",
                    loanId, revalidationResult.getValidationStatus(), revalidationResult.getValidationScore());

            return revalidationResult;

        } catch (Exception e) {
            log.error("触发重新验证异常，贷款ID: {}, 原因: {}", loanId, reason, e);

            // 创建重新验证失败记录
            LoanConsistencyValidation errorValidation = createErrorValidation(loanId,
                    "重新验证触发失败: " + e.getMessage() + ", 触发原因: " + reason);
            loanConsistencyMapper.insertLoanConsistencyValidation(errorValidation);

            return errorValidation;
        }
    }

    /**
     * 批量触发重新验证
     *
     * @param loanIds 贷款ID列表
     * @param reason 重新验证原因
     * @return 重新验证结果统计
     */
    @Override
    public Map<String, Object> batchTriggerRevalidation(List<Long> loanIds, String reason) {
        log.info("批量触发重新验证，贷款数量: {}, 原因: {}", loanIds.size(), reason);

        Map<String, Object> result = new HashMap<>();

        if (CollectionUtils.isEmpty(loanIds)) {
            result.put("totalCount", 0);
            result.put("successCount", 0);
            result.put("failureCount", 0);
            result.put("message", "没有需要重新验证的贷款");
            return result;
        }

        try {
            List<LoanConsistencyValidation> revalidationResults = new ArrayList<>();

            for (Long loanId : loanIds) {
                try {
                    LoanConsistencyValidation validation = triggerRevalidation(loanId, reason);
                    revalidationResults.add(validation);
                } catch (Exception e) {
                    log.error("批量重新验证中单个贷款处理失败，贷款ID: {}", loanId, e);

                    LoanConsistencyValidation errorValidation = createErrorValidation(loanId,
                            "批量重新验证失败: " + e.getMessage());
                    revalidationResults.add(errorValidation);
                }
            }

            // 统计结果
            long successCount = revalidationResults.stream()
                    .filter(LoanConsistencyValidation::isPassed)
                    .count();

            long failureCount = revalidationResults.stream()
                    .filter(v -> v.isFailed() || LoanConsistencyValidation.STATUS_ERROR.equals(v.getValidationStatus()))
                    .count();

            result.put("totalCount", revalidationResults.size());
            result.put("successCount", successCount);
            result.put("failureCount", failureCount);
            result.put("message", "批量重新验证完成");
            result.put("reason", reason);

            log.info("批量重新验证完成，总数: {}, 成功: {}, 失败: {}",
                    revalidationResults.size(), successCount, failureCount);

            return result;

        } catch (Exception e) {
            log.error("批量触发重新验证异常", e);
            result.put("error", "批量重新验证失败: " + e.getMessage());
            return result;
        }
    }

    @Override
    public Map<String, Object> startBackgroundValidation() {
        log.info("启动后台自动验证机制");

        Map<String, Object> result = new HashMap<>();

        try {
            // 启动后台验证机制时，立即执行一次完整的验证
            log.info("启动时执行一次完整的贷款一致性验证");
            Map<String, Object> validationResult = validateAllLoansInBackground();

            result.put("success", true);
            result.put("message", "后台自动验证机制已启动，并完成了一次完整验证");
            result.put("startTime", DateUtils.getTime());

            // 包含验证结果信息
            result.put("validationResult", validationResult);

            log.info("后台自动验证机制启动成功，验证结果: {}", validationResult);
            return result;

        } catch (Exception e) {
            log.error("启动后台自动验证机制失败", e);
            result.put("success", false);
            result.put("message", "启动失败: " + e.getMessage());
            return result;
        }
    }

    @Override
    public Map<String, Object> stopBackgroundValidation() {
        log.info("停止后台自动验证机制");

        Map<String, Object> result = new HashMap<>();

        try {
            // 这里可以添加停止后台验证的逻辑
            // 实际的停止逻辑在ValidationQueueManager的@PreDestroy中处理

            result.put("success", true);
            result.put("message", "后台自动验证机制已停止");
            result.put("stopTime", DateUtils.getTime());

            log.info("后台自动验证机制停止成功");
            return result;

        } catch (Exception e) {
            log.error("停止后台自动验证机制失败", e);
            result.put("success", false);
            result.put("message", "停止失败: " + e.getMessage());
            return result;
        }
    }

    @Override
    public Map<String, Object> getBackgroundValidationStatus() {
        log.debug("获取后台验证状态");

        Map<String, Object> status = new HashMap<>();

        try {
            // 获取验证队列状态（需要注入ValidationQueueManager）
            // 这里先返回基本状态信息
            status.put("running", true);
            status.put("currentTime", DateUtils.getTime());
            status.put("validationExecutorActive", validationExecutor != null && !validationExecutor.isShutdown());

            // 获取最近的验证统计
            Map<String, Object> recentStats = getValidationStatistics(null, null);
            status.put("recentStatistics", recentStats);

            log.debug("后台验证状态获取完成");
            return status;

        } catch (Exception e) {
            log.error("获取后台验证状态失败", e);
            status.put("error", "获取状态失败: " + e.getMessage());
            return status;
        }
    }

    /**
     * 清除验证缓存
     *
     * @param loanId 贷款ID
     */
    private void clearValidationCache(Long loanId) {
        log.debug("清除验证缓存，贷款ID: {}", loanId);

        try {
            // 这里可以集成Redis缓存清除逻辑
            // 目前先记录日志，后续可以扩展
            log.debug("验证缓存清除完成，贷款ID: {}", loanId);

        } catch (Exception e) {
            log.warn("清除验证缓存失败，贷款ID: {}", loanId, e);
        }
    }

    /**
     * 创建降级验证记录
     *
     * @param loanId 贷款ID
     * @param reason 降级原因
     * @return 降级验证记录
     */
    private LoanConsistencyValidation createDegradedValidation(Long loanId, String reason) {
        LoanConsistencyValidation validation = new LoanConsistencyValidation();
        validation.setLoanId(loanId);

        // 尝试获取合同ID
        try {
            Map<String, Object> loanInfo = loanConsistencyMapper.selectLoanCreditInfo(loanId);
            if (loanInfo != null) {
                validation.setContractId((Long) loanInfo.get("contractId"));
                validation.setCreditId((Long) loanInfo.get("creditId"));
                validation.setServicePeriodId((Long) loanInfo.get("servicePeriodId"));
            }
        } catch (Exception e) {
            log.warn("获取贷款相关信息失败，贷款ID: {}", loanId, e);
        }

        validation.setValidationTime(DateUtils.getNowDate());
        validation.setValidatedBy(getCurrentUser());
        validation.setValidationStatus(LoanConsistencyValidation.STATUS_ERROR);
        validation.setFailureReason(reason);
        validation.setValidationResult("系统降级: " + reason);
        validation.setValidationScore(0);
        validation.setRuleVersion("1.0.0");

        return validation;
    }

    /**
     * 获取当前用户
     *
     * @return 当前用户名
     */
    private String getCurrentUser() {
        try {
            return SecurityUtils.getUsername();
        } catch (Exception e) {
            return "system";
        }
    }

    /**
     * 获取客户端IP地址
     *
     * @return 客户端IP地址
     */
    private String getClientIp() {
        try {
            // 尝试从Spring Security上下文获取IP
            return "127.0.0.1"; // 默认值，实际项目中可以从HttpServletRequest获取
        } catch (Exception e) {
            return "unknown";
        }
    }

    @Override
    public List<Long> getLoansWithCreditCertificates() {
        log.debug("获取所有需要验证的贷款ID列表");

        try {
            List<Long> loanIds = loanConsistencyMapper.selectLoansWithCreditCertificates();
            log.info("获取到需要验证的贷款数量: {}, 贷款ID列表: {}", loanIds.size(), loanIds);
            
            // 如果没有找到贷款，提供详细的调试信息
            if (loanIds.isEmpty()) {
                log.warn("没有找到符合条件的贷款，开始调试分析...");
                
                // 检查各个表的数据量
                Integer totalLoans = loanConsistencyMapper.countAllLoans();
                Integer totalCredits = loanConsistencyMapper.countAllCredits();
                Integer totalServicePeriods = loanConsistencyMapper.countAllServicePeriods();
                Integer totalContracts = loanConsistencyMapper.countAllContracts();
                
                log.warn("数据库表统计: 贷款总数={}, 债权总数={}, 服务周期总数={}, 合同总数={}", 
                    totalLoans, totalCredits, totalServicePeriods, totalContracts);
                
                if (totalLoans == 0) {
                    log.error("数据库中没有任何贷款记录！");
                } else if (totalCredits == 0) {
                    log.error("数据库中没有任何债权记录！");
                } else if (totalServicePeriods == 0) {
                    log.error("数据库中没有任何服务周期记录！");
                } else if (totalContracts == 0) {
                    log.error("数据库中没有任何合同记录！");
                } else {
                    log.warn("各表都有数据，但查询条件可能过于严格，没有匹配的记录");
                    
                    // 尝试使用更宽松的查询
                    List<Long> allLoansWithCredit = loanConsistencyMapper.selectAllLoansWithAnyCredit();
                    log.warn("使用宽松条件查询到的贷款数量: {}, 贷款ID列表: {}", 
                        allLoansWithCredit.size(), allLoansWithCredit);
                }
            }
            
            return loanIds;

        } catch (Exception e) {
            log.error("获取需要验证的贷款列表失败", e);
            return new ArrayList<>();
        }
    }

    @Override
    public List<Long> getAllLoansWithAnyCredit() {
        log.debug("获取所有有债权的贷款ID列表（调试用）");

        try {
            List<Long> loanIds = loanConsistencyMapper.selectAllLoansWithAnyCredit();
            log.info("获取到所有有债权的贷款数量: {}, 贷款ID列表: {}", loanIds.size(), loanIds);
            return loanIds;

        } catch (Exception e) {
            log.error("获取所有有债权的贷款列表失败", e);
            return new ArrayList<>();
        }
    }

    /**
     * 调试方法：检查贷款数据完整性
     *
     * @param loanId 贷款ID
     * @return 调试信息
     */
    public Map<String, Object> debugLoanData(Long loanId) {
        log.info("开始调试贷款数据，贷款ID: {}", loanId);

        Map<String, Object> debugInfo = new HashMap<>();
        debugInfo.put("loanId", loanId);

        try {
            // 1. 检查基础贷款信息
            Map<String, Object> loanInfo = loanConsistencyMapper.selectLoanCreditInfo(loanId);
            debugInfo.put("loanInfo", loanInfo);
            debugInfo.put("loanInfoIsNull", loanInfo == null);

            if (loanInfo != null) {
                debugInfo.put("servicePeriodId", loanInfo.get("servicePeriodId"));
                debugInfo.put("contractId", loanInfo.get("contractId"));
                debugInfo.put("creditId", loanInfo.get("creditId"));
                debugInfo.put("loanAmount", loanInfo.get("loanAmount"));
                debugInfo.put("loanStatus", loanInfo.get("loanStatus"));
                debugInfo.put("periodStatus", loanInfo.get("periodStatus"));
                debugInfo.put("contractStatus", loanInfo.get("contractStatus"));
                debugInfo.put("creditStatus", loanInfo.get("creditStatus"));

                // 检查关键字段是否为空
                debugInfo.put("servicePeriodIdIsNull", loanInfo.get("servicePeriodId") == null);
                debugInfo.put("contractIdIsNull", loanInfo.get("contractId") == null);
                debugInfo.put("creditIdIsNull", loanInfo.get("creditId") == null);
                debugInfo.put("loanAmountIsNull", loanInfo.get("loanAmount") == null);
            }

            log.info("贷款数据调试完成，贷款ID: {}, 调试信息: {}", loanId, debugInfo);
            return debugInfo;

        } catch (Exception e) {
            log.error("调试贷款数据失败，贷款ID: {}", loanId, e);
            debugInfo.put("error", e.getMessage());
            debugInfo.put("exception", e.getClass().getSimpleName());
            return debugInfo;
        }
    }

    /**
     * 通过贷款ID查找关联的债权凭证ID
     *
     * @param loanId 贷款ID
     * @return 债权凭证ID，如果未找到则返回null
     */
    private Long findCreditIdByLoanId(Long loanId) {
        log.debug("通过贷款ID查找债权凭证ID: {}", loanId);
        
        try {
            // 1. 首先尝试从贷款信息中直接获取
            Map<String, Object> loanInfo = loanConsistencyMapper.selectLoanCreditInfo(loanId);
            if (loanInfo != null && loanInfo.get("creditId") != null) {
                Long creditId = (Long) loanInfo.get("creditId");
                log.debug("从贷款信息中找到债权凭证ID: loanId={}, creditId={}", loanId, creditId);
                return creditId;
            }
            
            // 2. 如果直接查询没有结果，尝试通过服务周期和合同关联查找
            if (loanInfo != null) {
                Long servicePeriodId = (Long) loanInfo.get("servicePeriodId");
                Long contractId = (Long) loanInfo.get("contractId");
                
                if (contractId != null) {
                    // 通过合同ID查找债权凭证
                    Long creditId = loanConsistencyMapper.selectCreditIdByContractId(contractId);
                    if (creditId != null) {
                        log.debug("通过合同ID找到债权凭证ID: loanId={}, contractId={}, creditId={}", 
                                loanId, contractId, creditId);
                        return creditId;
                    }
                }
            }
            
            log.debug("未找到贷款{}对应的债权凭证ID", loanId);
            return null;
            
        } catch (Exception e) {
            log.error("查找债权凭证ID失败: loanId={}", loanId, e);
            return null;
        }
    }

    /**
     * 通过贷款ID查找关联的服务周期ID
     *
     * @param loanId 贷款ID
     * @return 服务周期ID，如果未找到则返回null
     */
    private Long findServicePeriodIdByLoanId(Long loanId) {
        log.debug("通过贷款ID查找服务周期ID: {}", loanId);
        
        try {
            // 从贷款信息中获取服务周期ID
            Map<String, Object> loanInfo = loanConsistencyMapper.selectLoanCreditInfo(loanId);
            if (loanInfo != null && loanInfo.get("servicePeriodId") != null) {
                Long servicePeriodId = (Long) loanInfo.get("servicePeriodId");
                log.debug("找到服务周期ID: loanId={}, servicePeriodId={}", loanId, servicePeriodId);
                return servicePeriodId;
            }
            
            log.debug("未找到贷款{}对应的服务周期ID", loanId);
            return null;
            
        } catch (Exception e) {
            log.error("查找服务周期ID失败: loanId={}", loanId, e);
            return null;
        }
    }

    @Override
    public Integer countAllLoans() {
        try {
            return loanConsistencyMapper.countAllLoans();
        } catch (Exception e) {
            log.error("统计所有贷款记录数量失败", e);
            return 0;
        }
    }

    @Override
    public Integer countAllCredits() {
        try {
            return loanConsistencyMapper.countAllCredits();
        } catch (Exception e) {
            log.error("统计所有债权记录数量失败", e);
            return 0;
        }
    }

    @Override
    public Integer countAllServicePeriods() {
        try {
            return loanConsistencyMapper.countAllServicePeriods();
        } catch (Exception e) {
            log.error("统计所有服务周期记录数量失败", e);
            return 0;
        }
    }

    @Override
    public Integer countAllContracts() {
        try {
            return loanConsistencyMapper.countAllContracts();
        } catch (Exception e) {
            log.error("统计所有合同记录数量失败", e);
            return 0;
        }
    }

    /**
     * 记录验证统计信息
     *
     * @param validation 验证记录
     * @param executionTime 执行时间（毫秒）
     * @param cacheHit 是否命中缓存
     */
    private void recordValidationStatistics(LoanConsistencyValidation validation, long executionTime, boolean cacheHit) {
        try {
            Date validationDate = validation.getValidationTime();
            if (validationDate == null) {
                validationDate = DateUtils.getNowDate();
            }

            boolean passed = LoanConsistencyValidation.STATUS_PASS.equals(validation.getValidationStatus());
            String failureReason = validation.getFailureReason();

            // 调用ValidationStatisticsService记录统计信息
            validationStatisticsService.recordValidationResult(
                validationDate, 
                passed, 
                executionTime, 
                cacheHit, 
                failureReason
            );

            log.debug("验证统计信息记录完成，贷款ID: {}, 通过: {}, 耗时: {}ms, 缓存命中: {}", 
                validation.getLoanId(), passed, executionTime, cacheHit);

        } catch (Exception e) {
            log.error("记录验证统计信息失败，贷款ID: {}", validation.getLoanId(), e);
            // 不抛出异常，避免影响主要的验证流程
        }
    }
}
