package com.fufan.mtsaas.util;

import com.alibaba.fastjson.JSON;
import com.fufan.mtsaas.modules.sysmgr.common.tocken.LoginTokenBO;
import com.fufan.mtsaas.modules.sysmgr.common.tocken.LoginTokenBO;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Date;

public class JwtUtil {

    /**
     * 生成加密的令牌*/
    public static String createToken(LoginTokenBO loginTokenBO){

        //1、创建加密的技术-sha-256
        io.jsonwebtoken.SignatureAlgorithm signatureAlgorithm= io.jsonwebtoken.SignatureAlgorithm.HS256;
        //2、创建JWT建造者对象
        JwtBuilder jwtBuilder= Jwts.builder();
        //追加token时间
        loginTokenBO.setStartTime(System.currentTimeMillis());
        loginTokenBO.setEndTime(System.currentTimeMillis() + 1000 * 60 * 15);
        //3、设置JWt相关信息
        jwtBuilder.setIssuedAt(new Date());//开始时间
        jwtBuilder.setSubject(JSON.toJSONString(loginTokenBO));//设置JWT中的内容
        jwtBuilder.signWith(signatureAlgorithm,createKey());
        //4、生成JWT
        return jwtBuilder.compact();
    }


    //解析 令牌
    public static String parseJWT(String token){
        SecretKey key=createKey();
        Claims claims=Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
        return claims.getSubject();
    }

    //解析 令牌
    public static LoginTokenBO parseTokenBO(String token){
        SecretKey key=createKey();
        Claims claims=Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
        return JSON.parseObject(claims.getSubject(),LoginTokenBO.class);
    }

    //生成秘钥
    private static SecretKey createKey(){
        byte[] keys="videojet-udi".getBytes();
        SecretKey key=new SecretKeySpec(keys,0,keys.length,"AES");
        return key;
    }

    public static void main(String[] args) {
        LoginTokenBO loginTokenBO = new LoginTokenBO();
        loginTokenBO.setAppKey("666");
        loginTokenBO.setUserId("U888");
        loginTokenBO.setUserName("test");
//        loginTokenBO.setCompanyId("1");
        String token = JwtUtil.createToken(loginTokenBO);
        System.out.println("token" + token);
        System.out.println("result" + parseJWT(token));
    }


}