package com.guwan.service;
import com.guwan.config.JsonRedisTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class TokenService {

    @Autowired
    private JsonRedisTemplate redisTemplate;

  public String createToken(String userId, String ip) {
      if (userId == null) {
          throw new RuntimeException("userId 不能为空");
      }
      String token;
      if (redisTemplate.opsForValue().get("User-token:" + userId) != null) {
          redisTemplate.delete("User-info:" + redisTemplate.opsForValue().get("User-token:" + userId));
          redisTemplate.delete("User-token:" + userId);
      }
      token = UUID.randomUUID().toString();
      redisTemplate.opsForValue().set("User-token:" + userId, token, 30, TimeUnit.MINUTES);
      HashMap<String, Object> userInfo = new HashMap<>();
      userInfo.put("userId", userId);
      userInfo.put("ip", ip);
      userInfo.put("token", token);
      redisTemplate.opsForHash().putAll("User-info:" + token, userInfo);
      redisTemplate.expire("User-info:" + token, 30, TimeUnit.MINUTES);
      // 将所有用户信息存储在一个键中
      //redisTemplate.opsForValue().set("User-info-string:" + token, userInfo, 30, TimeUnit.MINUTES);
      return token;
  }

    public boolean checkToken(String token) {

        if (token != null) {
            String key = "User-info:" + token;
            Object value = redisTemplate.opsForHash().entries(key);
            @SuppressWarnings("unchecked")
            Map<String, String> map = (Map<String, String>) value;
            return map.get("userId") != null;
        }
        return false;
    }


    public void validateAndExtendToken(String token) {
            // 重置过期时间
            //redisTemplate.expire("User-info-string:" + token, 30, TimeUnit.MINUTES);
        String userId = (String) redisTemplate.opsForHash().get("User-info:" + token, "userId");

        redisTemplate.opsForValue().
                    set("User-token:" + userId, token,
                            30, TimeUnit.MINUTES);
            redisTemplate.expire("User-info:" + token, 30, TimeUnit.MINUTES);
    }


    public void getInfo(String token) {
        Map<Object, Object> map = redisTemplate.opsForHash().entries("User-info:" + token);
        if (!map.isEmpty()) {
            System.out.println(map);
        }
    }
}
