package com.ruoyi.redis;

import com.ruoyi.cache.RedisOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @author liwenlong
 * @date 2023/1/4 9:13
 */

@Component
public class RedisCollectUtil {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedisOperation redisOperation;


    /**
     * 判断是否收藏
     * @param key
     * @param userId 用户id
     * @return
     */
    public Boolean isCollcet(String key,Long userId) {

        //判断key中是否存在value值 存在返回true
        Boolean isMember = redisTemplate.opsForSet().isMember(key, userId.toString());

        return isMember;
    }


    /**
     * 收藏
     * @param key
     * @param userId 用户id
     * @param objectId 业务id
     * @return
     */
    public Boolean collcet(String key,Long userId,Long objectId) {

        //拼接key
        key = key + objectId;

        //是否收藏
        Boolean isCollcet = isCollcet(key, userId);

        if (isCollcet){
            // 保存用户到 Redis 的 set 集合
            redisTemplate.opsForSet().add(key, userId.toString());
        }else {
            // 把用户从 Redis 的 set 集合移除
            redisTemplate.opsForSet().remove(key, userId.toString());
        }

        return isCollcet;
    }

}
