package com.ruoyi.rocketmq.snmp.scheduler;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.enums.MsgEnum;
import com.ruoyi.rocketmq.domain.DeviceMessage;
import com.ruoyi.rocketmq.domain.InitialHeartbeatListen;
import com.ruoyi.rocketmq.domain.vo.CollectVo;
import com.ruoyi.rocketmq.domain.vo.SwitchOidVo;
import com.ruoyi.rocketmq.producer.MessageProducer;
import com.ruoyi.rocketmq.snmp.DynamicOidCollector;
import com.ruoyi.rocketmq.snmp.dto.CollectionResult;
import com.ruoyi.rocketmq.snmp.dto.SwitchOidDto;
import com.ruoyi.rocketmq.snmp.service.ProcessSwitchCollectDataService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.security.SecurityLevel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;

@Service
@Slf4j
public class MultiSwitchCollectionScheduler {

    private static final String PREFIX = "switch";
    private static final String SUFFIX = "Collect";
    private final TaskScheduler taskScheduler;
    private final DynamicOidCollector dynamicOidCollector;
    private boolean collectorInitialized = false;

    // 存储所有交换机的任务和配置
    private final Map<String, Map<String, ScheduledFuture<?>>> allSwitchTasks = new ConcurrentHashMap<>();
    private final Map<String, SwitchOidDto> allSwitchConfigs = new ConcurrentHashMap<>();
    private final Map<String, List<CollectVo>> allSwitchCollectConfigs = new ConcurrentHashMap<>();

    // 使用构造器注入而不是@Autowired
    public MultiSwitchCollectionScheduler(TaskScheduler taskScheduler,
                                          DynamicOidCollector dynamicOidCollector) {
        this.taskScheduler = taskScheduler;
        this.dynamicOidCollector = dynamicOidCollector;
    }
    @Autowired
    private ProcessSwitchCollectDataService processSwitchCollectDataService;

    @PostConstruct
    public void init() {
        try {
            // 初始化SNMP采集器
            dynamicOidCollector.init();
            collectorInitialized = true;
            log.info("MultiSwitchCollectionScheduler 初始化完成，SNMP服务已启动");
        } catch (Exception e) {
            log.error("SNMP服务初始化失败", e);
            collectorInitialized = false;
        }
    }
    /**
     * 确保采集器已初始化
     */
    private boolean ensureCollectorInitialized() {
        if (!collectorInitialized) {
            try {
                dynamicOidCollector.init();
                collectorInitialized = true;
                log.info("SNMP采集器初始化成功");
            } catch (Exception e) {
                log.error("SNMP采集器初始化失败", e);
                return false;
            }
        }
        return true;
    }
    /**
     * 根据CollectVo列表启动交换机采集任务（支持SNMP v3）
     */
    public void startSwitchCollection(String switchIp, String community, int port, String clientId,
                                      List<CollectVo> collectVos, SwitchOidVo switchOidVo) {
        // 确保采集器已初始化
        if (!ensureCollectorInitialized()) {
            log.error("SNMP采集器未初始化，无法启动交换机 {} 的采集任务", switchIp);
            return;
        }
        // 停止该交换机的现有任务
        stopSwitchCollection(switchIp);

        // 创建交换机配置
        SwitchOidDto switchVo = createSwitchConfig(switchIp, community, port, collectVos, switchOidVo);
        // 交换机心跳监测
        startHeartbeatCheck(switchIp, clientId, switchVo);

        // 初始化存储结构
        Map<String, ScheduledFuture<?>> switchTasks = new ConcurrentHashMap<>();

        // 根据CollectVo配置创建不同的定时任务
        for (CollectVo collectVo : collectVos) {
            if (collectVo.isCollect()) {
                ScheduledFuture<?> task;
                // 剔除switchVo中的其他oid
                if (switchVo.getOtherOID() != null) {
                    Map<String, String> otherOid = switchOidVo.getOtherOID();
                    String type = collectVo.getType();

                    // 创建新的 Map，避免修改原始数据
                    Map<String, String> filteredOid = new HashMap<>(otherOid);
                    filteredOid.entrySet().removeIf(entry ->
                            !entry.getValue().equalsIgnoreCase(extractMiddle(type))
                    );

                    // 创建新的 SwitchOidDto，避免修改原始 switchVo
                    SwitchOidDto resultMap = createSwitchMsg(switchVo);
                    resultMap.setOtherOID(filteredOid);

                    task = createCollectionTask(switchIp, clientId, resultMap, collectVo);
                } else {
                    task = createCollectionTask(switchIp, clientId, switchVo, collectVo);
                }
                if (task != null) {
                    switchTasks.put(collectVo.getType(), task);
                }
            }
        }

        // 存储配置
        allSwitchTasks.put(switchIp, switchTasks);
        allSwitchConfigs.put(switchIp, switchVo);
        allSwitchCollectConfigs.put(switchIp, new ArrayList<>(collectVos));

        log.info("启动交换机 {} 的采集任务，包含 {} 个采集类型{}",
                switchIp, switchTasks.size());
    }

