package com.icloud.server.web.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.icloud.server.web.err.ServicerunException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @Author : yang
 * @Date : 2019/4/1 1:05 PM
 * @Version : 1.2.1
 */
@Component
public class JwtUtils {
    //主题
    public   final String SUBJECT = "9e9b7";

    //过期时间，毫秒，18天
    public   final long EXPIRE = 1000*60*60*24*18;
    private static final long EXPIRE_TIME = 60 * 24 * 60 * 1000;


    //秘钥
    public   final  String APPSECRET = "OCCLOUD+JWT";
    private static final String SECRET = "OCCLOUD+JWT";

    /**
     * 生成jwt
     * @param jt
     * @return
     */
    public   String geneJsonWebToken(JwtEntity jt){

        if(jt == null || jt.getId() == null || jt.getUsername() == null
                || jt.getClientId()==null){
            return null;
        }
        String token = Jwts.builder().setSubject(SUBJECT)
                .claim("id",jt.getId())
                .claim("username",jt.getUsername())
                .claim("clientId",jt.getClientId())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis()+EXPIRE))
                .signWith(io.jsonwebtoken.SignatureAlgorithm.HS256,APPSECRET).compact();

        return token;
    }
    public static String createToken(String username,Long clientId) {
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        Algorithm algorithm = Algorithm.HMAC256(SECRET);
        // 附带username信息
        return JWT.create()
                .withClaim("username", username)
                .withClaim("clientId", clientId)
                //到期时间
                .withExpiresAt(date)
                //创建一个新的JWT，并使用给定的算法进行标记
                .sign(algorithm);
    }

    /**
     * 校验token
     * @param token
     * @return
     */
    public Claims checkJWT(String token ){

        try{
            Claims claims =  Jwts.parser().setSigningKey(APPSECRET).parseClaimsJws(token).getBody();
            return  claims;

        }catch (Exception e){ throw new ServicerunException("登陆过期,请重新登陆"); }
//        return null;
    }





}
