package com.njcn.energy.listener;

import com.alibaba.nacos.shaded.com.google.gson.Gson;
import com.github.tocrhz.mqtt.publisher.MqttPublisher;
import com.njcn.energy.pojo.dto.DeviceOperateDTO;
import com.njcn.energy.service.IModelService;
import com.njcn.energy.service.INetDevService;
import com.njcn.redis.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author hongawen
 * @version 1.0.0
 * @date 2022年04月02日 14:31
 */
@Slf4j
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private IModelService modelService;

    @Resource
    private MqttPublisher publisher;

    @Resource
    private INetDevService netDevService;

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }


    /**
     * 针对redis数据失效事件，进行数据处理
     * 注意message.toString()可以获取失效的key
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public void onMessage(Message message, byte[] pattern) {
        if (StringUtils.isBlank(message.toString())) {
            return;
        }
        //判断失效的key是否为MQTT消费端存入的
        String expiredKey = message.toString();
        if(expiredKey.startsWith("MQTT:")){
            Gson gson = new Gson();
            String ndid = expiredKey.split(":")[1];
            //网关下线
            netDevService.offlineNetDev(ndid);
            String result = (String) redisUtil.getObjectByKey(ndid);
            //装置下线
            List<String> list = modelService.monitorHeartbeat(ndid,result);
            //生成通知报文
            DeviceOperateDTO deviceOperateDTO = new DeviceOperateDTO();
            deviceOperateDTO.setNdid(ndid);
            deviceOperateDTO.setDid(list);
            deviceOperateDTO.setTime(Long.toString(System.currentTimeMillis()/1000));
            deviceOperateDTO.setMessage("装置下线");
            deviceOperateDTO.setType("005");
            publisher.send("/device/platform",gson.toJson(deviceOperateDTO),1,false);
        }
    }
}
