package test05.utils;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.Map;

public class JwtUtils {
    static private final SecretKey KEY=Keys.hmacShaKeyFor("12@529#5e2#54t8r8$0454g9&hj|03nb13df1h1351xY".getBytes());
    //                                      ms s m h d
    static private final int[] expireTime = {0,0,0,3,0};

    static public String getJwt(Map<String, Object> map){
        return Jwts.builder()
                // 设置头部信息header
                .header()
                .add("typ", "JWT")
                .add("alg", "HS256")
                .and()
                // 设置自定义负载信息payload
                .claim("data", map)
                // 过期日期
                .expiration(getExpireTime())
                // 签名8
                .signWith(KEY)
                .compact();
    }
    static public void setExpireTime(int ms, int seconds, int minutes, int hour,int day){
        expireTime[0] = ms;
        expireTime[1] = seconds;
        expireTime[2] = minutes;
        expireTime[3] = hour;
        expireTime[4] = day;
    }
    static public Date getExpireTime(){
        return new Date(System.currentTimeMillis()
                + (expireTime[0])
                + (expireTime[1] * 1000L)
                + (expireTime[2] * 60000L)
                + (expireTime[3] * 3600000L)
                + (expireTime[4] * 86400000L)
        );
    }
    static public Map<String, Object> parseJwt(String jwt){
        return Jwts.parser()
                .verifyWith(KEY)
                .build()
                .parseSignedClaims(jwt).getPayload();
    }
}
