package com.ruoyi.framework.service.impl;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ruoyi.framework.config.DepartmentDataConfig;
import com.ruoyi.framework.domain.DepartmentDataPerformanceMetrics;
import com.ruoyi.framework.service.IDepartmentDataPerformanceService;

/**
 * 部门数据隔离性能监控Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-01-12
 */
@Service
public class DepartmentDataPerformanceServiceImpl implements IDepartmentDataPerformanceService
{
    private static final Logger log = LoggerFactory.getLogger(DepartmentDataPerformanceServiceImpl.class);

    @Autowired
    private DataSource dataSource;

    @Autowired
    private DepartmentDataConfig config;

    /**
     * 性能监控开关
     */
    private final AtomicBoolean performanceMonitoringEnabled = new AtomicBoolean(true);

    /**
     * 性能指标缓存
     */
    private final Map<String, AtomicLong> performanceCounters = new ConcurrentHashMap<>();

    /**
     * 目标表集合
     */
    private static final Set<String> TARGET_TABLES = new HashSet<>(Arrays.asList(
        "dc_contract",
        "dc_service_period", 
        "dc_employee_info",
        "dc_employee_library",
        "dc_credit",
        "dc_bank_institution"
    ));

    /**
     * 预期的部门索引名称
     */
    private static final Map<String, List<String>> EXPECTED_INDEXES = new HashMap<>();
    
    static {
        EXPECTED_INDEXES.put("dc_contract", Arrays.asList("idx_contract_dept_id", "idx_contract_dept_status"));
        EXPECTED_INDEXES.put("dc_service_period", Arrays.asList("idx_service_period_dept_id", "idx_service_period_dept_status"));
        EXPECTED_INDEXES.put("dc_employee_info", Arrays.asList("idx_employee_dept_id", "idx_employee_dept_status"));
        EXPECTED_INDEXES.put("dc_employee_library", Arrays.asList("idx_employee_library_dept_id", "idx_employee_library_dept_status"));
        EXPECTED_INDEXES.put("dc_credit", Arrays.asList("idx_credit_dept_id", "idx_credit_dept_status"));
        EXPECTED_INDEXES.put("dc_bank_institution", Arrays.asList("idx_bank_dept_id", "idx_bank_dept_status"));
    }

    @Override
    public int recordPerformanceMetrics(DepartmentDataPerformanceMetrics metrics)
    {
        if (!performanceMonitoringEnabled.get())
        {
            return 0;
        }

        try
        {
            // 设置性能等级
            setPerformanceLevel(metrics);
            
            // 设置告警标识
            setAlertFlag(metrics);
            
            // 这里应该保存到数据库，但由于没有对应的Mapper，我们先记录到日志
            log.info("性能监控指标记录: 表={}, 操作={}, 执行时间={}ms, 使用索引={}, 扫描行数={}, 返回行数={}", 
                metrics.getTableName(), 
                metrics.getOperationType(), 
                metrics.getExecutionTime(), 
                metrics.getUsedDeptIndex(), 
                metrics.getRowsScanned(), 
                metrics.getRowsReturned());
            
            // 更新性能计数器
            updatePerformanceCounters(metrics);
            
            return 1;
        }
        catch (Exception e)
        {
            log.error("记录性能监控指标失败", e);
            return 0;
        }
    }

    @Override
    public List<DepartmentDataPerformanceMetrics> selectPerformanceMetricsList(DepartmentDataPerformanceMetrics metrics)
    {
        // 由于没有对应的Mapper，返回空列表
        // 在实际项目中，这里应该调用Mapper查询数据库
        return new ArrayList<>();
    }

