package cn.reghao.tnb.content.app.vod.service.rcmd;

import cn.reghao.tnb.content.app.util.redis.ds.RedisSetStr;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 基于用户-物品关系的协同过滤
 *
 * @author reghao
 * @date 2023-02-21 21:56:50
 */
@Service
public class UserItemsRelationshipBased {
    private final RedisSetStr redisSetStr;

    public UserItemsRelationshipBased(RedisSetStr redisSetStr) {
        this.redisSetStr = redisSetStr;
    }

    /**
     * 获取用户关联的 itemId
     *
     * @param
     * @return
     * @date 2023-02-21 10:05 PM
     */
    public Set<String> getUserRelatedItems(long userId) {
        return redisSetStr.smembers(RedisKeys.getUserItemstKey(userId));
    }

    /**
     * 获取和用户具有相同兴趣的其他用户
     *
     * @param
     * @return
     * @date 2023-02-21 10:12 PM
     */
    public List<Long> getUserRelatedUsers(long userId) {
        Set<String> keys = getUserRelatedItems(userId).stream()
                .map(RedisKeys::getItemUserstKey)
                .collect(Collectors.toSet());

        return redisSetStr.sunion(keys).stream()
                .map(Long::parseLong)
                .collect(Collectors.toList());
    }

    /**
     * 获取用户感兴趣类别的所有物品
     *
     * @param
     * @return
     * @date 2023-02-21 10:14 PM
     */
    public long getUserInterestItems(long userId) {
        List<Long> userIds = getUserRelatedUsers(userId);
        Set<String> keys = userIds.stream().map(RedisKeys::getUserItemstKey).collect(Collectors.toSet());
        return redisSetStr.sunionstore(RedisKeys.getUserRecommendKey(userId), keys);
    }
}
