package com.inkasso.adapter.util;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.google.common.collect.Lists;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;


public class Md5SignUtil {

  public static  final String SALT = "CHANGANYINKE";

  /**
   * MD5生成签名字符串
   *
   * @param map
   *            需签名参数
   * @param key
   *            MD5key
   * @return
   */
  public static String MD5sign(LinkedHashMap<String, Object> map, String key) {
    String genSign = "";
    try {
      LinkedHashSet<String> keys = (LinkedHashSet<String>) map.keySet();
      ArrayList<String> keyList = Lists.newArrayList(keys);
      JSONObject param = JSONObject.from(map);
      // 生成签名原文
      String signSrc = orgSignSrc(keyList, param);
      // MD5的方式签名
      signSrc += "&KEY=" + key;
      MessageDigest md5 = MessageDigest.getInstance("MD5");
      md5.update(SALT.getBytes(StandardCharsets.UTF_8));
      byte[] digest = md5.digest(signSrc.getBytes(StandardCharsets.UTF_8));
       


    } catch (Exception e) {
      e.printStackTrace();
    }
    return genSign;
  }



  /**
   * 构建签名原文
   *
   * @param signFields 参数顺序
   * @param param 参数与值的jsonbject
   * @return
   */
  private static String orgSignSrc(List<String> signFields, JSONObject param) {

    StringBuffer signSrc = new StringBuffer("");
    int i = 0;
    for (String field : signFields) {
      signSrc.append(field);
      signSrc.append("=");
      signSrc.append((StringUtils.isEmpty(param.getString(field)) ? ""
          : param.getString(field)));
      // 最后一个元素后面不加&
      if (i < (signFields.size() - 1)) {
        signSrc.append("&");
      }
      i++;
    }
    return signSrc.toString();
  }

}