    @Override
    public Map<String, Object> verifyDepartmentIndexes(String tableName)
    {
        Map<String, Object> result = new HashMap<>();
        result.put("tableName", tableName);
        result.put("checkTime", new Date());
        
        if (!TARGET_TABLES.contains(tableName))
        {
            result.put("status", "SKIP");
            result.put("message", "表不在部门隔离范围内");
            return result;
        }

        try (Connection conn = dataSource.getConnection())
        {
            List<String> expectedIndexes = EXPECTED_INDEXES.get(tableName);
            List<Map<String, Object>> indexDetails = new ArrayList<>();
            boolean allIndexesExist = true;

            for (String indexName : expectedIndexes)
            {
                Map<String, Object> indexInfo = checkIndexExists(conn, tableName, indexName);
                indexDetails.add(indexInfo);
                
                if (!(Boolean) indexInfo.get("exists"))
                {
                    allIndexesExist = false;
                }
            }

            result.put("status", allIndexesExist ? "PASS" : "FAIL");
            result.put("indexDetails", indexDetails);
            result.put("totalIndexes", expectedIndexes.size());
            result.put("existingIndexes", indexDetails.stream().mapToInt(idx -> (Boolean) idx.get("exists") ? 1 : 0).sum());
            
            if (allIndexesExist)
            {
                result.put("message", "所有部门索引都已正确创建");
            }
            else
            {
                result.put("message", "部分部门索引缺失，可能影响查询性能");
            }
        }
        catch (SQLException e)
        {
            log.error("验证表 {} 的部门索引时发生异常", tableName, e);
            result.put("status", "ERROR");
            result.put("message", "验证索引时发生异常: " + e.getMessage());
        }

        return result;
    }

    @Override
    public Map<String, Object> verifyAllDepartmentIndexes()
    {
        Map<String, Object> result = new HashMap<>();
        result.put("checkTime", new Date());
        
        List<Map<String, Object>> tableResults = new ArrayList<>();
        int totalTables = TARGET_TABLES.size();
        int passedTables = 0;

        for (String tableName : TARGET_TABLES)
        {
            Map<String, Object> tableResult = verifyDepartmentIndexes(tableName);
            tableResults.add(tableResult);
            
            if ("PASS".equals(tableResult.get("status")))
            {
                passedTables++;
            }
        }

        result.put("tableResults", tableResults);
        result.put("totalTables", totalTables);
        result.put("passedTables", passedTables);
        result.put("overallStatus", passedTables == totalTables ? "PASS" : "FAIL");
        
        if (passedTables == totalTables)
        {
            result.put("message", "所有目标表的部门索引都已正确创建");
        }
        else
        {
            result.put("message", String.format("有 %d 个表的部门索引存在问题，需要检查", totalTables - passedTables));
        }

        return result;
    }

    @Override
    public Map<String, Object> analyzeQueryPerformance(String sql, String tableName)
    {
        Map<String, Object> result = new HashMap<>();
        result.put("sql", sql);
        result.put("tableName", tableName);
        result.put("analyzeTime", new Date());

        try (Connection conn = dataSource.getConnection())
        {
            // 使用 EXPLAIN 分析查询计划
            String explainSql = "EXPLAIN " + sql;
            
            try (PreparedStatement stmt = conn.prepareStatement(explainSql);
                 ResultSet rs = stmt.executeQuery())
            {
                List<Map<String, Object>> queryPlan = new ArrayList<>();
                
                while (rs.next())
                {
                    Map<String, Object> planRow = new HashMap<>();
                    planRow.put("id", rs.getObject("id"));
                    planRow.put("select_type", rs.getString("select_type"));
                    planRow.put("table", rs.getString("table"));
                    planRow.put("type", rs.getString("type"));
                    planRow.put("possible_keys", rs.getString("possible_keys"));
                    planRow.put("key", rs.getString("key"));
                    planRow.put("key_len", rs.getString("key_len"));
                    planRow.put("ref", rs.getString("ref"));
                    planRow.put("rows", rs.getObject("rows"));
                    planRow.put("extra", rs.getString("Extra"));
                    
                    queryPlan.add(planRow);
                }
                
                result.put("queryPlan", queryPlan);
                
                // 分析是否使用了部门索引
                boolean usedDeptIndex = analyzeIndexUsage(queryPlan, tableName);
                result.put("usedDeptIndex", usedDeptIndex);
                
                // 评估查询性能
                String performanceLevel = evaluateQueryPerformance(queryPlan);
                result.put("performanceLevel", performanceLevel);
                
                // 提供优化建议
                List<String> suggestions = generateOptimizationSuggestions(queryPlan, tableName, usedDeptIndex);
                result.put("suggestions", suggestions);
            }
        }
        catch (SQLException e)
        {
            log.error("分析查询性能时发生异常", e);
            result.put("error", "分析查询性能时发生异常: " + e.getMessage());
        }

        return result;
    }

