package com.enterprise.manage.common.tools.secure;

import com.enterprise.manage.core.secure.domain.SecurityConstant;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.tomcat.util.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.HashMap;
import java.util.Map;

/**
 * jwt工具类
 *
 * @author PeiZhi Guo
 * 2022-4-11 14:25
 */
public class JwtUtil {

    private static final Logger log = LoggerFactory.getLogger(JwtUtil.class);

    public static String generateToken(String token) {
        Map<String, Object> map = new HashMap<>();
        map.put(SecurityConstant.LOGIN_USER_KEY, token);
        return generateToken(map);
    }

    public static String generateToken(Map<String, Object> map) {
        return Jwts.builder()
                .setClaims(map)
                .signWith(SignatureAlgorithm.HS256, generalKey()).compact();
    }

    public static String parseToken(String token) {
        try {
            Claims claims = Jwts
                    .parser()
                    .setSigningKey(generalKey())
                    .parseClaimsJws(token)
                    .getBody();
            if (claims != null) {
                Object answer = claims.get(SecurityConstant.LOGIN_USER_KEY);
                if (answer != null) {
                    return answer.toString();
                }
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("============ 获取token异常 ============", e);
        }
        return null;
    }

    private static SecretKey generalKey() {
        byte[] encodedKey = Base64.decodeBase64(SecurityConstant.SECRET);
        return new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
    }
}
