package com.ruoyi.credit.controller;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
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.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.monitor.ValidationPerformanceMonitor;
import com.ruoyi.credit.service.AsyncValidationService;
import com.ruoyi.credit.strategy.PerformanceDegradationStrategy;

/**
 * 验证性能监控控制器
 * 
 * @author ruoyi
 * @date 2025-12-31
 */
@RestController
@RequestMapping("/api/credit/validation-performance")
public class ValidationPerformanceController extends BaseController {

    @Autowired
    private ValidationPerformanceMonitor performanceMonitor;

    @Autowired
    private PerformanceDegradationStrategy degradationStrategy;

    @Autowired
    private AsyncValidationService asyncValidationService;

    /**
     * 获取性能统计信息
     */
    @GetMapping("/statistics")
    public AjaxResult getPerformanceStatistics() {
        Map<String, Object> statistics = performanceMonitor.getPerformanceStatistics();
        return success(statistics);
    }

    /**
     * 重置性能统计
     */
    @DeleteMapping("/statistics")
    @Log(title = "验证性能监控", businessType = BusinessType.DELETE)
    public AjaxResult resetPerformanceStatistics() {
        performanceMonitor.resetPerformanceStatistics();
        return success("性能统计数据已重置");
    }

    /**
     * 获取降级策略状态
     */
    @GetMapping("/degradation/status")
    public AjaxResult getDegradationStatus() {
        Map<String, Object> status = degradationStrategy.getDegradationStatus();
        return success(status);
    }

    /**
     * 手动启用降级策略
     */
    @PostMapping("/degradation/enable")
    @Log(title = "验证性能监控", businessType = BusinessType.UPDATE)
    public AjaxResult enableDegradation(@RequestParam String level) {
        try {
            PerformanceDegradationStrategy.DegradationLevel degradationLevel = 
                PerformanceDegradationStrategy.DegradationLevel.valueOf(level.toUpperCase());
            
            boolean success = degradationStrategy.enableDegradationManually(degradationLevel);
            
            if (success) {
                return success("降级策略已启用，级别: " + degradationLevel.getDescription());
            } else {
                return error("启用降级策略失败");
            }
        } catch (IllegalArgumentException e) {
            return error("无效的降级级别: " + level);
        }
    }

    /**
     * 手动禁用降级策略
     */
    @PostMapping("/degradation/disable")
    @Log(title = "验证性能监控", businessType = BusinessType.UPDATE)
    public AjaxResult disableDegradation() {
        boolean success = degradationStrategy.disableDegradationManually();
        
        if (success) {
            return success("降级策略已禁用");
        } else {
            return error("禁用降级策略失败");
        }
    }

    /**
     * 检查是否应该启用异步验证模式
     */
    @GetMapping("/async/should-enable")
    public AjaxResult shouldEnableAsyncValidation() {
        boolean shouldEnable = performanceMonitor.shouldEnableAsyncValidation();
        AjaxResult result = success();
        result.put("shouldEnableAsyncValidation", shouldEnable);
        return result;
    }

    /**
     * 获取异步验证服务状态
     */
    @GetMapping("/async/status")
    public AjaxResult getAsyncValidationServiceStatus() {
        Map<String, Object> status = asyncValidationService.getAsyncValidationServiceStatus();
        return success(status);
    }

    /**
     * 获取异步验证任务状态
     */
    @GetMapping("/async/task/{taskId}")
    public AjaxResult getAsyncValidationTaskStatus(@PathVariable String taskId) {
        Map<String, Object> status = asyncValidationService.getAsyncValidationTaskStatus(taskId);
        return success(status);
    }

    /**
     * 取消异步验证任务
     */
    @DeleteMapping("/async/task/{taskId}")
    @Log(title = "验证性能监控", businessType = BusinessType.DELETE)
    public AjaxResult cancelAsyncValidationTask(@PathVariable String taskId) {
        boolean success = asyncValidationService.cancelAsyncValidationTask(taskId);
        
        if (success) {
            return success("异步验证任务已取消");
        } else {
            return error("取消异步验证任务失败");
        }
    }

    /**
     * 获取系统性能概览
     */
    @GetMapping("/overview")
    public AjaxResult getPerformanceOverview() {
        Map<String, Object> performanceStats = performanceMonitor.getPerformanceStatistics();
        Map<String, Object> degradationStatus = degradationStrategy.getDegradationStatus();
        Map<String, Object> asyncStatus = asyncValidationService.getAsyncValidationServiceStatus();

        AjaxResult result = success();
        result.put("performanceStatistics", performanceStats);
        result.put("degradationStatus", degradationStatus);
        result.put("asyncValidationStatus", asyncStatus);
        
        return result;
    }
}