package com.loan.system.utils;

import com.loan.system.constant.JwtClaimsConstant;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @author EdwinXu
 * @date 2020/9/2 - 20:46
 */
@Component
public class JwtTokenUtil implements Serializable {
    private static final long serialVersionUID = 8998885548318234112L;

    private static String secret;
    private static Long expiration;
    private static String header;
    private static String token_prefix;
    private static String issuer;

    @Value("${JWT.SECRET}")
    public void setSecret(String secret) {
        JwtTokenUtil.secret = secret;
    }
    @Value("${JWT.EXPIRATION}")
    public void setExpiration(Long expiration) {
        JwtTokenUtil.expiration = expiration;
    }
    @Value("${JWT.HEADER}")
    public void setHeader(String header) {
        JwtTokenUtil.header = header;
    }
    @Value("${JWT.TOKEN_PREFIX}")
    public void setTokenPrefix(String tokenPrefix) {
        JwtTokenUtil.token_prefix = tokenPrefix;
    }
    @Value("${JWT.ISSUER}")
    public void setIssuer(String issuer) {
        JwtTokenUtil.issuer = issuer;
    }
    /**
     * 生成 token
     * @param username  用户
     * @param roles     角色
     */
    public static String generateToken(String number, String username, List<String> roles){
        // token 签发时间
        final Date createdDate = new Date();
        // token 过期时间
        final Date expirationDate = new Date(createdDate.getTime() + expiration * 1000);
        final HashMap<String, Object> claims = new HashMap<>(2);
        claims.put("number",number);
        claims.put("username",username);
        claims.put("role",String.join(",",roles));
        return token_prefix+Jwts.builder()
                .setClaims(claims)
                // token 签发者
                .setIssuer(issuer)
                .signWith(SignatureAlgorithm.HS256 , secret)
                .setIssuedAt(createdDate)
                .setExpiration(expirationDate)
                // token 面向对象
                .setSubject(username)
                .compact();
    }

    public static Claims getClaimsFromToken(String token) {
        Claims claims;
        try {
            claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
        } catch (ExpiredJwtException e) {
            claims = e.getClaims();
        }
        return claims;
    }

    public static String getUsernameFromToken(String token) {
        return getClaimsFromToken(token).getSubject();
    }
    public static Long getUserIdFromToken(String token){
        return (Long) getClaimsFromToken(token).get(JwtClaimsConstant.USER_ID);
    }
    public static String getNumberFromToken(String token){
        return (String) getClaimsFromToken(token).get("number");
    }

    public static Boolean validateToken(String token, UserDetails userDetails) {
        final String username = getUsernameFromToken(token);
        return username.equals(userDetails.getUsername());
    }

    public static Boolean isTokenExpired(String token) {
        final Date expiration = getExpirationDateFromToken(token);
        return expiration.before(new Date());
    }

    public static Date getExpirationDateFromToken(String token) {
        return getClaimsFromToken(token).getExpiration();
    }
}
