// signatureUtil.js
import md5 from "js-md5";
export function signatureGenerate({ data, url, headers }) {
  // 密钥
  let secret = "3g7Xn1yl";//富士secret
  // 时间戳
  let timestamp = new Date().getTime();
  // post参数
  let dataStr = dataSerialize(dataSort(data));
  // console.log("签名部分,排序后的请求参数");
  // console.log(dataStr);

  let str = (url + dataStr + "timestamp=" + timestamp).toUpperCase() + secret;

  const sign = md5(str).toUpperCase();

  return {
    signature: sign,
    timestamp,
    secret,
  };
}

// 参数排序
function dataSort(obj) {
  if (JSON.stringify(obj) == "{}" || obj == null) {
    return {};
  }
  let key = Object.keys(obj).sort();
  let newObj = {};
  for (let i = 0; i < key.length; i++) {
    newObj[key[i]] = obj[key[i]];
  }
  return newObj;
}

// 参数序列化
function dataSerialize(sortObj) {
  let strJoin = "";

  for (let key in sortObj) {
    if (notObject(sortObj[key])) {
      strJoin += key + "=" + sortObj[key] + "&";

    }
  }
  return strJoin;
}

function notObject(value) {
  return typeof value != 'object';
}
