package com.ruoyi.rocketmq.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.enums.MsgEnum;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.rocketmq.domain.*;
import com.ruoyi.rocketmq.domain.vo.*;
import com.ruoyi.rocketmq.mapper.*;
import com.ruoyi.rocketmq.model.ProducerMode;
import com.ruoyi.rocketmq.producer.MessageProducer;
import com.ruoyi.rocketmq.service.IRmMonitorPolicyService;
import com.ruoyi.rocketmq.snmp.scheduler.MultiSwitchCollectionScheduler;
import com.ruoyi.rocketmq.utils.DataProcessUtil;
import com.ruoyi.rocketmq.utils.FieldNameConverterUtil;
import com.ruoyi.system.api.domain.RmResourceRegistrationRemote;
import com.ruoyi.system.api.domain.RmSwitchManagementRemote;
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.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.Instant;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 资源监控策略Service业务层处理
 * 
 * @author gyt
 * @date 2025-09-10
 */
@Service
@Slf4j
public class RmMonitorPolicyServiceImpl implements IRmMonitorPolicyService 
{
    // 对应rocketmq键
    public static final String COLLECT_SUFFIX = "Collect";
    @Autowired
    private ProducerMode producerMode;
    @Autowired
    private RmMonitorPolicyMapper rmMonitorPolicyMapper;
    @Autowired
    private RmTemplateLinuxMapper rmTemplateLinuxMapper;
    @Autowired
    private RmTemplateSwitchMapper rmTemplateSwitchMapper;
    @Autowired
    private RmMonitorTemplateMapper rmMonitorTemplateMapper;
    @Autowired
    private RmInitialMonitorItemMapper rmInitialMonitorItemMapper;
    @Autowired
    private DataProcessUtil dataProcessUtil;

    private final MultiSwitchCollectionScheduler scheduler;

    public RmMonitorPolicyServiceImpl(MultiSwitchCollectionScheduler scheduler) {
        this.scheduler = scheduler;
    }


    /**
     * 查询资源监控策略
     * 
     * @param id 资源监控策略主键
     * @return 资源监控策略
     */
    @Override
    public RmMonitorPolicy selectRmMonitorPolicyById(Long id)
    {
        return rmMonitorPolicyMapper.selectRmMonitorPolicyById(id);
    }

    /**
     * 查询资源监控策略列表
     * 
     * @param rmMonitorPolicy 资源监控策略
     * @return 资源监控策略
     */
    @Override
    public List<RmMonitorPolicy> selectRmMonitorPolicyList(RmMonitorPolicy rmMonitorPolicy)
    {
        List<RmMonitorPolicy> list = rmMonitorPolicyMapper.selectRmMonitorPolicyList(rmMonitorPolicy);
        for (RmMonitorPolicy monitorPolicy : list) {
            // 资源组名称
            if(monitorPolicy.getResourceGroupId() != null){
                monitorPolicy.setResourceGroupName(dataProcessUtil.getResourceGroupNameById(monitorPolicy.getResourceGroupId()));
            }
            // 模板名称
            Long templateId = monitorPolicy.getTemplateId();
            RmMonitorTemplate rmMonitorTemplate = rmMonitorTemplateMapper.selectRmMonitorTemplateById(templateId);
            if(rmMonitorTemplate != null) {
                monitorPolicy.setTemplateName(rmMonitorTemplate.getTemplateName());
            }
        }
        return list;
    }

    /**
     * 新增资源监控策略
     * 
     * @param rmMonitorPolicy 资源监控策略
     * @return 结果
     */
    @Override
    public int insertRmMonitorPolicy(RmMonitorPolicy rmMonitorPolicy)
    {
        rmMonitorPolicy.setCreateTime(DateUtils.getNowDate());
        return rmMonitorPolicyMapper.insertRmMonitorPolicy(rmMonitorPolicy);
    }

