package com.tongran.system.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.tongran.common.core.constant.SecurityConstants;
import com.tongran.common.core.domain.R;
import com.tongran.common.core.enums.MsgEnum;
import com.tongran.common.core.utils.DateUtils;
import com.tongran.common.core.utils.StringUtils;
import com.tongran.common.core.web.domain.AjaxResult;
import com.tongran.common.core.web.page.PageDomain;
import com.tongran.common.security.utils.SecurityUtils;
import com.tongran.system.api.RemoteRocketMqService;
import com.tongran.system.api.domain.*;
import com.tongran.system.domain.*;
import com.tongran.system.domain.vo.MessageVo;
import com.tongran.system.domain.vo.ResourceVo;
import com.tongran.system.domain.vo.RspVo;
import com.tongran.system.mapper.*;
import com.tongran.system.service.IRmResourceRegistrationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.Duration;
import java.time.Instant;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

import static com.tongran.common.core.utils.PageUtils.startPage;

/**
 * 资源注册Service业务层处理
 * 
 * @author tongran
 * @date 2025-08-12
 */
@Service
@Slf4j
public class RmResourceRegistrationServiceImpl implements IRmResourceRegistrationService 
{
    @Autowired
    private RmResourceRegistrationMapper rmResourceRegistrationMapper;
    @Autowired
    private EpsServerRevenueConfigMapper epsServerRevenueConfigMapper;
    @Autowired
    private RmEpsTopologyManagementMapper rmEpsTopologyManagementMapper;
    @Autowired
    private EpsNodeBandwidthMapper epsNodeBandwidthMapper;
    @Autowired
    private RemoteRocketMqService remoteRocketMqService;
    @Autowired
    private EpsMethodChangeRecordMapper epsMethodChangeRecordMapper;
    @Autowired
    private RmRegistrationMachineMapper rmRegistrationMachineMapper;

    /**
     * 查询资源注册
     * 
     * @param id 资源注册主键
     * @return 资源注册
     */
    @Override
    public RmResourceRegistration selectRmResourceRegistrationById(Long id)
    {
        RmResourceRegistration rmResourceRegistration = rmResourceRegistrationMapper.selectRmResourceRegistrationById(id);
        if(rmResourceRegistration.getClientId()!= null){
            // set网卡信息
            setNetWorkMsg(rmResourceRegistration);
            // set昨日95值
            setBandwidthYestoday(rmResourceRegistration);
        }
        return rmResourceRegistration;
    }

    /**
     * 查询资源注册列表
     *
     * @param rmResourceRegistration 资源注册
     * @return 资源注册
     */
    @Override
    public Map<String, Object> getRegistrationTableInfoList(RmResourceRegistration rmResourceRegistration) {
        Map<String, Object> resultMap = new HashMap<>();

        // 获取参数
        String queryParam = rmResourceRegistration.getQueryParam();
        Integer bandwidthResultSort = rmResourceRegistration.getBandwidthResultSort();
        int pageNum = rmResourceRegistration.getPageNum() != null ? rmResourceRegistration.getPageNum() : 1;
        int pageSize = rmResourceRegistration.getPageSize() != null ? rmResourceRegistration.getPageSize() : 10;

        // 判断是否有查询条件
        boolean hasQueryParam = queryParam != null && !queryParam.trim().isEmpty();
        String queryValue = hasQueryParam ? queryParam.trim().toLowerCase() : null;

        // 情况1: 无查询参数且无特殊排序，使用数据库分页
        if (!hasQueryParam && (bandwidthResultSort == null || bandwidthResultSort == 3)) {
            PageDomain pageDomain = new PageDomain();
            pageDomain.setPageNum(pageNum);
            pageDomain.setPageSize(pageSize);
            startPage(pageDomain);

            List<RmResourceRegistration> list = rmResourceRegistrationMapper.getRegistrationTableInfoList(rmResourceRegistration);
            batchSetNetWorkMsg(list);
            // 只处理当前页的数据
            processCurrentPageData(list);

            resultMap.put("list", list);
            return resultMap;
        }

        // 情况2: 有查询参数或需要排序，全量查询+内存处理
        List<RmResourceRegistration> allData = rmResourceRegistrationMapper.getRegistrationTableInfoList(rmResourceRegistration);
        batchSetNetWorkMsg(allData);

        // 1. 过滤
        List<RmResourceRegistration> filteredList = allData;
        if (hasQueryParam) {
            filteredList = allData.stream()
                    .filter(item -> item != null && quickMatches(item, queryValue))
                    .collect(Collectors.toList());
        }

        // 2. 排序
        if (bandwidthResultSort != null && bandwidthResultSort != 3) {
            sortList(filteredList, bandwidthResultSort);
        }

        // 3. 内存分页
        int total = filteredList.size();
        List<RmResourceRegistration> pageList = applyPagination(filteredList, pageNum, pageSize);
        List<RmResourceRegistration> currentPageData = new ArrayList<>(pageList);

        // 4. 只处理当前页数据
        processCurrentPageData(currentPageData);

        resultMap.put("list", currentPageData);
        resultMap.put("total", total);

        return resultMap;
    }

    /**
     * 只处理当前页的数据
     */
    private void processCurrentPageData(List<RmResourceRegistration> pageList) {
        if (CollectionUtils.isEmpty(pageList)) {
            return;
        }

        long startTime = System.currentTimeMillis();

        for (RmResourceRegistration item : pageList) {
            if (item.getClientId() != null) {
                setBandwidthYestoday(item);
            }
        }
    }
    /**
     * 查询资源注册列表
     *
     * @param rmResourceRegistration 资源注册
     * @return 资源注册
     */
    @Override
    public List<RmResourceRegistration> selectRmResourceRegistrationList(RmResourceRegistration rmResourceRegistration) {
        List<RmResourceRegistration> allData = rmResourceRegistrationMapper.getRegistrationTableInfoList(rmResourceRegistration);
        batchSetNetWorkMsg(allData);

        // 获取参数
        String queryParam = rmResourceRegistration.getQueryParam();
        Integer bandwidthResultSort = rmResourceRegistration.getBandwidthResultSort();
        boolean hasQueryParam = queryParam != null && !queryParam.trim().isEmpty();
        String queryValue = hasQueryParam ? queryParam.trim().toLowerCase() : null;

        // 过滤
        List<RmResourceRegistration> filteredList = allData;
        if (hasQueryParam) {
            filteredList = allData.stream()
                    .filter(item -> item != null && quickMatches(item, queryValue))
                    .collect(Collectors.toList());
        }

        // 排序
        if (bandwidthResultSort != null && bandwidthResultSort != 3) {
            sortList(filteredList, bandwidthResultSort);
        }

        // 处理全部数据
        for (RmResourceRegistration item : filteredList) {
            if (item.getClientId() != null) {
                setBandwidthYestoday(item);
            }
        }

        return filteredList;
    }

