
package com.tmerclub.cloud.coupon.listener;

import com.tmerclub.cloud.common.cache.config.MultiRedisConfig;
import com.tmerclub.cloud.common.cache.enums.MultiStockEnum;
import com.tmerclub.cloud.common.constant.Constant;
import com.tmerclub.cloud.common.rocketmq.config.RocketMqConstant;
import com.tmerclub.cloud.coupon.bo.AddCouponStockMsgBO;
import com.tmerclub.cloud.coupon.bo.mongo.MongoCouponUserBO;
import com.tmerclub.cloud.coupon.service.CouponUserService;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author TRACK
 */
@Component
@RocketMQMessageListener(topic = RocketMqConstant.ADD_COUPON_STOCK_TOPIC, consumerGroup = RocketMqConstant.ADD_COUPON_STOCK_TOPIC)
public class AddCouponStockConsumer implements RocketMQListener<AddCouponStockMsgBO> {
    private static final Logger logger = LoggerFactory.getLogger(AddCouponStockConsumer.class);

    @Autowired
    private CouponUserService couponUserService;
    @Autowired
    private MultiRedisConfig multiRedisConfig;

    /**
     * 优惠券库存回退
     */
    @Override
    public void onMessage(AddCouponStockMsgBO addCouponStockMsgBO) {
        Map<Long, Integer> couponReturnStockMap = addCouponStockMsgBO.getCouponReturnStockMap();
        Map<Long, List<MongoCouponUserBO>> couponUserIdMap = addCouponStockMsgBO.getCouponUserIdMap();
        List<String> keys = new ArrayList<>(Constant.INITIAL_CAPACITY);
        for (Long couponId : couponReturnStockMap.keySet()) {
            Integer count = Math.abs(couponReturnStockMap.get(couponId));
            List<MongoCouponUserBO> userIdList = couponUserIdMap.get(couponId);
            logger.info("用户删除优惠券{}，还原库存{}，用户量{}", couponId, count, userIdList.size());
            couponUserService.addCouponStock(couponId, count, userIdList);
            for (MongoCouponUserBO mongoCouponUserBO : userIdList) {
                keys.add(MultiStockEnum.COUPON.value() + "addLock:" + couponId + Constant.UNDERLINE + mongoCouponUserBO.getUserId() +
                        Constant.UNDERLINE + mongoCouponUserBO.getCouponUserId());
            }
        }
        // 在里面加锁定记录，然后全部完成之后再一次删除掉，保证幂等，这里删除异常也没事，有mq重试
        int redisCount = multiRedisConfig.getRedisCount();
        for (int i = 0; i < redisCount; i++) {
            StringRedisTemplate stringRedisTemplate = multiRedisConfig.getRedisByIndex(i);
            stringRedisTemplate.delete(keys);
        }
    }
}
