package com.qaup.collision.rule.service.impl;

import com.qaup.collision.rule.model.entity.SpatialRule;
import com.qaup.collision.rule.model.enums.RuleCategory;
import com.qaup.collision.rule.model.enums.RuleStatus;
import com.qaup.collision.rule.model.enums.SpatialObjectType;
import com.qaup.collision.rule.service.RuleConfigurationService;
import com.qaup.collision.rule.service.SpatialRuleService;
import com.qaup.collision.rule.service.SpatialRuleService.RuleValidationResult;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 规则配置服务实现类
 * 提供基本的规则配置管理功能
 * 
 * @author AI Assistant
 * @version 1.0
 * @since 2025-01-17
 */
@Service
@Transactional
public class RuleConfigurationServiceImpl implements RuleConfigurationService {

    private static final Logger logger = LoggerFactory.getLogger(RuleConfigurationServiceImpl.class);
    
    @Autowired
    private SpatialRuleService spatialRuleService;
    
    @Autowired
    private ObjectMapper objectMapper;

    // 内存中的配置模板存储（生产环境可以改为数据库存储）
    private final Map<String, Map<String, Object>> configurationTemplates = new HashMap<>();
    
    // 配置历史存储（生产环境可以改为数据库存储）
    private final Map<String, List<RuleConfigurationHistory>> configurationHistories = new HashMap<>();

    // ==================== 基础配置功能 ====================

    @Override
    public SpatialRule createRuleTemplate(RuleCategory category, String name, String description) {
        logger.info("创建规则配置模板: category={}, name={}", category, name);
        
        try {
            // 生成规则ID
            String ruleId = generateRuleId(category);
            
            // 创建基础规则
            SpatialRule rule = new SpatialRule();
            rule.setRuleId(ruleId);
            rule.setName(name);
            rule.setDescription(description);
            rule.setCategory(category);
            rule.setStatus(RuleStatus.DRAFT);
            rule.setPriority(getDefaultPriority(category));
            rule.setCreatedAt(LocalDateTime.now());
            rule.setUpdatedAt(LocalDateTime.now());
            rule.setCreatedBy("SYSTEM");
            
            // 设置默认参数
            Map<String, Object> defaultParameters = getDefaultConfigurationTemplate(category);
            if (defaultParameters != null && !defaultParameters.isEmpty()) {
                try {
                    String parametersJson = objectMapper.writeValueAsString(defaultParameters);
                    rule.setParameters(parametersJson);
                } catch (Exception e) {
                    logger.warn("转换默认参数为JSON失败: {}", e.getMessage());
                    rule.setParameters("{}");
                }
            }
            
            // 保存规则
            SpatialRule savedRule = spatialRuleService.createRule(rule);
            
            // 保存配置快照
            saveConfigurationSnapshot(ruleId, "创建规则模板", "SYSTEM");
            
            logger.info("规则配置模板创建成功: ruleId={}", ruleId);
            return savedRule;
            
        } catch (Exception e) {
            logger.error("创建规则配置模板失败: category={}, name={}", category, name, e);
            throw new RuntimeException("创建规则配置模板失败", e);
        }
    }

