package top.continew.admin.common.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.function.Function;

public class JwtUtil {
    private static final String SECRET_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhF1cy7j57pBdPlO3Sm7N8expgroxq0br6fAinuXxiIAn3NklpgwLpw/V+leeKMzyYIJ2pFR6KmVybF9Z38Qs1H3C88r7ImYopBmO+IEqoEdm3UzNsNcdOSW4S9Lk1N5qtiniHDC/ZhlANzxeW7QbtS76RfZ4SSaeVUbfLJk/7RfFZ5HfLi1pBrT59SpfaJpKsbaMUBmdrEgGuGrT/K6jLsxqUcnOsbqAirtuP/NRpcO9OTsgpAh4tlFZKGg1hImIuAKwFZO0euZbjrQ9z7JwZoVSk0W99n0ULlofSIF939sSfhEX3UmgrEGsAwGVtZKROtJMHc/ywgBvaKpXKZsqjwIDAQAB"; // 应该使用强密钥，例如UUID.randomUUID().toString()
    private static final long EXPIRATION_TIME = 3600000; // 1 hour in milliseconds

    public static String generateToken(String username) {
        return Jwts.builder()
            .setSubject(username)
            .setIssuedAt(new Date())
            .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
            .signWith(SignatureAlgorithm.HS512, SECRET_KEY)
            .compact();
    }

    public static String getUsernameFromToken(String token) {
        return getClaimFromToken(token, Claims::getSubject);
    }

    public static Date getExpirationDateFromToken(String token) {
        return getClaimFromToken(token, Claims::getExpiration);
    }

    public static <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
        final Claims claims = getAllClaimsFromToken(token);
        return claimsResolver.apply(claims);
    }

    private static Claims getAllClaimsFromToken(String token) {
        return Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody();
    }

    public static void main(String[] args) {
        // 生成JWT Token
        String token = JwtUtil.generateToken("aa123");
        System.out.println("Generated Token: " + token);

        // 从Token中获取用户名和其他信息（例如过期时间）
        String username = JwtUtil.getUsernameFromToken(token);
        Date expirationDate = JwtUtil.getExpirationDateFromToken(token);
        System.out.println("Username: " + username);
        System.out.println("Expiration Date: " + expirationDate);
    }
}