    @Override
    public Map<String, Object> getPerformanceStatistics(Map<String, Object> params)
    {
        Map<String, Object> result = new HashMap<>();
        result.put("statisticsTime", new Date());
        
        // 从性能计数器获取统计数据
        Map<String, Object> counters = new HashMap<>();
        for (Map.Entry<String, AtomicLong> entry : performanceCounters.entrySet())
        {
            counters.put(entry.getKey(), entry.getValue().get());
        }
        
        result.put("performanceCounters", counters);
        result.put("monitoringEnabled", performanceMonitoringEnabled.get());
        
        // 计算一些基本统计
        long totalQueries = performanceCounters.getOrDefault("total_queries", new AtomicLong(0)).get();
        long slowQueries = performanceCounters.getOrDefault("slow_queries", new AtomicLong(0)).get();
        long indexedQueries = performanceCounters.getOrDefault("indexed_queries", new AtomicLong(0)).get();
        
        if (totalQueries > 0)
        {
            result.put("slowQueryRate", (double) slowQueries / totalQueries * 100);
            result.put("indexUsageRate", (double) indexedQueries / totalQueries * 100);
        }
        else
        {
            result.put("slowQueryRate", 0.0);
            result.put("indexUsageRate", 0.0);
        }
        
        return result;
    }

    @Override
    public List<DepartmentDataPerformanceMetrics> getSlowQueries(long thresholdMs, int limit)
    {
        // 由于没有对应的Mapper，返回空列表
        // 在实际项目中，这里应该查询数据库中执行时间超过阈值的记录
        return new ArrayList<>();
    }

    @Override
    public Map<String, Object> getIndexUsageStatistics()
    {
        Map<String, Object> result = new HashMap<>();
        result.put("statisticsTime", new Date());
        
        try
        {
            Map<String, Object> allIndexesResult = verifyAllDepartmentIndexes();
            result.put("indexVerification", allIndexesResult);
            
            // 从性能计数器获取索引使用统计
            long totalQueries = performanceCounters.getOrDefault("total_queries", new AtomicLong(0)).get();
            long indexedQueries = performanceCounters.getOrDefault("indexed_queries", new AtomicLong(0)).get();
            
            result.put("totalQueries", totalQueries);
            result.put("indexedQueries", indexedQueries);
            
            if (totalQueries > 0)
            {
                result.put("indexUsageRate", (double) indexedQueries / totalQueries * 100);
            }
            else
            {
                result.put("indexUsageRate", 0.0);
            }
            
            // 按表统计索引使用情况
            Map<String, Object> tableStats = new HashMap<>();
            for (String tableName : TARGET_TABLES)
            {
                long tableQueries = performanceCounters.getOrDefault("queries_" + tableName, new AtomicLong(0)).get();
                long tableIndexedQueries = performanceCounters.getOrDefault("indexed_queries_" + tableName, new AtomicLong(0)).get();
                
                Map<String, Object> tableStat = new HashMap<>();
                tableStat.put("totalQueries", tableQueries);
                tableStat.put("indexedQueries", tableIndexedQueries);
                
                if (tableQueries > 0)
                {
                    tableStat.put("indexUsageRate", (double) tableIndexedQueries / tableQueries * 100);
                }
                else
                {
                    tableStat.put("indexUsageRate", 0.0);
                }
                
                tableStats.put(tableName, tableStat);
            }
            
            result.put("tableStatistics", tableStats);
        }
        catch (Exception e)
        {
            log.error("获取索引使用统计时发生异常", e);
            result.put("error", "获取索引使用统计时发生异常: " + e.getMessage());
        }
        
        return result;
    }

