package com.aiup.service.utils;

import com.aiup.service.entity.UserInfo;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class JwtUtils {
    /**
     * 有效期2个小时
     */
    public static final long EXPIRE_TIME = 60L* 60 * 1000*2;
    //public static final long EXPIRE_TIME = 60L* 60 * 1000*24*365;

    public static final String SECRET = "SECRET_Yunzhongyu_AiUp";

    //签发token
    public static String sign(UserInfo user){
        Date expireDate = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        return JWT.create()
                .withClaim("account", user.getUserId())
                .withClaim("userName", user.getUserName())
                .withClaim("openId",user.getOpenId())
                .withExpiresAt(expireDate)
                .sign(Algorithm.HMAC256(SECRET));
    }


    //校验token
    public static boolean verify(String token){
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
            DecodedJWT decodedJWT  = verifier.verify(token);
            return true;
        }catch (Exception e){
            return false;
        }
    }

    //获取token内的携带的用户名信息
    public static String getUserNameByToken(String token){
        DecodedJWT decodedJWT = JWT.decode(token);
        return decodedJWT.getClaim("userName").asString();
    }

    public static  Date getExpireByToken(String token){
        DecodedJWT decodedJWT = JWT.decode(token);
        Date date=  decodedJWT.getExpiresAt();
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        // 把日期往前减5分钟
        calendar.add(Calendar.MINUTE, -5);
        // 这个时间就是日期往后推一天的结果
        date = calendar.getTime();
        return date;
    }

    //获取token内的携带OpenId
    public static String getOpenIdByToken(String token){
        DecodedJWT decodedJWT = JWT.decode(token);
        return decodedJWT.getClaim("openId").asString();
    }

    //获取token内的携带的用户信息
    public static UserInfo getUserByToken(String token){
        DecodedJWT decodedJWT = JWT.decode(token);
        UserInfo user = new UserInfo();
        user.setUserName(decodedJWT.getClaim("userName").asString());
        user.setUserId(decodedJWT.getClaim("account").asInt());
        user.setOpenId(decodedJWT.getClaim("openId").asString());
        return user;
    }

}

