package com.dcs.equipment.service.impl;

import com.dcs.equipment.domain.DeviceRequest;
import com.dcs.equipment.service.ProtocolService;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author: LaFantasque
 * @date: 2025-07-23 11:46
 */
@Service("mqttService")
public class MQTTServiceImpl implements ProtocolService {
    @Override
    public List<Object> getValues(DeviceRequest request) {
        return null;
    }

    @Override
    public boolean setValue(DeviceRequest request) {
        String broker = "tcp://" + request.getIpAddress() + ":" + request.getPort();
        String topic = request.getResource();
        String clientId = "java_client_" + System.currentTimeMillis();
        String username = request.getData().get(1).toString();
        String password = request.getData().get(2).toString();
        Integer qos = request.getLengthOrQos();

        try {
            MqttClient client = new MqttClient(broker, clientId, new MemoryPersistence());

            MqttConnectOptions options = new MqttConnectOptions();
            options.setCleanSession(true);
            options.setUserName(username);
            options.setPassword(password.toCharArray());

            // 设置回调，用于接收消息
            client.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable cause) {
                    System.out.println("连接丢失: " + cause.getMessage());
                }

                @Override
                public void messageArrived(String topic, MqttMessage message) {
                    System.out.println("接收到设备回复: " + new String(message.getPayload()));
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                    // 可选：消息确认送达后触发
                    System.out.println("消息已成功发送");
                }
            });

            client.connect(options);
            System.out.println("连接成功");

            // 订阅 topic 等待设备响应
            client.subscribe(topic, qos);
            System.out.println("已订阅 topic: " + topic);

            // 构建 JSON 消息并发布
            Object o = request.getData().get(0);
            String jsonPayload = o.toString();
            MqttMessage message = new MqttMessage(jsonPayload.getBytes());
            message.setQos(qos);
            client.publish(topic, message);
            System.out.println("已发送 JSON 消息: " + jsonPayload);

            // 保持连接等待回复（例如 30 秒）
//            System.out.println("等待设备回复中...");
//            Thread.sleep(30000); // 可根据需要调整等待时间

            // 关闭连接
            client.disconnect();
            client.close();
            System.out.println("连接已断开");
            return true;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public Object getValue(DeviceRequest request) {
        return null;
    }
}