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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tuoheng.admin.enums.MQTTTopicEnum;
import com.tuoheng.admin.pojo.entity.Airport;
import com.tuoheng.admin.service.IAirportService;
import com.tuoheng.admin.service.mqttService.consumer.MqttConsumerCallBack;
import com.tuoheng.common.utils.IpUtils;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.List;

/**
 * @Author: 吴彬
 * @CreateTime: 2023-05-22  19:09
 * @Description: MQTT配置类
 * @Version: 1.0
 */
@Configuration
@Slf4j
public class MqttProviderConfig {
    @Value("${spring.mqtt.username}")
    private String username;

    @Value("${spring.mqtt.password}")
    private String password;

    @Value("${spring.mqtt.url}")
    private String hostUrl;

    @Value("${spring.mqtt.client.id}")
    private String clientId;

    @Value("${spring.mqtt.default.topic}")
    private String defaultTopic;

    /**
     * 客户端对象
     */
    private MqttClient client;

    @Autowired
    private IAirportService airportService;
    /**
     * 在bean初始化后连接到服务器
     */
    @PostConstruct
    public void init(){
        connect();
    }

    /**
     * 客户端连接服务端
     */
    public void connect(){
        try{
            String ip = IpUtils.getHostIp();
            //创建MQTT客户端对象
            client = new MqttClient(hostUrl,ip,new MemoryPersistence());
            //连接设置
            MqttConnectOptions options = new MqttConnectOptions();
            //是否清空session，设置false表示服务器会保留客户端的连接记录（订阅主题，qos）,客户端重连之后能获取到服务器在客户端断开连接期间推送的消息
            //设置为true表示每次连接服务器都是以新的身份
            options.setCleanSession(true);
            //设置连接用户名
            options.setUserName(username);
            //设置连接密码
            options.setPassword(password.toCharArray());
            //设置超时时间，单位为秒
            options.setConnectionTimeout(100);
            //设置心跳时间 单位为秒，表示服务器每隔 1.5*20秒的时间向客户端发送心跳判断客户端是否在线
            options.setKeepAliveInterval(20);
            //设置遗嘱消息的话题，若客户端和服务器之间的连接意外断开，服务器将发布客户端的遗嘱信息
            options.setWill("willTopic",(ip + "与服务器断开连接").getBytes(),0,false);

            //防止 ERROR o.e.p.c.mqttv3.internal.ClientState - Timed out as no activity  错误
            options.setConnectionTimeout(0);

//mqttClient.reconnect(); 这个方法或者回调已经设置了重连
            //options.setAutomaticReconnect(true);
            //设置回调
            client.setCallback(new MqttConsumerCallBack());
            client.connect(options);


            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("mark",1);
            List airportList = airportService.list(wrapper);

            /**
             * 遍历所有的设备，一次订阅每个设备的对应事件的topic
             */
            airportList.forEach(item ->{
                Airport airport = (Airport)item;
                Arrays.stream(MQTTTopicEnum.values()).forEach(mqttTopicEnum -> {
                    try {
                        client.subscribe(String.format(mqttTopicEnum.getTopic(),airport.getEdgeId()),mqttTopicEnum.getQos());
                    } catch (MqttException e) {
                        log.error("订阅设备:{},对应topic:{}异常:{}",airport.getEdgeId(),mqttTopicEnum.getTopic(),e);
                    }
                });
            });
        } catch(MqttException e){
            log.error("MQTT链接异常：{}",e);
        }
    }

    public boolean isconnect() {
        try {
            String ip = IpUtils.getHostIp();
            //创建MQTT客户端对象
            client = new MqttClient(hostUrl,ip,new MemoryPersistence());
        }catch (Exception e){
            log.error("MQTT链接异常：{}",e);
        }
        return client.isConnected();
    }

    /**
     * MQTT发布消息
     * @param qos
     * @param retained
     * @param topic
     * @param message
     * @return
     */
    public MqttDeliveryToken publish(int qos,boolean retained,String topic,String message){
        if (!client.isConnected()){
                connect();
        }
        MqttDeliveryToken token=null;
        MqttMessage mqttMessage = new MqttMessage();
        mqttMessage.setQos(qos);
        mqttMessage.setRetained(retained);
        mqttMessage.setPayload(message.getBytes());
        //主题的目的地，用于发布/订阅信息
        MqttTopic mqttTopic = client.getTopic(topic);
        //提供一种机制来跟踪消息的传递进度
        //用于在以非阻塞方式（在后台运行）执行发布是跟踪消息的传递进度

        try {
            //将指定消息发布到主题，但不等待消息传递完成，返回的token可用于跟踪消息的传递状态
            //一旦此方法干净地返回，消息就已被客户端接受发布，当连接可用，将在后台完成消息传递。
            token = mqttTopic.publish(mqttMessage);
            token.waitForCompletion();
        } catch (MqttException e) {
            log.error("MQTT topic:{},message:{},消息发送异常：{}",topic,message,e);
        }
        return  token;
    }


    /**
     * 断开连接
     */
    public void disConnect(){
        try {
            client.disconnect();
        } catch (MqttException e) {
            log.error("MQTT断开链接异常：{}",e);
        }
    }
    /**
     * 订阅主题
     */
    public void subscribe(String topic,int qos){
        try {
            client.subscribe(topic,qos);
        } catch (MqttException e) {
            log.error("MQTT订阅topic:{}异常：{}",topic,e);
        }
    }

    public MqttClient getClient(){
        return client;
    }

    /**
     * 订阅集成列表
     */
    public void subscribeAllAirport(Airport airport) throws MqttException {
        if (!client.isConnected()){
            connect();
        }
        Arrays.stream(MQTTTopicEnum.values()).forEach(mqttTopicEnum -> {
            try {
                client.subscribe(String.format(mqttTopicEnum.getTopic(),airport.getEdgeId()),mqttTopicEnum.getQos());
            } catch (MqttException e) {
                log.error("订阅设备:{},对应topic:{}异常:{}",airport.getEdgeId(),mqttTopicEnum.getTopic(),e);
            }
        });
    }
}