    @Override
    public SpatialRule cloneRuleConfiguration(String sourceRuleId, String newRuleId, String newName) {
        logger.info("克隆规则配置: sourceRuleId={}, newRuleId={}", sourceRuleId, newRuleId);
        
        try {
            // 获取源规则
            Optional<SpatialRule> sourceRuleOpt = spatialRuleService.findRuleById(sourceRuleId);
            if (!sourceRuleOpt.isPresent()) {
                throw new IllegalArgumentException("源规则不存在: " + sourceRuleId);
            }
            
            SpatialRule sourceRule = sourceRuleOpt.get();
            
            // 创建新规则
            SpatialRule newRule = new SpatialRule();
            newRule.setRuleId(newRuleId);
            newRule.setName(newName);
            newRule.setDescription("克隆自: " + sourceRule.getName());
            newRule.setCategory(sourceRule.getCategory());
            newRule.setStatus(RuleStatus.DRAFT);
            newRule.setPriority(sourceRule.getPriority());
            newRule.setSpatialObjectType(sourceRule.getSpatialObjectType());
            newRule.setRelatedObjectId(sourceRule.getRelatedObjectId());
            newRule.setCustomGeometry(sourceRule.getCustomGeometry());
            newRule.setParameters(sourceRule.getParameters());
            newRule.setTimePatterns(sourceRule.getTimePatterns());
            newRule.setCreatedAt(LocalDateTime.now());
            newRule.setUpdatedAt(LocalDateTime.now());
            newRule.setCreatedBy("SYSTEM");
            
            // 保存新规则
            SpatialRule savedRule = spatialRuleService.createRule(newRule);
            
            // 保存配置快照
            saveConfigurationSnapshot(newRuleId, "克隆规则配置", "SYSTEM");
            
            logger.info("规则配置克隆成功: newRuleId={}", newRuleId);
            return savedRule;
            
        } catch (Exception e) {
            logger.error("克隆规则配置失败: sourceRuleId={}, newRuleId={}", sourceRuleId, newRuleId, e);
            throw new RuntimeException("克隆规则配置失败", e);
        }
    }

    @Override
    public boolean updateRuleBasicInfo(String ruleId, String name, String description, Integer priority) {
        logger.info("更新规则基本信息: ruleId={}, name={}, priority={}", ruleId, name, priority);
        
        try {
            // 保存更新前的快照
            saveConfigurationSnapshot(ruleId, "更新基本信息前", "SYSTEM");
            
            // 获取现有规则
            Optional<SpatialRule> ruleOpt = spatialRuleService.findRuleById(ruleId);
            if (!ruleOpt.isPresent()) {
                logger.warn("规则不存在: ruleId={}", ruleId);
                return false;
            }
            
            SpatialRule rule = ruleOpt.get();
            
            // 更新基本信息
            if (name != null && !name.trim().isEmpty()) {
                rule.setName(name.trim());
            }
            if (description != null) {
                rule.setDescription(description.trim());
            }
            if (priority != null) {
                rule.setPriority(priority);
            }
            rule.setUpdatedAt(LocalDateTime.now());
            rule.setUpdatedBy("SYSTEM");
            
            // 保存更新
            spatialRuleService.updateRule(ruleId, rule);
            
            // 保存更新后的快照
            saveConfigurationSnapshot(ruleId, "更新基本信息后", "SYSTEM");
            
            logger.info("规则基本信息更新成功: ruleId={}", ruleId);
            return true;
            
        } catch (Exception e) {
            logger.error("更新规则基本信息失败: ruleId={}", ruleId, e);
            return false;
        }
    }

    @Override
    public boolean configureRuleTimeWindow(String ruleId, LocalDateTime effectiveStartTime, 
                                           LocalDateTime effectiveEndTime, String timePattern) {
        logger.info("配置规则时间窗口: ruleId={}", ruleId);
        
        try {
            // 保存配置前的快照
            saveConfigurationSnapshot(ruleId, "配置时间窗口前", "SYSTEM");
            
            // 获取现有规则
            Optional<SpatialRule> ruleOpt = spatialRuleService.findRuleById(ruleId);
            if (!ruleOpt.isPresent()) {
                logger.warn("规则不存在: ruleId={}", ruleId);
                return false;
            }
            
            SpatialRule rule = ruleOpt.get();
            
            // 更新时间窗口配置
            rule.setEffectiveStartTime(effectiveStartTime);
            rule.setEffectiveEndTime(effectiveEndTime);
            
            if (timePattern != null && !timePattern.trim().isEmpty()) {
                try {
                    // 验证JSON格式有效性
                    objectMapper.readTree(timePattern);
                    rule.setTimePatterns(timePattern);
                } catch (Exception e) {
                    logger.warn("时间模式JSON解析失败，使用默认格式: ruleId={}", ruleId, e);
                    try {
                        String timePatternJson = objectMapper.writeValueAsString(timePattern);
                        rule.setTimePatterns(timePatternJson);
                    } catch (Exception ex) {
                        logger.warn("时间模式转换失败，使用空JSON: ruleId={}", ruleId, ex);
                        rule.setTimePatterns("[]");
                    }
                }
            }
            
            rule.setUpdatedAt(LocalDateTime.now());
            rule.setUpdatedBy("SYSTEM");
            
            // 保存更新
            spatialRuleService.updateRule(ruleId, rule);
            
            // 保存配置后的快照
            saveConfigurationSnapshot(ruleId, "配置时间窗口后", "SYSTEM");
            
            logger.info("规则时间窗口配置成功: ruleId={}", ruleId);
            return true;
            
        } catch (Exception e) {
            logger.error("配置规则时间窗口失败: ruleId={}", ruleId, e);
            return false;
        }
    }

