package com.yami.shop.wx.utils;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import lombok.SneakyThrows;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

/**
 * 公众平台通用接口工具类
 * @author kaur
 */
public class AccessTokenApi {

    /**
     * 获取微信公众号：access_token的接口地址（GET） 限2000（次/天）
     */
    public final static String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";


    /**
     * 获取access_token
     */
    @SneakyThrows
    public static AccessToken getAccessToken(String appid, String appsecret) {
        AccessToken accessToken = null;
        String requestUrl = ACCESS_TOKEN_URL.replace("APPID", appid).replace("APPSECRET", appsecret);

        JSONObject jsonObject = JSONObject.parseObject(Http5Util.get(requestUrl));
        if (jsonObject == null) {
            jsonObject = JSONObject.parseObject(Http5Util.get(requestUrl));
        }
        // 如果请求成功
        if (null != jsonObject) {
            try {
                accessToken = new AccessToken();
                accessToken.setToken(jsonObject.getString("access_token"));
                accessToken.setExpiresIn(jsonObject.getInteger("expires_in"));
            } catch (JSONException e) {
                accessToken = null;
            }
        }
        return accessToken;
    }

    public static String byteToStr(byte[] byteArray) {
        String strDigest = "";
        for (byte b : byteArray) {
            strDigest += byteToHexStr(b);
        }
        return strDigest;
    }

    public static String byteToHexStr(byte mByte) {
        char[] digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        char[] tempArr = new char[2];
        tempArr[0] = digit[(mByte >>> 4) & 0X0F];
        tempArr[1] = digit[mByte & 0X0F];
        return new String(tempArr);
    }

    public static String getSignature(String nonceStr, String jsapiTicket, String timestamp, String url) {
        String[] paramArr =
                new String[]{"jsapi_ticket=" + jsapiTicket, "timestamp=" + timestamp, "noncestr=" + nonceStr, "url=" + url};
        Arrays.sort(paramArr);
        // 将排序后的结果拼接成一个字符串
        String content = paramArr[0].concat("&" + paramArr[1]).concat("&" + paramArr[2])
                .concat("&" + paramArr[3]);
        String gensignature = null;
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            // 对拼接后的字符串进行 sha1 加密
            byte[] digest = md.digest(content.getBytes());
            gensignature = AccessTokenApi.byteToStr(digest);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        if (gensignature != null) {
            return gensignature;
        } else {
            return "false";
        }
    }

}
