package cn.com.poc.thirdparty.resource.demand.ai.function.memory_variable_writer;

import cn.com.poc.common.service.RedisService;
import cn.com.poc.common.utils.BlContext;
import cn.com.poc.common.utils.SpringUtils;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class MemoryVariableWriter {

    public static Map<Object, Object> get(String key) {
        String redisKey = MemoryVariableWriterConstants.REDIS_PREFIX + key;
        RedisService redisService = SpringUtils.getBean(RedisService.class);
        if (!redisService.hasKey(redisKey)) {
            return null;
        }
        Map<Object, Object> result = redisService.hmget(redisKey);
        return result;
    }

    public static void clean(String key) {
        String redisKey = MemoryVariableWriterConstants.REDIS_PREFIX + key;
        RedisService redisService = SpringUtils.getBean(RedisService.class);
        redisService.del(redisKey);
    }

    public static void cleanByPre(String key) {
        String redisKey = MemoryVariableWriterConstants.REDIS_PREFIX + key;
        RedisService redisService = SpringUtils.getBean(RedisService.class);
        redisService.delByPre(redisKey);
    }

    public static void delItem(String identifier, String... items) {
        String redisKey = MemoryVariableWriterConstants.REDIS_PREFIX + identifier;
        RedisService redisService = SpringUtils.getBean(RedisService.class);
        redisService.hdel(redisKey, items);
    }

    public static void addItem(String identifier, Map<String, Object> map) {
        String redisKey = MemoryVariableWriterConstants.REDIS_PREFIX + identifier;
        RedisService redisService = SpringUtils.getBean(RedisService.class);
        // 创建 JSONObject 对象
        Map<String, Object> result = new HashMap<>();
        if (redisService.hasKey(redisKey)) {
            Map<Object, Object> hmget = redisService.hmget(redisKey);
            hmget.putAll(map);
            for (Map.Entry<Object, Object> entry : hmget.entrySet()) {
                if (entry.getKey() instanceof String) {
                    String tempKey = (String) entry.getKey();
                    result.put(tempKey, entry.getValue());
                }
            }
        }
        result.putAll(map);
        // 30天有效期
        long expireTime = 30 * 60 * 24L;
        redisService.hmset(redisKey, result, expireTime);
    }

    private static void setMap(JSONObject jsonObject, Map<String, Object> result) {
        String key = jsonObject.getStr("key");
        String value = jsonObject.getStr("value");
        result.put(key, value);
    }
}
