package com.fs.app.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * jwt工具类

 */
@ConfigurationProperties(prefix = "fs.jwt")
@Component
public class JwtUtils {
    private Logger logger = LoggerFactory.getLogger(getClass());


    private String secret;
    private long expire;
    private String header;

    /**
     * 生成jwt token（使用配置的默认过期秒数）
     */
    public String generateToken(long userId) {
        return generateToken(userId, expire);
    }

    /**
     * 生成jwt token，可指定过期秒数（如 H5 公众号登录缓存 3 天）
     *
     * @param userId        用户ID
     * @param expireSeconds 过期秒数；小于等于 0 时回退为配置默认值
     */
    public String generateToken(long userId, long expireSeconds) {
        Date nowDate = new Date();
        long ttl = expireSeconds > 0 ? expireSeconds : expire;
        Date expireDate = new Date(nowDate.getTime() + ttl * 1000);
        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(userId + "")
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    public Claims getClaimByToken(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        }catch (Exception e){
            logger.error("验证令牌错误", e);
            return null;
        }
    }

    /**
     * token是否过期
     * @return  true：过期
     */
    public boolean isTokenExpired(Date expiration) {
        return expiration.before(new Date());
    }

    public String getSecret() {
        return secret;
    }

    public void setSecret(String secret) {
        this.secret = secret;
    }

    public long getExpire() {
        return expire;
    }

    public void setExpire(long expire) {
        this.expire = expire;
    }

    public String getHeader() {
        return header;
    }

    public void setHeader(String header) {
        this.header = header;
    }
}
