package com.fjhx.listener;

import com.alibaba.fastjson.JSONObject;
import com.fjhx.enums.ProductEnum;
import com.fjhx.params.IotData.MessageBody;
import com.fjhx.utils.amqp.AmqpClient;
import com.fjhx.utils.amqp.AmqpClientOptions;
import com.fjhx.utils.amqp.AmqpConstants;
import org.springblade.core.redis.cache.BladeRedis;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import java.util.List;

/**
 * iot数据推送监听器
 *
 * @author zlj
 */
@Component
public class IotDataListener {

    // 设备前缀
    private static final String DEVICE_PREFIX = "prefix:";

    @Resource
    private BladeRedis redisCache;

    @PostConstruct
    public void listener() throws Exception {
        AmqpClientOptions options = AmqpClientOptions.builder()
                .host(AmqpConstants.HOST)
                .port(AmqpConstants.PORT)
                .accessKey(AmqpConstants.ACCESS_KEY)
                .accessCode(AmqpConstants.ACCESS_CODE)
                .queuePrefetch(1000)
                .build();
        AmqpClient amqpClient = new AmqpClient(options);
        amqpClient.initialize();
        MessageConsumer consumer = amqpClient.newConsumer(AmqpConstants.DEFAULT_QUEUE);
        // 此处进行消息处理。如果处理比较耗时，最好进行开启新的线程处理，否则可能造成心跳超时链接断开。
        consumer.setMessageListener(this::handleData);
    }

    /**
     * 处理推送数据
     * <p>
     * remarks: 添加成功必须手动 message.acknowledge();
     * </p>
     *
     * @param message 推送消息
     */
    public void handleData(Message message) {
        try {
            MessageBody messageBody = JSONObject.parseObject(message.getBody(String.class), MessageBody.class);
            if (messageBody == null) {
                return;
            }
            MessageBody.NotifyData notifyData = messageBody.getNotifyData();
            if (notifyData == null) {
                return;
            }
            MessageBody.Header header = notifyData.getHeader();
            if (header == null) {
                return;
            }
            String productId = header.getProductId();
            if (productId == null || productId.isEmpty()) {
                return;
            }
            MessageBody.Body body = notifyData.getBody();
            if (body == null) {
                return;
            }
            List<MessageBody.Services> services = body.getServices();
            if (services == null || services.size() == 0) {
                return;
            }

            // 设备id
            String deviceId = header.getDeviceId();

            switch (ProductEnum.getEnumByProductId(productId)) {
                case JBJ:
                    defaultHandle(message, deviceId, services);
                    break;
                case YBJ:
                    defaultHandle(message, deviceId, services);
                    break;
                default:
                    return;
            }
            System.err.println(JSONObject.toJSONString(messageBody));

        } catch (JMSException e) {
            e.printStackTrace();
        }
    }


    private void defaultHandle(Message message, String deviceId, List<MessageBody.Services> services) {
        MessageBody.Services oldServices = redisCache.get(DEVICE_PREFIX + deviceId);
        MessageBody.Services newServices = services.get(0);

        if (oldServices == null || newServices.getEventTime().compareTo(oldServices.getEventTime()) > 0) {
            redisCache.set(DEVICE_PREFIX + deviceId, newServices);
        }

        try {
            message.acknowledge();
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }

}