    @Override
    public List<Map<String, Object>> checkPerformanceAlerts()
    {
        List<Map<String, Object>> alerts = new ArrayList<>();
        
        try
        {
            // 检查索引缺失告警
            Map<String, Object> indexResult = verifyAllDepartmentIndexes();
            if (!"PASS".equals(indexResult.get("overallStatus")))
            {
                Map<String, Object> alert = new HashMap<>();
                alert.put("type", "INDEX_MISSING");
                alert.put("level", "HIGH");
                alert.put("message", "部分表的部门索引缺失，可能严重影响查询性能");
                alert.put("details", indexResult);
                alert.put("alertTime", new Date());
                alerts.add(alert);
            }
            
            // 检查慢查询告警
            long totalQueries = performanceCounters.getOrDefault("total_queries", new AtomicLong(0)).get();
            long slowQueries = performanceCounters.getOrDefault("slow_queries", new AtomicLong(0)).get();
            
            if (totalQueries > 100 && slowQueries > 0)
            {
                double slowQueryRate = (double) slowQueries / totalQueries * 100;
                if (slowQueryRate > 10) // 慢查询率超过10%
                {
                    Map<String, Object> alert = new HashMap<>();
                    alert.put("type", "SLOW_QUERY_RATE");
                    alert.put("level", "MEDIUM");
                    alert.put("message", String.format("慢查询率过高: %.2f%%", slowQueryRate));
                    alert.put("slowQueryRate", slowQueryRate);
                    alert.put("totalQueries", totalQueries);
                    alert.put("slowQueries", slowQueries);
                    alert.put("alertTime", new Date());
                    alerts.add(alert);
                }
            }
            
            // 检查索引使用率告警
            long indexedQueries = performanceCounters.getOrDefault("indexed_queries", new AtomicLong(0)).get();
            
            if (totalQueries > 100 && indexedQueries < totalQueries)
            {
                double indexUsageRate = (double) indexedQueries / totalQueries * 100;
                if (indexUsageRate < 80) // 索引使用率低于80%
                {
                    Map<String, Object> alert = new HashMap<>();
                    alert.put("type", "LOW_INDEX_USAGE");
                    alert.put("level", "MEDIUM");
                    alert.put("message", String.format("索引使用率偏低: %.2f%%", indexUsageRate));
                    alert.put("indexUsageRate", indexUsageRate);
                    alert.put("totalQueries", totalQueries);
                    alert.put("indexedQueries", indexedQueries);
                    alert.put("alertTime", new Date());
                    alerts.add(alert);
                }
            }
        }
        catch (Exception e)
        {
            log.error("检查性能告警时发生异常", e);
            
            Map<String, Object> alert = new HashMap<>();
            alert.put("type", "MONITORING_ERROR");
            alert.put("level", "HIGH");
            alert.put("message", "性能监控检查异常: " + e.getMessage());
            alert.put("alertTime", new Date());
            alerts.add(alert);
        }
        
        return alerts;
    }

