package org.nl.system.service.redis.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.nl.system.service.redis.RedisService;
import org.nl.config.redis.RedisConvert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.DataType;
import org.springframework.data.redis.connection.RedisServerCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Author: lyd
 * @Description: Redis监控的实现类
 * @Date: 2022-08-04
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class RedisServiceImpl implements RedisService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public JSONObject getRedisMonitorInfo() {
        // 获得 Redis 统计信息
        Properties info = stringRedisTemplate.execute((RedisCallback<Properties>) RedisServerCommands::info);
        Long dbSize = stringRedisTemplate.execute(RedisServerCommands::dbSize);
        Properties commandStats = stringRedisTemplate.execute((
                RedisCallback<Properties>) connection -> connection.info("commandstats"));
        assert commandStats != null; // 断言，避免警告
        // 拼接结果返回
        // 转成实体
        JSONObject json = new JSONObject();
        json.put("info", RedisConvert.INSTANCE.build(info, dbSize, commandStats));
        return json;
    }

    @Override
    public JSONObject getKeyDefineList() {
//        List<RedisKeyDefine> keyDefines = RedisKeyRegistry.list();
        JSONObject json = new JSONObject();
//        json.put("info", RedisConvert.INSTANCE.convertList(keyDefines));
        return json;
    }

    @Override
    public JSONArray getKeyValueList() {
        JSONArray result = new JSONArray();
        Set<String> keys = stringRedisTemplate.keys("*");
        // 迭代
        Iterator<String> it = keys.iterator();
        while ( it.hasNext() ) {
            String key = it.next();
            JSONObject redis = new JSONObject();
            DataType dataType = stringRedisTemplate.type(key); // 数据类型
            String s = stringRedisTemplate.opsForValue().get(key); // 获取值
            Long expire = stringRedisTemplate.getExpire(key); // 获取剩余时间
            redis.put("dataType", dataType);
            redis.put("key", key);
            redis.put("value", s);
            redis.put("expire", expire);
            result.add(redis);
        }
        return result;
    }

    @Override
    public void deleteByKey(String[] ids) {
        stringRedisTemplate.delete(Arrays.asList(ids));
    }
}
