package com.junmp.jyzb.cache;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.junmp.jyzb.api.constant.JYZBConstant;
import com.junmp.jyzb.entity.Temp.OnlineState;
import com.junmp.v2.cache.AbstractRedisCache;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Set;



@Component
public class OnlineRedisCache extends AbstractRedisCache<Object> {
    public OnlineRedisCache(RedisTemplate<String, Object> redisTemplate) {
        super(redisTemplate);
    }

    @Override
    public String getCommonKeyPrefix() {
        return JYZBConstant.JYZB_ONLINE_PREFIX;
    }

    public void addSessionValue(String type,String sessionId,String typeId, long temperature) {
        OnlineState data = new OnlineState();
        data.setType(type);
        data.setTypeId(typeId);
        String key = sessionId;
        String jsonData;
        // 将OnlineState对象转换为JSON字符串
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            jsonData = objectMapper.writeValueAsString(data);
        } catch (Exception e) {
            // 处理转换异常
            e.printStackTrace();
            return;
        }
        getRedisTemplate().opsForValue().set(key, jsonData);
        put(key, data);
    }
    public OnlineState getDataValue(String sessionId) {
        boolean exists = getRedisTemplate().hasKey(sessionId);
        if (!exists) {
            // 处理不存在的情况
            return null;
        }

        Set<Object> dataInRange = getRedisTemplate().opsForZSet().range(sessionId, 0, -1);

        // 如果集合非空，返回第一个元素，否则返回null
        if (!dataInRange.isEmpty()) {
            Object firstElement = dataInRange.iterator().next();

            // 检查类型是否为 OnlineState
            if (firstElement instanceof OnlineState) {
                return (OnlineState) firstElement; // 执行强制类型转换
            } else {
                // 处理类型不匹配的情况
                return null;
            }
        } else {
            return null;
        }
    }
}