    /**
     * 修改资源监控策略
     * 
     * @param rmMonitorPolicy 资源监控策略
     * @return 结果
     */
    @Override
    public int updateRmMonitorPolicy(RmMonitorPolicy rmMonitorPolicy)
    {
        // 绑定资源组之前判断该资源组是否已经绑定其他模板
        Long resourceGroupId = rmMonitorPolicy.getResourceGroupId();
        // 查询资源组是否已绑定
        RmMonitorPolicy queryParam = new RmMonitorPolicy();
        queryParam.setResourceGroupId(resourceGroupId);
        List<RmMonitorPolicy> exits = rmMonitorPolicyMapper.selectRmMonitorPolicyList(queryParam);
        if(!exits.isEmpty()){
            if(exits.get(0).getId() != rmMonitorPolicy.getId()){
                return -1;
            }
        }
        rmMonitorPolicy.setUpdateTime(DateUtils.getNowDate());
        // 策略状态改为待下发
        rmMonitorPolicy.setStatus("0");
        rmMonitorPolicyMapper.updateRmMonitorPolicy(rmMonitorPolicy);
        // 模板绑定资源组信息
        RmMonitorTemplate rmMonitorTemplate = new RmMonitorTemplate();
        rmMonitorTemplate.setId(rmMonitorPolicy.getTemplateId());
        rmMonitorTemplate.setResourceGroupId(rmMonitorPolicy.getResourceGroupId());
        rmMonitorTemplateMapper.updateRmMonitorTemplate(rmMonitorTemplate);
        // 拿到采集周期
        List<RmMonitorPolicyVo> collectionAndIdList = rmMonitorPolicy.getCollectionAndIdList();
        if(!collectionAndIdList.isEmpty()){
            if("linux".equals(rmMonitorPolicy.getResourceType())){
                // 修改之前先置空所有采集周期
                rmTemplateLinuxMapper.updateByTemplateId(rmMonitorPolicy.getTemplateId());
                for (RmMonitorPolicyVo rmMonitorPolicyVo : collectionAndIdList) {
                    // 添加采集周期
                    RmTemplateLinux rmTemplateLinux = new RmTemplateLinux();
                    rmTemplateLinux.setId(rmMonitorPolicyVo.getId());
                    rmTemplateLinux.setCollectionCycle(rmMonitorPolicyVo.getCollectionCycle());
                    rmTemplateLinuxMapper.updateRmTemplateLinux(rmTemplateLinux);
                }
            }else if("switch".equals(rmMonitorPolicy.getResourceType())){
                // 修改之前先置空所有采集周期
                rmTemplateSwitchMapper.updateByTemplateId(rmMonitorPolicy.getTemplateId());
                for (RmMonitorPolicyVo rmMonitorPolicyVo : collectionAndIdList) {
                    // 添加采集周期
                    RmTemplateSwitch rmTemplateSwitch = new RmTemplateSwitch();
                    rmTemplateSwitch.setId(rmMonitorPolicyVo.getId());
                    rmTemplateSwitch.setCollectionCycle(rmMonitorPolicyVo.getCollectionCycle());
                    rmTemplateSwitchMapper.updateRmTemplateSwitch(rmTemplateSwitch);
                }
            }else {
                return 0;
            }
        }
        return 1;
    }

    /**
     * 批量删除资源监控策略
     * 
     * @param ids 需要删除的资源监控策略主键
     * @return 结果
     */
    @Override
    public int deleteRmMonitorPolicyByIds(Long[] ids)
    {
        for (Long id : ids) {
            // 根据id查询策略详情
            RmMonitorPolicy rmMonitorPolicy = rmMonitorPolicyMapper.selectRmMonitorPolicyById(id);
            Long templateId = rmMonitorPolicy.getTemplateId();
            // 删除策略的时候，把该模板的采集周期置空

            rmTemplateLinuxMapper.updateByTemplateId(templateId);
            rmTemplateSwitchMapper.updateByTemplateId(templateId);
            if(rmMonitorPolicy.getTemplateId()==null){
                rmTemplateLinuxMapper.deleteByPolicyId(id);
                rmTemplateSwitchMapper.deleteByPolicyId(id);
            }
        }
        return rmMonitorPolicyMapper.deleteRmMonitorPolicyByIds(ids);
    }

    /**
     * 删除资源监控策略信息
     * 
     * @param id 资源监控策略主键
     * @return 结果
     */
    @Override
    public int deleteRmMonitorPolicyById(Long id)
    {
        return rmMonitorPolicyMapper.deleteRmMonitorPolicyById(id);
    }

    @Override
    public int addRmMonitorPolicy(RmMonitorPolicy rmMonitorPolicy) {
        // 绑定资源组之前判断该资源组是否已经绑定其他模板
        Long resourceGroupId = rmMonitorPolicy.getResourceGroupId();
        // 查询资源组是否已绑定
        RmMonitorPolicy queryParam = new RmMonitorPolicy();
        queryParam.setResourceGroupId(resourceGroupId);
        List<RmMonitorPolicy> exits = rmMonitorPolicyMapper.selectRmMonitorPolicyList(queryParam);
        if(!exits.isEmpty()){
            return -1;
        }
        rmMonitorPolicyMapper.insertRmMonitorPolicy(rmMonitorPolicy);
        // 模板绑定资源组信息
        RmMonitorTemplate rmMonitorTemplate = new RmMonitorTemplate();
        rmMonitorTemplate.setId(rmMonitorPolicy.getTemplateId());
        rmMonitorTemplate.setResourceGroupId(rmMonitorPolicy.getResourceGroupId());
        rmMonitorTemplateMapper.updateRmMonitorTemplate(rmMonitorTemplate);
        // 拿到采集周期
        List<RmMonitorPolicyVo> collectionAndIdList = rmMonitorPolicy.getCollectionAndIdList();
        if(!collectionAndIdList.isEmpty()){
            if("linux".equals(rmMonitorPolicy.getResourceType())){
                for (RmMonitorPolicyVo rmMonitorPolicyVo : collectionAndIdList) {
                    // 添加采集周期
                    RmTemplateLinux rmTemplateLinux = new RmTemplateLinux();
                    rmTemplateLinux.setId(rmMonitorPolicyVo.getId());
                    rmTemplateLinux.setCollectionCycle(rmMonitorPolicyVo.getCollectionCycle());
                    rmTemplateLinuxMapper.updateRmTemplateLinux(rmTemplateLinux);
                }
            }else if("switch".equals(rmMonitorPolicy.getResourceType())){
                for (RmMonitorPolicyVo rmMonitorPolicyVo : collectionAndIdList) {
                    // 添加采集周期
                    RmTemplateSwitch rmTemplateSwitch = new RmTemplateSwitch();
                    rmTemplateSwitch.setId(rmMonitorPolicyVo.getId());
                    rmTemplateSwitch.setCollectionCycle(rmMonitorPolicyVo.getCollectionCycle());
                    rmTemplateSwitchMapper.updateRmTemplateSwitch(rmTemplateSwitch);
                }
            }else {
                return 0;
            }
        }
        return 1;
    }

