package com.bcxin.identify.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.bcxin.identify.util.common.cipher.MD5Util;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class TokenUtils {
    private static final String SECRET_KEY = "teemlink_obpm";

    public static String getUrlFromBcxToken(String bcxToken) {
        try {
            JWTVerifier xxx = JWT.require(Algorithm.HMAC256(SECRET_KEY)).withIssuer("auth0").acceptExpiresAt(1000 * 1000).build();
            DecodedJWT jwt = xxx.verify(bcxToken);
            String account = jwt.getClaim("username").asString();
            return account;
        } catch (Exception e) {
            return null;
        }
    }

    public static String getSourceIdFromVerify(String verify){
        try {
            JWTVerifier xxx = JWT.require(Algorithm.HMAC256(SECRET_KEY)).withIssuer("auth0").acceptExpiresAt(1000 * 1000).build();
            DecodedJWT jwt = xxx.verify(verify);
            String sourceId = jwt.getClaim("sourceId").asString();
            return sourceId;
        } catch (Exception e) {
            return null;
        }
    }

    public static String generateBcxToken(String userId) {
        String token = null;
        try {
            Date expiresAt = new Date(System.currentTimeMillis() + 12 * 60 * 60 * 1000);
            token = JWT.create().withIssuer("auth0").withClaim("username", userId).withExpiresAt(expiresAt)
                    // 使用了HMAC256加密算法。
                    .sign(Algorithm.HMAC256(SECRET_KEY));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return token;

    }

    public static void main(String[] args) {
        String user = "18292417675";//local user
//        String user = "org_aSuXCEfz";//test user
//        String user = "13888888888";//merchant
//        String user = "admin";//platform
//        String bcxToken = TokenUtils.generateBcxToken(user);
//        System.out.println(bcxToken);
//        String m = MD5Util.string2MD5("7BCX_ORDER_VERIFY1225");
//        System.out.println(m);
        String token = "eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJhdXRoMCIsImV4cCI6MTc1ODIzOTY4MCwidXNlcm5hbWUiOiJodHRwOi8vMTIwLjEzMy43OS44Mjo4MDkyL2FwaS9jeXlmL0dldFJlcG9ydFNnbFBkZj9zZ2xjaGVja2lkPTM1RkJBMEQ5MzFCRjdDOTE5MEY1Njk2M0JDNDk3REM4In0._G4TUR7l6D9lwMnkFhEq93FqIM8z0C_p1UA223yLKzc";
        System.out.println(TokenUtils.getUrlFromBcxToken(token));
    }
}