    @Override
    public boolean configureRuleSpatialScope(String ruleId, String spatialObjectType, 
                                             String relatedObjectId, String customGeometryWkt) {
        logger.info("配置规则空间范围: ruleId={}, spatialObjectType={}", ruleId, spatialObjectType);
        
        try {
            // 保存配置前的快照
            saveConfigurationSnapshot(ruleId, "配置空间范围前", "SYSTEM");
            
            // 获取现有规则
            Optional<SpatialRule> ruleOpt = spatialRuleService.findRuleById(ruleId);
            if (!ruleOpt.isPresent()) {
                logger.warn("规则不存在: ruleId={}", ruleId);
                return false;
            }
            
            SpatialRule rule = ruleOpt.get();
            
            // 更新空间范围配置
            if (spatialObjectType != null && !spatialObjectType.trim().isEmpty()) {
                try {
                    SpatialObjectType objectType = SpatialObjectType.valueOf(spatialObjectType.trim().toUpperCase());
                    rule.setSpatialObjectType(objectType);
                } catch (IllegalArgumentException e) {
                    logger.warn("无效的空间对象类型: {}", spatialObjectType);
                    return false;
                }
            }
            if (relatedObjectId != null && !relatedObjectId.trim().isEmpty()) {
                rule.setRelatedObjectId(relatedObjectId.trim());
            }
            if (customGeometryWkt != null && !customGeometryWkt.trim().isEmpty()) {
                // 这里应该验证WKT格式的有效性，简化实现暂时跳过几何设置
                // TODO: 实现WKT字符串到Geometry对象的转换
                logger.warn("自定义几何形状设置暂未实现，需要WKT解析功能");
            }
            
            rule.setUpdatedAt(LocalDateTime.now());
            rule.setUpdatedBy("SYSTEM");
            
            // 保存更新
            spatialRuleService.updateRule(ruleId, rule);
            
            // 保存配置后的快照
            saveConfigurationSnapshot(ruleId, "配置空间范围后", "SYSTEM");
            
            logger.info("规则空间范围配置成功: ruleId={}", ruleId);
            return true;
            
        } catch (Exception e) {
            logger.error("配置规则空间范围失败: ruleId={}", ruleId, e);
            return false;
        }
    }

    @Override
    public boolean configureRuleParameters(String ruleId, Map<String, Object> parameters) {
        logger.info("配置规则参数: ruleId={}", ruleId);
        
        try {
            // 保存配置前的快照
            saveConfigurationSnapshot(ruleId, "配置参数前", "SYSTEM");
            
            // 获取现有规则
            Optional<SpatialRule> ruleOpt = spatialRuleService.findRuleById(ruleId);
            if (!ruleOpt.isPresent()) {
                logger.warn("规则不存在: ruleId={}", ruleId);
                return false;
            }
            
            SpatialRule rule = ruleOpt.get();
            
            // 验证参数配置
            RuleValidationResult validationResult = validateRuleParameters(rule.getCategory(), parameters);
            if (!validationResult.isValid()) {
                logger.warn("规则参数验证失败: ruleId={}, errors={}", ruleId, validationResult.getErrors());
                return false;
            }
            
            // 更新参数配置
            if (parameters != null && !parameters.isEmpty()) {
                try {
                    String parametersJson = objectMapper.writeValueAsString(parameters);
                    rule.setParameters(parametersJson);
                } catch (Exception e) {
                    logger.error("转换参数为JSON失败: ruleId={}", ruleId, e);
                    return false;
                }
            } else {
                rule.setParameters("{}");
            }
            
            rule.setUpdatedAt(LocalDateTime.now());
            rule.setUpdatedBy("SYSTEM");
            
            // 保存更新
            spatialRuleService.updateRule(ruleId, rule);
            
            // 保存配置后的快照
            saveConfigurationSnapshot(ruleId, "配置参数后", "SYSTEM");
            
            logger.info("规则参数配置成功: ruleId={}", ruleId);
            return true;
            
        } catch (Exception e) {
            logger.error("配置规则参数失败: ruleId={}", ruleId, e);
            return false;
        }
    }

