package com.jsowell.common.util.sim;

import cn.hutool.http.HttpRequest;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Hashtable;
import java.util.List;

/**
 * 讯众物联Sim卡商工具类
 *
 * @author JS-ZZA
 * @date 2022/12/6 15:47
 */
@Component
public class XunZhongSimUtils {

    private static String API_SECRET;

    @Value("${xunzhong.apiSecret}")
    public void setAPI_SECRET(String API_SECRET) {
        XunZhongSimUtils.API_SECRET = API_SECRET;
    }

    // Base 64 加密
    private static String encode(final byte[] bytes) {
        return new String(Base64.encodeBase64(bytes));
    }

    // SHA 256 加密
    private static String SHA256(final String strText) {
        return SHA(strText, "SHA-256");
    }

    /**
     * SHA算法加密
     * @param strText
     * @param strType
     * @return
     */
    private static String SHA(final String strText, final String strType) {
        // 返回值
        String strResult = null;
        // 是否是有效字符串
        if (strText != null && strText.length() > 0) {
            try {
                // SHA 加密开始
                MessageDigest messageDigest = MessageDigest.getInstance(strType);
                // 传⼊要加密的字符串
                messageDigest.update(strText.getBytes());
                // 得到 byte 结果
                byte[] byteBuffer = messageDigest.digest();
                // 將 byte 转换 string
                StringBuilder strHexString = new StringBuilder();
                // 遍历 byte buffer
                for (byte b : byteBuffer) {
                    String hex = Integer.toHexString(0xff & b);
                    if (hex.length() == 1) {
                        strHexString.append('0');
                    }
                    strHexString.append(hex);
                }
                strResult = strHexString.toString();
            }
            // 得到返回結果
            catch(NoSuchAlgorithmException e){
                e.printStackTrace();
            }
        }

        return strResult;
    }


    /**
     * 生成signStr
     * @param params
     * @return
     */
    public static String getSignStr(Hashtable<String, Object> params) {
        // 参数按 key 排序
        List<String> keys = new ArrayList<>(params.keySet());
        Collections.sort(keys);

        StringBuilder sign = new StringBuilder();

        for (String key : keys) {
            Object obj = params.get(key);
            if (!sign.toString().equals("")) {
                sign.append("&");
            }
            sign.append(key).append("=").append(obj);
        }
        // ⽣成 sign
        sign.append(API_SECRET);
        // 添加加密的 sign
        String signStr = SHA256(encode(sign.toString().getBytes()));

        return signStr;
    }

    /**
     * 链式构建请求，引入hutool
     * @param url
     * @param params
     * @return
     */
    public static String sendPost(String url, Hashtable<String, Object> params) {
        String postResult = HttpRequest.post(url)
                .header("Content-type", "application/x-www-form-urlencoded;charset=utf-8")
                .form(params)
                .timeout(20000)//超时，毫秒
                .execute().body();

        return postResult;
    }


}