    /**
     * 快速匹配方法
     */
    private boolean quickMatches(RmResourceRegistration item, String queryValue) {
        if (item == null || queryValue == null) {
            return false;
        }

        // 优化检查顺序，先检查最可能匹配的字段
        String clientId = item.getClientId();
        String hardwareSn = item.getHardwareSn();

        if ((clientId != null && clientId.toLowerCase().contains(queryValue)) ||
                (hardwareSn != null && hardwareSn.toLowerCase().contains(queryValue))) {
            return true;
        }

        // 检查IP地址
        return containsValue(item.getIp1PublicIp(), queryValue) ||
                containsValue(item.getIp2PublicIp(), queryValue) ||
                containsValue(item.getIp3PublicIp(), queryValue) ||
                containsValue(item.getMgmtPublicIp(), queryValue) ||
                containsValue(item.getIp1Ipv4Address(), queryValue) ||
                containsValue(item.getIp2Ipv4Address(), queryValue) ||
                containsValue(item.getIp3Ipv4Address(), queryValue) ||
                containsValue(item.getMgmtIpv4Address(), queryValue) ||
                containsValue(item.getIp1Ipv6Address(), queryValue) ||
                containsValue(item.getIp2Ipv6Address(), queryValue) ||
                containsValue(item.getIp3Ipv6Address(), queryValue) ||
                containsValue(item.getMgmtIpv6Address(), queryValue);
    }

    private boolean containsValue(String value, String queryValue) {
        return value != null && value.toLowerCase().contains(queryValue);
    }

    /**
     * 排序方法
     */
    private void sortList(List<RmResourceRegistration> list, Integer sortType) {
        if (CollectionUtils.isEmpty(list) || sortType == null) {
            return;
        }

        Comparator<RmResourceRegistration> comparator = null;

        if (sortType == 1) { // 升序，对应 MySQL 的 ASC
            // MySQL 升序：NULL 值在最前面
            comparator = Comparator.comparing(
                    RmResourceRegistration::getBandwidthResult,
                    Comparator.nullsFirst(Comparator.naturalOrder())
            );
        } else if (sortType == 2) { // 降序，对应 MySQL 的 DESC
            // MySQL 降序：NULL 值在最后面
            comparator = Comparator.comparing(
                    RmResourceRegistration::getBandwidthResult,
                    Comparator.nullsLast(Comparator.reverseOrder())
            );
        } else if (sortType == 4) { // 告警优先排序
            comparator = (a, b) -> {
                // 设置告警标志
                boolean aAlarm = isAlarm(a);
                boolean bAlarm = isAlarm(b);
                a.setAlarmFlag(aAlarm);
                b.setAlarmFlag(bAlarm);

                // 告警优先级最高
                if (aAlarm && !bAlarm) return -1;
                if (!aAlarm && bAlarm) return 1;

                if (aAlarm && bAlarm) {
                    // 告警内按最大资源使用率倒序
                    BigDecimal aMax = getMaxUtilization(a);
                    BigDecimal bMax = getMaxUtilization(b);
                    if (aMax == null && bMax == null) return 0;
                    if (aMax == null) return 1;
                    if (bMax == null) return -1;
                    return bMax.compareTo(aMax);
                }

                return 0;
            };
        }

        if (comparator != null) {
            list.sort(comparator);
        }
    }
    private boolean isAlarm(RmResourceRegistration item) {
        Date delAlarmTime = item.getDelAlarmTime();
        boolean alarmFlag = true;

        if (delAlarmTime != null) {
            // 将Date转换为Instant
            Instant delAlarmInstant = delAlarmTime.toInstant();
            Instant now = Instant.now();

            // 如果当前时间-delAlarmTime<24小时，设置alarmFlag=false
            if (Duration.between(delAlarmInstant, now).toHours() < 24) {
                alarmFlag = false;
            }
        }
        return alarmFlag && ((item.getCpuUtil() != null && item.getCpuUtil().compareTo(BigDecimal.valueOf(80)) >= 0) ||
                (item.getMemUtil() != null && item.getMemUtil().compareTo(BigDecimal.valueOf(60)) >= 0));
    }