    // ==================== 配置验证功能 ====================

    @Override
    public RuleValidationResult validateRuleConfiguration(String ruleId) {
        logger.debug("验证规则配置: ruleId={}", ruleId);
        
        try {
            // 获取规则并手动验证，因为SpatialRuleService没有validateRuleConfiguration方法
            Optional<SpatialRule> ruleOpt = spatialRuleService.findRuleById(ruleId);
            if (!ruleOpt.isPresent()) {
                return new RuleValidationResult(false, Arrays.asList("规则不存在"), Collections.emptyList());
            }
            
            SpatialRule rule = ruleOpt.get();
            return spatialRuleService.validateRule(rule);
            
        } catch (Exception e) {
            logger.error("验证规则配置失败: ruleId={}", ruleId, e);
            return new RuleValidationResult(false, Arrays.asList("验证过程发生异常: " + e.getMessage()), Collections.emptyList());
        }
    }

    @Override
    public Map<String, RuleValidationResult> batchValidateRuleConfigurations(List<String> ruleIds) {
        logger.info("批量验证规则配置: ruleCount={}", ruleIds.size());
        
        Map<String, RuleValidationResult> results = new HashMap<>();
        
        for (String ruleId : ruleIds) {
            try {
                RuleValidationResult result = validateRuleConfiguration(ruleId);
                results.put(ruleId, result);
            } catch (Exception e) {
                logger.error("批量验证中单个规则失败: ruleId={}", ruleId, e);
                results.put(ruleId, new RuleValidationResult(false, 
                           Arrays.asList("验证失败: " + e.getMessage()), Collections.emptyList()));
            }
        }
        
        logger.info("批量验证完成: totalRules={}, validRules={}", 
                   ruleIds.size(), 
                   results.values().stream().mapToLong(r -> r.isValid() ? 1 : 0).sum());
        
        return results;
    }

    @Override
    public List<SpatialRule> checkConfigurationConflicts(String ruleId) {
        logger.debug("检查规则配置冲突: ruleId={}", ruleId);
        
        try {
            // 获取规则
            Optional<SpatialRule> ruleOpt = spatialRuleService.findRuleById(ruleId);
            if (!ruleOpt.isPresent()) {
                logger.warn("规则不存在: ruleId={}", ruleId);
                return Collections.emptyList();
            }
            
            SpatialRule rule = ruleOpt.get();
            
            // 查找可能冲突的规则（相同类别、相同空间范围）
            List<SpatialRule> potentialConflicts = spatialRuleService.findRulesByCategory(rule.getCategory());
            
            return potentialConflicts.stream()
                    .filter(r -> !r.getRuleId().equals(ruleId))
                    .filter(r -> hasConflict(rule, r))
                    .collect(Collectors.toList());
                    
        } catch (Exception e) {
            logger.error("检查规则配置冲突失败: ruleId={}", ruleId, e);
            return Collections.emptyList();
        }
    }

