package com.cpop.core.utils;

import com.cpop.common.constant.Constants;
import com.cpop.core.base.enums.UserType;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author: DB
 * @date: 2022-09-25 16:14
 * @Description: jwt核心工具类
 */
@Data
@Component
@ConfigurationProperties(prefix = "cpop.jwt")
public class JwtUtils {

    /**
     * 过期时间
     */
    private Long expire;
    /**
     * 密钥
     */
    private String secret;
    /**
     * 请求头
     */
    private String header;

    /**
     * 白名单
     */
    private String whiteList;

    /**
     * @author LOST.yuan
     * @description 生成JWT
     * @date 16:15 2022/9/25
     * @param username 用户名
     * @return {@link String}
     **/
    public String generateToken(String identification, String username, UserType userType) {
        Date nowDate = new Date();
        Date expireDate = new Date(nowDate.getTime() + 1000 * expire);
        return Jwts.builder()
                .setHeaderParam(Constants.USERNAME, username)
                .setHeaderParam(Constants.USER_TYPE, userType)
                .setSubject(identification)
                .setIssuedAt(nowDate)
                // 7天过期
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    /**
     * @author LOST.yuan
     * @description 解析JWT
     * @date 16:15 2022/9/25
     * @param jwt
     * @return {@link Claims}
     **/
    public Jws<Claims> getClaimsByToken(String jwt) {
        try {
            return Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(jwt);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * @author LOST.yuan
     * @description 判断JWT是否过期
     * @date 16:15 2022/9/25
     * @param claims jwt令牌
     * @return {@link boolean}
     **/
    public boolean isTokenExpired(Claims claims) {
        return claims.getExpiration().before(new Date());
    }
}
