package com.shanghaichengdi.ghjgitem.util;

import com.shanghaichengdi.ghjgitem.constant.Constants;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;
import java.util.Map;

/**
 * token生成工具
 */
public class JwtUtils {

  /**
   * 有效期，单位是毫秒
   */
//  private static Long expire = 259200000L;
  private static Long expire = 3600000L;

  /**
   * 生成JWT令牌
   */
  public static String generateJwt(Map<String, Object> claims, String signKey) {
    return Jwts.builder()
        .addClaims(claims)
        .signWith(SignatureAlgorithm.HS256, signKey)
        .setExpiration(new Date(System.currentTimeMillis() + expire))
        .compact();
  }

  /**
   * 生成JWT令牌
   */
  public static String generateJwt(Map<String, Object> claims, String signKey, Long expireTime) {
    return Jwts.builder()
        .addClaims(claims)
        .signWith(SignatureAlgorithm.HS256, signKey)
        .setExpiration(new Date(System.currentTimeMillis() + expireTime))
        .compact();
  }

  /**
   * 生成JWT令牌
   */
  public static String generateJwtNonExpire(Map<String, Object> claims, String signKey) {
    return Jwts.builder()
        .addClaims(claims)
        .signWith(SignatureAlgorithm.HS256, signKey)
        .compact();
  }

  /**
   * 解析JWT令牌
   */
  public static Claims parseJWT(String jwt, String signKey) {
    return Jwts.parser()
        .setSigningKey(signKey)
        .parseClaimsJws(jwt)
        .getBody();
  }

  public static void main(String[] args) {
//    Map<String, Object> claims = new HashMap<>();
//    claims.put("test", "test");
//    String s = generateJwt(claims, "test");
//    System.out.println(s);
    Claims test = parseJWT(
        "eyJhbGciOiJIUzI1NiJ9.eyJvU0l3a3VXWiI6IjEiLCJleHAiOjE3MTY3ODY1OTR9.TbZWQExNd_WbwhDxfJ_XjMxLnFDsVEitqLhwQ6eme7U",
        Constants.JWT_KEY);
    System.out.println(test);
  }
}