    @Override
    public RuleValidationResult validateRuleParameters(RuleCategory category, Map<String, Object> parameters) {
        logger.debug("验证规则参数: category={}", category);
        
        List<String> errors = new ArrayList<>();
        
        try {
            if (parameters == null || parameters.isEmpty()) {
                errors.add("规则参数不能为空");
                return new RuleValidationResult(false, errors, Collections.emptyList());
            }
            
            // 根据规则类别验证必需参数
            switch (category) {
                case ACCESS_CONTROL:
                    validateAccessControlParameters(parameters, errors);
                    break;
                case SPEED_LIMIT:
                    validateSpeedLimitParameters(parameters, errors);
                    break;
                case VEHICLE_RESTRICTION:
                    validateVehicleRestrictionParameters(parameters, errors);
                    break;
                default:
                    // 基本验证
                    break;
            }
            
            return new RuleValidationResult(errors.isEmpty(), errors, Collections.emptyList());
            
        } catch (Exception e) {
            logger.error("验证规则参数失败: category={}", category, e);
            errors.add("验证过程发生异常: " + e.getMessage());
            return new RuleValidationResult(false, errors, Collections.emptyList());
        }
    }

    // ==================== 配置模板管理 ====================

    @Override
    public Map<String, Object> getDefaultConfigurationTemplate(RuleCategory category) {
        logger.debug("获取默认配置模板: category={}", category);
        
        Map<String, Object> template = new HashMap<>();
        
        switch (category) {
            case ACCESS_CONTROL:
                template.put("allowedVehicleTypes", Arrays.asList("UNMANNED_VEHICLE"));
                template.put("requiresAuthorization", true);
                template.put("maxVehicleCount", 10);
                break;
                
            case SPEED_LIMIT:
                template.put("maxSpeed", 30);
                template.put("unit", "kmh");
                template.put("warningThreshold", 0.8);
                break;
                
            case VEHICLE_RESTRICTION:
                template.put("restrictedVehicleTypes", Arrays.asList("AIRCRAFT"));
                template.put("restrictionReason", "安全限制");
                break;
                
            case HEIGHT_LIMIT:
                template.put("maxHeight", 5.0);
                template.put("unit", "meters");
                break;
                
            case WEIGHT_LIMIT:
                template.put("maxWeight", 1000);
                template.put("unit", "kg");
                break;
                
            default:
                template.put("enabled", true);
                break;
        }
        
        return template;
    }

    @Override
    public boolean saveConfigurationTemplate(String templateName, RuleCategory category, Map<String, Object> template) {
        logger.info("保存配置模板: templateName={}, category={}", templateName, category);
        
        try {
            String key = category + ":" + templateName;
            configurationTemplates.put(key, new HashMap<>(template));
            
            logger.info("配置模板保存成功: templateName={}", templateName);
            return true;
            
        } catch (Exception e) {
            logger.error("保存配置模板失败: templateName={}", templateName, e);
            return false;
        }
    }

    @Override
    public Map<String, Map<String, Object>> getAvailableTemplates(RuleCategory category) {
        logger.debug("获取可用配置模板: category={}", category);
        
        Map<String, Map<String, Object>> availableTemplates = new HashMap<>();
        
        for (Map.Entry<String, Map<String, Object>> entry : configurationTemplates.entrySet()) {
            String key = entry.getKey();
            if (category == null || key.startsWith(category + ":")) {
                String templateName = key.contains(":") ? key.substring(key.indexOf(":") + 1) : key;
                availableTemplates.put(templateName, entry.getValue());
            }
        }
        
        // 添加默认模板
        if (category != null) {
            availableTemplates.put("默认模板", getDefaultConfigurationTemplate(category));
        }
        
        return availableTemplates;
    }

    @Override
    public boolean applyConfigurationTemplate(String ruleId, String templateName) {
        logger.info("应用配置模板: ruleId={}, templateName={}", ruleId, templateName);
        
        try {
            // 获取规则
            Optional<SpatialRule> ruleOpt = spatialRuleService.findRuleById(ruleId);
            if (!ruleOpt.isPresent()) {
                logger.warn("规则不存在: ruleId={}", ruleId);
                return false;
            }
            
            SpatialRule rule = ruleOpt.get();
            
            // 获取模板
            Map<String, Object> template;
            if ("默认模板".equals(templateName)) {
                template = getDefaultConfigurationTemplate(rule.getCategory());
            } else {
                String key = rule.getCategory() + ":" + templateName;
                template = configurationTemplates.get(key);
                if (template == null) {
                    logger.warn("配置模板不存在: templateName={}", templateName);
                    return false;
                }
            }
            
            // 应用模板
            return configureRuleParameters(ruleId, template);
            
        } catch (Exception e) {
            logger.error("应用配置模板失败: ruleId={}, templateName={}", ruleId, templateName, e);
            return false;
        }
    }

