package com.tuoheng.admin.service.mqttService.consumer;


import com.alibaba.fastjson.JSONObject;
import com.tuoheng.admin.service.mqttService.consumer.topicHandle.ITopicHandleService;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;


/**
 * @Author: 吴彬
 * @CreateTime: 2023-05-22  19:09
 * @Description: MQTT 消息监听回调
 * @Version: 1.0
 */
@Component
@Slf4j
public class MqttConsumerCallBack implements MqttCallback{

    @Autowired
    private List<ITopicHandleService> iTopicHandleServices;

    /**
     * 客户端断开连接的回调
     */
    @Override
    public void connectionLost(Throwable throwable) {
        System.out.println("与服务器断开连接，可重连");
        /*MqttProviderConfig client = SpringUtil.getBean(MqttProviderConfig.class);
        System.out.println(client.isconnect());
        if (!client.isconnect()) {
            client.connect();
            System.out.println("重连成功！");
        }*/
    }

    /**
     *  消费消息回调
     * @param topic name of the topic on the message was published to
     * @param message the actual message.
     */
    @Override
    public void messageArrived(String topic, MqttMessage message){
        try {
            log.info("接收消息主题 : {}\n{}",topic,JSONObject.parse(message.getPayload()));
            String edgId = topic.split("/")[2];
            //将topic中的设备编号替换成通用标识
            String topicSource = topic.replace(edgId,"%s");

            /**
             * 根据topic获取对应的消息处理类，后期扩展只需定义对应topic的处理类即可，注意：每个处理类对应的topic全局唯一
             */
            for(ITopicHandleService iTopicHandleService : iTopicHandleServices){
                if (topicSource.equals(iTopicHandleService.getTopic())){
                    iTopicHandleService.topicHandle(message,edgId);
                    break;
                }
            }
        }catch (Exception e){
            log.error("接收消息主题 : {},异常：{}",topic,e);
        }
    }

    /**
     * 消息发布成功的回调
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

    }

}

