import request from "@/utils/request";
import md5 from "md5";
function sortParams(params) {
  return Object.keys(params)
    .filter((k) => params[k] !== "") // 过滤空参数
    .sort() // 排序
    .reduce((obj, key) => {
      obj[key] = params[key];
      return obj;
    }, {});
}
function sort_ASCII(obj) {
  var arr = new Array();
  var num = 0;
  for (let i in obj) {
    arr[num] = i;
    num++;
  }
  var sortArr = arr.sort();
  var sortObj = {};
  for (let i in sortArr) {
    sortObj[sortArr[i]] = obj[sortArr[i]];
  }
  return sortObj;
}
/**
 * 排序参数并生成签名
 */
function generateSign(params = {}) {
  // 随机字符串
  const nonce_str = Math.random().toString(36).substr(2);

  // 排序参数并转 URL 键值对
  const strTemp = sortParams(Object.assign(params, { nonce_str }));

  console.log(strTemp);
  let arr = sort_ASCII(strTemp);
  let str = "";
  for (let key in arr) {
    if (arr[key] || arr[key] === 0) {
      str = str + key + "=" + arr[key] + "&";
    }
  }
  console.log(str + "appKey=1f26fe1a6a36daf7651d6437bb6a5fa6");
  // 生成 MD5 签名
  let sign = md5(str + "appKey=1f26fe1a6a36daf7651d6437bb6a5fa6").toUpperCase();
  // const sign = md5(
  //   `${strTemp}&appKey=1f26fe1a6a36daf7651d6437bb6a5fa6`
  // ).toUpperCase();
  return {
    ...params,
    nonce_str,
    sign,
  };
}
// 获取店铺满减
export function getStoreDecrement(data) {
  return request({
    url: "/getStoreDecrement",
    method: "post",
    data: generateSign(data),
  });
}
// 获取店铺优惠券
export function getStoreCoupon(data) {
  return request({
    url: "/getStoreCoupon",
    method: "post",
    data: generateSign(data),
  });
}
// 保存店铺优惠券
export function saveStoreCoupon(data) {
  return request({
    url: "/saveStoreCoupon",
    method: "post",
    data: generateSign(data),
  });
}
// 删除店铺优惠券
export function delStoreCoupon(data) {
  return request({
    url: "/delStoreCoupon",
    method: "post",
    data: generateSign(data),
  });
}
// 保存店铺满减
export function saveStoreDecrement(data) {
  return request({
    url: "/saveStoreDecrement",
    method: "post",
    data: generateSign(data),
  });
}
// 删除店铺满减
export function delStoreDecrement(data) {
  return request({
    url: "/delStoreDecrement",
    method: "post",
    data: generateSign(data),
  });
}
