package cn.ysk.cashier.config;

import cn.ysk.cashier.cons.rabbit.RabbitConstants;
import cn.ysk.cashier.service.order.TbOrderInfoService;
import cn.ysk.cashier.service.shop.TbShopInfoService;
import cn.ysk.cashier.system.service.UserService;
import cn.ysk.cashier.utils.CacheKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

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

@Slf4j
@Configuration
public class RedisKeyExpirationListener implements MessageListener {

    @Lazy
    @Autowired
    private TbShopInfoService shopInfoService;

    @Lazy
    @Autowired
    private UserService userServiceu;

    @Lazy
    @Autowired
    private TbOrderInfoService tbOrderInfoService;

    private final RabbitTemplate rabbitTemplate;

    public RedisKeyExpirationListener(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }

    //redis key失效监听
    @Bean
    public RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory connectionFactory) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        // 监听特定键的过期事件
        container.addMessageListener(this, new PatternTopic("__keyevent@0__:expired"));
        return container;
    }

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void onMessage(Message message, byte[] pattern) {
        String expiredKey = new String(message.getBody());

        // 检查过期的键是否以特定前缀开头
        if(expiredKey.startsWith(CacheKey.ACT_CODE)) {
            String account = expiredKey.substring("act_code:".length());
            log.info("商户到期 账户名为：{}",account);
            shopInfoService.update(account);
            userServiceu.upEnableByusername(account);

        }else if(expiredKey.startsWith(CacheKey.ORDER_EXPIRED)){
            log.info("监听到订单过期,{}",expiredKey);
            String orderId = expiredKey.substring(CacheKey.ORDER_EXPIRED.length());
            tbOrderInfoService.expired(orderId);
        }
    }
}
