package com.zbf.web.mqtt;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class MqttMessageSender {

    @Autowired
    private MqttConfig mqttConfig;

    @Autowired
    private MqttProperties mqttProperties;

    public boolean sendMessage(String method, Object[] params, String id) {
        JSONObject message = new JSONObject();
        message.put("jsonrpc", "2.0");
        message.put("method", method);
        message.put("params", params);
        message.put("id", id);

        String topic = mqttProperties.getTopics()[0]; // 使用topics数组中的第一个元素（即"test"主题）
        String payload = JSON.toJSONString(message);

        try {
            mqttConfig.sendMessage(topic, payload, mqttProperties.getQos());
            log.info("消息发送成功 - Topic: {}, Payload: {}", topic, payload);
            return true;
        } catch (RuntimeException e) {
            log.error("消息发送失败 - Topic: {}, Payload: {}, 错误: {}", topic, payload, e.getMessage());
            return false;
        }
    }
}