package cn.freemud.manager;

import cn.freemud.constant.RedisKeyConstant;
import cn.freemud.entities.dto.product.ProductInfo;
import cn.freemud.enums.ResponseResult;
import cn.freemud.redis.RedisCache;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author freemud
 * @title: BuyProductOnceManager
 * @projectName order-group
 * @description: 618活动一元秒杀抢18元券包活动专属manager
 * @date 2021/6/10上午9:53
 */
@Component
public class BuyProductOnceManager {
//    @Autowired
//    protected RedisTemplate redisTemplate;

    @Autowired
    private RedisCache redisCache;

    //用户限购：每人每单限购一次 / 禁用
    public ResponseResult checkBuyProductOnce(List<ProductInfo> products, String partnerId, String userId) {
        RedisTemplate redisTemplate = redisCache.getRedisTemplate();
        List<ProductInfo> productsCheck = products.stream().filter(product -> product.getIsLimitNumProduct() == 1).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(productsCheck)) {
            //每人每单限购一次
            if (productsCheck.size() > 1) {
                return ResponseResult.USER_BUY_PRODUCT_MORE_THAN_THE_NUMBER;
            }
            String key = this.getCheckBuyProductOnceKey(partnerId, userId,productsCheck.get(0).getPid());
            if (redisTemplate.hasKey(key)) {
                return ResponseResult.USER_BUY_PRODUCT_ALREADY;
            }
            redisTemplate.opsForValue().set(key, "Y");
            //活动时间10天，防止redis脏数据，设置过期时间
            redisTemplate.expire(key,10, TimeUnit.DAYS);
        }
        return ResponseResult.SUCCESS;
    }

    public String getCheckBuyProductOnceKey(String partnerId, String userId,String pid) {
        StringBuilder key = new StringBuilder(RedisKeyConstant.USER_BUY_PRODUCT_ONCE)
                .append(partnerId)
                .append(":")
                .append(userId)
                .append(":")
                .append(pid);
        return key.toString();
    }

    //清掉key
    public boolean removeCheckBuyProductOnceKey(String partnerId, String userId,String pid) {
        RedisTemplate redisTemplate = redisCache.getRedisTemplate();
        String key = this.getCheckBuyProductOnceKey(partnerId, userId,pid);
        redisTemplate.delete(key);
        return true;
    }


}
