package com.cnooc.expert.common.utils;

import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import com.cnooc.expert.common.constant.TokenConstants;

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

/**
 * JWT工具类，用于生成、解析和验证token
 * @author FuHongZhang
 */
@Slf4j
public class JwtUtils {
    // 密钥，实际项目中应放在配置文件中
    private static final String SECRET_KEY = TokenConstants.SECRET;
    
    // Token过期时间，这里设置为48小时
    private static final long EXPIRATION_TIME = 48 * 60 * 60 * 1000;

//    private static final long EXPIRATION_TIME = 3 * 1000;


    /**
     * 生成token
     * @return token字符串
     */
    public static String createToken(String userId , String uuidKey) {
        // 生成token
        return Jwts.builder()
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .setIssuedAt(new Date())
                .claim(TokenConstants.UUID_KEY, uuidKey)
                .claim(TokenConstants.USER_ID, userId)
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .compact();
    }

    /**
     * 从token中获取用于拼接缓存的key uuid_key 和用户 user_id
     */
    public static  Map<String, String> getTokenInfo(String token) {
//        如果过期，会抛Exception
        Map<String, String> userInfo = new HashMap<>();
        Claims claims = extractAllClaims(token);
        userInfo.put(TokenConstants.UUID_KEY, (String) claims.get(TokenConstants.UUID_KEY));
        userInfo.put(TokenConstants.USER_ID, claims.get(TokenConstants.USER_ID) + "");
        return userInfo;
    }


    /**
     *
     * @param token
     * @return
     */
    private static Claims extractAllClaims(String token) {
        return Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody();
    }

    public static void main(String[] args) throws  Exception{

        String portalToken = JwtUtils.createToken("111", "testtest");
        Thread.sleep(5000);
        Map<String, String> claims = JwtUtils.getTokenInfo(portalToken);
        System.out.print(JSON.toJSONString(claims, true));
    }
}
