package com.zd.laboratory.event;

import cn.hutool.core.util.StrUtil;
import com.zd.common.core.constant.CacheDevice;
import com.zd.common.core.enums.HardwareOperate;
import com.zd.common.core.utils.SpringUtils;
import com.zd.laboratory.mqtt.entiy.EquipmentStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

/**
 * 该方式会导致监听所有的库 所以没有使用
 * @Author: zhoupan
 * @Date: 2021/10/20/10:17
 */
@Deprecated
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    private final static Logger logger = LoggerFactory.getLogger(RedisKeyExpirationListener.class);

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

    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 用户做自己的业务处理即可,注意message.toString()可以获取失效的key
        String expiredKey = message.toString();
        //继电器状态
        if(expiredKey.startsWith(CacheDevice.RELAY_KEY.getRedisKey())){
            //TODO 抛出事件
            //得到 继电器编号

            String s = StrUtil.subAfter(expiredKey, CacheDevice.RELAY_KEY.getRedisKey(), false);
            logger.info("继电器离线:编号{}",s);
            //创建离线对象
            EquipmentStatus equipmentStatus = new EquipmentStatus();
            equipmentStatus.setNum(s);
            equipmentStatus.setHardwareOperate(HardwareOperate.OFFLINE);
            //抛出继电器上下线切换事件
            RelayHardwareStatusEvent relayHardwareStatusEvent = new RelayHardwareStatusEvent(equipmentStatus);
            SpringUtils.getApplicationContext().publishEvent(relayHardwareStatusEvent);
        }
    }
}