    @Override
    public int addResourcePolicy(RmMonitorPolicy rmMonitorPolicy) {
        // 保存策略信息
        rmMonitorPolicy.setCreateBy(SecurityUtils.getUsername());
        rmMonitorPolicyMapper.insertRmMonitorPolicy(rmMonitorPolicy);
        // 拿到采集周期
        List<RmMonitorPolicyVo> collectionAndIdList = rmMonitorPolicy.getCollectionAndIdList();
        if(!collectionAndIdList.isEmpty()){
            if("linux".equals(rmMonitorPolicy.getResourceType())){
                for (RmMonitorPolicyVo rmMonitorPolicyVo : collectionAndIdList) {
                    RmInitialMonitorItem monitorItems = rmInitialMonitorItemMapper.selectRmInitialMonitorItemById(rmMonitorPolicyVo.getId());
                    RmTemplateLinux linuxItem = new RmTemplateLinux();
                    linuxItem.setPolicyId(rmMonitorPolicy.getId());
                    linuxItem.setMetricKey(monitorItems.getMetricKey());
                    linuxItem.setMetricName(monitorItems.getMetricName());
                    linuxItem.setDataType(monitorItems.getDataType());
                    linuxItem.setItemType(monitorItems.getItemType());
                    linuxItem.setCollectionCycle(rmMonitorPolicyVo.getCollectionCycle());
                    rmTemplateLinuxMapper.insertRmTemplateLinux(linuxItem);
                }
            }else if("switch".equals(rmMonitorPolicy.getResourceType())){
                for (RmMonitorPolicyVo rmMonitorPolicyVo : collectionAndIdList) {
                    // 根据监控信息id查询详细信息
                    RmInitialMonitorItem monitorItems = rmInitialMonitorItemMapper.selectRmInitialMonitorItemById(rmMonitorPolicyVo.getId());
                    RmTemplateSwitch switchItem = new RmTemplateSwitch();
                    switchItem.setPolicyId(rmMonitorPolicy.getId());
                    switchItem.setMetricKey(monitorItems.getMetricKey());
                    switchItem.setMetricName(monitorItems.getMetricName());
                    switchItem.setOid(monitorItems.getOid());
                    switchItem.setFilterValue(monitorItems.getFilterValue());
                    switchItem.setSwitchDescription(monitorItems.getMonitorDescription());
                    switchItem.setDataType(monitorItems.getDataType());
                    switchItem.setItemType(monitorItems.getItemType());
                    switchItem.setCollectionCycle(rmMonitorPolicyVo.getCollectionCycle());
                    rmTemplateSwitchMapper.insertRmTemplateSwitch(switchItem);
                }
                // 添加交换机策略完成 下发该策略
                issueSwitchPolicy(rmMonitorPolicy.getId());
            }else {
                return 0;
            }
        }
        return 1;
    }
    /**
     * 修改资源监控策略
     *
     * @param rmMonitorPolicy 资源监控策略
     * @return 结果
     */
    @Override
    public int updateResourcePolicy(RmMonitorPolicy rmMonitorPolicy)
    {
        rmMonitorPolicy.setUpdateTime(DateUtils.getNowDate());
        // 策略状态改为待下发
        rmMonitorPolicy.setStatus("0");
        rmMonitorPolicyMapper.updateRmMonitorPolicy(rmMonitorPolicy);
        // 拿到采集周期
        List<RmMonitorPolicyVo> collectionAndIdList = rmMonitorPolicy.getCollectionAndIdList();
        if(!collectionAndIdList.isEmpty()){
            if("linux".equals(rmMonitorPolicy.getResourceType())){
                // 修改之前先删除
                rmTemplateLinuxMapper.deleteByPolicyId(rmMonitorPolicy.getId());
                for (RmMonitorPolicyVo rmMonitorPolicyVo : collectionAndIdList) {
                    RmInitialMonitorItem monitorItems = rmInitialMonitorItemMapper.selectRmInitialMonitorItemById(rmMonitorPolicyVo.getId());
                    RmTemplateLinux linuxItem = new RmTemplateLinux();
                    linuxItem.setPolicyId(rmMonitorPolicy.getId());
                    linuxItem.setMetricKey(monitorItems.getMetricKey());
                    linuxItem.setMetricName(monitorItems.getMetricName());
                    linuxItem.setDataType(monitorItems.getDataType());
                    linuxItem.setItemType(monitorItems.getItemType());
                    linuxItem.setCollectionCycle(rmMonitorPolicyVo.getCollectionCycle());
                    rmTemplateLinuxMapper.insertRmTemplateLinux(linuxItem);
                }
            }else if("switch".equals(rmMonitorPolicy.getResourceType())){
                // 修改之前先置空所有采集周期
                rmTemplateSwitchMapper.deleteByPolicyId(rmMonitorPolicy.getId());
                for (RmMonitorPolicyVo rmMonitorPolicyVo : collectionAndIdList) {
                    // 添加采集周期
                    RmInitialMonitorItem monitorItems = rmInitialMonitorItemMapper.selectRmInitialMonitorItemById(rmMonitorPolicyVo.getId());
                    RmTemplateSwitch switchItem = new RmTemplateSwitch();
                    switchItem.setPolicyId(rmMonitorPolicy.getId());
                    switchItem.setMetricKey(monitorItems.getMetricKey());
                    switchItem.setMetricName(monitorItems.getMetricName());
                    switchItem.setOid(monitorItems.getOid());
                    switchItem.setFilterValue(monitorItems.getFilterValue());
                    switchItem.setSwitchDescription(monitorItems.getMonitorDescription());
                    switchItem.setDataType(monitorItems.getDataType());
                    switchItem.setItemType(monitorItems.getItemType());
                    switchItem.setCollectionCycle(rmMonitorPolicyVo.getCollectionCycle());
                    rmTemplateSwitchMapper.insertRmTemplateSwitch(switchItem);
                }
            }else {
                return 0;
            }
        }
        return 1;
    }

