package com.elab.redis.spring;

import com.elab.core.utils.StringUtils;
import com.elab.marketing.auth.service.response.organize.OrganizeInfoModel;
import com.elab.redis.CacheTemplate;
import com.elab.redis.RedisSpringBoot;
import com.elab.redis.serializers.CompatibilityJsonRedisSerializer;
import com.google.common.base.Splitter;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;

import java.io.IOException;
import java.util.*;

/**
 * springData
 *
 * @author ： liukx
 * @time ： 2020/7/15 - 11:12
 */
public class SpringDataTest extends RedisSpringBoot {

    @Autowired
    private CacheTemplate cacheTemplate;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Test
    public void serializerTest() {
        RedisTemplate<String, Object> redisTemplate = cacheTemplate.getRedisTemplate();
        //        Set<Object> lyx =
        //                setOperations.members("lyx");
        //        List<String> collect = lyx.stream().map(String::valueOf).collect(Collectors.toList());
        //        redisTemplate.delete(collect);
        String typeKey = "user:organize:userInfo:10018:13602651614";
        String classKey = "user:organize:userInfo:10018:18154115526";

        // 默认当前版本是 [GenericFastJsonRedisSerializer]
        //        Object classObject = redisTemplate.opsForValue().get(classKey);
        //        Object typeObject = redisTemplate.opsForValue().get(typeKey);
        //        String tmpKey = "user:organize:userInfo:10018:testKey2";
        //        redisTemplate.opsForValue().set(tmpKey, "1");
        //        redisTemplate.opsForValue().increment(tmpKey, 10);
        //        // 之前版本是 [GenericJackson2JsonRedisSerializer]
        //        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        //        Object classObject1 = redisTemplate.opsForValue().get(classKey);
        //        Object typeObject1 = redisTemplate.opsForValue().get(typeKey);
        //        tmpKey = "user:organize:userInfo:10018:testKey";
        //        redisTemplate.opsForValue().set(tmpKey, "1");
        //        redisTemplate.opsForValue().increment(tmpKey, 10);
        //        // 兼容版本
        //        redisTemplate.setValueSerializer(new CompatibilityJsonRedisSerializer());
        //        Object classObject2 = redisTemplate.opsForValue().get(classKey);
        //        Object typeObject2 = redisTemplate.opsForValue().get(typeKey);
        //
        //        if (classObject instanceof OrganizeInfoModel) {
        //            System.out.println(true);
        //        }

        //        redisTemplate.setHashKeySerializer(new GenericJackson2JsonRedisSerializer());
        //        redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.opsForHash().put("aaaa", 10, 1000L);
        Object aaaa = redisTemplate.opsForHash().get("aaaa", 10);
        System.out.println("=================" + aaaa);
    }

