package com.ruoyi.mtragent.handler;

import com.ruoyi.common.core.enums.MsgEnum;
import com.ruoyi.mtragent.domain.DeviceMessage;
import com.ruoyi.mtragent.domain.vo.RspVo;
import com.ruoyi.mtragent.service.IRmAgentManagementService;
import com.ruoyi.mtragent.utils.JsonDataParser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

/**
 * 设备消息处理器
 */
@Slf4j
@Component
@EnableScheduling
public class MessageHandler {

    private final Map<String, Consumer<DeviceMessage>> messageHandlers = new HashMap<>();
    // 心跳状态
    private static final String HEARTBEAT_STATUS_PREFIX = "heartbeat:status:";
    // 心跳时间
    private static final String HEARTBEAT_TIME_PREFIX = "heartbeat:time:";
    // 心跳告警
    private static final String HEARTBEAT_ALERT_PREFIX = "heartbeat:alert:";
    String HEARTBEAT_RECOVERY_COUNT_PREFIX = "heartbeat:recovery:count:";

    String HEARTBEAT_COUNT_PREFIX = "heartbeat:count:";
    private static final long HEARTBEAT_TIMEOUT = 30000; // 3分钟超时


    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private IRmAgentManagementService rmAgentManagementService;


    /**
     * 初始化处理器映射
     */
    @PostConstruct
    public void init() {
        registerHandler(MsgEnum.Agent版本更新应答.getValue(), this::handleAgentUpdateRspMessage);

        // 其他类型消息可以单独注册处理器
        registerHandler(MsgEnum.注册.getValue(), this::handleRegisterMessage);
    }
    private void handleRegisterMessage(DeviceMessage message) {

    }
    /**
     * agent更新响应
     * @param message
     */
    private void handleAgentUpdateRspMessage(DeviceMessage message) {
        List<RspVo> rspVoList = JsonDataParser.parseJsonData(message.getData(), RspVo.class);
    }

    /**
     * 注册消息处理器
     */
    private void registerHandler(String dataType, Consumer<DeviceMessage> handler) {
        messageHandlers.put(dataType, handler);
    }

    /**
     * 处理设备消息（对外暴露的主方法）
     */
    public void handleMessage(DeviceMessage message) {
        String dataType = message.getDataType();
        Consumer<DeviceMessage> handler = messageHandlers.get(dataType);

        if (handler != null) {
            handler.accept(message);
        } else {
            log.warn("未知数据类型：{}", dataType);
        }
    }

    // ========== 具体的消息处理方法 ==========


}