    /**
     * 赋值oid
     * @param switchVo
     */
    public SwitchOidDto createSwitchMsg(SwitchOidDto switchVo){
        SwitchOidDto resultMap = new SwitchOidDto();
        resultMap.setIp(switchVo.getIp());
        resultMap.setCommunity(switchVo.getCommunity());
        resultMap.setPort(switchVo.getPort());
        resultMap.setVersion(switchVo.getVersion());
        resultMap.setTimeout(switchVo.getTimeout());
        resultMap.setRetries(switchVo.getRetries());

        // SNMP v3 特有参数
        resultMap.setSecurityName(switchVo.getSecurityName());
        resultMap.setAuthProtocol(switchVo.getAuthProtocol());
        resultMap.setAuthPassword(switchVo.getAuthPassword());
        resultMap.setPrivProtocol(switchVo.getPrivProtocol());
        resultMap.setPrivPassword(switchVo.getPrivPassword());
        resultMap.setSecurityLevel(switchVo.getSecurityLevel());

        // OID配置（复制所有OID Map）
        resultMap.setNetOID(new LinkedHashMap<>(switchVo.getNetOID()));
        resultMap.setPwrOID(new LinkedHashMap<>(switchVo.getPwrOID()));
        resultMap.setFanOID(new LinkedHashMap<>(switchVo.getFanOID()));
        resultMap.setMpuOID(new LinkedHashMap<>(switchVo.getMpuOID()));
        resultMap.setModuleOID(new LinkedHashMap<>(switchVo.getModuleOID()));
        resultMap.setPowerOID(new LinkedHashMap<>(switchVo.getPowerOID()));

        // 过滤条件
        resultMap.setFilters(new HashMap<>(switchVo.getFilters()));
        return resultMap;
    }
    /**
     * 提取字符串的中间部分（去除固定的前缀和后缀）
     * @param type 输入字符串（如 "switchAssCollect"）
     * @return 中间部分（如 "Ass"）
     */
    public String extractMiddle(String type) {
        if (type == null || type.isEmpty()) {
            return type;
        }

        // 检查是否以 "switch" 开头
        if (!type.startsWith(PREFIX)) {
            throw new IllegalArgumentException("Type must start with 'switch'");
        }

        // 检查是否以 "Collect" 结尾
        if (!type.endsWith(SUFFIX)) {
            throw new IllegalArgumentException("Type must end with 'Collect'");
        }

        // 计算中间部分的起始和结束位置
        int prefixLength = PREFIX.length();
        int suffixLength = SUFFIX.length();
        int middleStart = prefixLength;
        int middleEnd = type.length() - suffixLength;

        // 提取中间部分
        return type.substring(middleStart, middleEnd);
    }
    /**
     * 启动SNMP v3交换机采集任务
     */
    public void startV3SwitchCollection(String switchIp, int port, String clientId, String securityName,
                                        String authProtocol, String authPassword,
                                        String privProtocol, String privPassword,
                                        int securityLevel, List<CollectVo> collectVos,
                                        SwitchOidVo switchOidVo) {
        // 停止该交换机的现有任务
        stopSwitchCollection(switchIp);

        // 创建SNMP v3交换机配置
        SwitchOidDto switchVo = createV3SwitchConfig(switchIp, port, securityName,
                authProtocol, authPassword, privProtocol, privPassword,
                securityLevel, collectVos, switchOidVo);

        // 初始化存储结构
        Map<String, ScheduledFuture<?>> switchTasks = new ConcurrentHashMap<>();

        // 根据CollectVo配置创建不同的定时任务
        for (CollectVo collectVo : collectVos) {
            if (collectVo.isCollect()) {
                ScheduledFuture<?> task = createCollectionTask(switchIp, clientId, switchVo, collectVo);
                if (task != null) {
                    switchTasks.put(collectVo.getType(), task);
                }
            }
        }

        // 存储配置
        allSwitchTasks.put(switchIp, switchTasks);
        allSwitchConfigs.put(switchIp, switchVo);
        allSwitchCollectConfigs.put(switchIp, new ArrayList<>(collectVos));

        log.info("启动SNMP v3交换机 {} 的采集任务，包含 {} 个采集类型{}",
                switchIp, switchTasks.size());
    }

