package com.yeejoin.equipmanage.config;

import com.yeejoin.equipmanage.common.entity.vo.EquipmentSpecificVo;
import com.yeejoin.equipmanage.common.enums.ConfigPageTopicEnum;
import com.yeejoin.equipmanage.common.enums.TopicEnum;
import com.yeejoin.equipmanage.common.utils.StringUtil;
import com.yeejoin.equipmanage.mapper.EquipmentSpecificMapper;
import com.yeejoin.equipmanage.service.IEquipmentSpecificSerivce;
import com.yeejoin.equipmanage.service.ISyncDataService;
import com.yeejoin.equipmanage.service.MqttEventReceiveService;
import com.yeejoin.equipmanage.service.MqttReceiveService;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.integration.annotation.IntegrationComponentScan;
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 java.awt.image.DirectColorModel;
import java.util.ArrayList;
import java.util.List;

/**
 * @author keyong
 * @title: EquipmentIotMQConsumer
 * <pre>
 * @description: MQTT订阅模式消费类
 * </pre>
 * @date 2020/10/29 19:23
 */
@Configuration
@IntegrationComponentScan
public class EquipmentIotMqttReceiveConfig {


    @Value("${emqx.user-name}")
    private String userName;

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

    @Value("${emqx.broker}")
    private String hostUrl;

    @Value("${emqx.client-id}")
    private String clientId;

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

    @Value("${spring.mqtt.completionTimeout}")
    private int completionTimeout;


    private  EquipmentSpecificMapper equipmentSpecificMapper;


    private  MqttEventReceiveService mqttEventReceiveService;


    private ISyncDataService iSyncDataService;

    @Autowired
    public void setEquipmentSpecificMapper(EquipmentSpecificMapper equipmentSpecificMapper) {
        this.equipmentSpecificMapper = equipmentSpecificMapper;
    }
    @Autowired
    public void setMqttEventReceiveService(MqttEventReceiveService mqttEventReceiveService) {
        this.mqttEventReceiveService = mqttEventReceiveService;
    }
    @Autowired
    public void setiSyncDataService(ISyncDataService iSyncDataService) {
        this.iSyncDataService = iSyncDataService;
    }

    @Autowired
    @Lazy
    MqttReceiveService mqttReceiveService;

    // 全局变量adapter
    public MqttPahoMessageDrivenChannelAdapter adapter;


    @Bean
    public MqttConnectOptions getMqttConnectOptions() {
        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
        mqttConnectOptions.setUserName(userName);
        mqttConnectOptions.setPassword(password.toCharArray());
        mqttConnectOptions.setServerURIs(new String[]{hostUrl});
        mqttConnectOptions.setKeepAliveInterval(20);
        mqttConnectOptions.setAutomaticReconnect(true);
        return mqttConnectOptions;
    }

    @Bean
    public MqttPahoClientFactory mqttPahoClientFactory() {
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        factory.setConnectionOptions(getMqttConnectOptions());
        return factory;
    }

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

    //配置client,监听的topic
    @Bean
    public MessageProducer inbound() {
        List<EquipmentSpecificVo> equipAndCars = equipmentSpecificMapper.getEquipOrCarByIotCode(null);
        iSyncDataService.saveOrUpdateEquipIotCodeRedisData(equipAndCars);
        List<String> list = new ArrayList<String>();
        if (equipAndCars.size() <= 0) {
            list.add(defaultTopic);
        }
        list.addAll(ConfigPageTopicEnum.getEnumTopicList());          //大屏数据推送接口订阅
        list.add("+/+/property"); // 添加iot車輛裝備數據上報事件监听
        list.add("+/+/event"); // 添加iot事件监听
        String[] arr = list.toArray(new String[list.size()]);
        adapter = new MqttPahoMessageDrivenChannelAdapter(clientId + "_inbound", mqttPahoClientFactory(), arr);
        adapter.setCompletionTimeout(completionTimeout);
        adapter.setConverter(new DefaultPahoMessageConverter());
        adapter.setQos(0);
        adapter.setOutputChannel(mqttInputChannel());
        return adapter;
    }

    //通过通道获取数据
    @Bean
    @ServiceActivator(inputChannel = "mqttInputChannel")
    public MessageHandler handler() {
        return message -> {
            String topic = message.getHeaders().get("mqtt_receivedTopic").toString();
            String msg = message.getPayload().toString();
            int endIndex = topic.lastIndexOf("/");
            if (endIndex > 0 && StringUtil.isNotEmpty(message)) {
                String dataType = topic.substring(endIndex + 1);
                if (dataType.equals("property") && StringUtil.isNotEmpty(msg)) {
                    mqttReceiveService.handlerMqttIncrementMessage(topic, msg);
                } else if (dataType.equals("event") && StringUtil.isNotEmpty(msg)) {
                    mqttEventReceiveService.handlerMqttIncrementMessage(topic, msg);
                }
            }
        };
    }

    public void setMqttReceiveService(MqttReceiveService mqttReceiveService) {
        this.mqttReceiveService = mqttReceiveService;
    }
}
