package cn.codesensi.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.Set;

public class RedisUtil {

    /**
     * key
     */
    private static final String CLICK_KEY = "click_key_";

    /**
     * 最大保留次数
     */
    private static final Integer MAX_NUM = 5;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 获取最近使用菜单
     *
     * @return
     */
    public static List<String> queryRecent() {
        String userId = "xxxxx";
        String key = PRODUCT_CLICK_PRE_KEY + userId;
        Set<ZSetOperations.TypedTuple<String>> scoreWithScores = stringRedisTemplate.opsForZSet().reverseRangeWithScores(key, 0, MAX_NUM - 1);
        List<String> list = new LinkedList<>();
        Optional.ofNullable(scoreWithScores).ifPresent(scores -> {
            for (ZSetOperations.TypedTuple<String> score: scores) {
                Double time = score.getScore(); //点击时间戳
                String name = score.getValue(); //点击的菜单
                list.add(name);
            }
        });
        return list;
    }

	/**
	* 菜单点击记录
	*
	* @param name 菜单名称
	*/
    public static void saveClick(String name) {
        // 当前用户
        String userId = "xxxxx";
        String key = CLICK_KEY + userId;
        stringRedisTemplate.opsForZSet().add(key, name, System.currentTimeMillis());
        //检索是否有旧记录 1.无则插入记录值 2.有则删除 再次插入
        Double score = stringRedisTemplate.opsForZSet().score(key, name);
        if (null != score) {
            //删除旧的
            stringRedisTemplate.opsForZSet().remove(key, name);
        }
        //加入新的记录,设置当前时间戳为分数score
        stringRedisTemplate.opsForZSet().add(key, name, System.currentTimeMillis());
        //获取总记录数
        Long total = stringRedisTemplate.opsForZSet().zCard(key);
        Optional.ofNullable(total).ifPresent(t -> {
            if (t > MAX_NUM) {
                //获取阈值之后的记录 (0,1] 并移除
                stringRedisTemplate.opsForZSet().removeRange(key, 0, t - MAX_NUM - 1);
            }
        });
    }
}