// #ifndef H5
class URLSearchParams {
  constructor(queryString) {
    this.params = new Map();
    if (queryString) {
      queryString.split('&').forEach(pair => {
        const [key, value] = pair.split('=');
        this.params.set(decodeURIComponent(key), decodeURIComponent(value));
      });
    }
  }

  append(key, value) {
    this.params.set(key, value);
  }

  delete(key) {
    this.params.delete(key);
  }

  get(key) {
    const values = [...this.params.values()];
    return values.length ? values[0] : null;
  }

  getAll(key) {
    return this.params.get(key) || [];
  }

  has(key) {
    return this.params.has(key);
  }

  set(key, value) {
    this.params.set(key, value);
  }

  sort() {
    // 按键排序
    const sortedEntries = [...this.params.entries()].sort((a, b) => a[0].localeCompare(b[0]));
    this.params = new Map(sortedEntries);
  }

  forEach(callbackFn, thisArg) {
    this.params.forEach(callbackFn, thisArg);
  }

  toString() {
    return [...this.params.entries()].map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`).join('&');
  }
}

// #endif

// #ifdef H5
const URLSearchParams = window.URLSearchParams;
// #endif

function params(param) {
  if (param == null || param == "") {
    return new URLSearchParams();
  }
  if (param.constructor == Array) {
    let param1 = new URLSearchParams();
    for (let obj of param) {
      param1.append(obj.name, obj.value);
    }
    param = param1;
  } else {
    let param1 = new URLSearchParams();
    for (let name in param) {
      param1.append(name, param[name]);
    }
    param = param1;
  }

  return param;
}

export {
  params, URLSearchParams
}