package com.ningdatech.carapi.car.monitor.mqtt;


import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.core.MessageProducer;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;
import org.springframework.scheduling.concurrent.ConcurrentTaskScheduler;

@Configuration
//@IntegrationComponentScan
@Slf4j
public class MqttReceiveConfig {

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

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

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

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

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

    @Value("${spring.mqtt.completionTimeout}")
    private int completionTimeout;   //连接超时

//    @Bean
    public MqttPahoClientFactory mqttClientFactory() {
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
        mqttConnectOptions.setUserName(username);
        mqttConnectOptions.setPassword(password.toCharArray());
        // 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录，
        // 把配置里的 cleanSession 设为false，客户端掉线后 服务器端不会清除session，
        // 当重连后可以接收之前订阅主题的消息。当客户端上线后会接受到它离线的这段时间的消息
        mqttConnectOptions.setCleanSession(false);
        mqttConnectOptions.setServerURIs(new String[]{hostUrl});
        // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线，但这个方法并没有重连的机制
        mqttConnectOptions.setKeepAliveInterval(20);
        factory.setConnectionOptions(mqttConnectOptions);
        return factory;
    }

    //接收通道
//    @Bean
    public MessageChannel mqttInputChannel() {
        return new DirectChannel();
    }

//    @Bean
    public MessageProducer inbound() {
        MqttPahoMessageDrivenChannelAdapter adapter =
                new MqttPahoMessageDrivenChannelAdapter(clientId, mqttClientFactory(), defaultTopic);
        adapter.setCompletionTimeout(completionTimeout);
        adapter.setConverter(new DefaultPahoMessageConverter());
        adapter.setQos(1);
        adapter.setOutputChannel(mqttInputChannel());
        adapter.setTaskScheduler(new ConcurrentTaskScheduler());
        log.info("adapter ==> " + adapter);
        return adapter;
    }

    //通过通道获取数据
//    @Bean
    @ServiceActivator(inputChannel = "mqttInputChannel")
    public MessageHandler handler() {
        return message -> {
            try {
                String string = message.getPayload().toString();
                String res = "{\"method\":\"OnEventNotify\",\"params\":{\"ability\":\"event_msa_alarm\",\"events\":[{\"data\":{\"alarmId\":\"35323136353734221026091604000200\",\"alarmInfo\":\"{\\\"BSDRightRearWarn\\\":[{\\\"accelerateMaxValue\\\":0,\\\"accelerateValue\\\":0,\\\"alarmAttachMent\\\":{\\\"audioChans\\\":\\\"\\\",\\\"audioNum\\\":0,\\\"othersNum\\\":0,\\\"picChans\\\":\\\"\\\",\\\"picNum\\\":0,\\\"res\\\":\\\"\\\",\\\"serverType\\\":0,\\\"totalNum\\\":2,\\\"videoChans\\\":\\\"\\\",\\\"videoNum\\\":0},\\\"alarmID\\\":\\\"35323136353734221026091604000200\\\",\\\"alarmMaxValue\\\":0,\\\"alarmSeq\\\":0,\\\"alarmType\\\":0,\\\"alarmValue\\\":0,\\\"angularMaxValue\\\":0,\\\"angularValue\\\":0,\\\"fatigueValue\\\":0,\\\"frontCarDistance\\\":0,\\\"frontCarSpeed\\\":0,\\\"identifiData\\\":0.0,\\\"logicalChannel\\\":0,\\\"publicData\\\":{\\\"driverCertificatesID\\\":\\\"\\\",\\\"durationTime\\\":0,\\\"gps\\\":{\\\"altitude\\\":\\\"4000\\\",\\\"direction\\\":\\\"0\\\",\\\"directionEW\\\":\\\"E\\\",\\\"directionNS\\\":\\\"N\\\",\\\"latitude\\\":\\\"10984327\\\",\\\"longitude\\\":\\\"43253100\\\",\\\"speed\\\":\\\"0\\\"},\\\"vehicleStatus\\\":4097},\\\"similarity\\\":0,\\\"similarityMax\\\":0,\\\"targetAttrs\\\":{\\\"cameraIndexCode\\\":\\\"6f6e67980cf842a4b8fba5aa9dc68d18\\\",\\\"cameraType\\\":\\\"CZ\\\",\\\"deviceIndexCode\\\":\\\"049704746b384849b7cc8ffad89dbdda\\\"}}],\\\"channelID\\\":1,\\\"dateTime\\\":\\\"2022-10-26T09:16:04.000+08:00\\\",\\\"eventDescription\\\":\\\"BSDRightRearWarn\\\",\\\"eventType\\\":\\\"BSDRightRearWarn\\\",\\\"ipAddress\\\":\\\"36.113.97.203\\\",\\\"portNo\\\":22592}\",\"alarmTime\":\"2022-10-26 09:16:04\",\"deviceIndexCode\":\"049704746b384849b7cc8ffad89dbdda\",\"direction\":0,\"driverIndexCode\":\"\",\"driverNo\":\"\",\"eventId\":\"30FD188342653C44B9ABA7F2DA19A65\",\"eventType\":132385,\"height\":4000,\"latitude\":10984327,\"level\":\"m\",\"longitude\":43253100,\"picNum\":0,\"sourceType\":0,\"speed\":0,\"status\":0,\"vehicleIndexCode\":\"549b8b8a734a497596d43ab6f6d88241\",\"videoNum\":0},\"eventId\":\"30FD188342653C44B9ABA7F2DA19A65\",\"eventType\":5201154049,\"happenTime\":\"2022-10-26 09:17:07\",\"srcIndex\":\"549b8b8a734a497596d43ab6f6d88241\",\"srcType\":\"vehicle\",\"status\":0,\"timeout\":0}],\"sendTime\":\"2022-10-26 09:17:07\"}}\n";
                log.info("接收到消息：" + string);
            } catch (MessagingException e) {
                e.printStackTrace();
            }
        };
    }
}