    @Override
    public List<Map<String, Object>> getIndexOptimizationSuggestions(String tableName)
    {
        List<Map<String, Object>> suggestions = new ArrayList<>();
        
        if (!TARGET_TABLES.contains(tableName))
        {
            return suggestions;
        }
        
        try
        {
            Map<String, Object> indexResult = verifyDepartmentIndexes(tableName);
            
            if (!"PASS".equals(indexResult.get("status")))
            {
                @SuppressWarnings("unchecked")
                List<Map<String, Object>> indexDetails = (List<Map<String, Object>>) indexResult.get("indexDetails");
                
                for (Map<String, Object> indexInfo : indexDetails)
                {
                    if (!(Boolean) indexInfo.get("exists"))
                    {
                        Map<String, Object> suggestion = new HashMap<>();
                        suggestion.put("type", "CREATE_INDEX");
                        suggestion.put("priority", "HIGH");
                        suggestion.put("indexName", indexInfo.get("indexName"));
                        suggestion.put("tableName", tableName);
                        suggestion.put("description", "创建缺失的部门索引以提高查询性能");
                        suggestion.put("sqlCommand", generateCreateIndexSql(tableName, (String) indexInfo.get("indexName")));
                        suggestions.add(suggestion);
                    }
                }
            }
            
            // 基于查询统计提供优化建议
            long tableQueries = performanceCounters.getOrDefault("queries_" + tableName, new AtomicLong(0)).get();
            long tableIndexedQueries = performanceCounters.getOrDefault("indexed_queries_" + tableName, new AtomicLong(0)).get();
            
            if (tableQueries > 50 && tableIndexedQueries < tableQueries * 0.8)
            {
                Map<String, Object> suggestion = new HashMap<>();
                suggestion.put("type", "OPTIMIZE_QUERIES");
                suggestion.put("priority", "MEDIUM");
                suggestion.put("tableName", tableName);
                suggestion.put("description", "该表的索引使用率偏低，建议检查查询语句是否正确使用了部门索引");
                suggestion.put("currentIndexUsageRate", (double) tableIndexedQueries / tableQueries * 100);
                suggestions.add(suggestion);
            }
        }
        catch (Exception e)
        {
            log.error("获取表 {} 的索引优化建议时发生异常", tableName, e);
        }
        
        return suggestions;
    }

    @Override
    public int cleanExpiredPerformanceData(int retentionDays)
    {
        // 由于没有对应的Mapper，这里只是记录日志
        log.info("清理 {} 天前的性能监控数据", retentionDays);
        return 0;
    }

    @Override
    public Map<String, Object> generatePerformanceReport(Map<String, Object> params)
    {
        Map<String, Object> report = new HashMap<>();
        report.put("reportTime", new Date());
        report.put("reportParams", params);
        
        // 获取基本统计信息
        Map<String, Object> statistics = getPerformanceStatistics(params);
        report.put("statistics", statistics);
        
        // 获取索引验证结果
        Map<String, Object> indexVerification = verifyAllDepartmentIndexes();
        report.put("indexVerification", indexVerification);
        
        // 获取索引使用统计
        Map<String, Object> indexUsage = getIndexUsageStatistics();
        report.put("indexUsage", indexUsage);
        
        // 获取性能告警
        List<Map<String, Object>> alerts = checkPerformanceAlerts();
        report.put("alerts", alerts);
        
        // 获取优化建议
        Map<String, List<Map<String, Object>>> suggestions = new HashMap<>();
        for (String tableName : TARGET_TABLES)
        {
            List<Map<String, Object>> tableSuggestions = getIndexOptimizationSuggestions(tableName);
            if (!tableSuggestions.isEmpty())
            {
                suggestions.put(tableName, tableSuggestions);
            }
        }
        report.put("optimizationSuggestions", suggestions);
        
        return report;
    }

    @Override
    public void enablePerformanceMonitoring()
    {
        performanceMonitoringEnabled.set(true);
        log.info("部门数据隔离性能监控已启用");
    }

    @Override
    public void disablePerformanceMonitoring()
    {
        performanceMonitoringEnabled.set(false);
        log.info("部门数据隔离性能监控已禁用");
    }

    @Override
    public boolean isPerformanceMonitoringEnabled()
    {
        return performanceMonitoringEnabled.get();
    }

