package com.bcxin.utils;

import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Component;

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

@Component
public class JwtUtil {
    /**
     * 数据请求返回码
     */
    public static final int RESCODE_SUCCESS = 1000;				//成功
    public static final int RESCODE_SUCCESS_MSG = 1001;			//成功(有返回信息)
    public static final int RESCODE_EXCEPTION = 1002;			//请求抛出异常
    public static final int RESCODE_NOLOGIN = 1003;				//未登陆状态
    public static final int RESCODE_NOEXIST = 1004;				//查询结果为空
    public static final int RESCODE_NOAUTH = 1005;				//无操作权限

    /**
     * jwt
     */
    public static final String JWT_ID = "blb";
    public static final String JWT_SECRET = "18disdkfd83DPQ012I8VcnSkq"; //私钥
    //	public static final int JWT_TTL = 24*60*60*1000;  //millisecond 1天 客户端去申请token
    public static final int JWT_TTL = 365*24*60*60*1000;  //millisecond 1天 客户端去申请token
    public static final int JWT_REFRESH_INTERVAL = 55*60*1000;  //millisecond token无效的时间间隔
    public static final int JWT_REFRESH_TTL = 7*24*60*60*1000;  //millisecond 7天重新登录的时间间隔

    /**
     * 由字符串生成加密key
     * @return
     */
    private static SecretKey generalKey(String stringKey){
//        String stringKey = JwtUtil.JWT_SECRET;
        byte[] encodedKey = Base64.decodeBase64(stringKey);
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }

    /**
     * 创建jwt，ttlMillis为负数表示不过期
     * @param id
     * @param subject
     * @param ttlMillis
     * @return
     * @throws Exception
     */
    public static String createJWT(String id, String subject, String stringKey, long ttlMillis) throws Exception {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        JwtBuilder builder = Jwts.builder()
                .setId(id)
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setSubject(subject)
                .signWith(signatureAlgorithm, generalKey(stringKey));
        if (ttlMillis >= 0) {
            long expMillis = System.currentTimeMillis() + ttlMillis;
            Date exp = new Date(expMillis);
            builder.setExpiration(exp);
        }
        return builder.compact();
    }
    /**
     * 创建jwt
     * @param subject
     * @return
     */
    public static String createJWT(Map<Object,Object> subject, String stringKey, long ttlMillis) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        JwtBuilder builder = Jwts.builder()
//				.setId(JwtUtil.JWT_ID) // 暂时不用，减少流量
//				.setIssuedAt(new Date(System.currentTimeMillis())) //发行时间  暂时不用，减少流量
                .setSubject(JSON.toJSONString(subject)) //主题，就是附带在token中的信息
                .signWith(signatureAlgorithm, generalKey(stringKey)); //选择的算法，和私钥值
        if (ttlMillis >= 0) { //如果过期时间为负数，那么不设置过期时间
            long expMillis = System.currentTimeMillis() + ttlMillis;
            Date exp = new Date(expMillis);
            builder.setExpiration(exp);
        }
        return builder.compact();
    }

    /**
     * 解密jwt
     * @param jwttoken
     * @return
     * @throws Exception
     */
    public static Claims parseJWT(String jwttoken, String stringKey) throws Exception {
        Claims claims = Jwts.parser()
                .setSigningKey(generalKey(stringKey)) //没有私钥是解密不了的
                .parseClaimsJws(jwttoken).getBody();
        return claims;
    }

    public static void main(String[] args) throws Exception  {
        //http://10.172.126.43:8012//preview?token=
        //http://47.93.117.58:8012/preview?token=
        String a = "aHR0cHM6Ly93d3cucHNzMzYwLmNuLy9nZXRSZXNvdXJjZS5kbz9wYXRoPTIwMjUtMDctMTEvcGcvMTEzMTU1XzE3NTIyMjUxMDIyNzkuZG9jeA==";
        Claims aa = JwtUtil.parseJWT(a,"sdoDFyzfieqMrisd4H5o5t9weOl6GmSr" );
        System.out.println("-----------解析地址："+aa.getSubject());
        //"http://outsxbbd.test.baibaodun.cn/ars-web//getResource.do?path=upload/2018-03-15/1521045450283.zip"
    }


}
