package com.hfkj.msg;

import com.hfkj.entity.BsGasOilPriceTask;
import com.hfkj.service.gas.BsGasOilPriceTaskService;
import org.apache.commons.lang3.StringUtils;
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;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;


@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

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

    @Resource
    private BsGasOilPriceTaskService gasOilPriceTaskService;

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

    public void onMessage(Message message, byte[] pattern) {
        try {
            if (message != null && StringUtils.isNotBlank(message.toString())) {
                // 加油站价格任务
                if (message.toString().contains(MsgTopic.oilPriceTask.getName())) {
                    // 截取任务id
                    Long taskId = Long.parseLong(StringUtils.substringAfterLast(message.toString(), MsgTopic.oilPriceTask.getName() + "-"));
                    if (taskId != null) {
                        // 查询任务
                        BsGasOilPriceTask gasOilPriceTask = gasOilPriceTaskService.getDetailById(taskId);
                        if (gasOilPriceTask != null) {
                            // 任务处理
                            gasOilPriceTaskService.businessHandle(gasOilPriceTask);
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error("redis过期事件异常：", e);
        }
    }
}