    /**
     * 检查索引是否存在
     */
    private Map<String, Object> checkIndexExists(Connection conn, String tableName, String indexName) throws SQLException
    {
        Map<String, Object> result = new HashMap<>();
        result.put("indexName", indexName);
        result.put("tableName", tableName);
        
        String sql = "SELECT COUNT(*) as count FROM information_schema.statistics " +
                    "WHERE table_schema = DATABASE() AND table_name = ? AND index_name = ?";
        
        try (PreparedStatement stmt = conn.prepareStatement(sql))
        {
            stmt.setString(1, tableName);
            stmt.setString(2, indexName);
            
            try (ResultSet rs = stmt.executeQuery())
            {
                if (rs.next())
                {
                    boolean exists = rs.getInt("count") > 0;
                    result.put("exists", exists);
                    
                    if (exists)
                    {
                        // 获取索引详细信息
                        Map<String, Object> indexDetails = getIndexDetails(conn, tableName, indexName);
                        result.putAll(indexDetails);
                    }
                }
                else
                {
                    result.put("exists", false);
                }
            }
        }
        
        return result;
    }

    /**
     * 获取索引详细信息
     */
    private Map<String, Object> getIndexDetails(Connection conn, String tableName, String indexName) throws SQLException
    {
        Map<String, Object> details = new HashMap<>();
        
        String sql = "SELECT column_name, seq_in_index, cardinality " +
                    "FROM information_schema.statistics " +
                    "WHERE table_schema = DATABASE() AND table_name = ? AND index_name = ? " +
                    "ORDER BY seq_in_index";
        
        try (PreparedStatement stmt = conn.prepareStatement(sql))
        {
            stmt.setString(1, tableName);
            stmt.setString(2, indexName);
            
            try (ResultSet rs = stmt.executeQuery())
            {
                List<String> columns = new ArrayList<>();
                long totalCardinality = 0;
                
                while (rs.next())
                {
                    columns.add(rs.getString("column_name"));
                    totalCardinality += rs.getLong("cardinality");
                }
                
                details.put("columns", columns);
                details.put("cardinality", totalCardinality);
                details.put("columnCount", columns.size());
            }
        }
        
        return details;
    }

    /**
     * 分析查询计划中的索引使用情况
     */
    private boolean analyzeIndexUsage(List<Map<String, Object>> queryPlan, String tableName)
    {
        for (Map<String, Object> planRow : queryPlan)
        {
            String table = (String) planRow.get("table");
            String key = (String) planRow.get("key");
            
            if (tableName.equals(table) && key != null)
            {
                // 检查是否使用了部门相关的索引
                List<String> expectedIndexes = EXPECTED_INDEXES.get(tableName);
                if (expectedIndexes != null && expectedIndexes.contains(key))
                {
                    return true;
                }
                
                // 检查索引名称是否包含dept相关字段
                if (key.toLowerCase().contains("dept"))
                {
                    return true;
                }
            }
        }
        
        return false;
    }

    /**
     * 评估查询性能等级
     */
    private String evaluateQueryPerformance(List<Map<String, Object>> queryPlan)
    {
        for (Map<String, Object> planRow : queryPlan)
        {
            String type = (String) planRow.get("type");
            Object rowsObj = planRow.get("rows");
            
            if ("ALL".equals(type))
            {
                return "POOR"; // 全表扫描
            }
            
            if (rowsObj != null)
            {
                long rows = Long.parseLong(rowsObj.toString());
                if (rows > 10000)
                {
                    return "POOR";
                }
                else if (rows > 1000)
                {
                    return "FAIR";
                }
            }
        }
        
        return "GOOD";
    }

    /**
     * 生成优化建议
     */
    private List<String> generateOptimizationSuggestions(List<Map<String, Object>> queryPlan, String tableName, boolean usedDeptIndex)
    {
        List<String> suggestions = new ArrayList<>();
        
        if (!usedDeptIndex)
        {
            suggestions.add("查询未使用部门索引，建议检查WHERE条件是否包含dept_id字段");
        }
        
        for (Map<String, Object> planRow : queryPlan)
        {
            String type = (String) planRow.get("type");
            
            if ("ALL".equals(type))
            {
                suggestions.add("查询使用了全表扫描，建议添加适当的索引或优化WHERE条件");
            }
            
            Object rowsObj = planRow.get("rows");
            if (rowsObj != null)
            {
                long rows = Long.parseLong(rowsObj.toString());
                if (rows > 10000)
                {
                    suggestions.add("查询扫描行数过多(" + rows + "行)，建议优化查询条件或添加索引");
                }
            }
        }
        
        if (suggestions.isEmpty())
        {
            suggestions.add("查询性能良好，无需优化");
        }
        
        return suggestions;
    }