    @Test
    public void set() throws IOException {

        RedisTemplate<String, Object> redisTemplate = cacheTemplate.getRedisTemplate();
        //        Set<Object> lyx =
        //                setOperations.members("lyx");
        //        List<String> collect = lyx.stream().map(String::valueOf).collect(Collectors.toList());
        //        redisTemplate.delete(collect);

        //        cacheTemplate.set().add("aaa","a","b","c");
        //
        //
        //        RLock xxx = cacheTemplate.getRedissonClient().getLock("xxx");
        //        cacheTemplate.string().set("abc", "cccc");
        //        Object abc = cacheTemplate.string().get("abc");
        //        System.out.println("--->" + abc);
        //
        //        redisTemplate.opsForValue().set("kkx", "abc");
        //
        //        Map<String, String> map = new HashMap<>();
        //        map.put("lkx", "xxx");
        //        map.put("xxx", "sss");
        //        redisTemplate.opsForValue().set("obj", map);
        //        Map<String, String> xiong = (Map<String, String>) redisTemplate.opsForValue().get("obj");
        //        System.out.println(xiong);

        //        // 存储值
        //        cacheTemplate.map().put("aaa", "a-key", "v-value");
        //        cacheTemplate.map().put("aaa", "b-key", "b-value");
        //        cacheTemplate.map().put("aaa", "c-key", "c-value");
        //        cacheTemplate.map().put("aaa", "d-key", "d-value");
        //
        //        // 获取key的hashkey的值
        //        String val = (String) cacheTemplate.map().get("aaa", "d-key");
        //        String val = (String) cacheTemplate.map().get("aaa", "fff");

        //        String key = "data_center:material_labels_key:1";
        //        Object value = cacheTemplate.string().get(key);
        //
        //        List<JSONObject> jsonObjects = JSON.parseArray(value.toString(), JSONObject.class);
        //        jsonObjects.forEach((str) -> {
        //            String materialsId = str.getString("materialsId");
        //            cacheTemplate.map().put("data_center:material_labels_key:1111", materialsId, str.toJSONString());
        //        });
        //
        //        System.out.println(jsonObjects.toArray());
        //
        //        // 获取hash的key的所有值
        ////        Map<String, Object> dataMap = cacheTemplate.map().entries("data_center:material_labels_key:1");
        ////        System.out.println(dataMap.toString());
        ////        System.out.println(val);
        //
        //        System.out.println("OK");
        //        System.in.read();
    }

    @Test
    public void delKey(){
        List<String> delKeyList = new ArrayList<>();
        delKeyList.add("user:userId:mobile:3234916");
        //delKeyList.add("user:userId:mobile:3258428");
        Long delete = redisTemplate.delete(delKeyList);
        System.out.println(delete);
    }



    @Test
    public void del() {

        String prefKey = "user:userId:mobile:*";
        Set<String> keys = redisTemplate.keys(prefKey);
        // redisTemplate.delete(keys);
        Set<String> mobiles = new HashSet<>();
        List<Object> objects = redisTemplate.opsForValue().multiGet(keys);
        objects.forEach((V)->{
            mobiles.add(V.toString());
        });
        System.out.println(objects);
        //        List<String> delKey = new ArrayList<>();
        //
        //        redisTemplate.delete(Arrays.asList(""));
    }

    @Test
    public void delToken() {
        String mobiles =
            "15123317643,18423586949,15730080319,13330396258,15683552125,13996022227,13896140216,18580429360,\n"
                + "    18696697989,13436008391,15025446540,13436020926,15025634510,17754989043,17723039715,15123224136,\n"
                + "    13789996159,15023632596,17708327136,15213163035,15002377412,18702366654,18623383017,13637911168,\n"
                + "    18716287371,15683169135,18696760033,18608003962,15555044400";

        String prefixKey = "gateway:LOGIN:UID:token:";
        String prefixTokenKey = "gateway:LOGIN:TOKEN:token:";
        List<String> mobileList = Splitter.on(",").trimResults().splitToList(mobiles);
        Set<String> delKey = new HashSet<>();
        for (int i = 0; i < mobileList.size(); i++) {
            System.out.println(mobileList.get(i));
            String mobile = mobileList.get(i);
            String key = prefixKey + mobile;
            delKey.add(key);
        }
        List<Object> tokenKeys = redisTemplate.opsForValue().multiGet(delKey);

        List<String> tokenName = new ArrayList<>();

        tokenKeys.forEach((key) -> {
            if (key != null) {
                tokenName.add(prefixTokenKey + key);
            }
        });

        Long delete = redisTemplate.delete(tokenName);
        System.out.println("删除key个数：" + tokenName.size() + " 删除总数：" + delete);
    }

    private Cursor<String> scan(String match, int count) {
        ScanOptions scanOptions = ScanOptions.scanOptions().match(match).count(count).build();
        RedisSerializer<?> keySerializer = redisTemplate.getKeySerializer();
        return (Cursor)redisTemplate.executeWithStickyConnection(
            (RedisCallback)redisConnection -> new ConvertingCursor<>(redisConnection.scan(scanOptions),
                keySerializer::deserialize));
    }
}
