package com.ruoyi.credit.controller;

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.ValidationCacheManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

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

/**
 * 验证缓存管理控制器
 * 
 * 提供验证结果缓存的管理API接口，包括缓存清除、刷新和状态查询功能
 * 支持单个和批量缓存操作，具备完整的权限控制机制
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/api/credit/validation-cache")
public class ValidationCacheController extends BaseController {

    @Autowired
    private ValidationCacheManager validationCacheManager;

    /**
     * 获取缓存的验证结果
     */
    @PreAuthorize("@ss.hasPermi('credit:validation:query')")
    @GetMapping("/{loanId}")
    public AjaxResult getCachedValidationResult(@PathVariable Long loanId) {
        
        LoanConsistencyValidation cachedResult = validationCacheManager.getCachedValidationResult(loanId);
        
        if (cachedResult != null) {
            return success(cachedResult);
        } else {
            return success("缓存中未找到该贷款的验证结果");
        }
    }

    /**
     * 清除指定贷款的验证缓存
     */
    @PreAuthorize("@ss.hasPermi('credit:validation:edit')")
    @Log(title = "验证缓存管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{loanId}")
    public AjaxResult invalidateCache(@PathVariable Long loanId) {
        
        validationCacheManager.invalidateCache(loanId);
        return success("已清除贷款 " + loanId + " 的验证缓存");
    }

    /**
     * 批量清除验证缓存
     */
    @PreAuthorize("@ss.hasPermi('credit:validation:edit')")
    @Log(title = "验证缓存管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/batch")
    public AjaxResult invalidateCacheBatch(@RequestBody List<Long> loanIds) {
        
        if (loanIds == null || loanIds.isEmpty()) {
            return error("贷款ID列表不能为空");
        }
        
        validationCacheManager.invalidateCacheBatch(loanIds);
        return success("已批量清除 " + loanIds.size() + " 个贷款的验证缓存");
    }

    /**
     * 清除所有验证缓存
     */
    @PreAuthorize("@ss.hasPermi('credit:validation:edit')")
    @Log(title = "验证缓存管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/all")
    public AjaxResult clearAllValidationCache() {
        
        validationCacheManager.clearAllValidationCache();
        return success("已清除所有验证缓存");
    }

    /**
     * 获取缓存状态信息
     */
    @PreAuthorize("@ss.hasPermi('credit:validation:query')")
    @GetMapping("/status/{loanId}")
    public AjaxResult getCacheStatus(@PathVariable Long loanId) {
        
        Map<String, Object> status = new HashMap<>();
        status.put("loanId", loanId);
        status.put("exists", validationCacheManager.isCacheExists(loanId));
        status.put("expireTime", validationCacheManager.getCacheExpireTime(loanId));
        
        // 如果缓存存在，获取缓存内容的基本信息
        if (validationCacheManager.isCacheExists(loanId)) {
            LoanConsistencyValidation cachedResult = validationCacheManager.getCachedValidationResult(loanId);
            if (cachedResult != null) {
                status.put("validationStatus", cachedResult.getValidationStatus());
                status.put("validationTime", cachedResult.getValidationTime());
            }
        }
        
        return success(status);
    }

    /**
     * 获取系统整体缓存状态
     */
    @PreAuthorize("@ss.hasPermi('credit:validation:query')")
    @GetMapping("/status")
    public AjaxResult getOverallCacheStatus() {
        
        Map<String, Object> overallStatus = new HashMap<>();
        
        try {
            // 这里可以添加获取整体缓存统计的逻辑
            // 由于ValidationCacheManager没有提供整体统计方法，我们提供基本信息
            overallStatus.put("cacheEnabled", true);
            overallStatus.put("cacheExpireMinutes", 5); // 从ValidationCacheManager中的常量获取
            overallStatus.put("message", "缓存服务正常运行");
            
            return success(overallStatus);
        } catch (Exception e) {
            overallStatus.put("cacheEnabled", false);
            overallStatus.put("message", "缓存服务异常: " + e.getMessage());
            return error("获取缓存状态失败");
        }
    }

    /**
     * 刷新缓存过期时间
     */
    @PreAuthorize("@ss.hasPermi('credit:validation:edit')")
    @Log(title = "验证缓存管理", businessType = BusinessType.UPDATE)
    @PutMapping("/refresh/{loanId}")
    public AjaxResult refreshCacheExpire(@PathVariable Long loanId) {
        
        if (!validationCacheManager.isCacheExists(loanId)) {
            return error("缓存中不存在该贷款的验证结果");
        }
        
        validationCacheManager.refreshCacheExpire(loanId);
        return success("已刷新贷款 " + loanId + " 的缓存过期时间");
    }

    /**
     * 批量刷新缓存过期时间
     */
    @PreAuthorize("@ss.hasPermi('credit:validation:edit')")
    @Log(title = "验证缓存管理", businessType = BusinessType.UPDATE)
    @PutMapping("/refresh/batch")
    public AjaxResult refreshCacheExpireBatch(@RequestBody List<Long> loanIds) {
        
        if (loanIds == null || loanIds.isEmpty()) {
            return error("贷款ID列表不能为空");
        }
        
        int refreshedCount = 0;
        for (Long loanId : loanIds) {
            if (validationCacheManager.isCacheExists(loanId)) {
                validationCacheManager.refreshCacheExpire(loanId);
                refreshedCount++;
            }
        }
        
        return success("已刷新 " + refreshedCount + " 个贷款的缓存过期时间");
    }

    /**
     * 预加载验证缓存
     * 
     * 注意：此接口主要用于系统内部调用，需要管理员权限
     */
    @PreAuthorize("@ss.hasPermi('credit:validation:admin')")
    @Log(title = "验证缓存管理", businessType = BusinessType.UPDATE)
    @PostMapping("/preload")
    public AjaxResult preloadValidationCache(@RequestBody List<LoanConsistencyValidation> validations) {
        
        if (validations == null || validations.isEmpty()) {
            return error("验证结果列表不能为空");
        }
        
        validationCacheManager.preloadValidationCache(validations);
        return success("已预加载 " + validations.size() + " 个验证结果到缓存");
    }
}