    // ==================== 配置导入导出 ====================

    @Override
    public String exportRuleConfiguration(String ruleId) {
        logger.info("导出规则配置: ruleId={}", ruleId);
        
        try {
            Optional<SpatialRule> ruleOpt = spatialRuleService.findRuleById(ruleId);
            if (!ruleOpt.isPresent()) {
                logger.warn("规则不存在: ruleId={}", ruleId);
                return null;
            }
            
            SpatialRule rule = ruleOpt.get();
            return objectMapper.writeValueAsString(rule);
            
        } catch (Exception e) {
            logger.error("导出规则配置失败: ruleId={}", ruleId, e);
            return null;
        }
    }

    @Override
    public String exportRuleConfigurations(List<String> ruleIds) {
        logger.info("批量导出规则配置: ruleCount={}", ruleIds.size());
        
        try {
            List<SpatialRule> rules = new ArrayList<>();
            for (String ruleId : ruleIds) {
                Optional<SpatialRule> ruleOpt = spatialRuleService.findRuleById(ruleId);
                if (ruleOpt.isPresent()) {
                    rules.add(ruleOpt.get());
                }
            }
            
            return objectMapper.writeValueAsString(rules);
            
        } catch (Exception e) {
            logger.error("批量导出规则配置失败", e);
            return null;
        }
    }

    @Override
    public List<SpatialRule> importRuleConfiguration(String configurationJson) {
        logger.info("导入规则配置");
        
        try {
            // 尝试解析为单个规则
            try {
                SpatialRule rule = objectMapper.readValue(configurationJson, SpatialRule.class);
                SpatialRule savedRule = spatialRuleService.createRule(rule);
                return Arrays.asList(savedRule);
            } catch (Exception e) {
                // 尝试解析为规则列表
                SpatialRule[] rules = objectMapper.readValue(configurationJson, SpatialRule[].class);
                List<SpatialRule> savedRules = new ArrayList<>();
                for (SpatialRule rule : rules) {
                    SpatialRule savedRule = spatialRuleService.createRule(rule);
                    savedRules.add(savedRule);
                }
                return savedRules;
            }
            
        } catch (Exception e) {
            logger.error("导入规则配置失败", e);
            return Collections.emptyList();
        }
    }

    @Override
    public int importRuleConfigurationFromFile(String filePath) {
        logger.info("从文件导入规则配置: filePath={}", filePath);
        
        try {
            String content = new String(Files.readAllBytes(Paths.get(filePath)));
            List<SpatialRule> importedRules = importRuleConfiguration(content);
            
            logger.info("从文件导入规则配置成功: importedCount={}", importedRules.size());
            return importedRules.size();
            
        } catch (Exception e) {
            logger.error("从文件导入规则配置失败: filePath={}", filePath, e);
            return 0;
        }
    }

    // ==================== 配置历史管理 ====================

    @Override
    public List<RuleConfigurationHistory> getRuleConfigurationHistory(String ruleId, int limit) {
        logger.debug("获取规则配置历史: ruleId={}, limit={}", ruleId, limit);
        
        List<RuleConfigurationHistory> histories = configurationHistories.getOrDefault(ruleId, Collections.emptyList());
        
        return histories.stream()
                .sorted((h1, h2) -> h2.getTimestamp().compareTo(h1.getTimestamp()))
                .limit(limit)
                .collect(Collectors.toList());
    }

