package com.fs.app.redis;

import com.fs.common.utils.spring.SpringUtils;

import com.fs.store.constants.StoreConstants;
import com.fs.store.service.IFsStoreOrderService;
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 java.nio.charset.StandardCharsets;

@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

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

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

    /**
     * 针对redis数据失效事件，进行数据处理
     * @param message
     * @param pattern
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        String channel = new String(message.getChannel(), StandardCharsets.UTF_8);
        //过期的key
        String key = new String(message.getBody(),StandardCharsets.UTF_8);
        log.info("rediskey过期：pattern={},channel={},key={}",new String(pattern),channel,key);
        //订单自动取消
        if(key.contains(StoreConstants.REDIS_ORDER_OUTTIME_UNPAY)) {
            key = key.replace(StoreConstants.REDIS_ORDER_OUTTIME_UNPAY, "");
            log.info("body:{}",key);
            String orderId = key;
            IFsStoreOrderService orderService= SpringUtils.getBean(IFsStoreOrderService.class);
            orderService.cancelOrder(Long.parseLong(orderId));
            log.info("订单id:{},未在规定时间支付取消成功",orderId);

        }
    }
}
