package com.ruoyi.credit.service.validator;

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;

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

import java.util.Map;

/**
 * 合同匹配验证器
 * 验证债权凭证与服务周期合同的匹配关系
 * 
 * @author ruoyi
 * @date 2025-01-05
 */
@Component
public class ContractMatchValidator implements RuleValidator {
    
    private static final Logger log = LoggerFactory.getLogger(ContractMatchValidator.class);
    
    @Autowired
    private LoanConsistencyMapper loanConsistencyMapper;
    
    @Override
    public ValidationResult validate(ValidationRule rule, RuleConfig config, ValidationContext context) {
        log.debug("开始执行合同匹配验证，贷款ID: {}, 债权凭证ID: {}, 服务周期ID: {}", 
            context.getLoanId(), context.getCreditId(), context.getServicePeriodId());
        
        try {
            Long creditId = context.getCreditId();
            Long servicePeriodId = context.getServicePeriodId();
            Long contractId = context.getContractId();
            Long loanId = context.getLoanId();
            
            if (creditId == null) {
                return ValidationResult.failure("债权凭证ID不能为空");
            }
            
            if (servicePeriodId == null) {
                return ValidationResult.failure("服务周期ID不能为空");
            }
            
            // 如果合同ID为空，尝试通过贷款ID查找合同信息
            if (contractId == null && loanId != null) {
                try {
                    log.debug("合同ID为空，尝试通过贷款ID查找合同信息，贷款ID: {}", loanId);
                    Map<String, Object> loanInfo = loanConsistencyMapper.selectLoanCreditInfo(loanId);
                    if (loanInfo != null) {
                        contractId = (Long) loanInfo.get("contractId");
                        if (contractId != null) {
                            // 将查找到的合同ID设置回验证上下文
                            context.setContractId(contractId);
                            log.debug("通过贷款ID查找到合同ID: {}", contractId);
                        }
                    }
                } catch (Exception e) {
                    log.warn("通过贷款ID查找合同信息失败，贷款ID: {}", loanId, e);
                }
            }
            
            if (contractId == null) {
                return ValidationResult.failure("未找到对应的合同信息，请检查债权凭证与服务周期的关联关系");
            }
            
            // 这里可以添加更复杂的合同匹配验证逻辑
            // 比如验证债权凭证关联的合同ID与服务周期的合同ID是否一致
            
            log.debug("合同匹配验证通过，合同ID: {}", contractId);
            return ValidationResult.success("合同匹配验证通过，合同ID: " + contractId);
            
        } catch (Exception e) {
            log.error("合同匹配验证异常，贷款ID: {}", context.getLoanId(), e);
            return ValidationResult.error("合同匹配验证异常: " + e.getMessage(), "contract_match");
        }
    }
    
    @Override
    public String getValidatorName() {
        return "合同匹配验证器";
    }
    
    @Override
    public String getSupportedRuleType() {
        return ValidationRule.TYPE_CONTRACT_MATCH;
    }
}