    /**
     * 根据CollectVo创建对应的采集任务
     */
    private ScheduledFuture<?> createCollectionTask(String switchIp, String clientId, SwitchOidDto switchVo, CollectVo collectVo) {
        String type = collectVo.getType();
        long interval = collectVo.getInterval() != null ? collectVo.getInterval() : 300L;
        if (isTrafficCollection(type)) {
            // 流量采集：固定时间点（0,5,10,15...分钟）
            return startTrafficCollection(switchIp, clientId, switchVo, collectVo);
        } else {
            // 常规采集：相对间隔
            return startRegularCollection(switchIp, clientId, switchVo, collectVo);
        }
    }

    /**
     * 启动心跳检测任务（30秒一次）
     */
    private ScheduledFuture<?> startHeartbeatCheck(String switchIp, String clientId, SwitchOidDto switchVo) {
        MessageProducer messageProducer = new MessageProducer();
        // 确保采集器已初始化
        if (!ensureCollectorInitialized()) {
            log.error("SNMP采集器未初始化，无法启动交换机 {} 的心跳检测任务", switchIp);
            return null;
        }
        Runnable heartbeatTask = () -> {
            try {
                // 获取当前时间作为检测时间戳
                long checkTimestamp = System.currentTimeMillis();

                log.debug("[心跳检测] 开始检测交换机 {} 的心跳状态, 时间: {}", switchIp, checkTimestamp);

                // 使用系统名称OID (1.3.6.1.2.1.1.5.0) 进行心跳检测
                // 创建专门用于心跳检测的OID配置
                Map<String, String> heartbeatOids = new HashMap<>();
                heartbeatOids.put("1.3.6.1.2.1.1.5.0", "sysName");

                // 临时设置心跳检测OID
                switchVo.setOtherOID(heartbeatOids);

                long startTime = System.currentTimeMillis();
                CollectionResult result = dynamicOidCollector.getInterfaceInfoByType(switchVo, "other");
                long responseTime = System.currentTimeMillis() - startTime;

                // 设置检测时间戳
                result.setTimestamp(checkTimestamp);
                if(result != null && result.isSuccess()){
                    // 构建心跳消息
                    DeviceMessage message = new DeviceMessage();
                    message.setClientId(clientId);
                    message.setDataType(MsgEnum.心跳上报.getValue());
                    InitialHeartbeatListen initialHeartbeatListen = new InitialHeartbeatListen();
                    initialHeartbeatListen.setClientId(clientId);
                    initialHeartbeatListen.setStrength(31L);
                    initialHeartbeatListen.setName("saa平台");
                    initialHeartbeatListen.setTimestamp(checkTimestamp);
                    String jsonStr = JSONObject.toJSONString(initialHeartbeatListen);
                    message.setData(jsonStr);
                    // 发送消息
                    messageProducer.sendAsyncProducerMessage(
                            "tr_agent_up",
                            "",
                            "heartbeat",
                            JSONObject.toJSONString(message)
                    );
                    log.debug("[心跳检测] 完成检测交换机 {} 的心跳状态, 响应时间: {}ms", switchIp, responseTime);
                }else{
                    log.error("[心跳检测] 检测交换机 {} 心跳失败: {}", switchIp, result.getErrorMessage());
                }

            } catch (Exception e) {
                log.error("[心跳检测] 检测交换机 {} 心跳失败: {}", switchIp, e.getMessage());
            }
        };

        long intervalSeconds = 30L;
        Duration initialDelay = Duration.ofSeconds(10);
        Duration interval = Duration.ofSeconds(intervalSeconds);
        ScheduledFuture<?> future = taskScheduler.scheduleWithFixedDelay(
                heartbeatTask, Instant.now().plus(initialDelay), interval);

        log.info("交换机 {} 心跳检测任务启动，检测间隔: 30秒", switchIp);
        return future;
    }

    /**
     * 判断是否为流量采集
     */
    private boolean isTrafficCollection(String type) {
        return "switchNetCollect".equals(type);
    }

