package com.blueland.common.core.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.blueland.common.core.constan.RedisConstan;
import com.blueland.common.core.domain.International;
import org.jetbrains.annotations.NotNull;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class RedisUtil {

    /**
     * 批量添加
     *
     * @param lang
     * @param list
     */
    public static void hashMultiSet(String lang, List<International> list) {
        Map<String, International> data = list.stream()
                .collect(Collectors.toMap(el -> getHashKey(el), Function.identity()));
        getRedisTemplate().opsForHash().putAll(getKey(lang), data);
    }

    @NotNull
    private static String getKey(String lang) {
        return UserUtils.getTenantId() + ":" + RedisConstan.I18N + lang;
    }


    public static RedisTemplate getRedisTemplate() {
        return SpringUtil.getBean("redisTemplate");
    }

    /**
     * 单个添加
     *
     * @param international
     */
    public static void hashSet(International international) {
        getRedisTemplate().opsForHash().put(getKey(international.getLang()), getHashKey(international), international);
    }

    /**
     * 单个删除
     *
     * @param international
     */
    public static void hashRemvoe(International international) {
        getRedisTemplate().opsForHash().delete(getKey(international.getLang()), getHashKey(international));
    }

    public static String getHashKey(International international) {
        return StrUtil.format("{}:{}", international.getCode(), international.getType());
    }

}
