package com.ruoyi.dj.websocket.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import com.ruoyi.dj.websocket.core.MessageHandler;
import com.ruoyi.dj.websocket.config.CustomWebSocketHandler;

import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class MessagingService {
    private Map<String, MessageHandler> handlers;
    private CustomWebSocketHandler webSocketHandler;

    @Autowired
    public MessagingService(ApplicationContext context, CustomWebSocketHandler webSocketHandler) {
        this.handlers = context.getBeansOfType(MessageHandler.class).values().stream()
                .collect(Collectors.toMap(MessageHandler::getType, handler -> handler));
        this.webSocketHandler = webSocketHandler;
        log.info("完成动态收集系统中所有的 MessageHandler");
    }

    /**
     * 发送消息方法
     */
    public void sendMessage(String type, String gateway, String message) {
        // 发送消息的逻辑
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            // 将字符串解析为 JSON 对象
            ObjectNode jsonNode = (ObjectNode) objectMapper.readTree(message);
            // 添加新的字段 "businessType" 和 "gateway"
            jsonNode.put("businessType", type);
            jsonNode.put("gateway", gateway);
            // 将 JSON 对象转换为字符串
            String updatedMessage = objectMapper.writeValueAsString(jsonNode);
            // 继续处理更新后的消息
            MessageHandler handler = handlers.get(type);
            if (handler != null) {
                handler.handleMessage(updatedMessage);
            }
        } catch (Exception e) {
            log.error("发送消息时发生异常: ", e);
        }
    }
}