    @Override
    public int updatePolicyMsgInner(RmMonitorPolicy rmMonitorPolicy) {
        return rmMonitorPolicyMapper.updateRmMonitorPolicy(rmMonitorPolicy);
    }

    /**
     * 根据id查询监控策略详情
     * @param id
     * @return
     */
    @Override
    public Map<String, Object> getRmMonitorPolicyMsgById(Long id) {
        Map<String, Object> result = new HashMap<>();

        // 1. 获取资源监控策略基础信息
        RmMonitorPolicy rmMonitorPolicy = rmMonitorPolicyMapper.selectRmMonitorPolicyById(id);
        if(rmMonitorPolicy != null){
            String clientIds = rmMonitorPolicy.getDeployDevice();
            if(clientIds != null){
                String[] clientArr = clientIds.split("\n");
                if(StringUtils.equals("switch",rmMonitorPolicy.getResourceType())){
                    List<String> names = new ArrayList<>();
                    for (String clientId : clientArr) {
                        // 根据clientId查询设备名称
                        String switchName = dataProcessUtil.getDeviceNameByClientId(clientId);
                        names.add(switchName);
                    }
                    rmMonitorPolicy.setDeployDevice(String.join(",", names));
                }
                if(StringUtils.equals("linux",rmMonitorPolicy.getResourceType())){
                    rmMonitorPolicy.setDeployDevice(String.join(",", clientArr));
                }
            }
            if(rmMonitorPolicy.getResourceGroupId()!=null){
                rmMonitorPolicy.setResourceGroupName(dataProcessUtil.getResourceGroupNameById(rmMonitorPolicy.getResourceGroupId()));
            }
            result.put("policy", rmMonitorPolicy);
            // 模板id
            Long templateId = rmMonitorPolicy.getTemplateId() == null ? id : rmMonitorPolicy.getTemplateId();

            if(rmMonitorPolicy.getTemplateId() == null){
                // 2. 处理Linux模板数据
                dataProcessUtil.processLinuxPolicyData(templateId, result);

                // 3. 处理Switch模板数据
                dataProcessUtil.processSwitchPolicyData(templateId, result);
            }else{
                // 2. 处理Linux模板数据
                dataProcessUtil.processLinuxTemplateData(templateId, result);

                // 3. 处理Switch模板数据
                dataProcessUtil.processSwitchTemplateData(templateId, result);
            }
        }

        return result;
    }
    /**
     * 下发策略v1.1
     * @param id
     * @return
     */
    @Override
    public int issueSwitchPolicy(Long id) {
        try {
            // 获取策略详情和资源设备
            RmMonitorPolicy policy = rmMonitorPolicyMapper.selectRmMonitorPolicyById(id);
            if (policy == null) {
                log.error("策略不存在，id: {}", id);
                return 0;
            }
            // 构建并发送采集配置
            Map<String, Object> policyDetails = getRmMonitorPolicyMsgById(id);
            boolean isSwitch = false;
            if(policyDetails.get("switch") != null){
                isSwitch = true;
            }
            List<CollectVo> collectVos = buildCollectConfigurations(policyDetails);
            // 去重
            List<CollectVo> uniqueList = collectVos.stream().distinct().collect(Collectors.toList());
            if(isSwitch){
                SwitchOidVo switchOidVo = buildOids(policyDetails);
                startCollectSwitchMsgToDevices(policy.getDeployDevice(), uniqueList, switchOidVo);
            }
            // 更新策略状态为已下发
            if("1".equals(policy.getPriority()) && "0".equals(policy.getStatus())){
                RmMonitorPolicy policyUpdate = new RmMonitorPolicy();
                policyUpdate.setId(id);
                policyUpdate.setStatus("1");
                policyUpdate.setDeployTime(DateUtils.getNowDate());
                rmMonitorPolicyMapper.updateRmMonitorPolicy(policyUpdate);
            }
            return 1;
        } catch (Exception e) {
            log.error("下发策略失败，id: {}", id, e);
            return 0;
        }
    }

