package com.diaoyun.zion.master.listener;

import com.diaoyun.zion.chinafrica.constant.KeyConstant;
import com.diaoyun.zion.chinafrica.service.TbCfOrderService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
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;

@Component
public class RedisKeyExpirationListener  extends KeyExpirationEventMessageListener {

    @Autowired
    private TbCfOrderService tbCfOrderService;

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

    /**
     * 针对redis数据失效事件，进行数据处理
     * 需要配置redis文件 notify-keyspace-events Ex
     * @param message
     * @param pattern
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 用户做自己的业务处理即可,注意message.toString()可以获取失效的key
        String expiredKey = message.toString();
        if(expiredKey.startsWith(KeyConstant.ORDER_EXP)){
            String substring = expiredKey.substring(KeyConstant.ORDER_EXP.length()); //去掉orderNo
            //: 隔开 第一个为orderId，第二个为userId，第三个为couponId 用优惠券才有
            String info[]= substring.split(":",-1);
            //取消订单，那么要返回优惠券，以及更改订单状态为关闭交易
            tbCfOrderService.cancelOrder(info[0],info[1],info[2]);
        }
    }
}
