package com.ruoyi.credit.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.credit.domain.LoanConsistencyValidation;
import com.ruoyi.credit.service.ILoanConsistencyService;

/**
 * 贷款一致性验证Controller
 * 
 * @author ruoyi
 * @date 2025-12-31
 */
@RestController
@RequestMapping("/credit/loan-consistency")
public class LoanConsistencyController extends BaseController
{
    @Autowired
    private ILoanConsistencyService loanConsistencyService;

    /**
     * 获取通过验证的贷款列表
     * 实现获取通过验证的贷款列表API
     * 后端自动验证所有记录，返回通过验证的贷款详细信息列表
     */
    @PreAuthorize("@ss.hasPermi('credit:financing:list')")
    @GetMapping("/validated-loans")
    public AjaxResult getValidatedLoanList(
            @RequestParam(required = false) Map<String, Object> queryParams,
            @RequestParam(required = false, defaultValue = "false") Boolean forceValidation)
    {
        logger.info("获取通过验证的贷款列表，查询参数: {}, 强制验证: {}", queryParams, forceValidation);
        
        try {
            // 如果需要强制验证，添加到查询参数中
            if (forceValidation) {
                if (queryParams == null) {
                    queryParams = new HashMap<>();
                }
                queryParams.put("forceValidation", true);
            }
            
            // 获取通过验证的贷款详细信息列表
            List<Map<String, Object>> validatedLoanDetails = loanConsistencyService.getValidatedLoanDetailsList(queryParams);
            
            logger.info("获取通过验证的贷款列表成功，数量: {}", validatedLoanDetails.size());
            return success(validatedLoanDetails);
            
        } catch (Exception e) {
            logger.error("获取通过验证的贷款列表失败", e);
            return error("获取通过验证的贷款列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取通过验证的贷款ID列表
     * 返回通过验证的贷款ID列表（向后兼容性接口）
     */
    @PreAuthorize("@ss.hasPermi('credit:financing:list')")
    @GetMapping("/validated-loan-ids")
    public AjaxResult getValidatedLoanIds(
            @RequestParam(required = false) Map<String, Object> queryParams,
            @RequestParam(required = false, defaultValue = "false") Boolean forceValidation)
    {
        logger.info("获取通过验证的贷款ID列表，查询参数: {}, 强制验证: {}", queryParams, forceValidation);
        
        try {
            // 如果需要强制验证，添加到查询参数中
            if (forceValidation) {
                if (queryParams == null) {
                    queryParams = new HashMap<>();
                }
                queryParams.put("forceValidation", true);
            }
            
            List<Long> validatedLoanIds = loanConsistencyService.getValidatedLoanList(queryParams);
            
            logger.info("获取通过验证的贷款ID列表成功，数量: {}", validatedLoanIds.size());
            return success(validatedLoanIds);
            
        } catch (Exception e) {
            logger.error("获取通过验证的贷款ID列表失败", e);
            return error("获取通过验证的贷款ID列表失败: " + e.getMessage());
        }
    }

    /**
     * 重新验证贷款
     * 添加重新验证贷款的API接口
     * 支持手动触发单个贷款记录的重新验证
     */
    @PreAuthorize("@ss.hasPermi('credit:financing:revalidate')")
    @Log(title = "贷款一致性验证", businessType = BusinessType.UPDATE)
    @PutMapping("/revalidate/{loanId}")
    public AjaxResult revalidateLoan(@PathVariable("loanId") Long loanId)
    {
        logger.info("开始重新验证贷款，贷款ID: {}", loanId);
        
        if (loanId == null) {
            return error("贷款ID不能为空");
        }

        try {
            LoanConsistencyValidation validation = loanConsistencyService.revalidateLoan(loanId);
            
            logger.info("重新验证贷款完成，贷款ID: {}, 验证状态: {}", loanId, validation.getValidationStatus());
            return success(validation);
            
        } catch (IllegalArgumentException e) {
            logger.warn("重新验证贷款参数错误，贷款ID: {}, 错误: {}", loanId, e.getMessage());
            return error(e.getMessage());
            
        } catch (Exception e) {
            logger.error("重新验证贷款失败，贷款ID: {}", loanId, e);
            return error("重新验证贷款失败: " + e.getMessage());
        }
    }

    /**
     * 后台批量验证触发
     * 实现后台批量验证触发API
     * 触发系统对所有贷款记录进行后台批量验证
     */
    @PreAuthorize("@ss.hasPermi('credit:financing:validate')")
    @Log(title = "贷款一致性验证", businessType = BusinessType.OTHER)
    @PostMapping("/validate-all")
    public AjaxResult validateAllLoansInBackground()
    {
        logger.info("触发后台批量验证所有贷款记录");
        
        try {
            Map<String, Object> result = loanConsistencyService.validateAllLoansInBackground();
            
            logger.info("后台批量验证触发成功，结果: {}", result);
            return success(result);
            
        } catch (Exception e) {
            logger.error("触发后台批量验证失败", e);
            return error("触发后台批量验证失败: " + e.getMessage());
        }
    }

    /**
     * 简化版批量验证 - 用于调试
     * 不依赖复杂的验证逻辑，直接返回基本统计信息
     */
    @PreAuthorize("@ss.hasPermi('credit:financing:batch-validate')")
    @Log(title = "贷款一致性验证", businessType = BusinessType.OTHER)
    @PostMapping("/validate-all-simple")
    public AjaxResult validateAllLoansSimple()
    {
        logger.info("触发简化版后台批量验证");
        
        try {
            Map<String, Object> result = new HashMap<>();
            
            // 获取基本统计信息
            List<Long> loansWithCredit = loanConsistencyService.getLoansWithCreditCertificates();
            int totalCount = loansWithCredit.size();
            
            if (totalCount == 0) {
                result.put("totalCount", 0);
                result.put("successCount", 0);
                result.put("failureCount", 0);
                result.put("message", "没有找到需要验证的贷款记录");
                result.put("debugInfo", "请检查数据库中的贷款、债权、服务周期和合同数据");
            } else {
                // 如果找到了贷款，尝试进行简单验证
                int successCount = 0;
                int failureCount = 0;
                
                for (Long loanId : loansWithCredit) {
                    try {
                        // 简单验证：只检查贷款是否存在相关联的债权信息
                        LoanConsistencyValidation validation = loanConsistencyService.validateLoanConsistency(loanId, null, null);
                        if (validation != null && validation.isPassed()) {
                            successCount++;
                        } else {
                            failureCount++;
                        }
                    } catch (Exception e) {
                        logger.warn("验证贷款{}时出现异常: {}", loanId, e.getMessage());
                        failureCount++;
                    }
                }
                
                result.put("totalCount", totalCount);
                result.put("successCount", successCount);
                result.put("failureCount", failureCount);
                result.put("message", "简化版批量验证完成");
                result.put("loanIds", loansWithCredit);
            }
            
            logger.info("简化版后台批量验证完成，结果: {}", result);
            return success(result);
            
        } catch (Exception e) {
            logger.error("简化版后台批量验证失败", e);
            return error("简化版后台批量验证失败: " + e.getMessage());
        }
    }

    /**
     * 获取贷款验证历史记录
     * 查询指定贷款的所有验证历史记录
     */
    @PreAuthorize("@ss.hasPermi('credit:financing:query')")
    @GetMapping("/history/{loanId}")
    public AjaxResult getLoanValidationHistory(@PathVariable("loanId") Long loanId)
    {
        logger.info("获取贷款验证历史记录，贷款ID: {}", loanId);
        
        if (loanId == null) {
            return error("贷款ID不能为空");
        }

        try {
            List<LoanConsistencyValidation> history = loanConsistencyService.getLoanValidationHistory(loanId);
            
            logger.info("获取贷款验证历史记录成功，贷款ID: {}, 记录数量: {}", loanId, history.size());
            return success(history);
            
        } catch (IllegalArgumentException e) {
            logger.warn("获取贷款验证历史记录参数错误，贷款ID: {}, 错误: {}", loanId, e.getMessage());
            return error(e.getMessage());
            
        } catch (Exception e) {
            logger.error("获取贷款验证历史记录失败，贷款ID: {}", loanId, e);
            return error("获取贷款验证历史记录失败: " + e.getMessage());
        }
    }

    /**
     * 获取验证统计信息
     * 查询指定时间范围内的验证统计信息
     */
    @PreAuthorize("@ss.hasPermi('credit:financing:query')")
    @GetMapping("/statistics")
    public AjaxResult getValidationStatistics(
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate)
    {
        logger.info("获取验证统计信息，开始日期: {}, 结束日期: {}", startDate, endDate);
        
        try {
            Map<String, Object> statistics = loanConsistencyService.getValidationStatistics(startDate, endDate);
            
            logger.info("获取验证统计信息成功");
            return success(statistics);
            
        } catch (Exception e) {
            logger.error("获取验证统计信息失败", e);
            return error("获取验证统计信息失败: " + e.getMessage());
        }
    }

    /**
     * 检查是否需要重新验证
     * 检查指定贷款是否需要重新验证
     */
    @PreAuthorize("@ss.hasPermi('credit:financing:query')")
    @GetMapping("/needs-revalidation/{loanId}")
    public AjaxResult needsRevalidation(@PathVariable("loanId") Long loanId)
    {
        logger.info("检查是否需要重新验证，贷款ID: {}", loanId);
        
        if (loanId == null) {
            return error("贷款ID不能为空");
        }

        try {
            boolean needsRevalidation = loanConsistencyService.needsRevalidation(loanId);
            
            logger.info("检查是否需要重新验证完成，贷款ID: {}, 需要重新验证: {}", loanId, needsRevalidation);
            return success(needsRevalidation);
            
        } catch (Exception e) {
            logger.error("检查是否需要重新验证失败，贷款ID: {}", loanId, e);
            return error("检查是否需要重新验证失败: " + e.getMessage());
        }
    }

    /**
     * 获取验证失败的贷款列表
     * 查询所有验证失败的贷款ID列表
     */
    @PreAuthorize("@ss.hasPermi('credit:financing:query')")
    @GetMapping("/failed-loans")
    public AjaxResult getFailedValidationLoans()
    {
        logger.info("获取验证失败的贷款列表");
        
        try {
            List<Long> failedLoanIds = loanConsistencyService.getFailedValidationLoans();
            
            logger.info("获取验证失败的贷款列表成功，数量: {}", failedLoanIds.size());
            return success(failedLoanIds);
            
        } catch (Exception e) {
            logger.error("获取验证失败的贷款列表失败", e);
            return error("获取验证失败的贷款列表失败: " + e.getMessage());
        }
    }

    /**
     * 批量重新验证贷款
     * 支持批量触发多个贷款记录的重新验证
     */
    @PreAuthorize("@ss.hasPermi('credit:financing:revalidate')")
    @Log(title = "贷款一致性验证", businessType = BusinessType.UPDATE)
    @PutMapping("/batch-revalidate")
    public AjaxResult batchRevalidateLoans(@RequestBody Map<String, Object> requestData)
    {
        logger.info("开始批量重新验证贷款，请求数据: {}", requestData);
        
        try {
            @SuppressWarnings("unchecked")
            List<Long> loanIds = (List<Long>) requestData.get("loanIds");
            String reason = (String) requestData.get("reason");
            
            if (loanIds == null || loanIds.isEmpty()) {
                return error("贷款ID列表不能为空");
            }
            
            if (reason == null || reason.trim().isEmpty()) {
                reason = "批量重新验证请求";
            }

            Map<String, Object> result = loanConsistencyService.batchTriggerRevalidation(loanIds, reason);
            
            logger.info("批量重新验证贷款完成，结果: {}", result);
            return success(result);
            
        } catch (ClassCastException e) {
            logger.warn("批量重新验证贷款参数格式错误: {}", e.getMessage());
            return error("请求参数格式错误，请检查loanIds和reason字段");
            
        } catch (Exception e) {
            logger.error("批量重新验证贷款失败", e);
            return error("批量重新验证贷款失败: " + e.getMessage());
        }
    }

    /**
     * 验证单个贷款记录
     * 手动触发单个贷款记录的完整验证流程
     */
    @PreAuthorize("@ss.hasPermi('credit:financing:validate')")
    @Log(title = "贷款一致性验证", businessType = BusinessType.OTHER)
    @PostMapping("/validate/{loanId}")
    public AjaxResult validateLoanConsistency(
            @PathVariable("loanId") Long loanId,
            @RequestParam(required = false) Long creditId,
            @RequestParam(required = false) Long servicePeriodId)
    {
        logger.info("验证单个贷款记录，贷款ID: {}, 债权凭证ID: {}, 服务周期ID: {}", loanId, creditId, servicePeriodId);
        
        if (loanId == null) {
            return error("贷款ID不能为空");
        }

        try {
            LoanConsistencyValidation validation = loanConsistencyService.validateLoanConsistency(loanId, creditId, servicePeriodId);
            
            logger.info("验证单个贷款记录完成，贷款ID: {}, 验证状态: {}", loanId, validation.getValidationStatus());
            return success(validation);
            
        } catch (IllegalArgumentException e) {
            logger.warn("验证单个贷款记录参数错误，贷款ID: {}, 错误: {}", loanId, e.getMessage());
            return error(e.getMessage());
            
        } catch (Exception e) {
            logger.error("验证单个贷款记录失败，贷款ID: {}", loanId, e);
            return error("验证单个贷款记录失败: " + e.getMessage());
        }
    }

    /**
     * 批量验证贷款记录
     * 批量验证多个贷款记录的一致性
     */
    @PreAuthorize("@ss.hasPermi('credit:financing:validate')")
    @Log(title = "贷款一致性验证", businessType = BusinessType.OTHER)
    @PostMapping("/batch-validate")
    public AjaxResult batchValidateLoans(@RequestBody List<Long> loanIds)
    {
        logger.info("批量验证贷款记录，贷款数量: {}", loanIds != null ? loanIds.size() : 0);
        
        if (loanIds == null || loanIds.isEmpty()) {
            return error("贷款ID列表不能为空");
        }

        try {
            List<LoanConsistencyValidation> validations = loanConsistencyService.batchValidateLoans(loanIds);
            
            long successCount = validations.stream().filter(LoanConsistencyValidation::isPassed).count();
            long failureCount = validations.stream().filter(LoanConsistencyValidation::isFailed).count();
            
            logger.info("批量验证贷款记录完成，总数: {}, 成功: {}, 失败: {}", 
                validations.size(), successCount, failureCount);
            
            return success(validations);
            
        } catch (Exception e) {
            logger.error("批量验证贷款记录失败", e);
            return error("批量验证贷款记录失败: " + e.getMessage());
        }
    }

    /**
     * 清理过期验证记录
     * 清理指定天数之前的过期验证记录
     */
    @PreAuthorize("@ss.hasPermi('credit:financing:remove')")
    @Log(title = "贷款一致性验证", businessType = BusinessType.DELETE)
    @PostMapping("/cleanup")
    public AjaxResult cleanupExpiredValidations(@RequestParam("daysToKeep") Integer daysToKeep)
    {
        logger.info("清理过期验证记录，保留天数: {}", daysToKeep);
        
        if (daysToKeep == null || daysToKeep <= 0) {
            return error("保留天数必须大于0");
        }

        try {
            int deletedCount = loanConsistencyService.cleanupExpiredValidations(daysToKeep);
            
            logger.info("清理过期验证记录完成，删除记录数: {}", deletedCount);
            return success("清理完成，删除记录数: " + deletedCount);
            
        } catch (IllegalArgumentException e) {
            logger.warn("清理过期验证记录参数错误: {}", e.getMessage());
            return error(e.getMessage());
            
        } catch (Exception e) {
            logger.error("清理过期验证记录失败", e);
            return error("清理过期验证记录失败: " + e.getMessage());
        }
    }

    /**
     * 获取后台验证状态
     * 查询后台自动验证机制的运行状态
     */
    @PreAuthorize("@ss.hasPermi('credit:financing:query')")
    @GetMapping("/background-status")
    public AjaxResult getBackgroundValidationStatus()
    {
        logger.info("获取后台验证状态");
        
        try {
            Map<String, Object> status = loanConsistencyService.getBackgroundValidationStatus();
            
            logger.info("获取后台验证状态成功");
            return success(status);
            
        } catch (Exception e) {
            logger.error("获取后台验证状态失败", e);
            return error("获取后台验证状态失败: " + e.getMessage());
        }
    }

    /**
     * 调试接口：获取验证数据详情
     * 用于排查验证数据问题
     */
    @PreAuthorize("@ss.hasPermi('credit:financing:query')")
    @GetMapping("/debug-info")
    public AjaxResult getDebugInfo()
    {
        logger.info("获取验证调试信息");
        
        try {
            Map<String, Object> debugInfo = new HashMap<>();
            
            // 获取需要验证的贷款总数
            List<Long> loansWithCredit = loanConsistencyService.getLoansWithCreditCertificates();
            debugInfo.put("totalLoansWithCredit", loansWithCredit.size());
            debugInfo.put("loansWithCreditIds", loansWithCredit);
            
            // 获取通过验证的贷款数量
            List<Long> validatedLoans = loanConsistencyService.getValidatedLoanList(null);
            debugInfo.put("validatedLoansCount", validatedLoans.size());
            debugInfo.put("validatedLoanIds", validatedLoans);
            
            // 获取失败验证的贷款数量
            List<Long> failedLoans = loanConsistencyService.getFailedValidationLoans();
            debugInfo.put("failedLoansCount", failedLoans.size());
            debugInfo.put("failedLoanIds", failedLoans);
            
            // 获取验证统计信息
            Map<String, Object> statistics = loanConsistencyService.getValidationStatistics(null, null);
            debugInfo.put("statistics", statistics);
            
            logger.info("获取验证调试信息成功");
            return success(debugInfo);
            
        } catch (Exception e) {
            logger.error("获取验证调试信息失败", e);
            return error("获取验证调试信息失败: " + e.getMessage());
        }
    }

    /**
     * 调试接口：获取数据库表数据统计
     * 用于排查数据库数据问题
     */
    @PreAuthorize("@ss.hasPermi('credit:financing:list')")
    @GetMapping("/debug-tables")
    public AjaxResult getDebugTablesInfo()
    {
        logger.info("获取数据库表调试信息");
        
        try {
            Map<String, Object> debugInfo = new HashMap<>();
            
            // 直接查询各个表的数据统计
            debugInfo.put("totalLoans", loanConsistencyService.countAllLoans());
            debugInfo.put("totalCredits", loanConsistencyService.countAllCredits());
            debugInfo.put("totalServicePeriods", loanConsistencyService.countAllServicePeriods());
            debugInfo.put("totalContracts", loanConsistencyService.countAllContracts());
            debugInfo.put("message", "数据库表统计信息");
            
            logger.info("获取数据库表调试信息成功");
            return success(debugInfo);
            
        } catch (Exception e) {
            logger.error("获取数据库表调试信息失败", e);
            return error("获取数据库表调试信息失败: " + e.getMessage());
        }
    }

    /**
     * 调试接口：获取贷款查询结果对比
     * 用于排查查询条件问题
     */
    @PreAuthorize("@ss.hasPermi('credit:financing:list')")
    @GetMapping("/debug-loans")
    public AjaxResult getDebugLoansInfo()
    {
        logger.info("获取贷款查询调试信息");
        
        try {
            Map<String, Object> debugInfo = new HashMap<>();
            
            // 获取严格条件下的贷款
            List<Long> strictLoans = loanConsistencyService.getLoansWithCreditCertificates();
            debugInfo.put("strictConditionLoans", strictLoans);
            debugInfo.put("strictConditionCount", strictLoans.size());
            
            // 获取宽松条件下的贷款
            List<Long> allLoans = loanConsistencyService.getAllLoansWithAnyCredit();
            debugInfo.put("allLoansWithCredit", allLoans);
            debugInfo.put("allLoansWithCreditCount", allLoans.size());
            
            debugInfo.put("message", "贷款查询条件对比");
            
            logger.info("获取贷款查询调试信息成功");
            return success(debugInfo);
            
        } catch (Exception e) {
            logger.error("获取贷款查询调试信息失败", e);
            return error("获取贷款查询调试信息失败: " + e.getMessage());
        }
    }

    /**
     * 手动触发融资申请创建（调试用）
     * 用于测试验证通过后的融资申请创建逻辑
     */
    @PreAuthorize("@ss.hasPermi('credit:financing:validate')")
    @PostMapping("/debug/create-financing/{loanId}")
    public AjaxResult debugCreateFinancing(@PathVariable("loanId") Long loanId)
    {
        logger.info("手动触发融资申请创建，贷款ID: {}", loanId);
        
        if (loanId == null) {
            return error("贷款ID不能为空");
        }

        try {
            // 首先验证贷款
            LoanConsistencyValidation validation = loanConsistencyService.validateLoanConsistency(loanId, null, null);
            
            Map<String, Object> result = new HashMap<>();
            result.put("validation", validation);
            result.put("validationPassed", validation.isPassed());
            
            // 如果验证通过，尝试创建融资申请
            if (validation.isPassed()) {
                logger.info("验证通过，尝试创建融资申请，贷款ID: {}", loanId);
                result.put("message", "验证通过，融资申请应该已自动创建");
            } else {
                logger.warn("验证未通过，无法创建融资申请，贷款ID: {}, 失败原因: {}", 
                        loanId, validation.getFailureReason());
                result.put("message", "验证未通过: " + validation.getFailureReason());
            }
            
            return success(result);
            
        } catch (Exception e) {
            logger.error("手动触发融资申请创建失败，贷款ID: {}", loanId, e);
            return error("操作失败: " + e.getMessage());
        }
    }

    /**
     * 启动后台验证
     * 手动启动后台自动验证机制
     */
    @PreAuthorize("@ss.hasPermi('credit:financing:control')")
    @Log(title = "贷款一致性验证", businessType = BusinessType.OTHER)
    @PostMapping("/background/start")
    public AjaxResult startBackgroundValidation()
    {
        logger.info("启动后台验证机制");
        
        try {
            Map<String, Object> result = loanConsistencyService.startBackgroundValidation();
            
            logger.info("启动后台验证机制完成，结果: {}", result);
            return success(result);
            
        } catch (Exception e) {
            logger.error("启动后台验证机制失败", e);
            return error("启动后台验证机制失败: " + e.getMessage());
        }
    }

    /**
     * 停止后台验证
     * 手动停止后台自动验证机制
     */
    @PreAuthorize("@ss.hasPermi('credit:financing:control')")
    @Log(title = "贷款一致性验证", businessType = BusinessType.OTHER)
    @PostMapping("/background/stop")
    public AjaxResult stopBackgroundValidation()
    {
        logger.info("停止后台验证机制");
        
        try {
            Map<String, Object> result = loanConsistencyService.stopBackgroundValidation();
            
            logger.info("停止后台验证机制完成，结果: {}", result);
            return success(result);
            
        } catch (Exception e) {
            logger.error("停止后台验证机制失败", e);
            return error("停止后台验证机制失败: " + e.getMessage());
        }
    }
}