    private BigDecimal getMaxUtilization(RmResourceRegistration item) {
        BigDecimal max = BigDecimal.ZERO;
        if (item.getCpuUtil() != null && item.getCpuUtil().compareTo(max) > 0) {
            max = item.getCpuUtil();
        }
        if (item.getMemUtil() != null && item.getMemUtil().compareTo(max) > 0) {
            max = item.getMemUtil();
        }
        return max.equals(BigDecimal.ZERO) ? null : max;
    }
    /**
     * 内存分页
     */
    private List<RmResourceRegistration> applyPagination(List<RmResourceRegistration> list, int pageNum, int pageSize) {
        if (list == null || list.isEmpty()) {
            return new ArrayList<>();
        }

        int fromIndex = (pageNum - 1) * pageSize;
        if (fromIndex >= list.size()) {
            return new ArrayList<>();
        }

        int toIndex = Math.min(fromIndex + pageSize, list.size());
        return list.subList(fromIndex, toIndex);
    }
    /**
     * 批量处理网络信息
     */
    private void batchSetNetWorkMsg(List<RmResourceRegistration> pageList) {
        if (CollectionUtils.isEmpty(pageList)) {
            return;
        }

        long startTime = System.currentTimeMillis();
        int batchSize = 200;
        int totalBatches = (int) Math.ceil((double) pageList.size() / batchSize);

        for (int batchNum = 0; batchNum < totalBatches; batchNum++) {
            int fromIndex = batchNum * batchSize;
            int toIndex = Math.min(fromIndex + batchSize, pageList.size());
            List<RmResourceRegistration> batchList = pageList.subList(fromIndex, toIndex);

            String clientIdsStr = batchList.parallelStream()
                    .map(RmResourceRegistration::getClientId)
                    .filter(Objects::nonNull)
                    .distinct()
                    .collect(Collectors.joining(","));

            if (StringUtils.isBlank(clientIdsStr)) {
                continue;
            }

            try {
                // 并行查询
                CompletableFuture<List<RmResourceRegistration>> cpuFuture = CompletableFuture
                        .supplyAsync(() -> rmResourceRegistrationMapper.getCpuUtil(clientIdsStr));

                CompletableFuture<List<RmResourceRegistration>> memFuture = CompletableFuture
                        .supplyAsync(() -> rmResourceRegistrationMapper.getMemUtil(clientIdsStr));

                CompletableFuture<List<RmNetworkInterfaceRemote>> networkFuture = CompletableFuture
                        .supplyAsync(() -> {
                            RmNetworkInterfaceRemote queryParam = new RmNetworkInterfaceRemote();
                            queryParam.setAllClientIds(clientIdsStr);
                            queryParam.setNewFlag(1);
                            R<List<RmNetworkInterfaceRemote>> result = remoteRocketMqService.getNetworkInterfaceList(queryParam, SecurityConstants.INNER);
                            return result != null ? result.getData() : Collections.emptyList();
                        });

                CompletableFuture.allOf(cpuFuture, memFuture, networkFuture).join();

                List<RmResourceRegistration> cpuUtilList = cpuFuture.get() == null ? new ArrayList<>() : cpuFuture.get();
                List<RmResourceRegistration> memUtilList = memFuture.get() == null ? new ArrayList<>() : memFuture.get();
                List<RmNetworkInterfaceRemote> networkList = networkFuture.get() == null ? new ArrayList<>() : networkFuture.get();

                // 构建查找Map
                Map<String, BigDecimal> cpuUtilMap = cpuUtilList.stream()
                        .filter(item -> item.getClientId() != null && item.getCpuUtil() != null)
                        .collect(Collectors.toMap(
                                RmResourceRegistration::getClientId,
                                RmResourceRegistration::getCpuUtil
                        ));

                Map<String, BigDecimal> memUtilMap = memUtilList.stream()
                        .filter(item -> item.getClientId() != null && item.getMemUtil() != null)
                        .collect(Collectors.toMap(
                                RmResourceRegistration::getClientId,
                                RmResourceRegistration::getMemUtil
                        ));

                Map<String, List<RmNetworkInterfaceRemote>> networkMap = networkList.stream()
                        .filter(Objects::nonNull)
                        .filter(item -> item.getClientId() != null)
                        .collect(Collectors.groupingBy(RmNetworkInterfaceRemote::getClientId));

                // 并行处理
                batchList.parallelStream().forEach(registration -> {
                    String clientId = registration.getClientId();
                    if (clientId != null) {
                        BigDecimal cpuUtil = cpuUtilMap.get(clientId);
                        if (cpuUtil != null) {
                            registration.setCpuUtil(cpuUtil);
                        }

                        BigDecimal memUtil = memUtilMap.get(clientId);
                        if (memUtil != null) {
                            registration.setMemUtil(memUtil);
                        }

                        List<RmNetworkInterfaceRemote> clientNetworks = networkMap.get(clientId);
                        if (clientNetworks != null && !clientNetworks.isEmpty()) {
                            setNetWorkMsgWithNetworkList(registration, clientNetworks);
                        }
                    }
                });

            } catch (Exception e) {
                log.error("第{}批查询资源信息异常", batchNum + 1, e);
            }

            if (batchNum < totalBatches - 1) {
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        }

        log.info("批量设置资源信息完成，耗时: {}ms", System.currentTimeMillis() - startTime);
    }
    /**
     * 使用批量查询的结果设置网络信息
     */
    private void setNetWorkMsgWithNetworkList(RmResourceRegistration registration, List<RmNetworkInterfaceRemote> networkList) {
        if (registration == null || CollectionUtils.isEmpty(networkList)) {
            return;
        }

        int businessIpCount = 1;

        for (RmNetworkInterfaceRemote network : networkList) {

            if ("1".equals(network.getBindIp()) || "3".equals(network.getBindIp())) {
                // 业务IP处理
                if (businessIpCount > 3) {
                    continue; // 最多只处理3个业务IP
                }

                // 设置业务IP字段
                switch (businessIpCount) {
                    case 1:
                        registration.setIp1Isp(network.getIsp());
                        registration.setIp1Province(network.getProvince());
                        registration.setIp1City(network.getCity());
                        registration.setIp1PublicIp(network.getPublicIp());
                        registration.setIp1InterfaceName(network.getInterfaceName());
                        registration.setIp1MacAddress(network.getMacAddress());
                        registration.setIp1InterfaceType(network.getInterfaceType());
                        registration.setIp1Ipv4Address(network.getIpv4Address());
                        registration.setIp1Ipv6Address(network.getIpv6Address());
                        registration.setIp1Gateway(network.getGateway());
                        break;
                    case 2:
                        registration.setIp2Isp(network.getIsp());
                        registration.setIp2Province(network.getProvince());
                        registration.setIp2City(network.getCity());
                        registration.setIp2PublicIp(network.getPublicIp());
                        registration.setIp2InterfaceName(network.getInterfaceName());
                        registration.setIp2MacAddress(network.getMacAddress());
                        registration.setIp2InterfaceType(network.getInterfaceType());
                        registration.setIp2Ipv4Address(network.getIpv4Address());
                        registration.setIp2Ipv6Address(network.getIpv6Address());
                        registration.setIp2Gateway(network.getGateway());
                        break;
                    case 3:
                        registration.setIp3Isp(network.getIsp());
                        registration.setIp3Province(network.getProvince());
                        registration.setIp3City(network.getCity());
                        registration.setIp3PublicIp(network.getPublicIp());
                        registration.setIp3InterfaceName(network.getInterfaceName());
                        registration.setIp3MacAddress(network.getMacAddress());
                        registration.setIp3InterfaceType(network.getInterfaceType());
                        registration.setIp3Ipv4Address(network.getIpv4Address());
                        registration.setIp3Ipv6Address(network.getIpv6Address());
                        registration.setIp3Gateway(network.getGateway());
                        break;
                }

                businessIpCount++;
            }
            if ("2".equals(network.getBindIp()) || "3".equals(network.getBindIp())) {
                // 管理网IP处理
                registration.setMgmtIsp(network.getIsp());
                registration.setMgmtProvince(network.getProvince());
                registration.setMgmtCity(network.getCity());
                registration.setMgmtPublicIp(network.getPublicIp());
                registration.setMgmtInterfaceName(network.getInterfaceName());
                registration.setMgmtMacAddress(network.getMacAddress());
                registration.setMgmtInterfaceType(network.getInterfaceType());
                registration.setMgmtIpv4Address(network.getIpv4Address());
                registration.setMgmtIpv6Address(network.getIpv6Address());
                registration.setMgmtGateway(network.getGateway());
            }
        }
    }


    /**
     * 网卡信息赋值
     * @param registration
     */
    public void setNetWorkMsg(RmResourceRegistration registration) {
        String clientId = registration.getClientId();
        // 根据clientId查询cpu利用率
        List<RmResourceRegistration> cpuUtilList = rmResourceRegistrationMapper.getCpuUtil(clientId);
        // 根据clientId查询mem利用率
        List<RmResourceRegistration> memUtilList = rmResourceRegistrationMapper.getMemUtil(clientId);
        // 查询agent最新版本
        RmResourceRegistration rmResourceRegistration = rmResourceRegistrationMapper.getMaxAgentVersion();
        if(cpuUtilList != null && !cpuUtilList.isEmpty()){
            registration.setCpuUtil(cpuUtilList.get(0).getCpuUtil());
            registration.setCpuCores(cpuUtilList.get(0).getCpuCores());
        }
        if(memUtilList != null && !memUtilList.isEmpty()){
            registration.setMemUtil(memUtilList.get(0).getMemUtil());
        }
        if(rmResourceRegistration != null){
            registration.setMaxAgentVersion(rmResourceRegistration.getMaxAgentVersion());
        }
        // 根据clientId查询网卡信息
        RmNetworkInterfaceRemote queryParam = new RmNetworkInterfaceRemote();
        queryParam.setClientId(clientId);
        queryParam.setNewFlag(1);
        // 安全获取网络接口列表
        R<List<RmNetworkInterfaceRemote>> result = remoteRocketMqService.getNetworkInterfaceList(queryParam, SecurityConstants.INNER);
        // 多层安全判断
        if (result == null || result.getData() == null) {
            log.warn("获取网络接口列表为空，clientId: {}", clientId);
            return;
        }

        List<RmNetworkInterfaceRemote> networkList = result.getData();

        if (networkList == null || networkList.isEmpty()) {
            return;
        }

        // 初始化业务IP计数器
        int businessIpCount = 1;

        for (RmNetworkInterfaceRemote network : networkList) {
            if ("1".equals(network.getBindIp()) || "3".equals(network.getBindIp())) {
                // 查询是否存在子网卡
                int count = rmResourceRegistrationMapper.countChildNetwork(clientId, network.getInterfaceName());
                boolean isVirth = false;
                if(count > 0){
                    isVirth = true;
                }
                // 业务IP处理
                if (businessIpCount > 3) {
                    continue; // 最多只处理3个业务IP
                }

                // 设置业务IP字段
                switch (businessIpCount) {
                    case 1:
                        registration.setIp1Isp(network.getIsp());
                        registration.setIp1Province(network.getProvince());
                        registration.setIp1City(network.getCity());
                        registration.setIp1PublicIp(network.getPublicIp());
                        registration.setIp1InterfaceName(network.getInterfaceName());
                        registration.setIp1MacAddress(network.getMacAddress());
                        registration.setIp1InterfaceType(network.getInterfaceType());
                        registration.setIp1Ipv4Address(network.getIpv4Address());
                        registration.setIp1Ipv6Address(network.getIpv6Address());
                        registration.setIp1Gateway(network.getGateway());
                        registration.setIp1IsVirth(isVirth);
                        break;
                    case 2:
                        registration.setIp2Isp(network.getIsp());
                        registration.setIp2Province(network.getProvince());
                        registration.setIp2City(network.getCity());
                        registration.setIp2PublicIp(network.getPublicIp());
                        registration.setIp2InterfaceName(network.getInterfaceName());
                        registration.setIp2MacAddress(network.getMacAddress());
                        registration.setIp2InterfaceType(network.getInterfaceType());
                        registration.setIp2Ipv4Address(network.getIpv4Address());
                        registration.setIp2Ipv6Address(network.getIpv6Address());
                        registration.setIp2Gateway(network.getGateway());
                        registration.setIp2IsVirth(isVirth);
                        break;
                    case 3:
                        registration.setIp3Isp(network.getIsp());
                        registration.setIp3Province(network.getProvince());
                        registration.setIp3City(network.getCity());
                        registration.setIp3PublicIp(network.getPublicIp());
                        registration.setIp3InterfaceName(network.getInterfaceName());
                        registration.setIp3MacAddress(network.getMacAddress());
                        registration.setIp3InterfaceType(network.getInterfaceType());
                        registration.setIp3Ipv4Address(network.getIpv4Address());
                        registration.setIp3Ipv6Address(network.getIpv6Address());
                        registration.setIp3Gateway(network.getGateway());
                        registration.setIp3IsVirth(isVirth);
                        break;
                }

                businessIpCount++;
            }
            if ("2".equals(network.getBindIp())  || "3".equals(network.getBindIp())) {
                // 查询是否存在子网卡
                int count = rmResourceRegistrationMapper.countChildNetwork(clientId, network.getInterfaceName());
                boolean isVirth = false;
                if(count > 0){
                    isVirth = true;
                }
                // 管理网IP处理
                registration.setMgmtIsp(network.getIsp());
                registration.setMgmtProvince(network.getProvince());
                registration.setMgmtCity(network.getCity());
                registration.setMgmtPublicIp(network.getPublicIp());
                registration.setMgmtInterfaceName(network.getInterfaceName());
                registration.setMgmtMacAddress(network.getMacAddress());
                registration.setMgmtInterfaceType(network.getInterfaceType());
                registration.setMgmtIpv4Address(network.getIpv4Address());
                registration.setMgmtIpv6Address(network.getIpv6Address());
                registration.setMgmtGateway(network.getGateway());
                registration.setMgmIsVirth(isVirth);
            }
        }
    }

    /**
     * 设置金山machineCode
     * @param registration
     */
    public void setMachineMsg(RmResourceRegistration registration){
        // 设置金山machineCode
        RmRegistrationMachine rmRegistrationMachine = new RmRegistrationMachine();
        rmRegistrationMachine.setClientId(registration.getClientId());
        List<RmRegistrationMachine> machineList = rmRegistrationMachineMapper.selectRmRegistrationMachineList(rmRegistrationMachine);
        if(!machineList.isEmpty()){
            RmRegistrationMachine machineMsg = machineList.get(0);
            registration.setMachineCode(machineMsg.getMachineCode());
        }
    }

    public void setBandwidthYestoday(RmResourceRegistration registration){
        // 查询昨日95值
        BigDecimal bandwidthResult = registration.getBandwidthResult();
        BigDecimal reportedBandwidth = registration.getReportedBandwidth();
        if(reportedBandwidth != null && bandwidthResult != null){
            if(reportedBandwidth.compareTo(BigDecimal.ZERO) == 0){
                registration.setBandwidthRate(null);
            }else{
                // 计算日95带宽值利用率
                BigDecimal bandwidthRate = bandwidthResult.multiply(new BigDecimal(100)).divide(reportedBandwidth, 1, RoundingMode.HALF_UP);
                registration.setBandwidthRate(bandwidthRate + "%");
            }
        }
    }
    /**
     * 新增资源注册
     * 
     * @param rmResourceRegistration 资源注册
     * @return 结果
     */
    @Override
    public int insertRmResourceRegistration(RmResourceRegistration rmResourceRegistration)
    {
        rmResourceRegistration.setCreateBy(SecurityUtils.getUsername());
        rmResourceRegistration.setCreateTime(DateUtils.getNowDate());
        // 查询此硬件sn是否已存在
        int exits = rmResourceRegistrationMapper.countBySn(rmResourceRegistration.getHardwareSn());
        if(exits>0){
            return -1;
        }
        return rmResourceRegistrationMapper.insertRmResourceRegistration(rmResourceRegistration);
    }

    /**
     * 修改资源注册
     * 
     * @param rmResourceRegistration 资源注册
     * @return 结果
     */
    @Override
    public int updateRmResourceRegistration(RmResourceRegistration rmResourceRegistration)
    {
        rmResourceRegistration.setUpdateTime(DateUtils.getNowDate());
        rmResourceRegistration.setUpdateBy(SecurityUtils.getUsername());
        // 拿到需要修改的id
        Long id = rmResourceRegistration.getId();
        // 根据id查询sn信息
        RmResourceRegistration resourceRegistration = rmResourceRegistrationMapper.selectRmResourceRegistrationById(id);
        String hardwareSn = resourceRegistration.getHardwareSn();
        String newResourceName = rmResourceRegistration.getResourceName();

        // 如果资源名称有修改，同步修改其他表的资源名称
        if (!resourceRegistration.getResourceName().equals(newResourceName)) {
            // 公共的更新对象创建
            RmEpsTopologyManagement rmEpsTopologyManagement = new RmEpsTopologyManagement();
            EpsNodeBandwidth epsNodeBandwidth = new EpsNodeBandwidth();

            switch (resourceRegistration.getResourceType()) {
                case "1": // 服务器类型
                    // 更新拓扑管理配置
                    rmEpsTopologyManagement.setServerSn(hardwareSn);
                    rmEpsTopologyManagement.setServerName(newResourceName);
                    rmEpsTopologyManagementMapper.updateRmEpsTopologyManagementByServerSn(rmEpsTopologyManagement);

                    // 更新服务器收益配置表
                    EpsServerRevenueConfig epsServerRevenueConfig = new EpsServerRevenueConfig();
                    epsServerRevenueConfig.setHardwareSn(hardwareSn);
                    epsServerRevenueConfig.setNodeName(newResourceName);
                    epsServerRevenueConfigMapper.updateEpsServerRevenueConfigByServerSn(epsServerRevenueConfig);

                    // 更新95收益信息表
                    epsNodeBandwidth.setHardwareSn(hardwareSn);
                    epsNodeBandwidth.setNodeName(newResourceName);
                    epsNodeBandwidthMapper.updateEpsNodeBandwidthByServerSn(epsNodeBandwidth);
                    break;

                case "2": // 交换机类型
                    // 更新拓扑管理配置
                    rmEpsTopologyManagement.setSwitchSn(hardwareSn);
                    rmEpsTopologyManagement.setSwitchName(newResourceName);
                    rmEpsTopologyManagementMapper.updateRmEpsTopologyManagementBySwitchSn(rmEpsTopologyManagement);

                    // 更新95收益信息表
                    epsNodeBandwidth.setSwitchSn(hardwareSn);
                    epsNodeBandwidth.setUplinkSwitch(newResourceName);
                    epsNodeBandwidthMapper.updateEpsNodeBandwidthBySwitchSn(epsNodeBandwidth);
                    break;
            }
        }
        // 禁止修改sn序列号
        rmResourceRegistration.setHardwareSn(null);
        // 已注册状态修改--仅可修改资源名称，描述
        if ("1".equals(rmResourceRegistration.getRegistrationStatus())){
            // 拿到需要修改的资源名称
            String resourceName = rmResourceRegistration.getResourceName();
            // 初始化
            rmResourceRegistration = new RmResourceRegistration();
            // id赋值
            rmResourceRegistration.setId(id);
            // 可修改资源名称
            rmResourceRegistration.setResourceName(resourceName);

        }
        return rmResourceRegistrationMapper.updateRmResourceRegistration(rmResourceRegistration);
    }

    /**
     * 资源注册-注册
     *
     * @param rmResourceRegistration 资源注册
     * @return 结果
     */
    @Override
    public int register(RmResourceRegistration rmResourceRegistration) {
        // 设置更新信息
        rmResourceRegistration.setUpdateTime(DateUtils.getNowDate());
        rmResourceRegistration.setUpdateBy(SecurityUtils.getUsername());

        // 处理服务器资源注册
        if ("1".equals(rmResourceRegistration.getResourceType())) {
            handleServerRegistration(rmResourceRegistration);
        }

        // 发送消息通知
        sendRegistrationMessage(rmResourceRegistration);
        // 更新注册状态
        return updateRegistrationStatus(rmResourceRegistration);
    }

    /**
     * 处理服务器资源注册
     */
    private void handleServerRegistration(RmResourceRegistration registration) {
        EpsServerRevenueConfig config = new EpsServerRevenueConfig();
        config.setHardwareSn(registration.getHardwareSn());
        config.setNodeName(registration.getResourceName());
        config.setCreateTime(DateUtils.getNowDate());
        config.setRegistrationStatus(registration.getRegistrationStatus());

        EpsServerRevenueConfig existing = epsServerRevenueConfigMapper.countBySn(config.getHardwareSn());
        if (existing != null) {
            config.setId(existing.getId());
            epsServerRevenueConfigMapper.updateEpsServerRevenueConfig(config);
        } else {
            epsServerRevenueConfigMapper.insertEpsServerRevenueConfig(config);
        }
    }

    /**
     * 发送注册/断开连接消息
     */
    private void sendRegistrationMessage(RmResourceRegistration registration) {
        String messageType = "1".equals(registration.getRegistrationStatus()) ? MsgEnum.注册.getValue() : MsgEnum.断开.getValue();
        ResourceVo resourceVo = createResourceVo(registration);
        MessageVo messageVo = new MessageVo();
        messageVo.setClientId(registration.getHardwareSn());
        messageVo.setDataType(messageType);
        messageVo.setData(JSONObject.toJSONString(resourceVo));

        remoteRocketMqService.sendAsyncProducerMessage(
                "tongran_agent_down", "", "", JSONObject.toJSONString(messageVo), SecurityConstants.INNER);
    }

    /**
     * 创建资源VO对象
     */
    private ResourceVo createResourceVo(RmResourceRegistration registration) {
        ResourceVo resourceVo = new ResourceVo();
        return resourceVo;
    }

    /**
     * 更新注册状态
     */
    private int updateRegistrationStatus(RmResourceRegistration registration) {
        RmResourceRegistration updateParam = new RmResourceRegistration();
        updateParam.setId(registration.getId());
        updateParam.setRegistrationStatus(registration.getRegistrationStatus());
        return rmResourceRegistrationMapper.updateRmResourceRegistration(updateParam);
    }
    /**
     * 批量删除资源注册
     * 
     * @param ids 需要删除的资源注册主键
     * @return 结果
     */
    @Override
    public int deleteRmResourceRegistrationByIds(Long[] ids)
    {
        return rmResourceRegistrationMapper.deleteRmResourceRegistrationByIds(ids);
    }

    /**
     * 删除资源注册信息
     * 
     * @param id 资源注册主键
     * @return 结果
     */
    @Override
    public int deleteRmResourceRegistrationById(Long id)
    {
        return rmResourceRegistrationMapper.deleteRmResourceRegistrationById(id);
    }

    /**
     * 检测到服务器离线，修改状态为离线
     * @param rmResourceRegistration
     * @return
     */
    @Override
    public R<String> updateStatusByResource(RmResourceRegistration rmResourceRegistration) {
        rmResourceRegistrationMapper.updateStatusByResource(rmResourceRegistration);
        return R.ok("状态修改成功");
    }

    /**
     * 服务器在线率
     * @return
     */
    @Override
    public AjaxResult getServerOnlineRate() {
        // 查询所有符合条件的资源
        RmResourceRegistration queryParam = new RmResourceRegistration();
        queryParam.setResourceType("1");
        List<RmResourceRegistration> resourceList = rmResourceRegistrationMapper.selectRmResourceRegistrationList(queryParam);

        // 计算在线数量和总数
        int totalCount = resourceList.size();
        if (totalCount == 0) {
            return AjaxResult.error("没有找到符合条件的资源");
        }

        int onlineCount = (int) resourceList.stream()
                .filter(resource -> "1".equals(resource.getOnlineStatus()))
                .count();
        int offlineCount = (int) resourceList.stream()
                .filter(resource -> "0".equals(resource.getOnlineStatus()))
                .count();

        // 计算在线率
        BigDecimal onlineRate = BigDecimal.valueOf(onlineCount)
                .divide(BigDecimal.valueOf(totalCount), 0, RoundingMode.HALF_UP).multiply(new BigDecimal(100));

        // 返回结果
        return AjaxResult.success()
                .put("onlineCount", onlineCount)
                .put("offlineCount", offlineCount)
                .put("total", totalCount)
                .put("onlineRate", onlineRate);
    }

    /**
     * 根据id查询资源注册信息
     * @param ids
     * @return
     */
    @Override
    public List<RmResourceRegistration> getRegistrationByIds(String[] ids) {
        return rmResourceRegistrationMapper.getRegistrationByIds(ids);
    }

    /**
     * 自动注册
     * @param registerMsg
     * @return
     */
    @Override
    public int innerAddRegist(RmRegisterMsgRemote registerMsg) {
        if(registerMsg.getClientId() == null) {
            log.error("注册失败：clientId为null");
            return 0;
        }
        // 解析mq接收的消息
        // 时间戳转换
        long timestamp = registerMsg.getTimestamp();
        long millis = timestamp * 1000;
        Date createTime = new Date(millis / 1000 * 1000); // 去除毫秒
        String timeStr = DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", createTime);
        List<NetworkInfo> networkInfoList = registerMsg.getNetworkInfo();
        if(!networkInfoList.isEmpty()){
            // 查询此数据是否存在
            RmResourceRegistration queryParam = new RmResourceRegistration();
            queryParam.setClientId(registerMsg.getClientId());
            RmResourceRegistration exits = rmResourceRegistrationMapper.selectRegistMsgByClientId(queryParam);
            if(exits == null){
                // 构建服务器信息
                RmResourceRegistration insertData = new RmResourceRegistration();
                try {
                    // 如果网卡信息只有1条，自动绑定多公网IP
                    if(networkInfoList.size()==1){
                        NetworkInfo networkInfo = networkInfoList.get(0);
                        insertData.setClientId(registerMsg.getClientId());
                        insertData.setHardwareSn(registerMsg.getSn());
                        insertData.setRegistrationStatus("1");
                        insertData.setMultiPublicIpStatus("1");
                        insertData.setHeartbeatCount(3);
                        insertData.setHeartbeatInterval(30);
                        insertData.setResourceType("1");
                        insertData.setCreateTime(createTime);
                        rmResourceRegistrationMapper.insertRmResourceRegistration(insertData);
                        // 添加业务变更记录
                        EpsMethodChangeRecord recordAddData = new EpsMethodChangeRecord();
                        recordAddData.setClientId(registerMsg.getClientId());
                        recordAddData.setTrafficPort(networkInfo.getName());
                        recordAddData.setUpdateTime(DateUtils.getNowDate());
                        recordAddData.setCreateTime(DateUtils.getNowDate());
                        recordAddData.setUpdateBy(SecurityUtils.getUsername());
                        recordAddData.setCreatBy(SecurityUtils.getUsername());
                        StringBuilder content = new StringBuilder();
                        content.append("流量网口设置为").append(networkInfo.getName());
                        recordAddData.setChangeContent(content.toString());
                        epsMethodChangeRecordMapper.insertEpsMethodChangeRecord(recordAddData);
                        // 设置路由信息
                        RouteMsg routeMsg = new RouteMsg();
                        routeMsg.setName(networkInfo.getName());
                        routeMsg.setGateway(networkInfo.getGateway());
                        // 构建注册应答信息
                        MessageVo messageVo = new MessageVo();
                        messageVo.setClientId(registerMsg.getClientId());
                        messageVo.setDataType(MsgEnum.注册应答.getValue());
                        RspVo rspVo = new RspVo();
                        rspVo.setResCode(1);
                        rspVo.setResMag("注册成功");
                        rspVo.setAddRoute(JSONObject.toJSONString(routeMsg));
                        rspVo.setNetName(networkInfo.getName());
                        messageVo.setData(JSONObject.toJSONString(rspVo));
                        remoteRocketMqService.sendAsyncProducerMessage(
                                "tr_agent_down", "", "regist_rsp", JSONObject.toJSONString(messageVo), SecurityConstants.INNER
                        );
                        // 第一次注册
                        return 2;
                    }else{
                        insertData.setClientId(registerMsg.getClientId());
                        insertData.setHardwareSn(registerMsg.getSn());
                        insertData.setRegistrationStatus("0");
                        insertData.setMultiPublicIpStatus("0");
                        insertData.setResourceType("1");
                        insertData.setCreateTime(createTime);
                        insertData.setHeartbeatCount(3);
                        insertData.setHeartbeatInterval(30);
                        rmResourceRegistrationMapper.insertRmResourceRegistration(insertData);
                    }
                }catch (Exception e){
                    log.error("注册服务器失败：{}",e.getMessage());
                    return 0;
                }
            }
        }
        return 1;
    }

    /**
     * 添加节点标识
     * @param rmResourceRegistration
     * @return
     */
    @Override
    public int innerUpdateRegist(RmResourceRegistrationRemote rmResourceRegistration) {
        // 查询此数据是否存在
        RmResourceRegistration queryParam = new RmResourceRegistration();
        queryParam.setClientId(rmResourceRegistration.getClientId());
        RmResourceRegistration exits = rmResourceRegistrationMapper.selectRegistMsgByClientId(queryParam);
        if(exits != null){
            RmResourceRegistration updateData = new RmResourceRegistration();
            boolean needUpdate = false;
            // 如果上机时间为空 设置上机时间
            if(exits.getOnboardTime() == null){
                // 如果服务器已注册 增加节点标识
                updateData.setOnboardTime(DateUtils.getNowDate());
                updateData.setOnlineStatus("1");
                needUpdate = true;
            }
            if((exits.getLogicalNodeId() == null && rmResourceRegistration.getLogicalNodeId()!=null) ||
                    !StringUtils.equals(rmResourceRegistration.getLogicalNodeId(),exits.getLogicalNodeId())){
                // 如果服务器已注册 增加节点标识
                updateData.setLogicalNodeId(rmResourceRegistration.getLogicalNodeId());
                needUpdate = true;
            }
            if((exits.getAgentVersion() == null && rmResourceRegistration.getAgentVersion()!=null) ||
                    !StringUtils.equals(rmResourceRegistration.getAgentVersion(),exits.getAgentVersion())){
                // 如果服务器已注册 增加版本信息
                updateData.setAgentVersion(rmResourceRegistration.getAgentVersion());
                needUpdate = true;
            }
            if((exits.getHardwareSn() == null && rmResourceRegistration.getHardwareSn()!=null) ||
                    !StringUtils.equals(rmResourceRegistration.getHardwareSn(),exits.getHardwareSn())){
                // 如果服务器已注册 增加SN信息
                updateData.setHardwareSn(rmResourceRegistration.getHardwareSn());
                needUpdate = true;
            }
            if(needUpdate){
                updateData.setId(exits.getId());
                rmResourceRegistrationMapper.updateRmResourceRegistration(updateData);
                log.info("设备：{}，更新成功",rmResourceRegistration.getClientId());
                return 1;
            }
        }
        return 0;
    }

    @Override
    public int bindBusinessPublicIp(RmResourceRegistration rmResourceRegistration) {
        // 参数校验
        if (rmResourceRegistration == null || StringUtils.isEmpty(rmResourceRegistration.getClientId())) {
            throw new IllegalArgumentException("参数不合法");
        }

        String clientId = rmResourceRegistration.getClientId();
        String username = SecurityUtils.getUsername();
        Date now = DateUtils.getNowDate();

        // 1. 处理IP绑定和记录
        rmResourceRegistration.getBindNetworkMsg().forEach(map -> {
            // 绑定IP
            if (map.get("id") == null) {
                return;
            }
            RmNetworkInterfaceRemote network = new RmNetworkInterfaceRemote();
            network.setId(Long.parseLong(map.get("id").toString()));
            network.setBindIp(map.get("status").toString());
            remoteRocketMqService.bindPublicIp(network, SecurityConstants.INNER);
            if("1".equals(map.get("status").toString()) || "3".equals(map.get("status").toString())){
                // 添加变更记录
                EpsMethodChangeRecord record = new EpsMethodChangeRecord();
                record.setClientId(clientId);
                record.setTrafficPort(map.get("interfaceName").toString());
                record.setCreateTime(now);
                record.setUpdateTime(now);
                record.setUpdateBy(username);
                record.setCreatBy(username);
                record.setChangeContent("流量网口设置为" + map.get("interfaceName"));
                epsMethodChangeRecordMapper.insertEpsMethodChangeRecord(record);
            }
        });

        // 2. 更新注册状态
        RmResourceRegistration updateData = new RmResourceRegistration();
        updateData.setId(rmResourceRegistration.getId());
        updateData.setMultiPublicIpStatus("1");

        // 处理未注册情况
        RmResourceRegistration isRegist = rmResourceRegistrationMapper.selectRmResourceRegistrationById(rmResourceRegistration.getId());
        if (isRegist != null && "0".equals(isRegist.getRegistrationStatus())) {
            RmNetworkInterfaceRemote queryParam = new RmNetworkInterfaceRemote();
            queryParam.setClientId(clientId);

            R<List<RmNetworkInterfaceRemote>> netList = remoteRocketMqService.getNetworkInterfaceList(queryParam, SecurityConstants.INNER);

            // 获取所有bindIp为1或3的网络接口
            List<RmNetworkInterfaceRemote> filteredNetworks = Optional.ofNullable(netList)
                    .map(R::getData)
                    .map(list -> list.stream()
                            .filter(ni -> "1".equals(ni.getBindIp()) || "3".equals(ni.getBindIp()))
                            .collect(Collectors.toList()))
                    .orElse(Collections.emptyList());
            // 管理网信息
            List<RmNetworkInterfaceRemote> mtmNetworks = Optional.ofNullable(netList)
                    .map(R::getData)
                    .map(list -> list.stream()
                            .filter(ni -> "2".equals(ni.getBindIp()) || "3".equals(ni.getBindIp()))
                            .collect(Collectors.toList()))
                    .orElse(Collections.emptyList());

            // 如果有符合条件的网络接口
            if (!filteredNetworks.isEmpty()) {
                updateData.setRegistrationStatus("1");
                List<RmNetworkInterfaceRemote> childList = new ArrayList<>();
                filteredNetworks.forEach(netMsg -> {
                    RmNetworkInterfaceRemote query = new RmNetworkInterfaceRemote();
                    query.setClientId(clientId);
                    query.setParentInterface(netMsg.getInterfaceName());
                    R<List<RmNetworkInterfaceRemote>> children = remoteRocketMqService.innerGetChildList(query, SecurityConstants.INNER);
                    if(children != null && children.getData()!=null && !children.getData().isEmpty()){
                        childList.addAll(children.getData());
                    }
                });
                // 拼接所有符合条件的网络接口名称，用分号隔开
                StringBuilder netNameBuilder = new StringBuilder();
                for (int i = 0; i < filteredNetworks.size(); i++) {
                    if (i > 0) {
                        netNameBuilder.append(";");
                    }
                    netNameBuilder.append(filteredNetworks.get(i).getInterfaceName());
                }
                // 添加子接口名称
                for (int i = 0; i < childList.size(); i++) {
                    if (netNameBuilder.length() > 0 || i > 0) {
                        netNameBuilder.append(";");
                    }
                    netNameBuilder.append(childList.get(i).getInterfaceName());
                }
                String netName = netNameBuilder.toString();

                // 发送注册响应
                MessageVo messageVo = new MessageVo();
                messageVo.setClientId(clientId);
                messageVo.setDataType(MsgEnum.注册应答.getValue());

                RspVo rspVo = new RspVo();
                rspVo.setResCode(1);
                rspVo.setResMag("注册成功");
                if(mtmNetworks != null && !mtmNetworks.isEmpty()){
                    RouteMsg routeMsg = new RouteMsg();
                    String gateWay = mtmNetworks.get(0).getGateway();
                    routeMsg.setName(mtmNetworks.get(0).getInterfaceName()); // 使用拼接后的网络接口名称
                    routeMsg.setGateway(gateWay); // 使用第一个网络接口的网关，或者您可以根据需要调整
//                    if(gateWay != null){
//                        rspVo.setAddRoute(JSONObject.toJSONString(routeMsg));
//                    }
                }
                rspVo.setNetName(netName);

                messageVo.setData(JSONObject.toJSONString(rspVo));

                remoteRocketMqService.sendAsyncProducerMessage(
                        "tr_agent_down", "", "regist_rsp", JSONObject.toJSONString(messageVo), SecurityConstants.INNER
                );

                // 注册成功，下发优先级为0的策略
                remoteRocketMqService.issueDefaultPolicyByClientId(clientId, SecurityConstants.INNER);
            }
        }

        rmResourceRegistrationMapper.updateRmResourceRegistration(updateData);
        return 1;
    }

    /**
     * 查询所有逻辑节点标识
     * @return
     */
    @Override
    public List<Map> getAllLogicalNodeId() {
        return rmResourceRegistrationMapper.getAllLogicalNodeId();
    }

    /**
     * 绑定业务
     * @param rmResourceRegistration
     * @return
     */
    @Override
    public int bindBusinessByClientIds(RmResourceRegistration rmResourceRegistration) {
        String clientIds = rmResourceRegistration.getDeployDevice();
        String[] clientIdArr = clientIds.split("\n");
        for (String clientId : clientIdArr) {
            RmResourceRegistration updateData = new RmResourceRegistration();
            updateData.setClientId(clientId);
            updateData.setBusinessName(rmResourceRegistration.getBusinessName());
            rmResourceRegistrationMapper.updateStatusByResource(updateData);
            // 增加业务变更记录
            EpsMethodChangeRecord changeRecord = new EpsMethodChangeRecord();
            // 设置基本信息
            changeRecord.setClientId(clientId);
            changeRecord.setBusinessCode(rmResourceRegistration.getBusinessCode());
            changeRecord.setBusinessName(rmResourceRegistration.getBusinessName());
            changeRecord.setCreateTime(DateUtils.getNowDate());
            changeRecord.setUpdateTime(DateUtils.getNowDate());
            changeRecord.setCreatBy(SecurityUtils.getUsername());
            changeRecord.setUpdateBy(SecurityUtils.getUsername());
            // 修改内容
            String content = "业务为" + rmResourceRegistration.getBusinessName();
            changeRecord.setChangeContent(content);
            // 保存数据
            epsMethodChangeRecordMapper.insertEpsMethodChangeRecord(changeRecord);
        }
        return 1;
    }

    @Override
    public int addRemark(RmResourceRegistration rmResourceRegistration) {
        rmResourceRegistration.setDeployDevice(rmResourceRegistration.getDeployDevice().replace("\n",","));
        int rows = rmResourceRegistrationMapper.addRemark(rmResourceRegistration);
        return 1;
    }
    @Override
    public int updateRemark(RmResourceRegistration rmResourceRegistration) {
        rmResourceRegistration.setDeployDevice(rmResourceRegistration.getDeployDevice().replace("\n",","));
        int rows = rmResourceRegistrationMapper.updateRemark(rmResourceRegistration);
        return 1;
    }
    @Override
    public int addReportedBandwidth(RmResourceRegistration rmResourceRegistration) {
        if(rmResourceRegistration.getId() == null){
            throw new RuntimeException("id不可为null");
        }
        int rows = rmResourceRegistrationMapper.addReportedBandwidth(rmResourceRegistration);
        return rows;
    }

    @Override
    public int removeAlarmFlag(RmResourceRegistration rmResourceRegistration) {
        if(rmResourceRegistration.getId() == null){
            throw new RuntimeException("id不可为null");
        }
        int rows = rmResourceRegistrationMapper.removeAlarmFlag(rmResourceRegistration);
        return 1;
    }
    @Override
    public int removeServer(Long[] ids)
    {
        return rmResourceRegistrationMapper.removeServer(ids);
    }
}
