package com.czg.config;

import com.czg.account.service.ShopTableService;
import com.czg.market.entity.MkShopCouponRecord;
import com.czg.market.service.AcPushEventService;
import com.czg.market.service.MkShopCouponRecordService;
import com.czg.market.service.PpPackageOrderService;
import com.czg.market.service.SmsPushEventService;
import com.czg.order.service.GbOrderService;
import com.czg.order.service.OrderInfoCustomService;
import com.mybatisflex.core.query.QueryWrapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;

/**
 * redis key过期监听
 *
 * @author ww
 */
@Slf4j
@Configuration
public class RedisKeyExpirationListener implements MessageListener {

    @Value("${spring.data.redis.database}")
    private String database;
    @Resource
    private OrderInfoCustomService orderInfoCustomService;
    @DubboReference
    private ShopTableService tableService;
    @Resource
    private MkShopCouponRecordService mkShopCouponRecordService;
    @Resource
    private SmsPushEventService smsPushEventService;
    @Resource
    private AcPushEventService acPushEventService;
    @Resource
    private GbOrderService gbOrderService;
    @DubboReference
    private PpPackageOrderService ppPackageOrderService;


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

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String expiredKey = new String(message.getBody());

        // 检查过期的键是否以特定前缀开头
        if (expiredKey.startsWith(RedisCst.classKeyExpired.EXPIRED_ORDER)) {
            log.info("监听到订单过期,订单Id: {}", expiredKey);
            String orderId = expiredKey.substring(RedisCst.classKeyExpired.EXPIRED_ORDER.length());
            orderInfoCustomService.expired(Long.parseLong(orderId));
        } else if (expiredKey.startsWith(RedisCst.classKeyExpired.EXPIRED_TABLE)) {
            log.info("监听到台桌清台过期,台桌Id: {}", expiredKey);
            String tableId = expiredKey.substring(RedisCst.classKeyExpired.EXPIRED_TABLE.length());
            tableService.expiredTable(Long.parseLong(tableId));
        } else if (expiredKey.startsWith(RedisCst.classKeyExpired.EXPIRED_COUPON)) {
            log.info("监听到优惠券过期,优惠券Id: {}", expiredKey);
            String couponId = expiredKey.substring(RedisCst.classKeyExpired.EXPIRED_COUPON.length());
            mkShopCouponRecordService.update(MkShopCouponRecord.builder().status(2).build(), new QueryWrapper()
                    .eq(MkShopCouponRecord::getStatus, 0)
                    .eq(MkShopCouponRecord::getId, Long.parseLong(couponId))
            );
        } else if (expiredKey.startsWith(RedisCst.classKeyExpired.EXPIRED_GB_ORDER)) {
            log.info("监听到拼团任务过期,gb_order任务Id: {}", expiredKey);
            String eventId = expiredKey.substring(RedisCst.classKeyExpired.EXPIRED_GB_ORDER.length());
            gbOrderService.expireRefund(Long.parseLong(eventId), null);
        } else if (expiredKey.startsWith(RedisCst.classKeyExpired.EXPIRED_PP_ORDER)) {
            log.info("监听到套餐推广任务过期,pp_order任务Id: {}", expiredKey);
            String eventId = expiredKey.substring(RedisCst.classKeyExpired.EXPIRED_PP_ORDER.length());
            ppPackageOrderService.expiredOrder(Long.parseLong(eventId));
        } else if (expiredKey.startsWith(RedisCst.classKeyExpired.EXPIRED_SMS)) {
            log.info("监听到短信定时发放优惠券,sms_push_event任务Id: {}", expiredKey);
            String eventId = expiredKey.substring(RedisCst.classKeyExpired.EXPIRED_SMS.length());
            smsPushEventService.sendPushEventCoupon(eventId);
        } else if (expiredKey.startsWith(RedisCst.classKeyExpired.EXPIRED_WECHAT)) {
            log.info("监听到公众号推送优惠券,ac_push_event任务Id: {}", expiredKey);
            String eventId = expiredKey.substring(RedisCst.classKeyExpired.EXPIRED_WECHAT.length());
            acPushEventService.sendPushEventCoupon(eventId);
        }
    }
}
