package com.ruoyi.framework.util;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ruoyi.framework.service.IDepartmentDataPerformanceService;
import com.ruoyi.framework.service.impl.DepartmentDataPerformanceServiceImpl;

/**
 * 部门数据隔离性能监控验证工具
 * 
 * @author ruoyi
 * @date 2025-01-12
 */
public class DepartmentDataPerformanceVerification
{
    private static final Logger log = LoggerFactory.getLogger(DepartmentDataPerformanceVerification.class);

    /**
     * 验证性能监控功能
     */
    public static void verifyPerformanceMonitoring()
    {
        log.info("开始验证部门数据隔离性能监控功能...");
        
        try
        {
            // 创建性能监控服务实例
            IDepartmentDataPerformanceService performanceService = new DepartmentDataPerformanceServiceImpl();
            
            // 1. 验证所有部门索引
            log.info("1. 验证所有部门索引...");
            Map<String, Object> indexResult = performanceService.verifyAllDepartmentIndexes();
            log.info("索引验证结果: {}", indexResult);
            
            // 2. 获取性能统计
            log.info("2. 获取性能统计...");
            Map<String, Object> statsResult = performanceService.getPerformanceStatistics(null);
            log.info("性能统计结果: {}", statsResult);
            
            // 3. 检查性能告警
            log.info("3. 检查性能告警...");
            java.util.List<Map<String, Object>> alerts = performanceService.checkPerformanceAlerts();
            log.info("性能告警数量: {}", alerts.size());
            for (Map<String, Object> alert : alerts)
            {
                log.info("告警: {}", alert);
            }
            
            // 4. 获取索引使用统计
            log.info("4. 获取索引使用统计...");
            Map<String, Object> indexUsage = performanceService.getIndexUsageStatistics();
            log.info("索引使用统计: {}", indexUsage);
            
            // 5. 测试性能监控开关
            log.info("5. 测试性能监控开关...");
            boolean initialState = performanceService.isPerformanceMonitoringEnabled();
            log.info("初始监控状态: {}", initialState);
            
            performanceService.disablePerformanceMonitoring();
            log.info("禁用后监控状态: {}", performanceService.isPerformanceMonitoringEnabled());
            
            performanceService.enablePerformanceMonitoring();
            log.info("启用后监控状态: {}", performanceService.isPerformanceMonitoringEnabled());
            
            // 6. 生成性能报告
            log.info("6. 生成性能报告...");
            Map<String, Object> report = performanceService.generatePerformanceReport(null);
            log.info("性能报告生成完成，包含 {} 个部分", report.size());
            
            log.info("部门数据隔离性能监控功能验证完成！");
        }
        catch (Exception e)
        {
            log.error("验证性能监控功能时发生异常", e);
        }
    }

    /**
     * 验证单个表的索引
     * 
     * @param tableName 表名
     */
    public static void verifyTableIndexes(String tableName)
    {
        log.info("开始验证表 {} 的部门索引...", tableName);
        
        try
        {
            IDepartmentDataPerformanceService performanceService = new DepartmentDataPerformanceServiceImpl();
            
            Map<String, Object> result = performanceService.verifyDepartmentIndexes(tableName);
            
            log.info("表 {} 索引验证结果:", tableName);
            log.info("  状态: {}", result.get("status"));
            log.info("  消息: {}", result.get("message"));
            log.info("  总索引数: {}", result.get("totalIndexes"));
            log.info("  存在索引数: {}", result.get("existingIndexes"));
            
            if (result.get("indexDetails") != null)
            {
                @SuppressWarnings("unchecked")
                java.util.List<Map<String, Object>> indexDetails = 
                    (java.util.List<Map<String, Object>>) result.get("indexDetails");
                
                for (Map<String, Object> indexInfo : indexDetails)
                {
                    log.info("  索引 {}: 存在={}", 
                        indexInfo.get("indexName"), 
                        indexInfo.get("exists"));
                }
            }
        }
        catch (Exception e)
        {
            log.error("验证表 {} 索引时发生异常", tableName, e);
        }
    }

    /**
     * 获取索引优化建议
     * 
     * @param tableName 表名
     */
    public static void getOptimizationSuggestions(String tableName)
    {
        log.info("获取表 {} 的索引优化建议...", tableName);
        
        try
        {
            IDepartmentDataPerformanceService performanceService = new DepartmentDataPerformanceServiceImpl();
            
            java.util.List<Map<String, Object>> suggestions = 
                performanceService.getIndexOptimizationSuggestions(tableName);
            
            if (suggestions.isEmpty())
            {
                log.info("表 {} 无需优化", tableName);
            }
            else
            {
                log.info("表 {} 的优化建议:", tableName);
                for (int i = 0; i < suggestions.size(); i++)
                {
                    Map<String, Object> suggestion = suggestions.get(i);
                    log.info("  建议 {}: {}", i + 1, suggestion.get("description"));
                    log.info("    类型: {}", suggestion.get("type"));
                    log.info("    优先级: {}", suggestion.get("priority"));
                    
                    if (suggestion.get("sqlCommand") != null)
                    {
                        log.info("    SQL命令: {}", suggestion.get("sqlCommand"));
                    }
                }
            }
        }
        catch (Exception e)
        {
            log.error("获取表 {} 优化建议时发生异常", tableName, e);
        }
    }

    /**
     * 主方法，用于手动测试
     */
    public static void main(String[] args)
    {
        System.out.println("=== 部门数据隔离性能监控验证 ===");
        
        // 验证整体功能
        verifyPerformanceMonitoring();
        
        System.out.println("\n=== 验证各个表的索引 ===");
        
        // 验证各个表的索引
        String[] tables = {
            "dc_contract",
            "dc_service_period", 
            "dc_employee_info",
            "dc_employee_library",
            "dc_credit",
            "dc_bank_institution"
        };
        
        for (String table : tables)
        {
            verifyTableIndexes(table);
            getOptimizationSuggestions(table);
            System.out.println();
        }
        
        System.out.println("=== 验证完成 ===");
    }
}