    /**
     * 下发策略
     * @param id
     * @return
     */
    @Override
    public int issuePolicy(Long id) {
        try {
            // 获取策略详情和资源设备
            RmMonitorPolicy policy = rmMonitorPolicyMapper.selectRmMonitorPolicyById(id);
            if (policy == null) {
                log.error("策略不存在，id: {}", id);
                return 0;
            }

            List<RmResourceRegistrationRemote> devices = dataProcessUtil.getResourceDevices(policy.getResourceGroupId());
            if (CollectionUtils.isEmpty(devices)) {
                return 0;
            }

            // 构建并发送采集配置
            Map<String, Object> policyDetails = getRmMonitorPolicyMsgById(id);
            boolean isSwitch = false;
            if(policyDetails.get("switch") != null){
                isSwitch = true;
            }
            List<CollectVo> collectVos = buildCollectConfigurations(policyDetails);
            // 去重
            List<CollectVo> uniqueList = collectVos.stream().distinct().collect(Collectors.toList());
            if(isSwitch){
                SwitchOidVo switchOidVo = buildOids(policyDetails);
                sendSwitchConfigurationsToDevices(devices, uniqueList, switchOidVo);
            }else{
                sendConfigurationsToDevices(devices, uniqueList);
            }
            // 更新策略状态为已下发
            RmMonitorPolicy policyUpdate = new RmMonitorPolicy();
            policyUpdate.setId(id);
            policyUpdate.setStatus("1");
            rmMonitorPolicyMapper.updateRmMonitorPolicy(policyUpdate);

            return 1;
        } catch (Exception e) {
            log.error("下发策略失败，id: {}", id, e);
            return 0;
        }
    }
    /**
     * 根据clientId下发优先级为0的监控策略信息
     * @param clientId
     * @return
     */
    @Override
    public int issueDefaultPolicyByClientId(String clientId) {
        try {
            // 根据clientId查询未下发的策略信息
            RmMonitorPolicy queryParam = new RmMonitorPolicy();
            queryParam.setPriority("0");
            queryParam.setResourceType("linux");

            // 添加NPE保护
            List<RmMonitorPolicy> policies = Optional.ofNullable(rmMonitorPolicyMapper.selectRmMonitorPolicyList(queryParam))
                    .orElse(Collections.emptyList());

            if (policies.isEmpty()) {
                log.warn("未设置默认策略，clientId: {}", clientId);
                return 0;
            }

            // 构建并发送采集配置
            Map<String, Object> policyDetails = Optional.ofNullable(getRmMonitorPolicyMsgById(policies.get(0).getId()))
                    .orElse(Collections.emptyMap());

            List<CollectVo> collectVos = Optional.ofNullable(buildCollectConfigurations(policyDetails))
                    .orElse(Collections.emptyList());

            // 去重
            List<CollectVo> uniqueList = collectVos.stream().distinct().collect(Collectors.toList());
            String[] clientIdArr = new String[]{clientId};
            sendMonitorPolicy(clientIdArr, uniqueList);
            return 1;
        } catch (Exception e) {
            log.error("下发策略失败，clientId: {}", clientId, e);
            return 0;
        }
    }
    /**
     * 根据clientId下发监控策略信息
     * @param clientId
     * @return
     */
    @Override
    public int issuePolicyMsgByClientId(String clientId) {
        try {
            // 根据clientId查询未下发的策略信息
            RmMonitorPolicy queryParam = new RmMonitorPolicy();
            queryParam.setDeployDevice(clientId);
            queryParam.setPriority("1");
            queryParam.setStatus("0");
            queryParam.setResourceType("linux");
            RmMonitorPolicy policy = rmMonitorPolicyMapper.selectRmMonitorPolicyByClientId(queryParam);
            if (policy == null) {
                log.warn("无待下发策略，clientId: {}", clientId);
                return 0;
            }

            // 构建并发送采集配置
            Map<String, Object> policyDetails = getRmMonitorPolicyMsgById(policy.getId());
            List<CollectVo> collectVos = buildCollectConfigurations(policyDetails);
            // 去重
            List<CollectVo> uniqueList = collectVos.stream().distinct().collect(Collectors.toList());
            String[] clientIdArr = policy.getDeployDevice().split("\n");
            sendMonitorPolicy(clientIdArr, uniqueList);
            // 更新策略状态为已下发
            RmMonitorPolicy policyUpdate = new RmMonitorPolicy();
            policyUpdate.setId(policy.getId());
            policyUpdate.setStatus("1");
            rmMonitorPolicyMapper.updateRmMonitorPolicy(policyUpdate);
            return 1;
        } catch (Exception e) {
            log.error("下发策略失败，clientId: {}", clientId, e);
            return 0;
        }
    }
    /**
     * 发送监控策略到设备
     */
    private void sendMonitorPolicy(String[] clientIdArr, List<CollectVo> collectVos) {
        MessageProducer messageProducer = new MessageProducer();

        PolicyVo<CollectVo> policyVo = new PolicyVo();
        policyVo.setContents(collectVos);
        String policyVoStr = JSONObject.toJSONString(policyVo);
        PolicyTypeVo policyTypeVo = new PolicyTypeVo();
        policyTypeVo.setMonitors(policyVoStr);
        String configJson = JSONObject.toJSONString(policyTypeVo);
        for (String clientId : clientIdArr) {
            try {
                DeviceMessage message = new DeviceMessage();
                message.setClientId(clientId);
                message.setData(configJson);
                message.setDataType(MsgEnum.获取最新策略应答.getValue());

                messageProducer.sendDelayMessage(
                        producerMode.getAgentTopic(),
                        "",
                        "",
                        JSONObject.toJSONString(message),1
                );
            } catch (Exception e) {
                log.error("发送设备配置失败，clientId: {}", clientId, e);
            }
        }
    }
    private SwitchOidVo buildOids(Map<String, Object> policyDetails) {
        // 处理Switch配置
        Map<String, List<RmTemplateSwitch>> switchConfigs = (Map<String, List<RmTemplateSwitch>>) policyDetails.get("switch");
        // 拿到所有oid
        SwitchOidVo switchOidVo = processSwitchOids(switchConfigs, new String[]{"switchOther", "switchMpu", "switchPwr", "switchNet", "switchModule", "switchFan"});
        return switchOidVo;
    }