    @Override
    public boolean saveConfigurationSnapshot(String ruleId, String changeReason, String changedBy) {
        logger.debug("保存规则配置快照: ruleId={}, changeReason={}", ruleId, changeReason);
        
        try {
            Optional<SpatialRule> ruleOpt = spatialRuleService.findRuleById(ruleId);
            if (!ruleOpt.isPresent()) {
                logger.warn("规则不存在，无法保存配置快照: ruleId={}", ruleId);
                return false;
            }
            
            SpatialRule rule = ruleOpt.get();
            String snapshot = objectMapper.writeValueAsString(rule);
            String snapshotId = UUID.randomUUID().toString();
            
            RuleConfigurationHistory history = new RuleConfigurationHistory(
                    snapshotId, ruleId, LocalDateTime.now(), changeReason, changedBy, snapshot);
            
            configurationHistories.computeIfAbsent(ruleId, k -> new ArrayList<>()).add(history);
            
            logger.debug("规则配置快照保存成功: ruleId={}, snapshotId={}", ruleId, snapshotId);
            return true;
            
        } catch (Exception e) {
            logger.error("保存规则配置快照失败: ruleId={}", ruleId, e);
            return false;
        }
    }

    @Override
    public boolean restoreConfigurationFromSnapshot(String ruleId, String snapshotId, String restoredBy) {
        logger.info("恢复规则配置: ruleId={}, snapshotId={}", ruleId, snapshotId);
        
        try {
            List<RuleConfigurationHistory> histories = configurationHistories.get(ruleId);
            if (histories == null || histories.isEmpty()) {
                logger.warn("没有找到规则配置历史: ruleId={}", ruleId);
                return false;
            }
            
            Optional<RuleConfigurationHistory> historyOpt = histories.stream()
                    .filter(h -> h.getSnapshotId().equals(snapshotId))
                    .findFirst();
                    
            if (!historyOpt.isPresent()) {
                logger.warn("没有找到指定的配置快照: ruleId={}, snapshotId={}", ruleId, snapshotId);
                return false;
            }
            
            RuleConfigurationHistory history = historyOpt.get();
            SpatialRule rule = objectMapper.readValue(history.getConfigurationSnapshot(), SpatialRule.class);
            
            // 更新时间戳和恢复人信息
            rule.setUpdatedAt(LocalDateTime.now());
            rule.setUpdatedBy(restoredBy);
            
            spatialRuleService.updateRule(ruleId, rule);
            
            // 保存恢复操作的快照
            saveConfigurationSnapshot(ruleId, "恢复到快照: " + snapshotId, restoredBy);
            
            logger.info("规则配置恢复成功: ruleId={}, snapshotId={}", ruleId, snapshotId);
            return true;
            
        } catch (Exception e) {
            logger.error("恢复规则配置失败: ruleId={}, snapshotId={}", ruleId, snapshotId, e);
            return false;
        }
    }

    // ==================== 配置统计分析 ====================

    @Override
    public ConfigurationStatistics getConfigurationStatistics() {
        logger.debug("获取配置统计信息");
        
        try {
            // 获取所有规则
            List<SpatialRule> allRules = spatialRuleService.findAllRules();
            
            long totalConfigurations = allRules.size();
            long validConfigurations = allRules.stream()
                    .mapToLong(rule -> {
                        try {
                            RuleValidationResult result = validateRuleConfiguration(rule.getRuleId());
                            return result.isValid() ? 1 : 0;
                        } catch (Exception e) {
                            return 0;
                        }
                    })
                    .sum();
            long invalidConfigurations = totalConfigurations - validConfigurations;
            
            Map<RuleCategory, Long> configurationsByCategory = allRules.stream()
                    .collect(Collectors.groupingBy(SpatialRule::getCategory, Collectors.counting()));
                    
            Map<RuleStatus, Long> configurationsByStatus = allRules.stream()
                    .collect(Collectors.groupingBy(SpatialRule::getStatus, Collectors.counting()));
                    
            double configurationValidityRate = totalConfigurations > 0 ? 
                    (double) validConfigurations / totalConfigurations : 0.0;
            
            return new ConfigurationStatistics(totalConfigurations, validConfigurations, invalidConfigurations,
                                             configurationsByCategory, configurationsByStatus, configurationValidityRate);
                                             
        } catch (Exception e) {
            logger.error("获取配置统计信息失败", e);
            return new ConfigurationStatistics(0, 0, 0, Collections.emptyMap(), 
                                             Collections.emptyMap(), 0.0);
        }
    }

