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.utils.StringUtil;
import com.yeejoin.equipmanage.mapper.EquipmentSpecificMapper;
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.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;

    @Value("${equip.center.risk.topic}")
    private String riskMsgCenterEquipTopic;

    @Value("${patrol.center.risk.topic}")
    private String riskMsgCenterPatrolTopic;

    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事件监听
        list.add("+/+/transmit"); // 添加交换站事件监听
        list.add("+/+/perspective"); // 添加交换站事件监听
        list.add(riskMsgCenterEquipTopic);
        list.add(riskMsgCenterPatrolTopic);
        list.add("+/+/eventAlarm"); // 添加换流站韶山监听事件   --- shaoshan 修改为 eventAlarm：事件告警 - 统一
        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);
                }else if (dataType.equals("transmit") && StringUtil.isNotEmpty(msg)){ // 遥信遥测信号
                    mqttReceiveService.handlerMqttRomaMessage(topic,msg);
                }else if (dataType.equals("eventAlarm") && StringUtil.isNotEmpty(msg)){ // 告警信号
                    mqttReceiveService.handlerMqttStationMessage(topic,msg);
                }
            }
        };
    }

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