package com.ruoyi.system.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.R;
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.core.web.domain.AjaxResult;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.RemoteRocketMqService;
import com.ruoyi.system.api.domain.*;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.vo.MessageVo;
import com.ruoyi.system.domain.vo.ResourceVo;
import com.ruoyi.system.domain.vo.RspVo;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.IRmResourceRegistrationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 资源注册Service业务层处理
 * 
 * @author gyt
 * @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);
        }
        return rmResourceRegistration;
    }

    /**
     * 查询资源注册列表
     * 
     * @param rmResourceRegistration 资源注册
     * @return 资源注册
     */
    @Override
    public List<RmResourceRegistration> selectRmResourceRegistrationList(RmResourceRegistration rmResourceRegistration)
    {
        List<RmResourceRegistration> rmResourceRegistrationList = rmResourceRegistrationMapper.selectRmResourceRegistrationList(rmResourceRegistration);
        for (RmResourceRegistration resourceRegistration : rmResourceRegistrationList) {
            if(resourceRegistration.getClientId() != null){
                // 网卡信息
                setNetWorkMsg(resourceRegistration);
            }
        }
        if(rmResourceRegistration.getQueryParam() != null){
            String queryValue = rmResourceRegistration.getQueryParam().trim();
            // 筛选公网IP私网IP设备SN相等的数据
            // 从rmResourceRegistrationList列表中筛选符合条件的数据
            List<RmResourceRegistration> filteredList = rmResourceRegistrationList.stream()
                    .filter(item -> item != null)
                    .filter(item ->
                            // 检查公网IP (IP1-3和管理网)
                            queryValue.equals(item.getIp1PublicIp()) ||
                                    queryValue.equals(item.getIp2PublicIp()) ||
                                    queryValue.equals(item.getIp3PublicIp()) ||
                                    queryValue.equals(item.getMgmtPublicIp()) ||

                                    // 检查私网IP (IP1-3和管理网)
                                    queryValue.equals(item.getIp1Ipv4Address()) ||
                                    queryValue.equals(item.getIp2Ipv4Address()) ||
                                    queryValue.equals(item.getIp3Ipv4Address()) ||
                                    queryValue.equals(item.getMgmtIpv4Address()) ||

                                    // 检查设备SN
                                    queryValue.equals(item.getHardwareSn()))
                    .collect(Collectors.toList());
            return filteredList;
        }
        return rmResourceRegistrationList;
    }

    /**
     * 网卡信息赋值
     * @param registration
     */
    public void setNetWorkMsg(RmResourceRegistration registration) {
        String clientId = registration.getClientId();
        // 根据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())) {
                // 业务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.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.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.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.setMgmtGateway(network.getGateway());
            }
        }
        // 设置金山machineCode
        RmRegistrationMachine rmRegistrationMachine = new RmRegistrationMachine();
        rmRegistrationMachine.setClientId(clientId);
        List<RmRegistrationMachine> machineList = rmRegistrationMachineMapper.selectRmRegistrationMachineList(rmRegistrationMachine);
        if(!machineList.isEmpty()){
            RmRegistrationMachine machineMsg = machineList.get(0);
            registration.setMachineCode(machineMsg.getMachineCode());
        }

    }
    /**
     * 新增资源注册
     * 
     * @param rmResourceRegistration 资源注册
     * @return 结果
     */
    @Override
    public int insertRmResourceRegistration(RmResourceRegistration rmResourceRegistration)
    {
        rmResourceRegistration.setCreatorId(SecurityUtils.getUserId());
        rmResourceRegistration.setCreatorName(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.setUpdaterId(SecurityUtils.getUserId());
        rmResourceRegistration.setUpdaterName(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();
            // 拿到需要修改的描述
            String description = rmResourceRegistration.getDescription();
            // 初始化
            rmResourceRegistration = new RmResourceRegistration();
            // id赋值
            rmResourceRegistration.setId(id);
            // 可修改资源名称
            rmResourceRegistration.setResourceName(resourceName);
            // 可修改描述
            rmResourceRegistration.setDescription(description);

        }
        return rmResourceRegistrationMapper.updateRmResourceRegistration(rmResourceRegistration);
    }

    /**
     * 资源注册-注册
     *
     * @param rmResourceRegistration 资源注册
     * @return 结果
     */
    @Override
    public int register(RmResourceRegistration rmResourceRegistration) {
        // 设置更新信息
        rmResourceRegistration.setUpdateTime(DateUtils.getNowDate());
        rmResourceRegistration.setUpdaterId(SecurityUtils.getUserId());
        rmResourceRegistration.setUpdaterName(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());
        config.setServerIp(registration.getIpAddress());

        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();
        resourceVo.setClientIp(registration.getIpAddress());
        resourceVo.setClientPort(Integer.valueOf(registration.getResourcePort()));

        if (!"1".equals(registration.getResourceType())) {
            if("1".equals(registration.getSnmpDetect())){
                Map<String, String> switchMap = new HashMap<>();
                switchMap.put("community", registration.getTeamName());
                switchMap.put("ip", registration.getSnmpCollectAddr());
                switchMap.put("port", registration.getSnmpCollectPort());
                resourceVo.setSwitchBoard(JSONObject.toJSONString(switchMap));
            }
        }
        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);
    }
    @Override
    public List<Map> selectAllResourceName()
    {
        return rmResourceRegistrationMapper.selectAllResourceName();
    }
    @Override
    public List<Map> selectAllResourceNameByType(RmResourceRegistration resourceRegistration)
    {
        return rmResourceRegistrationMapper.selectAllResourceNameByType(resourceRegistration);
    }

    /**
     * 检测到服务器离线，修改状态为离线
     * @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));
                        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());
                needUpdate = true;
            }
            if(exits.getLogicalNodeId() == null ||
                    !StringUtils.equals(rmResourceRegistration.getLogicalNodeId(),exits.getLogicalNodeId())){
                // 如果服务器已注册 增加节点标识
                updateData.setLogicalNodeId(rmResourceRegistration.getLogicalNodeId());
                needUpdate = true;
            }
            if(exits.getAgentVersion() == null ||
                    !StringUtils.equals(rmResourceRegistration.getAgentVersion(),exits.getAgentVersion())){
                // 如果服务器已注册 增加版本信息
                updateData.setAgentVersion(rmResourceRegistration.getAgentVersion());
                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
            RmNetworkInterfaceRemote network = new RmNetworkInterfaceRemote();
            network.setId((Long) map.get("id"));
            network.setBindIp(map.get("status").toString());
            remoteRocketMqService.bindPublicIp(network, SecurityConstants.INNER);

            // 添加变更记录
            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);

            Optional.ofNullable(remoteRocketMqService.getNetworkInterfaceList(queryParam, SecurityConstants.INNER))
                    .map(R::getData)
                    .flatMap(list -> list.stream()
                            .filter(ni -> "1".equals(ni.getBindIp()) || "3".equals(ni.getBindIp()))
                            .findFirst())
                    .ifPresent(network -> {
                        updateData.setRegistrationStatus("1");

                        // 发送注册响应
                        RouteMsg routeMsg = new RouteMsg();
                        routeMsg.setName(network.getInterfaceName());
                        routeMsg.setGateway(network.getGateway());

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

                        RspVo rspVo = new RspVo();
                        rspVo.setResCode(1);
                        rspVo.setResMag("注册成功");
                        rspVo.setAddRoute(JSONObject.toJSONString(routeMsg));

                        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;
    }


}
