package com.ruoyi.framework.controller;

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.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.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.framework.domain.DepartmentDataPerformanceMetrics;
import com.ruoyi.framework.service.IDepartmentDataPerformanceService;

/**
 * 部门数据隔离性能监控Controller
 * 
 * @author ruoyi
 * @date 2025-01-12
 */
@RestController
@RequestMapping("/framework/performance")
public class DepartmentDataPerformanceController extends BaseController
{
    @Autowired
    private IDepartmentDataPerformanceService performanceService;

    /**
     * 查询性能监控指标列表
     */
    @PreAuthorize("@ss.hasPermi('framework:performance:list')")
    @GetMapping("/list")
    public TableDataInfo list(DepartmentDataPerformanceMetrics metrics)
    {
        startPage();
        List<DepartmentDataPerformanceMetrics> list = performanceService.selectPerformanceMetricsList(metrics);
        return getDataTable(list);
    }

    /**
     * 验证指定表的部门索引
     */
    @PreAuthorize("@ss.hasPermi('framework:performance:query')")
    @GetMapping("/index/verify/{tableName}")
    public AjaxResult verifyTableIndexes(@PathVariable("tableName") String tableName)
    {
        Map<String, Object> result = performanceService.verifyDepartmentIndexes(tableName);
        return success(result);
    }

    /**
     * 验证所有目标表的部门索引
     */
    @PreAuthorize("@ss.hasPermi('framework:performance:query')")
    @GetMapping("/index/verify-all")
    public AjaxResult verifyAllIndexes()
    {
        Map<String, Object> result = performanceService.verifyAllDepartmentIndexes();
        return success(result);
    }

    /**
     * 分析查询性能
     */
    @PreAuthorize("@ss.hasPermi('framework:performance:query')")
    @PostMapping("/analyze")
    public AjaxResult analyzeQueryPerformance(@RequestBody Map<String, String> request)
    {
        String sql = request.get("sql");
        String tableName = request.get("tableName");
        
        if (sql == null || sql.trim().isEmpty())
        {
            return error("SQL语句不能为空");
        }
        
        Map<String, Object> result = performanceService.analyzeQueryPerformance(sql, tableName);
        return success(result);
    }

    /**
     * 获取性能统计报告
     */
    @PreAuthorize("@ss.hasPermi('framework:performance:query')")
    @PostMapping("/statistics")
    public AjaxResult getPerformanceStatistics(@RequestBody(required = false) Map<String, Object> params)
    {
        if (params == null)
        {
            params = new java.util.HashMap<>();
        }
        
        Map<String, Object> result = performanceService.getPerformanceStatistics(params);
        return success(result);
    }

    /**
     * 获取慢查询列表
     */
    @PreAuthorize("@ss.hasPermi('framework:performance:query')")
    @GetMapping("/slow-queries")
    public AjaxResult getSlowQueries(@RequestParam(defaultValue = "1000") long thresholdMs,
                                   @RequestParam(defaultValue = "50") int limit)
    {
        List<DepartmentDataPerformanceMetrics> result = performanceService.getSlowQueries(thresholdMs, limit);
        return success(result);
    }

    /**
     * 获取索引使用率统计
     */
    @PreAuthorize("@ss.hasPermi('framework:performance:query')")
    @GetMapping("/index/usage")
    public AjaxResult getIndexUsageStatistics()
    {
        Map<String, Object> result = performanceService.getIndexUsageStatistics();
        return success(result);
    }

    /**
     * 检查性能告警
     */
    @PreAuthorize("@ss.hasPermi('framework:performance:query')")
    @GetMapping("/alerts")
    public AjaxResult checkPerformanceAlerts()
    {
        List<Map<String, Object>> result = performanceService.checkPerformanceAlerts();
        return success(result);
    }

    /**
     * 获取索引优化建议
     */
    @PreAuthorize("@ss.hasPermi('framework:performance:query')")
    @GetMapping("/suggestions/{tableName}")
    public AjaxResult getIndexOptimizationSuggestions(@PathVariable("tableName") String tableName)
    {
        List<Map<String, Object>> result = performanceService.getIndexOptimizationSuggestions(tableName);
        return success(result);
    }

    /**
     * 生成性能监控报告
     */
    @PreAuthorize("@ss.hasPermi('framework:performance:query')")
    @PostMapping("/report")
    public AjaxResult generatePerformanceReport(@RequestBody(required = false) Map<String, Object> params)
    {
        if (params == null)
        {
            params = new java.util.HashMap<>();
        }
        
        Map<String, Object> result = performanceService.generatePerformanceReport(params);
        return success(result);
    }

    /**
     * 启用性能监控
     */
    @PreAuthorize("@ss.hasPermi('framework:performance:edit')")
    @Log(title = "部门数据性能监控", businessType = BusinessType.UPDATE)
    @PostMapping("/enable")
    public AjaxResult enablePerformanceMonitoring()
    {
        performanceService.enablePerformanceMonitoring();
        return success("性能监控已启用");
    }

    /**
     * 禁用性能监控
     */
    @PreAuthorize("@ss.hasPermi('framework:performance:edit')")
    @Log(title = "部门数据性能监控", businessType = BusinessType.UPDATE)
    @PostMapping("/disable")
    public AjaxResult disablePerformanceMonitoring()
    {
        performanceService.disablePerformanceMonitoring();
        return success("性能监控已禁用");
    }

    /**
     * 获取性能监控状态
     */
    @PreAuthorize("@ss.hasPermi('framework:performance:query')")
    @GetMapping("/status")
    public AjaxResult getPerformanceMonitoringStatus()
    {
        boolean enabled = performanceService.isPerformanceMonitoringEnabled();
        return success(enabled);
    }

    /**
     * 清理过期的性能监控数据
     */
    @PreAuthorize("@ss.hasPermi('framework:performance:remove')")
    @Log(title = "部门数据性能监控", businessType = BusinessType.CLEAN)
    @PostMapping("/clean")
    public AjaxResult cleanExpiredPerformanceData(@RequestParam(defaultValue = "30") int retentionDays)
    {
        int deletedCount = performanceService.cleanExpiredPerformanceData(retentionDays);
        return success("已清理 " + deletedCount + " 条过期数据");
    }
}