package com.yeejoin.equipmanage.config;

import com.yeejoin.equipmanage.common.entity.vo.EquipmentSpecificVo;
import com.yeejoin.equipmanage.common.enums.AnalysisReportEnum;
import com.yeejoin.equipmanage.common.enums.ConfigPageTopicEnum;
import com.yeejoin.equipmanage.common.enums.TopicEnum;
import com.yeejoin.equipmanage.common.utils.DateUtils;
import com.yeejoin.equipmanage.common.utils.SpringUtils;
import com.yeejoin.equipmanage.common.utils.StringUtil;
import com.yeejoin.equipmanage.controller.EquipmentDetailController;
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.redisson.api.RLock;
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 org.springframework.scheduling.annotation.Async;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

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


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

    @Value("${emqx.client-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;

    @Autowired(required = false)
    org.redisson.api.RedissonClient redisson;

    @Value("${spring.redis.mode}")
    private String cluster;

    @Autowired
    EquipmentSpecificMapper equipmentSpecificMapper;
    
    @Autowired
    MqttEventReceiveService mqttEventReceiveService;
    
    @Autowired
    private 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(10);
        mqttConnectOptions.setAutomaticReconnect(true);
        mqttConnectOptions.setMaxInflight(1000);
//        mqttConnectOptions.setConnectionTimeout(0);

        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) {
//            for (EquipmentSpecificVo specificVo : equipAndCars) {
//                String iotCode = specificVo.getIotCode();
//                if (iotCode.length() > 8) {
//                    String prefix = iotCode.substring(0, 8);
//                    String suffix = iotCode.substring(8);
//                    String topicTotal = String.format("%s/%s/property", prefix, suffix);
//                    list.add(topicTotal);
//                }
//            }
        } else {
            list.add(defaultTopic);
        }
        list.addAll(ConfigPageTopicEnum.getEnumTopicList());          //大屏数据推送接口订阅
        list.add("$share/AMOS-EQUIPMANAGE/+/+/property"); // 添加iot車輛裝備數據上報事件监听
        list.add("$share/AMOS-EQUIPMANAGE/+/+/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();
            //异步处理
            EquipmentIotMqttReceiveConfig controllerProxy = SpringUtils.getBean(EquipmentIotMqttReceiveConfig.class);
            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);

                    controllerProxy.namePrefixhandlerMqttIncrementMessage(topic, msg);

                } else if (dataType.equals("event") && StringUtil.isNotEmpty(msg)) {

                   // mqttEventReceiveService.handlerMqttIncrementMessage(topic, msg);
                    controllerProxy.namePrefixhandlerMqttIncrementMessageEven(topic, msg);
                }
            }
        };
    }

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

    @Async("equipAsyncExecutor")
    public void namePrefixhandlerMqttIncrementMessageEven(String topic, String msg) {
        mqttEventReceiveService.handlerMqttIncrementMessage(topic, msg);
    }

    @Async("equipAsyncExecutor")
    public void namePrefixhandlerMqttIncrementMessage(String topic, String msg) {

        if(cluster.equals("cluster")){
            //不同设备加锁，防止消息顺序错乱，此处加锁高并发下小概率会出现顺序错乱，
            //为了减少加锁前耗时，引起后续强锁失败，直接用topic(按每个设备锁)减少顺序错乱概率。
            RLock lock = redisson.getLock(topic);
            try {
                //拿锁失败10停止尝试，20秒后直接释放锁 无论是返回 true 还是 false，都会继续执行之后的代码。
            boolean flag= lock.tryLock(10, 20, TimeUnit.SECONDS);
            
                mqttReceiveService.handlerMqttIncrementMessage(topic, msg);

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock(); //释放锁
            }


        }else {
            //捕获处理异常
            try {
                mqttReceiveService.handlerMqttIncrementMessage(topic, msg);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


}