    /**
     * 启动流量采集任务（固定时间点）
     */
    private ScheduledFuture<?> startTrafficCollection(String switchIp, String clientId, SwitchOidDto switchVo, CollectVo collectVo) {
        // 确保采集器已初始化
        if (!ensureCollectorInitialized()) {
            log.error("SNMP采集器未初始化，无法启动交换机 {} 的采集任务", switchIp);
            return null;
        }
        // 创建Cron表达式：每5分钟的第0秒执行（0,5,10,15...）
        String cronExpression = "0 0/5 * * * ?";

        Runnable trafficTask = () -> {
            try {
                // 获取当前时间作为采集时间戳（对齐到5分钟整点）
                long collectionTimestamp = getAlignedTimestamp();

                log.info("[流量采集] 开始采集交换机 {} 的网络数据, 时间: {}", switchIp, collectionTimestamp);

                CollectionResult result = dynamicOidCollector.getInterfaceInfoByType(switchVo, "net");

                // 设置采集时间戳
                result.setTimestamp(collectionTimestamp);

                // 这里可以处理采集结果，比如保存到数据库或发送到消息队列
                processCollectionResult(result, clientId);

                log.info("[流量采集] 完成采集交换机 {} 的网络数据, 时间戳: {}", switchIp, collectionTimestamp);

            } catch (Exception e) {
                log.error("[流量采集] 采集交换机 {} 数据失败: {}", switchIp, e.getMessage());
            }
        };

        CronTrigger trigger = new CronTrigger(cronExpression);
        ScheduledFuture<?> future = taskScheduler.schedule(trafficTask, trigger);

        log.info("交换机 {} 流量采集任务启动，时间点: 每5分钟整点", switchIp);
        return future;
    }
    /**
     * 获取对齐的时间戳（5分钟整点，精确到秒）
     */
    private long getAlignedTimestamp() {
        long currentTime = System.currentTimeMillis() / 1000; // 当前时间戳（秒）

        // 计算5分钟的秒数
        long fiveMinutes = 5 * 60;

        // 对齐到5分钟整点
        long alignedTimestamp = (currentTime / fiveMinutes) * fiveMinutes;

        return alignedTimestamp;
    }
    /**
     * 处理采集结果
     */
    private void processCollectionResult(CollectionResult result, String clientId) {
        if (result.isSuccess()) {
            log.debug("流量采集成功 - 交换机: {}, 设备类型: {}, 时间: {}, 数据量: {}",
                    result.getSwitchIp(), result.getDeviceType(),
                    result.getTimestamp(), result.getData().size());
            processSwitchCollectDataService.handleSwitchDataMessage(result, clientId);

        } else {
            log.warn("流量采集失败 - 交换机: {}, 设备类型: {}, 时间: {}, 错误: {}",
                    result.getSwitchIp(), result.getDeviceType(),
                    result.getTimestamp(), result.getErrorMessage());
        }
    }

