package com.ruoyi.credit.service.validator;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.ruoyi.credit.domain.ValidationRule;
import com.ruoyi.credit.mapper.LoanConsistencyMapper;
import com.ruoyi.credit.service.RuleConfig;
import com.ruoyi.credit.service.RuleValidator;
import com.ruoyi.credit.service.ValidationContext;
import com.ruoyi.credit.service.ValidationResult;

/**
 * 债权凭证存在性验证器
 * 验证指定贷款是否存在对应的债权凭证
 * 
 * @author ruoyi
 * @date 2025-01-05
 */
@Component
public class CreditExistenceValidator implements RuleValidator {
    
    private static final Logger log = LoggerFactory.getLogger(CreditExistenceValidator.class);
    
    @Autowired
    private LoanConsistencyMapper loanConsistencyMapper;
    
    @Override
    public ValidationResult validate(ValidationRule rule, RuleConfig config, ValidationContext context) {
        log.debug("开始执行债权凭证存在性验证，贷款ID: {}", context.getLoanId());
        
        try {
            Long loanId = context.getLoanId();
            if (loanId == null) {
                return ValidationResult.failure("贷款ID不能为空");
            }
            
            // 如果上下文中已经有债权凭证ID，直接验证通过
            if (context.getCreditId() != null) {
                log.debug("债权凭证ID已存在于上下文中，跳过查询，贷款ID: {}, 债权凭证ID: {}", 
                    loanId, context.getCreditId());
                return ValidationResult.success("债权凭证存在性验证通过，债权凭证ID: " + context.getCreditId());
            }
            
            // 查询贷款相关的债权凭证信息
            Map<String, Object> loanInfo = loanConsistencyMapper.selectLoanCreditInfo(loanId);
            
            if (loanInfo == null) {
                log.warn("贷款ID: {} 未找到对应的服务周期和合同信息", loanId);
                return ValidationResult.failure("未找到对应的服务周期和合同信息");
            }
            
            // 更新验证上下文中的基本信息
            context.setServicePeriodId((Long) loanInfo.get("servicePeriodId"));
            context.setContractId((Long) loanInfo.get("contractId"));
            
            Long creditId = (Long) loanInfo.get("creditId");
            if (creditId != null) {
                // 如果有债权凭证，设置到上下文中
                context.setCreditId(creditId);
                log.debug("债权凭证存在性验证通过，贷款ID: {}, 债权凭证ID: {}", loanId, creditId);
                return ValidationResult.success("债权凭证存在性验证通过，债权凭证ID: " + creditId);
            } else {
                // 如果没有债权凭证，也认为验证通过（因为现在允许没有债权凭证）
                log.debug("贷款ID: {} 没有对应的债权凭证，但验证通过", loanId);
                return ValidationResult.success("验证通过（无债权凭证要求）");
            }
            
        } catch (Exception e) {
            log.error("债权凭证存在性验证异常，贷款ID: {}", context.getLoanId(), e);
            return ValidationResult.error("债权凭证存在性验证异常: " + e.getMessage(), "credit_existence");
        }
    }
    
    @Override
    public String getValidatorName() {
        return "债权凭证存在性验证器";
    }
    
    @Override
    public String getSupportedRuleType() {
        return ValidationRule.TYPE_CREDIT_EXISTENCE;
    }
}