    /**
     * 构建采集配置
     */
    private List<CollectVo> buildCollectConfigurations(Map<String, Object> policyDetails) {
        List<CollectVo> collectVos = new ArrayList<>();

        // 处理Linux配置
        if (policyDetails.containsKey("linux")) {
            Map<String, List<RmTemplateLinux>> linuxConfigs = (Map<String, List<RmTemplateLinux>>) policyDetails.get("linux");
            processConfigurations(linuxConfigs, collectVos, new String[]{"cpu", "other", "vfs", "net", "disk", "docker"});
        }

        // 处理Switch配置
        if (policyDetails.containsKey("switch")) {
            Map<String, List<RmTemplateSwitch>> switchConfigs = (Map<String, List<RmTemplateSwitch>>) policyDetails.get("switch");
            processConfigurations(switchConfigs, collectVos, new String[]{"switchOther", "switchMpu", "switchPwr", "switchNet", "switchModule", "switchFan"});
        }

        return collectVos;
    }

    /**
     * 通用配置处理方法
     */
    private <T> void processConfigurations(Map<String, List<T>> configs, List<CollectVo> collectVos, String[] types) {
        for (String type : types) {
            if (configs.get(type) != null) {
                for (T config : configs.get(type)) {
                    CollectVo vo = new CollectVo();
                    vo.setCollect(true);

                    if (config instanceof RmTemplateLinux) {
                        RmTemplateLinux linuxConfig = (RmTemplateLinux) config;
                        if("other".equals(type)){
                            vo.setType(FieldNameConverterUtil.convertToJavaProperty(linuxConfig.getMetricKey()));
                        }else{
                            vo.setType(type + COLLECT_SUFFIX);
                        }
                        vo.setInterval(linuxConfig.getCollectionCycle());
                    } else if (config instanceof RmTemplateSwitch) {
                        RmTemplateSwitch switchConfig = (RmTemplateSwitch) config;
                        if("switchOther".equals(type)){
                            vo.setType(FieldNameConverterUtil.convertToSwitchProperty(switchConfig.getMetricKey()));
                        }else{
                            vo.setType(type + COLLECT_SUFFIX);
                        }
                        vo.setInterval(switchConfig.getCollectionCycle());
                    }

                    collectVos.add(vo);
                }
            }
        }
    }
    private <T> SwitchOidVo processSwitchOids(Map<String, List<T>> configs, String[] types) {
        // oid集合
        Map<String, Map<String, String>> resultMap = new HashMap<>();
        // 过滤值集合
        List<String> otherFilterValueList = new ArrayList<>();
        List<String> netFilterValueList = new ArrayList<>();
        List<String> moduleFilterValueList = new ArrayList<>();
        List<String> mpuFilterValueList = new ArrayList<>();
        List<String> pwrFilterValueList = new ArrayList<>();
        List<String> fanFilterValueList = new ArrayList<>();

        // 初始化各个OID类型的Map
        resultMap.put("otherOID", new HashMap<>());
        resultMap.put("netOID", new HashMap<>());
        resultMap.put("moduleOID", new HashMap<>());
        resultMap.put("mpuOID", new HashMap<>());
        resultMap.put("pwrOID", new HashMap<>());
        resultMap.put("fanOID", new HashMap<>());
        for (String type : types) {
            if (configs.get(type) != null) {
                for (T config : configs.get(type)) {
                    if (config instanceof RmTemplateSwitch) {
                        RmTemplateSwitch switchConfig = (RmTemplateSwitch) config;
                        String oid = switchConfig.getOid();
                        String metricKey = switchConfig.getMetricKey();
                        String filterValue = switchConfig.getFilterValue();

                        switch(type) {
                            case "switchOther":
                                resultMap.get("otherOID").put(oid, metricKey);
                                if(filterValue != null){
                                    otherFilterValueList.add(filterValue);
                                }
                                break;
                            case "switchMpu":
                                resultMap.get("mpuOID").put(oid, metricKey);
                                if(filterValue != null){
                                    mpuFilterValueList.add(filterValue);
                                }
                                break;
                            case "switchPwr":
                                resultMap.get("pwrOID").put(oid, metricKey);
                                if(filterValue != null){
                                    pwrFilterValueList.add(filterValue);
                                }
                                break;
                            case "switchNet":
                                if(oid != null && oid != "null"){
                                    resultMap.get("netOID").put(oid, metricKey);
                                    if(filterValue != null){
                                        netFilterValueList.add(filterValue);
                                    }
                                }
                                break;
                            case "switchModule":
                                resultMap.get("moduleOID").put(oid, metricKey);
                                if(filterValue != null){
                                    moduleFilterValueList.add(filterValue);
                                }
                                break;
                            case "switchFan":
                                resultMap.get("fanOID").put(oid, metricKey);
                                if(filterValue != null){
                                    fanFilterValueList.add(filterValue);
                                }
                                break;
                            default:
                                break;
                        }
                    }
                }
            }
        }
        Map<String, List<String>> filtersMap = new HashMap();
        filtersMap.put("otherOID", otherFilterValueList);
        filtersMap.put("netOID", netFilterValueList);
        filtersMap.put("moduleOID", moduleFilterValueList);
        filtersMap.put("mpuOID", mpuFilterValueList);
        filtersMap.put("pwrOID", pwrFilterValueList);
        filtersMap.put("fanOID", fanFilterValueList);
        SwitchOidVo switchOidVo = new SwitchOidVo();
        // 将Map转换为字符串格式
        switchOidVo.setOtherOID(resultMap.get("otherOID"));
        switchOidVo.setNetOID(resultMap.get("netOID"));
        switchOidVo.setModuleOID(resultMap.get("moduleOID"));
        switchOidVo.setMpuOID(resultMap.get("mpuOID"));
        switchOidVo.setPwrOID(resultMap.get("pwrOID"));
        switchOidVo.setFanOID(resultMap.get("fanOID"));
        switchOidVo.setFilters(filtersMap);
        return switchOidVo;
    }

