package com.template.common.utils;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.template.model.pojo.AlumniUser;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * jwt 工具
 **/
@Slf4j
public class JWTUtil {

    private static String SIGNATURE = "token!@#$%^7890";

    /**
     * token过期时间，7天
     */
//    private static final long EXPIRED = 1000 * 60 * 60 * 24 * 7;
    private static final long EXPIRED = 1000 * 60 * 60 * 24;

    /**
     * 生成token 有过期时间
     * @return 返回token
     */
    public static String getToken(AlumniUser ra, Long expired){
        System.out.println("生成token："+ra.getCardNumber());

        // 签发时间
        Date iatDate = new Date();

//        // 过期时间
//        Calendar nowTime = Calendar.getInstance();
//        nowTime.add(Calendar.DAY_OF_WEEK, 3);
//        Date expiresDate = nowTime.getTime();

        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HMAC256");
        map.put("typ", "JWT");
        Date ExpiredDate = new Date(CommonUtil.getCurrentTimestamp() + (expired == null ? EXPIRED : expired));
        String eStr = TimeExchange.DateToString(ExpiredDate,"yyyy-MM-dd HH:mm:ss");
        System.out.println("token有效期："+eStr);
        String token = JWT.create()
                .withHeader(map) // header
                .withClaim("userId", ra.getId()) // 账号
                .withExpiresAt(ExpiredDate) // 设置过期时间。过期时间要大于签发时间
                .withIssuedAt(iatDate) // 设置签发时间
                .sign(Algorithm.HMAC256(SIGNATURE)); // 加密
        return token;

//
//        JWTCreator.Builder builder = JWT.create();
//        map.forEach((k,v)->{
//            builder.withClaim(k,v);
//        });
//        Calendar instance = Calendar.getInstance();
//        instance.add(Calendar.SECOND,7);
//        builder.withExpiresAt(instance.getTime());
//        return builder.sign(Algorithm.HMAC256(SIGNATURE)).toString();
    }

    public static long getExpired() {
        return EXPIRED;
    }


    /**
     * 验证token
     * @param token
     */
    public static void verify(String token){
        JWT.require(Algorithm.HMAC256(SIGNATURE)).build().verify(token);
    }

    /**
     * 获取token中payload
     * @param token
     * @return
     */
    public static DecodedJWT getToken(String token){
        return JWT.require(Algorithm.HMAC256(SIGNATURE)).build().verify(token);
    }



    /*
     * 解密Token
     * */
    public static Map<String, Claim> verifyToken(String token)  {
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SIGNATURE)).build();
        DecodedJWT jwt = null;
        try {
            jwt = verifier.verify(token);
        } catch (Exception e) {
            throw new RuntimeException("登录凭证已过去，请重新登录");
        }

        return jwt.getClaims();
    }

    /*
     * 解密Token获取token中的信息
     * */
    public static Map<String, Claim> verifyTokenInfo(String token)  {
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SIGNATURE)).build();
        DecodedJWT jwt = null;
        try {
            jwt = verifier.verify(token);
            String userId = jwt.getClaims().get("identifierId").asString();
            Integer userIds = jwt.getClaims().get("userId").asInt();
            String userIdstr = jwt.getClaims().get("userId").asString();//它要指定类型的才能转换
            String sdsd = "";
        } catch (Exception e) {
            log.error(e.getMessage());
            return null;
        }

        return jwt.getClaims();
    }
}
