package com.ruoyi.mtragent.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.enums.MsgEnum;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.mtragent.domain.DeviceMessage;
import com.ruoyi.mtragent.domain.RmMtrClientRegistration;
import com.ruoyi.mtragent.domain.vo.AgentUpdateMsgVo;
import com.ruoyi.mtragent.domain.vo.PolicyTypeVo;
import com.ruoyi.mtragent.domain.vo.PolicyVo;
import com.ruoyi.mtragent.mapper.RmMtrClientRegistrationMapper;
import com.ruoyi.mtragent.model.ProducerMode;
import com.ruoyi.mtragent.producer.MessageProducer;
import com.ruoyi.mtragent.service.IRmMtrClientRegistrationService;
import com.ruoyi.system.api.domain.NetworkInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.StringJoiner;

/**
 * MTR客户端注册Service业务层处理
 * 
 * @author gyt
 * @date 2025-11-18
 */
@Service
@Slf4j
public class RmMtrClientRegistrationServiceImpl implements IRmMtrClientRegistrationService 
{
    @Autowired
    private RmMtrClientRegistrationMapper rmMtrClientRegistrationMapper;
    @Autowired
    private ProducerMode producerMode;

    /**
     * 查询MTR客户端注册
     * 
     * @param id MTR客户端注册主键
     * @return MTR客户端注册
     */
    @Override
    public RmMtrClientRegistration selectRmMtrClientRegistrationById(Long id)
    {
        RmMtrClientRegistration rmMtrClientRegistration = rmMtrClientRegistrationMapper.selectRmMtrClientRegistrationById(id);
        // 处理网卡信息
        setNetworkMsg(rmMtrClientRegistration);
        return rmMtrClientRegistration;
    }

    /**
     * 查询MTR客户端注册列表
     * 
     * @param rmMtrClientRegistration MTR客户端注册
     * @return MTR客户端注册
     */
    @Override
    public List<RmMtrClientRegistration> selectRmMtrClientRegistrationList(RmMtrClientRegistration rmMtrClientRegistration)
    {
        List<RmMtrClientRegistration> list = rmMtrClientRegistrationMapper.selectRmMtrClientRegistrationList(rmMtrClientRegistration);
        for (RmMtrClientRegistration mtrClientRegistration : list) {
            // 处理网卡信息
            setNetworkMsg(rmMtrClientRegistration);
        }
        return list;
    }

    /**
     * 网卡信息处理
     * @param rmMtrClientRegistration
     */
    public void setNetworkMsg(RmMtrClientRegistration rmMtrClientRegistration){
        String networkMsg = rmMtrClientRegistration.getNetworkInfo();
        StringJoiner resultJoiner = new StringJoiner(";");
        if(networkMsg != null){
            List<NetworkInfo> networkInfoList = JSONObject.parseArray(networkMsg, NetworkInfo.class);
            for (NetworkInfo networkInfo : networkInfoList) {
                String name = networkInfo.getName() != null ? networkInfo.getName() : "";
                String mac = networkInfo.getMac() != null ? networkInfo.getMac() : "";
                String type = networkInfo.getType() != null ? networkInfo.getType() : "";
                String ipv4 = networkInfo.getIpv4() != null ? networkInfo.getIpv4() : "";
                // 单个对象的字段用逗号隔开
                StringJoiner objectJoiner = new StringJoiner(",");
                objectJoiner.add("接口名称：" + name)
                        .add("MAC地址：" + mac)
                        .add("接口类型：" + type)
                        .add("IPv4地址：" + ipv4);
                resultJoiner.add(objectJoiner.toString());
            }
            rmMtrClientRegistration.setNetworkInfo(resultJoiner.toString());
        }
    }
    /**
     * 新增MTR客户端注册
     * 
     * @param rmMtrClientRegistration MTR客户端注册
     * @return 结果
     */
    @Override
    public int insertRmMtrClientRegistration(RmMtrClientRegistration rmMtrClientRegistration)
    {
        rmMtrClientRegistration.setCreateTime(DateUtils.getNowDate());
        return rmMtrClientRegistrationMapper.insertRmMtrClientRegistration(rmMtrClientRegistration);
    }

