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.rocketmq.domain.DeviceMessage;
import com.ruoyi.rocketmq.domain.RmNetworkInterface;
import com.ruoyi.rocketmq.domain.vo.PolicyTypeVo;
import com.ruoyi.rocketmq.mapper.RmNetworkInterfaceMapper;
import com.ruoyi.rocketmq.model.ProducerMode;
import com.ruoyi.rocketmq.producer.MessageProducer;
import com.ruoyi.rocketmq.service.IRmNetworkInterfaceService;
import com.ruoyi.system.api.domain.RouteMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 客户端网络接口信息Service业务层处理
 * 
 * @author gyt
 * @date 2025-10-14
 */
@Service
public class RmNetworkInterfaceServiceImpl implements IRmNetworkInterfaceService 
{
    @Autowired
    private RmNetworkInterfaceMapper rmNetworkInterfaceMapper;
    @Autowired
    private ProducerMode producerMode;

    /**
     * 查询客户端网络接口信息
     * 
     * @param id 客户端网络接口信息主键
     * @return 客户端网络接口信息
     */
    @Override
    public RmNetworkInterface selectRmNetworkInterfaceById(Long id)
    {
        return rmNetworkInterfaceMapper.selectRmNetworkInterfaceById(id);
    }

    /**
     * 查询客户端网络接口信息列表
     * 
     * @param rmNetworkInterface 客户端网络接口信息
     * @return 客户端网络接口信息
     */
    @Override
    public List<RmNetworkInterface> selectRmNetworkInterfaceList(RmNetworkInterface rmNetworkInterface)
    {
        return rmNetworkInterfaceMapper.selectRmNetworkInterfaceList(rmNetworkInterface);
    }

    /**
     * 新增客户端网络接口信息
     * 
     * @param rmNetworkInterface 客户端网络接口信息
     * @return 结果
     */
    @Override
    public int insertRmNetworkInterface(RmNetworkInterface rmNetworkInterface)
    {
        rmNetworkInterface.setCreateTime(DateUtils.getNowDate());
        return rmNetworkInterfaceMapper.insertRmNetworkInterface(rmNetworkInterface);
    }

    /**
     * 修改客户端网络接口信息
     * 
     * @param rmNetworkInterface 客户端网络接口信息
     * @return 结果
     */
    @Override
    public int updateRmNetworkInterface(RmNetworkInterface rmNetworkInterface)
    {
        rmNetworkInterface.setUpdateTime(DateUtils.getNowDate());
        return rmNetworkInterfaceMapper.updateRmNetworkInterface(rmNetworkInterface);
    }

    @Override
    public int updateRmNetworkInterfaceByMac(RmNetworkInterface rmNetworkInterface) {
        rmNetworkInterface.setUpdateTime(DateUtils.getNowDate());
        return rmNetworkInterfaceMapper.updateRmNetworkInterfaceByMac(rmNetworkInterface);
    }

    /**
     * 批量删除客户端网络接口信息
     * 
     * @param ids 需要删除的客户端网络接口信息主键
     * @return 结果
     */
    @Override
    public int deleteRmNetworkInterfaceByIds(Long[] ids)
    {
        return rmNetworkInterfaceMapper.deleteRmNetworkInterfaceByIds(ids);
    }

    /**
     * 删除客户端网络接口信息信息
     * 
     * @param id 客户端网络接口信息主键
     * @return 结果
     */
    @Override
    public int deleteRmNetworkInterfaceById(Long id)
    {
        return rmNetworkInterfaceMapper.deleteRmNetworkInterfaceById(id);
    }

    /**
     * 绑定公网ip
     * @param rmNetworkInterface
     * @return
     */
    @Override
    public int bindPublicIp(RmNetworkInterface rmNetworkInterface) {
        return rmNetworkInterfaceMapper.updateRmNetworkInterface(rmNetworkInterface);
    }

    /**
     * 更新路由信息
     * @param clientId
     */
    public void updateRouteMsg(String clientId){
        MessageProducer messageProducer = new MessageProducer();
        // 查询路由是否有变化
        RmNetworkInterface rmNetworkInterface = new RmNetworkInterface();
        rmNetworkInterface.setClientId(clientId);
        rmNetworkInterface.setBindIp("2");
        List<RmNetworkInterface> networkInterfaces = rmNetworkInterfaceMapper.selectRmNetworkInterfaceList(rmNetworkInterface);
        if(!networkInterfaces.isEmpty()){
            List<RmNetworkInterface> oldList = networkInterfaces.stream()
                    .filter(networkInterface -> networkInterface.getNewFlag() == 0)
                    .collect(Collectors.toList());
            if(!oldList.isEmpty()){
                Map<String, Object> resultMap = new HashMap<>();
                // 增加静态路由
                RmNetworkInterface oldMsg = oldList.get(0);
                RouteMsg oldRouteMsg = new RouteMsg();
                oldRouteMsg.setGateway(oldMsg.getGateway());
                oldRouteMsg.setName(oldMsg.getInterfaceName());
                resultMap.put("delRoute", oldRouteMsg);
                List<RmNetworkInterface> newList = networkInterfaces.stream()
                        .filter(networkInterface -> networkInterface.getNewFlag() == 1)
                        .collect(Collectors.toList());
                RmNetworkInterface newMsg = newList.get(0);
                RouteMsg newRouteMsg = new RouteMsg();
                newRouteMsg.setGateway(newMsg.getGateway());
                newRouteMsg.setName(newMsg.getInterfaceName());
                resultMap.put("addRoute", newRouteMsg);
                resultMap.put("upTime", Instant.now().getEpochSecond());
                PolicyTypeVo policyTypeVo = new PolicyTypeVo();
                policyTypeVo.setRoutes(JSONObject.toJSONString(resultMap));
                String configJson = JSONObject.toJSONString(policyTypeVo);
                // 构建发送消息
                DeviceMessage message = new DeviceMessage();
                message.setClientId(clientId);
                message.setData(configJson);
                message.setDataType(MsgEnum.获取最新策略应答.getValue());

                messageProducer.sendAsyncProducerMessage(
                        producerMode.getAgentTopic(),
                        "",
                        "",
                        JSONObject.toJSONString(message)
                );
                // 更新网卡信息表
                RmNetworkInterface updateQuery = new RmNetworkInterface();
                updateQuery.setNewFlag(999);
                updateQuery.setMacAddress(networkInterfaces.get(0).getMacAddress());
                rmNetworkInterfaceMapper.updateRmNetworkInterfaceByMac(updateQuery);
            }
        }
    }
}
