package com.bohuikeji.frame.module.admin.utils.maiyatian;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.DigestUtils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;

/**
 * 麦芽田签名
 */
@Slf4j
public class maiyatianSignUtils {

    private static final String app_key  = "uupUexMG";
    private static final String app_secret  = "b6b690a49afff949274cd2ecd8ea248a";
    private static final String tag  = "JISONG";

    public static String getSignature(Map<String, Object> dto, String command) throws Exception {
        Map<String, Object> map = new HashMap<>();
        map.put("app_key","uupUexMG");
        map.put("command",command);
        map.put("data",dto.get("data"));
        map.put("timestamp",String.valueOf(LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"))));
        map.put("token",dto.get("token"));

        // 先将参数以其参数名的字典序升序进行排序
        Map<String, Object> sortedParams = new TreeMap<>(map);
        Set<Map.Entry<String, Object>> entrySet = sortedParams.entrySet();

        // 遍历排序后的字典，将所有参数按"key=value"格式拼接在一起
        StringBuilder stringToSign = new StringBuilder();
        for (Map.Entry<String, Object> param : entrySet) {
            stringToSign.append(param.getKey()).append("=").append(param.getValue()).append(",");
        }
        stringToSign.deleteCharAt(stringToSign.length() - 1);

        System.out.println(stringToSign);
        return calSignature(app_secret, stringToSign.toString());
    }

    private static String calSignature(String appSecret, String dataToSign) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(appSecret.getBytes("UTF-8"), "HmacSHA256");
        Mac sha256HMAC = Mac.getInstance("HmacSHA256");
        sha256HMAC.init(secretKeySpec);
        byte[] hmacResult = sha256HMAC.doFinal(dataToSign.getBytes("UTF-8"));
        Base64.Encoder encoder = Base64.getUrlEncoder();
        byte[] base64Result = encoder.encode(hmacResult);
        return new String(base64Result);
    }

}