    /**
     * 启动常规采集任务（相对间隔）
     */
    private ScheduledFuture<?> startRegularCollection(String switchIp, String clientId, SwitchOidDto switchVo, CollectVo collectVo) {
        // 确保采集器已初始化
        if (!ensureCollectorInitialized()) {
            log.error("SNMP采集器未初始化，无法启动交换机 {} 的采集任务", switchIp);
            return null;
        }
        long intervalSeconds = collectVo.getInterval() != null ? collectVo.getInterval() : 300L;
        Instant startTime = calculateAlignedStartTime(intervalSeconds);
        Duration interval = Duration.ofSeconds(intervalSeconds);

        Runnable regularTask = () -> {
            try {
                log.info("[{}] 开始采集交换机 {} 的数据, 时间: {}",
                        collectVo.getType(), switchIp, LocalDateTime.now());
                // 获取对齐到整分钟的时间戳
                long collectionTimestamp = getAlignedMinuteTimestamp();
                // 根据类型执行对应的采集
                CollectionResult result = executeCollectionByType(switchVo, collectVo.getType());
                // 设置采集时间戳
                result.setTimestamp(collectionTimestamp);
                // 处理采集结果
                processCollectionResult(result, clientId);

                log.info("[{}] 完成采集交换机 {} 的数据", collectVo.getType(), switchIp);

            } catch (Exception e) {
                log.error("[{}] 采集交换机 {} 数据失败: {}",
                        collectVo.getType(), switchIp, e.getMessage());
            }
        };

        ScheduledFuture<?> future = taskScheduler.scheduleWithFixedDelay(
                regularTask, startTime, interval);

        log.info("交换机 {} [{}] 采集任务启动，间隔: {}秒, 开始时间: {}",
                switchIp, collectVo.getType(), intervalSeconds, startTime);
        return future;
    }
    /**
     * 获取对齐到整分钟的时间戳（秒为00）
     */
    private long getAlignedMinuteTimestamp() {
        long currentTime = System.currentTimeMillis() / 1000; // 当前时间戳（秒）

        // 对齐到整分钟（去掉秒部分）
        long alignedTimestamp = (currentTime / 60) * 60;

        return alignedTimestamp;
    }
    /**
     * 根据采集类型执行对应的采集
     */
    private CollectionResult executeCollectionByType(SwitchOidDto switchVo, String type) {
        String deviceType;

        switch (type) {
            case "switchSysDescrCollect":
            case "switchSysObjectIDCollect":
            case "switchSysUpTimeCollect":
            case "switchSysContactCollect":
            case "switchSysNameCollect":
            case "switchSysLocationCollect":
            case "switchHwStackSystemMacCollect":
            case "switchEntIndexCollect":
            case "switchEntPhysicalNameCollect":
            case "switchEntPhysicalSoftwareRevCollect":
            case "switchHwEntityCpuUsageCollect":
            case "switchHwEntityMemUsageCollect":
            case "switchHwAveragePowerCollect":
            case "switchHwCurrentPowerCollect":
                deviceType = "other";
                break;
            case "switchPwrCollect":
                deviceType = "pwr";
                break;
            case "switchFanCollect":
                deviceType = "fan";
                break;
            case "switchMpuCollect":
                deviceType = "mpu";
                break;
            case "switchModuleCollect":
                deviceType = "module";
                break;
            default:
                // 返回错误结果
                throw new RuntimeException(switchVo.getIp() + " 未知的采集类型：" + type);
        }

        return dynamicOidCollector.getInterfaceInfoByType(switchVo, deviceType);
    }

    /**
     * 计算对齐的开始时间（智能对齐到整秒，使用上海时区）
     */
    private Instant calculateAlignedStartTime(long intervalSeconds) {
        // 指定上海时区
        ZoneId shanghaiZone = ZoneId.of("Asia/Shanghai");
        LocalDateTime now = LocalDateTime.now(shanghaiZone);

        LocalDateTime alignedTime;

        // 检查当前时间是否已经是整秒（秒为0）
        if (now.getSecond() == 0) {
            // 如果当前时间已经是整秒，立即开始（或者延迟几秒开始）
            alignedTime = now.plusSeconds(5); // 延迟5秒开始，避免立即执行可能的问题
        } else {
            // 否则对齐到下一分钟的00秒
            alignedTime = now.plusMinutes(1)
                    .withSecond(0)
                    .withNano(0);
        }

        Instant instant = alignedTime.atZone(shanghaiZone).toInstant();

        log.info("任务启动时间: {} (上海时间), 间隔: {}秒", alignedTime, intervalSeconds);
        return instant;
    }

    /**
     * 创建交换机配置（根据SwitchOidVo和CollectVo）
     */
    private SwitchOidDto createSwitchConfig(String ip, String community, int port,
                                            List<CollectVo> collectVos, SwitchOidVo switchOidVo) {
        SwitchOidDto switchVo = new SwitchOidDto(ip, community);
        switchVo.setPort(port);

        switchVo.setVersion(switchOidVo.getVersion());

        // 使用SwitchOidVo中的OID配置
        if (switchOidVo.getNetOID() != null && !switchOidVo.getNetOID().isEmpty()) {
            switchVo.setNetOID(new LinkedHashMap<>(switchOidVo.getNetOID()));
        }

        if (switchOidVo.getOtherOID() != null && !switchOidVo.getOtherOID().isEmpty()) {
            switchVo.setOtherOID(new LinkedHashMap<>(switchOidVo.getOtherOID()));
        }

        if (switchOidVo.getModuleOID() != null && !switchOidVo.getModuleOID().isEmpty()) {
            // 将moduleOID映射到对应的设备类型
            switchVo.setModuleOID(new LinkedHashMap<>(switchOidVo.getModuleOID()));
        }

        // 设置过滤条件
        if (switchOidVo.getFilters() != null && !switchOidVo.getFilters().isEmpty()) {
            switchVo.setFilters(new HashMap<>(switchOidVo.getFilters()));
        }

        // 设置超时和重试次数
        if (switchOidVo.getTimeout() > 0) {
            switchVo.setTimeout(switchOidVo.getTimeout());
        }
        if (switchOidVo.getRetries() > 0) {
            switchVo.setRetries(switchOidVo.getRetries());
        }

        return switchVo;
    }

