package com.hdkj.lt.utils.security;

import com.hdkj.lt.base.exception.ExceptionCast;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;

import java.security.SecureRandom;
import java.util.Base64;
import java.util.Date;
import java.util.Map;

/**
 * @Description:
 * @Author: wenhao
 * @Create: 2024/03/22 11:32
 * @Version: 1.0
 */
@Slf4j
public class JwtUtils {

    private JwtUtils() {
    }

    private static final String SIGNING_KEY = "OZ82vyNIhjs58Dt6G/MvmPHaEsB6dj2Qrl+krVUQGdc=";

    public static String createJwtToken(Map<String, Object> claims, long expirationMillis) {
        Date now = new Date();
        return Jwts.builder()
                .addClaims(claims)
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                .setIssuedAt(now)
                .setExpiration(new Date(now.getTime() + expirationMillis))
                .signWith(SignatureAlgorithm.HS256, SIGNING_KEY)
                .compact();
    }

    public static void parseJwtToken(String jwtToken) {
        try {
            Claims body = Jwts.parser()
                    .setSigningKey(SIGNING_KEY)
                    .parseClaimsJws(jwtToken)
                    .getBody();
            log.info("parse result: {}", body.toString());
        } catch (ExpiredJwtException e) {
            ExceptionCast.cast("token已失效！");
        } catch (Exception e) {
            ExceptionCast.cast(e.getMessage());
        }
    }

    public static void main(String[] args) {
        byte[] keyBytes = new byte[32];
        SecureRandom secureRandom = new SecureRandom();
        secureRandom.nextBytes(keyBytes);
        String signingKey = Base64.getEncoder().encodeToString(keyBytes);
        System.out.println(signingKey);
    }

}