    /**
     * 发送配置到设备
     */
    private void sendConfigurationsToDevices(List<RmResourceRegistrationRemote> devices, List<CollectVo> collectVos) {
        MessageProducer messageProducer = new MessageProducer();
        Map map = new HashMap();
        map.put("collects", collectVos);
        map.put("timestamp", Instant.now().getEpochSecond());
        String configJson = JSONObject.toJSONString(map);
        Map stopMap = new HashMap();
        map.put("timestamp", Instant.now().getEpochSecond());

        for (RmResourceRegistrationRemote device : devices) {
            try {
                DeviceMessage stopMsg = new DeviceMessage();
                stopMsg.setClientId(device.getHardwareSn());
                stopMsg.setData(JSONObject.toJSONString(stopMap));
                stopMsg.setDataType(MsgEnum.关闭系统采集.getValue());

                messageProducer.sendAsyncProducerMessage(
                        producerMode.getAgentTopic(),
                        "",
                        "",
                        JSONObject.toJSONString(stopMsg)
                );
                DeviceMessage message = new DeviceMessage();
                message.setClientId(device.getHardwareSn());
                message.setData(configJson);
                message.setDataType(MsgEnum.开启系统采集.getValue());
                // 延迟1s防止同时读取关闭和开启
                messageProducer.sendDelayMessage(
                        producerMode.getAgentTopic(),
                        "",
                        "",
                        JSONObject.toJSONString(message),1
                );
            } catch (Exception e) {
                log.error("发送设备配置失败，deviceId: {}", device.getHardwareSn(), e);
            }
        }
    }
    /**
     * 发送配置到设备
     */
    private void sendSwitchConfigurationsToDevices(List<RmResourceRegistrationRemote> devices, List<CollectVo> collectVos, SwitchOidVo switchOidVo) {
        MessageProducer messageProducer = new MessageProducer();
        Map map = new HashMap();
        map.put("collects", collectVos);
        map.put("timestamp", Instant.now().getEpochSecond());
        Map stopCollectMap = new HashMap();
        map.put("timestamp", Instant.now().getEpochSecond());
        String configJson = JSONObject.toJSONString(map);

        for (RmResourceRegistrationRemote device : devices) {
            try {
                String clientIp = device.getIpAddress();
                String clientPort = device.getResourcePort();
                // 交换机信息
                String switchIp = device.getSnmpCollectAddr();
                String switchPort = device.getSnmpCollectPort();
                String community = device.getTeamName();
                switchOidVo.setIp(switchIp);
                switchOidVo.setCommunity(community);
                switchOidVo.setPort(Integer.valueOf(switchPort));
                RegisterSwitchVo registerSwitchVo = new RegisterSwitchVo();
                registerSwitchVo.setClientIp(clientIp);
                registerSwitchVo.setClientPort(Integer.valueOf(clientPort));
                registerSwitchVo.setSwitchBoard(switchOidVo);
                DeviceMessage registerMessage = new DeviceMessage();
                registerMessage.setDataType(MsgEnum.注册.getValue());
                registerMessage.setData(JSONObject.toJSONString(registerSwitchVo));
                registerMessage.setClientId(device.getHardwareSn());
                // 交换机注册
                messageProducer.sendAsyncProducerMessage(
                        producerMode.getAgentTopic(),
                        "",
                        "",
                        JSONObject.toJSONString(registerMessage)
                );
                // 先停止采集，再开启采集，防止采集其他策略的信息
                DeviceMessage stopCollectMsg = new DeviceMessage();
                stopCollectMsg.setClientId(device.getHardwareSn());
                stopCollectMsg.setData(JSONObject.toJSONString(stopCollectMap));
                stopCollectMsg.setDataType(MsgEnum.关闭交换机采集.getValue());
                // 待注册后下发策略，1秒延迟
                messageProducer.sendDelayMessage(
                        producerMode.getAgentTopic(),
                        "",
                        "",
                        JSONObject.toJSONString(stopCollectMsg),1
                );
                // 交换机采集
                DeviceMessage message = new DeviceMessage();
                message.setClientId(device.getHardwareSn());
                message.setData(configJson);
                message.setDataType(MsgEnum.开启交换机采集.getValue());
                // 待注册后下发策略，5秒延迟
                messageProducer.sendDelayMessage(
                        producerMode.getAgentTopic(),
                        "",
                        "",
                        JSONObject.toJSONString(message),2
                );
            } catch (Exception e) {
                log.error("发送设备配置失败，deviceId: {}", device.getHardwareSn(), e);
            }
        }
    }
    /**
     * 开始采集交换机信息 (支持SNMP v1/v2c/v3)
     */
    private void startCollectSwitchMsgToDevices(String clientIds, List<CollectVo> collectVos, SwitchOidVo switchOidVo) {
        String[] clientIdArray = clientIds.split("\n");
        List<MultiSwitchCollectionScheduler.DeviceConfig> deviceConfigs = new ArrayList<>();

        for (String clientId : clientIdArray) {
            try {
                // 根据clientId 查询 交换机信息
                RmSwitchManagementRemote switchMsg = dataProcessUtil.getSwitchMsg(clientId);
                if(switchMsg == null){
                    continue;
                }
                String switchIp = switchMsg.getSnmpAddress();
                String community = switchMsg.getCommunityName();
                int port = Math.toIntExact(switchMsg.getSnmpPort());

                // 获取SNMP版本
                String snmpVersion = switchMsg.getSnmpVersion();
                int version = parseSnmpVersion(snmpVersion);

                // 创建设备配置
                MultiSwitchCollectionScheduler.DeviceConfig deviceConfig =
                        new MultiSwitchCollectionScheduler.DeviceConfig();
                deviceConfig.setSwitchIp(switchIp);
                deviceConfig.setPort(port);
                deviceConfig.setClientId(clientId);
                deviceConfig.setCollectVos(new ArrayList<>(collectVos));
                deviceConfig.setSwitchOidVo(switchOidVo);
                deviceConfig.setVersion(version);

                // 根据SNMP版本设置不同的参数
                if (version == SnmpConstants.version3) {
                    // SNMP v3配置
                    setupV3DeviceConfig(deviceConfig, switchMsg);
                } else {
                    // SNMP v1/v2c配置
                    deviceConfig.setCommunity(community != null ? community : "public");
                }

                deviceConfigs.add(deviceConfig);

            } catch (Exception e) {
                log.error("处理设备配置失败，deviceId: {}", clientId, e);
            }
        }

        // 批量启动交换机采集任务
        scheduler.batchProcessSwitchConfigurations(deviceConfigs);
    }
    /**
     * 解析SNMP版本字符串为对应的常量
     */
    private int parseSnmpVersion(String snmpVersion) {
        if (snmpVersion == null) {
            return SnmpConstants.version2c; // 默认v2c
        }

        switch (snmpVersion.toLowerCase()) {
            case "0":
                return SnmpConstants.version1;
            case "1":
                return SnmpConstants.version2c;
            case "3":
                return SnmpConstants.version3;
            default:
                return SnmpConstants.version2c; // 默认v2c
        }
    }
    /**
     * 设置SNMP v3设备配置
     */
    private void setupV3DeviceConfig(MultiSwitchCollectionScheduler.DeviceConfig deviceConfig,
                                     RmSwitchManagementRemote switchMsg) {
        // 设置安全名称（用户名）
        String securityName = switchMsg.getSwitchUser();
        if (securityName == null || securityName.trim().isEmpty()) {
            securityName = switchMsg.getCommunityName(); // 如果没有用户名，使用团体名作为fallback
        }
        deviceConfig.setSecurityName(securityName != null ? securityName : "defaultUser");

        // 设置认证协议
        String authProtocol = parseAuthProtocol(switchMsg.getEncryptionMethod());
        deviceConfig.setAuthProtocol(authProtocol);

        // 设置认证密码
        String authPassword = switchMsg.getSwitchPassword();
        deviceConfig.setAuthPassword(authPassword != null ? authPassword : "");

        // 设置加密协议（默认使用AES128）
        deviceConfig.setPrivProtocol("AES128");
        deviceConfig.setPrivPassword(authPassword != null ? authPassword : ""); // 通常加密密码与认证密码相同

        // 设置安全级别
        int securityLevel = parseSecurityLevel(switchMsg.getSecurityLevel());
        deviceConfig.setSecurityLevel(securityLevel);
    }

    /**
     * 解析认证协议
     */
    private String parseAuthProtocol(String encryptionMethod) {
        if (encryptionMethod == null) {
            return "MD5"; // 默认MD5
        }

        switch (encryptionMethod.toLowerCase()) {
            case "md5":
                return "MD5";
            case "sha":
            case "sha1":
                return "SHA";
            default:
                return "MD5"; // 默认MD5
        }
    }

    /**
     * 解析安全级别
     */
    private int parseSecurityLevel(String securityLevel) {
        if (securityLevel == null) {
            return SecurityLevel.AUTH_PRIV; // 默认认证+加密
        }

        switch (securityLevel.toLowerCase()) {
            case "1":
                return SecurityLevel.NOAUTH_NOPRIV;
            case "2":
                return SecurityLevel.AUTH_NOPRIV;
            case "3":
            default:
                return SecurityLevel.AUTH_PRIV;
        }
    }
}
