package com.muchinfo.mtp3common.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class JwtUtil {

    public static final String TOKEN_HEADER = "Authorization";
    public static final String TOKEN_PREFIX = "Bearer";
    public static final long TTL = 2 * 60 * 60 * 1000;
    public static final String SECRET_KEY = "muchinfo@86-755-82535618#";
    public static final String AUTHORITIES = "authorities";

    /**
     * 生成 token
     *
     * @param username
     * @param authorities
     * @return
     */
    public static String generateToken(String username, String authorities) {
        return Jwts.builder()
                .setSubject(username) // 主题
                .claim(AUTHORITIES, authorities)
                .setIssuedAt(new Date()) // 发布时间
                .setExpiration(new Date(System.currentTimeMillis() + TTL)) // 到期时间
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY) // 签名
                .compact();
    }

    /**
     * 生成 token
     *
     * @param claims
     * @return
     */
    private static String generateToken(Claims claims) {
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis() + TTL)) // 到期时间
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY) // 签名
                .compact();
    }

    /**
     * 解析 token
     *
     * @param token
     * @return
     */
    public static Claims parseToken(String token) {
        return Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody();
    }

    /**
     * 获取 username
     *
     * @param claims
     * @return
     */
    public static String getUsername(Claims claims) {
        return claims.getSubject();
    }

    /**
     * 是否过期
     *
     * @param claims
     * @return
     */
    public static boolean isExpiration(Claims claims) {
        return claims.getExpiration().before(new Date());
    }

    /**
     * 获取角色
     *
     * @param claims
     * @return
     */
    public static List<String> getAuthorities(Claims claims) throws JsonProcessingException {
        String authorities = claims.get(AUTHORITIES, String.class);
        String jsonListStr = authorities.substring(0, authorities.length() - 1);
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.readValue(jsonListStr, new TypeReference<List<String>>() {});
    }

    /**
     * 刷新 token
     *
     * @param token
     * @return
     */
    public static String refreshToken(String token) {
        return generateToken(parseToken(token));
    }

}