    /**
     * 设置性能等级
     */
    private void setPerformanceLevel(DepartmentDataPerformanceMetrics metrics)
    {
        BigDecimal executionTime = metrics.getExecutionTime();
        
        if (executionTime == null)
        {
            metrics.setPerformanceLevel("UNKNOWN");
            return;
        }
        
        double timeMs = executionTime.doubleValue();
        
        if (timeMs < 100)
        {
            metrics.setPerformanceLevel("EXCELLENT");
        }
        else if (timeMs < 500)
        {
            metrics.setPerformanceLevel("GOOD");
        }
        else if (timeMs < 1000)
        {
            metrics.setPerformanceLevel("FAIR");
        }
        else if (timeMs < 5000)
        {
            metrics.setPerformanceLevel("POOR");
        }
        else
        {
            metrics.setPerformanceLevel("CRITICAL");
        }
    }

    /**
     * 设置告警标识
     */
    private void setAlertFlag(DepartmentDataPerformanceMetrics metrics)
    {
        boolean alert = false;
        
        // 执行时间超过1秒
        if (metrics.getExecutionTime() != null && metrics.getExecutionTime().doubleValue() > 1000)
        {
            alert = true;
        }
        
        // 未使用部门索引
        if (Boolean.FALSE.equals(metrics.getUsedDeptIndex()))
        {
            alert = true;
        }
        
        // 扫描行数过多
        if (metrics.getRowsScanned() != null && metrics.getRowsScanned() > 10000)
        {
            alert = true;
        }
        
        metrics.setAlertFlag(alert);
    }

    /**
     * 更新性能计数器
     */
    private void updatePerformanceCounters(DepartmentDataPerformanceMetrics metrics)
    {
        // 总查询数
        performanceCounters.computeIfAbsent("total_queries", k -> new AtomicLong(0)).incrementAndGet();
        
        // 按表统计查询数
        String tableName = metrics.getTableName();
        if (tableName != null)
        {
            performanceCounters.computeIfAbsent("queries_" + tableName, k -> new AtomicLong(0)).incrementAndGet();
        }
        
        // 慢查询统计
        if (metrics.getExecutionTime() != null && metrics.getExecutionTime().doubleValue() > 1000)
        {
            performanceCounters.computeIfAbsent("slow_queries", k -> new AtomicLong(0)).incrementAndGet();
        }
        
        // 索引使用统计
        if (Boolean.TRUE.equals(metrics.getUsedDeptIndex()))
        {
            performanceCounters.computeIfAbsent("indexed_queries", k -> new AtomicLong(0)).incrementAndGet();
            
            if (tableName != null)
            {
                performanceCounters.computeIfAbsent("indexed_queries_" + tableName, k -> new AtomicLong(0)).incrementAndGet();
            }
        }
    }

    /**
     * 生成创建索引的SQL语句
     */
    private String generateCreateIndexSql(String tableName, String indexName)
    {
        if (indexName.contains("dept_status"))
        {
            // 复合索引：dept_id + status字段
            String statusField = getStatusFieldName(tableName);
            return String.format("CREATE INDEX %s ON %s(dept_id, %s);", indexName, tableName, statusField);
        }
        else
        {
            // 单列索引：dept_id
            return String.format("CREATE INDEX %s ON %s(dept_id);", indexName, tableName);
        }
    }

    /**
     * 获取表的状态字段名
     */
    private String getStatusFieldName(String tableName)
    {
        switch (tableName)
        {
            case "dc_contract":
                return "contract_status";
            case "dc_service_period":
                return "period_status";
            case "dc_employee_info":
                return "employee_status";
            case "dc_employee_library":
                return "library_status";
            case "dc_credit":
                return "credit_status";
            case "dc_bank_institution":
                return "status";
            default:
                return "status";
        }
    }
}