    /**
     * 修改MTR客户端注册
     * 
     * @param rmMtrClientRegistration MTR客户端注册
     * @return 结果
     */
    @Override
    public int updateRmMtrClientRegistration(RmMtrClientRegistration rmMtrClientRegistration)
    {
        rmMtrClientRegistration.setUpdateTime(DateUtils.getNowDate());
        return rmMtrClientRegistrationMapper.updateRmMtrClientRegistration(rmMtrClientRegistration);
    }

    /**
     * 批量删除MTR客户端注册
     * 
     * @param ids 需要删除的MTR客户端注册主键
     * @return 结果
     */
    @Override
    public int deleteRmMtrClientRegistrationByIds(Long[] ids)
    {
        return rmMtrClientRegistrationMapper.deleteRmMtrClientRegistrationByIds(ids);
    }

    /**
     * 删除MTR客户端注册信息
     * 
     * @param id MTR客户端注册主键
     * @return 结果
     */
    @Override
    public int deleteRmMtrClientRegistrationById(Long id)
    {
        return rmMtrClientRegistrationMapper.deleteRmMtrClientRegistrationById(id);
    }

    /**
     * 配置更新策略
     * @param rmMtrClientRegistration
     * @return
     */
    @Override
    public int addAgentUpdatePolicy(RmMtrClientRegistration rmMtrClientRegistration) {
        String mtrClientIdStr = rmMtrClientRegistration.getMtrClientIds();
        String[] mtrClientIdArr = mtrClientIdStr.split("\n");

        // 只提取公共变量
        String method = rmMtrClientRegistration.getMethod();
        String fileMd5 = rmMtrClientRegistration.getFileMd5();
        String filePath = rmMtrClientRegistration.getFilePath();
        Date scheduledUpdateTime = rmMtrClientRegistration.getScheduledUpdateTime();

        for (String mtrClientId : mtrClientIdArr) {
            // 配置更新参数
            RmMtrClientRegistration updateData = new RmMtrClientRegistration();
            updateData.setMtrClientId(mtrClientId);
            updateData.setMethod(method);
            updateData.setFileMd5(fileMd5);
            updateData.setFilePath(filePath);
            updateData.setScheduledUpdateTime(scheduledUpdateTime);
            if("0".equals(method)){
                updateData.setScheduledUpdateTime(null);
            }
            rmMtrClientRegistrationMapper.updateRmMtrClientRegistration(updateData);
            // 构建更新策略
            AgentUpdateMsgVo agentUpdateMsgVo = new AgentUpdateMsgVo();
            agentUpdateMsgVo.setFileUrl(filePath);
            agentUpdateMsgVo.setFileMd5(fileMd5);
            agentUpdateMsgVo.setMethod(Integer.valueOf(method));
            if("1".equals(method)){
                Date scheduledUpdateTimeInner = scheduledUpdateTime;
                long scheduledTime = scheduledUpdateTimeInner.toInstant().getEpochSecond();
                agentUpdateMsgVo.setPolicyTime(scheduledTime);
            }
            try {
                PolicyVo<AgentUpdateMsgVo> policyVo = new PolicyVo();
                List<AgentUpdateMsgVo> list = new ArrayList<>();
                list.add(agentUpdateMsgVo);
                policyVo.setContents(list);
                String policyVoStr = JSONObject.toJSONString(policyVo);
                PolicyTypeVo policyTypeVo = new PolicyTypeVo();
                policyTypeVo.setVersions(policyVoStr);
                String configJson = JSONObject.toJSONString(policyTypeVo);
                DeviceMessage deviceMessage = new DeviceMessage();
                deviceMessage.setClientId(mtrClientId);
                deviceMessage.setDataType(MsgEnum.获取最新策略应答.getValue());
                deviceMessage.setData(configJson);
                MessageProducer messageProducer = new MessageProducer();

                messageProducer.sendAsyncProducerMessage(
                        producerMode.getAgentTopic(),
                        "",
                        "",
                        JSONObject.toJSONString(deviceMessage)
                );
            } catch (Exception e) {
                log.error("发送设备配置失败，deviceId: {}", mtrClientId, e);
            }
        }
        return 1;
    }
}