    @Override
    public Map<String, Long> getMostUsedConfigurationParameters(RuleCategory category, int limit) {
        logger.debug("获取最常用的配置参数: category={}, limit={}", category, limit);
        
        try {
            List<SpatialRule> rules = spatialRuleService.findRulesByCategory(category);
            Map<String, Long> parameterCounts = new HashMap<>();
            
            for (SpatialRule rule : rules) {
                if (rule.getParameters() != null && !rule.getParameters().trim().isEmpty()) {
                    try {
                        JsonNode parametersNode = objectMapper.readTree(rule.getParameters());
                        parametersNode.fieldNames().forEachRemaining(fieldName -> {
                            parameterCounts.merge(fieldName, 1L, Long::sum);
                        });
                    } catch (Exception e) {
                        logger.warn("解析规则参数失败: ruleId={}", rule.getRuleId(), e);
                    }
                }
            }
            
            return parameterCounts.entrySet().stream()
                    .sorted(Map.Entry.<String, Long>comparingByValue().reversed())
                    .limit(limit)
                    .collect(Collectors.toMap(
                            Map.Entry::getKey,
                            Map.Entry::getValue,
                            (e1, e2) -> e1,
                            LinkedHashMap::new));
                            
        } catch (Exception e) {
            logger.error("获取最常用配置参数失败: category={}", category, e);
            return Collections.emptyMap();
        }
    }

    @Override
    public Map<String, Long> getConfigurationErrorStatistics(LocalDateTime startTime, LocalDateTime endTime) {
        logger.debug("获取配置错误统计: startTime={}, endTime={}", startTime, endTime);
        
        // 简化实现，实际应该从错误日志或数据库中获取统计数据
        Map<String, Long> errorStats = new HashMap<>();
        errorStats.put("参数验证错误", 0L);
        errorStats.put("空间范围错误", 0L);
        errorStats.put("时间窗口错误", 0L);
        errorStats.put("权限配置错误", 0L);
        
        return errorStats;
    }

    // ==================== 私有辅助方法 ====================

    private String generateRuleId(RuleCategory category) {
        String prefix = category.name().toLowerCase().substring(0, 3);
        return prefix + "_" + System.currentTimeMillis() + "_" + UUID.randomUUID().toString().substring(0, 8);
    }
    
    private Integer getDefaultPriority(RuleCategory category) {
        switch (category) {
            case SAFETY_ZONE: return 100;
            case ACCESS_CONTROL: return 90;
            case PRIORITY_CONTROL: return 80;
            case SPEED_LIMIT: return 70;
            case VEHICLE_RESTRICTION: return 60;
            case HEIGHT_LIMIT: return 50;
            case WEIGHT_LIMIT: return 40;
            case TIME_RESTRICTION: return 30;
            default: return 10;
        }
    }
    
    private boolean hasConflict(SpatialRule rule1, SpatialRule rule2) {
        // 简化的冲突检测逻辑
        // 实际应该检查空间范围、时间窗口、优先级等是否有冲突
        return rule1.getCategory() == rule2.getCategory() &&
               Objects.equals(rule1.getRelatedObjectId(), rule2.getRelatedObjectId());
    }
    
    private void validateAccessControlParameters(Map<String, Object> parameters, List<String> errors) {
        if (!parameters.containsKey("allowedVehicleTypes")) {
            errors.add("准入控制规则必须指定允许的车辆类型");
        }
    }
    
    private void validateSpeedLimitParameters(Map<String, Object> parameters, List<String> errors) {
        if (!parameters.containsKey("maxSpeed")) {
            errors.add("限速规则必须指定最大速度");
        } else {
            Object maxSpeed = parameters.get("maxSpeed");
            if (!(maxSpeed instanceof Number) || ((Number) maxSpeed).doubleValue() <= 0) {
                errors.add("最大速度必须是正数");
            }
        }
    }
    
    private void validateVehicleRestrictionParameters(Map<String, Object> parameters, List<String> errors) {
        if (!parameters.containsKey("restrictedVehicleTypes")) {
            errors.add("车辆限制规则必须指定受限的车辆类型");
        }
    }
} 