    /**
     * 创建SNMP v3交换机配置
     */
    private SwitchOidDto createV3SwitchConfig(String ip, int port, String securityName,
                                              String authProtocol, String authPassword,
                                              String privProtocol, String privPassword,
                                              int securityLevel, List<CollectVo> collectVos,
                                              SwitchOidVo switchOidVo) {
        SwitchOidDto switchVo = new SwitchOidDto(ip, null);
        switchVo.setPort(port);
        switchVo.setVersion(SnmpConstants.version3);
        switchVo.setSecurityName(securityName);
        switchVo.setAuthProtocol(authProtocol);
        switchVo.setAuthPassword(authPassword);
        switchVo.setPrivProtocol(privProtocol);
        switchVo.setPrivPassword(privPassword);
        switchVo.setSecurityLevel(securityLevel);

        // 使用SwitchOidVo中的OID配置
        if (switchOidVo.getNetOID() != null && !switchOidVo.getNetOID().isEmpty()) {
            switchVo.setNetOID(new LinkedHashMap<>(switchOidVo.getNetOID()));
        }

        if (switchOidVo.getOtherOID() != null && !switchOidVo.getOtherOID().isEmpty()) {
            switchVo.setOtherOID(new LinkedHashMap<>(switchOidVo.getOtherOID()));
        }

        if (switchOidVo.getModuleOID() != null && !switchOidVo.getModuleOID().isEmpty()) {
            switchVo.setModuleOID(new LinkedHashMap<>(switchOidVo.getModuleOID()));
        }

        // 设置过滤条件
        if (switchOidVo.getFilters() != null && !switchOidVo.getFilters().isEmpty()) {
            switchVo.setFilters(new HashMap<>(switchOidVo.getFilters()));
        }

        // 设置超时和重试次数
        if (switchOidVo.getTimeout() > 0) {
            switchVo.setTimeout(switchOidVo.getTimeout());
        }
        if (switchOidVo.getRetries() > 0) {
            switchVo.setRetries(switchOidVo.getRetries());
        }

        return switchVo;
    }

    /**
     * 停止单个交换机的所有采集任务
     */
    public void stopSwitchCollection(String switchIp) {
        Map<String, ScheduledFuture<?>> tasks = allSwitchTasks.remove(switchIp);
        if (tasks != null) {
            tasks.values().forEach(future -> future.cancel(false));
            log.info("停止交换机 {} 的所有采集任务{}", switchIp);
        }
        allSwitchConfigs.remove(switchIp);
        allSwitchCollectConfigs.remove(switchIp);
    }

    /**
     * 停止所有交换机的采集任务
     */
    public void stopAllSwitchCollections() {
        allSwitchTasks.values().forEach(tasks ->
                tasks.values().forEach(future -> future.cancel(false)));
        allSwitchTasks.clear();
        allSwitchConfigs.clear();
        allSwitchCollectConfigs.clear();
        System.out.println("停止所有交换机的采集任务");
    }

    /**
     * 获取交换机的任务状态
     */
    public Map<String, Object> getSwitchStatus(String switchIp) {
        Map<String, Object> status = new HashMap<>();
        status.put("switchIp", switchIp);

        Map<String, ScheduledFuture<?>> tasks = allSwitchTasks.get(switchIp);
        List<CollectVo> collectConfigs = allSwitchCollectConfigs.get(switchIp);

        if (tasks != null && collectConfigs != null) {
            status.put("isRunning", true);
            status.put("taskCount", tasks.size());

            // 获取交换机配置信息
            SwitchOidDto switchConfig = allSwitchConfigs.get(switchIp);
            if (switchConfig != null) {
                status.put("snmpVersion", switchConfig.getVersion() == SnmpConstants.version3 ? "v3" : "v2c");
                status.put("securityName", switchConfig.getSecurityName());
                status.put("securityLevel", getSecurityLevelDescription(switchConfig.getSecurityLevel()));
            }

            List<Map<String, Object>> taskStatusList = new ArrayList<>();
            for (CollectVo collectVo : collectConfigs) {
                Map<String, Object> taskStatus = new HashMap<>();
                taskStatus.put("type", collectVo.getType());
                taskStatus.put("collect", collectVo.isCollect());
                taskStatus.put("interval", collectVo.getInterval());

                ScheduledFuture<?> task = tasks.get(collectVo.getType());
                taskStatus.put("isActive", task != null && !task.isCancelled());

                taskStatusList.add(taskStatus);
            }
            status.put("tasks", taskStatusList);
        } else {
            status.put("isRunning", false);
        }

        return status;
    }

