package com.zbkj.common.token;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.zbkj.common.constants.Constants;
import com.zbkj.common.utils.MD5Util;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

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

    public static String getBcxToken(HttpServletRequest request) {
        return request.getHeader(Constants.BCX_HEADER_AUTHORIZATION_KEY);
    }

    public static String getAccountFromBcxToken(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);
    }
}
