package com.heketai.website.common.utils;

import com.alibaba.fastjson.JSON;
import com.heketai.website.common.vo.LoginUserInfo;
import com.heketai.website.constant.PublicConstant;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.codec.binary.Base64;

import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.Calendar;

/**
 * @创建人：yanBin
 * @创建时间：2022/4/14
 * @简介：JWT Token 解析工具
 */

@Slf4j
public class TokenParseUtil {

    public static LoginUserInfo parseUserInfoFromToken(String token) {
        try {
            if (StringUtils.isBlank(token)) {
                return null;
            }
            Jws<Claims> claimsJws = parseToken(token, getPublicKey());
            Claims body = claimsJws.getBody();
            //如果token已经过期了，返回null。
            if (body.getExpiration().before(Calendar.getInstance().getTime())) {
                return null;
            }
            LoginUserInfo loginUserInfo = JSON.parseObject(body.get(PublicConstant.JWT_USER_INFO_KEY).toString(), LoginUserInfo.class);
            return loginUserInfo;
        } catch (Exception e) {
            log.error("解析token：[{}]", e.getLocalizedMessage());
            return null;
        }

    }


    /**
     * 通过公钥去解析jwt token
     */
    public static Jws<Claims> parseToken(String token, PublicKey publicKey) {
        return Jwts.parser().setSigningKey(publicKey).parseClaimsJws(token);
    }

    /**
     * 根据本地存储的公钥取到 PublicKey 对象
     */
    public static PublicKey getPublicKey() throws Exception {
      /*  X509EncodedKeySpec keySpec = new X509EncodedKeySpec(
                new BASE64Decoder().decodeBuffer(PublicConstant.PUBLIC_KEY)
        );*/
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.decodeBase64(PublicConstant.PUBLIC_KEY));
        PublicKey rsa = KeyFactory.getInstance("RSA").generatePublic(keySpec);
        return rsa;
    }

    /**
     * 测试解析token
     */
    public static void main(String[] args) {
        String token = "eyJhbGciOiJSUzI1NiJ9.eyJzeXMtdXNlciI6IntcImlkXCI6MjgsXCJ1c2VybmFtZVwiOlwiaGVrZXRhaVwifSIsImp0aSI6ImY5M2QxNjNiLTgzNWMtNGZjYi1hYjJmLWJiNTllOTU5MDM5NiIsImV4cCI6MTY1MjgwMzIwMH0.FUos97dTO3sjymtQIpsNlnH6AnbGgvwJFcCAkDv3YNTVZ5ISNyu2XF7E2a64c0LsPQmqET9ugKcRCylwTz69JrPG1p7oPu29UJlLDrHwi__vRKdpQs5QhnikeJcdhx9SPHKwTtOY6Ee_gB2ZlZtA9IVPSnmHwrllfl4cd8TmtgfgH0fTHBMg0BXjfYypAJEpnRTuU5jInp7Bx-iQbRj41UEABIMDxoqwCnTXNDyaDkhB9gVNJPPyeRIlNvwKlid4_gSSwRHaFNDY0kEkYVZwB6ykDCRsqx5-ETed2klKh5zOIyw5KwFRpi5NBc1Oepi9FtJwZ_4zczGQG06b0hFACw";
        LoginUserInfo loginUserInfo = parseUserInfoFromToken(token);
        System.out.println(loginUserInfo);
    }

}