    /**
     * 获取安全级别描述
     */
    private String getSecurityLevelDescription(int securityLevel) {
        switch (securityLevel) {
            case SecurityLevel.NOAUTH_NOPRIV:
                return "noAuthNoPriv";
            case SecurityLevel.AUTH_NOPRIV:
                return "authNoPriv";
            case SecurityLevel.AUTH_PRIV:
                return "authPriv";
            default:
                return "unknown";
        }
    }

    /**
     * 获取所有交换机的状态
     */
    public Map<String, Map<String, Object>> getAllSwitchesStatus() {
        Map<String, Map<String, Object>> allStatus = new HashMap<>();
        for (String switchIp : allSwitchTasks.keySet()) {
            allStatus.put(switchIp, getSwitchStatus(switchIp));
        }
        return allStatus;
    }

    /**
     * 更新交换机的采集配置
     */
    public void updateSwitchConfig(String switchIp, String community, int port, String clientId,
                                   List<CollectVo> collectVos, SwitchOidVo switchOidVo) {
        // 先停止现有任务
        stopSwitchCollection(switchIp);

        // 重新启动任务
        startSwitchCollection(switchIp, community, port, clientId, collectVos, switchOidVo);
        log.info("更新交换机 {} 的采集配置{}", switchIp);
    }

    /**
     * 更新SNMP v3交换机的采集配置
     */
    public void updateV3SwitchConfig(String switchIp, int port, String clientId, String securityName,
                                     String authProtocol, String authPassword,
                                     String privProtocol, String privPassword,
                                     int securityLevel, List<CollectVo> collectVos,
                                     SwitchOidVo switchOidVo) {
        // 先停止现有任务
        stopSwitchCollection(switchIp);

        // 重新启动任务
        startV3SwitchCollection(switchIp, port, clientId, securityName, authProtocol, authPassword,
                privProtocol, privPassword, securityLevel, collectVos, switchOidVo);
        log.info("更新SNMP v3交换机 {} 的采集配置{}", switchIp);
    }

    /**
     * 批量处理设备配置（支持v2c和v3混合）
     */
    public void batchProcessSwitchConfigurations(List<DeviceConfig> devices) {
        for (DeviceConfig device : devices) {
            try {
                if (device.getVersion() == SnmpConstants.version3) {
                    // SNMP v3设备
                    startV3SwitchCollection(
                            device.getSwitchIp(),
                            device.getPort(),
                            device.getClientId(),
                            device.getSecurityName(),
                            device.getAuthProtocol(),
                            device.getAuthPassword(),
                            device.getPrivProtocol(),
                            device.getPrivPassword(),
                            device.getSecurityLevel(),
                            device.getCollectVos(),
                            device.getSwitchOidVo()
                    );
                } else {
                    // SNMP v2c设备
                    startSwitchCollection(
                            device.getSwitchIp(),
                            device.getCommunity(),
                            device.getPort(),
                            device.getClientId(),
                            device.getCollectVos(),
                            device.getSwitchOidVo()
                    );
                }
            } catch (Exception e) {
                log.error("处理交换机配置失败，switchIp: {}", device.getSwitchIp(), e);
            }
        }
    }

    /**
     * 设备配置类（用于批量处理，支持v2c和v3）
     */
    @Data
    public static class DeviceConfig {
        private String switchIp;
        private String community;
        private int port;
        private String clientId;
        private List<CollectVo> collectVos;
        private SwitchOidVo switchOidVo;

        // SNMP v3特有字段
        private int version = SnmpConstants.version2c; // 默认v2c
        private String securityName;
        private String authProtocol;
        private String authPassword;
        private String privProtocol;
        private String privPassword;
        private int securityLevel = SecurityLevel.AUTH_PRIV; // 默认认证+加密
    }
}