package com.mmc.iuav.auth;

import com.mmc.iuav.general.CodeUtil;
import com.mmc.iuav.response.ResultBody;
import com.mmc.iuav.response.ResultEnum;
import io.jsonwebtoken.*;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;
import java.util.Map;

/**
 * @author: zj
 * @Date: 2023/5/16 20:14
 */
public class JwtUtil {
    /**
     * 根据map中的信息生成token， tokenId为随机生成码，有效时间为24h
     *
     * @param claims 封装到token中的map
     * @return
     */
    public static String createJwt(Map<String, Object> claims) {
        return createJwt(claims, JwtConstant.EXPIRATION);
    }

    public static String createJwt(Map<String, Object> claims, long expiration) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(JwtConstant.BASE64KEY);
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
        long nowMillis = System.currentTimeMillis();
        long expMillis = nowMillis + expiration;
        Date now = new Date(nowMillis);
        Date exp = new Date(expMillis);
        JwtBuilder builder = Jwts.builder().setClaims(claims).setId(CodeUtil.randomCode(6)).setIssuedAt(now)
                .setSubject(JwtConstant.SUBJECT).setIssuer(JwtConstant.ISSUER).signWith(signatureAlgorithm, signingKey)
                .setExpiration(exp);
        return builder.compact();
    }

    /**
     * 解析前端传来的token，解析成功则返回Claims,解析失败返回null;解析成功后可通过claims获取信息
     *
     * @param jwt
     * @return
     */
    public static Claims parseJwt(String jwt) {
        Claims claims = Jwts.parser().setSigningKey(DatatypeConverter.parseBase64Binary(JwtConstant.BASE64KEY))
                .parseClaimsJws(jwt).getBody();
        return claims;
    }
}
