// 工具函数

/**
 * 提取url查询参数
 * @example
 * ```js
 * const url = 'https://baidu.com?s=hello&k=world'
 *
 * parseQueryParams(url)  // { s:'hello', k:'world' }
 *
 * const url2 = 'https://www.baidu.com'
 *
 * parseQueryParams(url2) // {}
 *
 * ```
 */
export const parseQueryParams = (url: string) => {
  const param = {};
  if (!url) {
    throw new ReferenceError("param url can not be undefined");
  }
  // if the url not includes ? then return result straight
  if (!url.includes("?")) {
    return param;
  }

  const [, queryParamsString] = url.split("?");

  const queryParamsArray = queryParamsString.split("&");

  queryParamsArray.forEach((queryItem) => {
    const [key, value] = queryItem.split("=");
    param[key] = value;
  });

  return param;
};

/**
 * 判断是直接跳转内部H5还是外部获取url进行跳转
 */
export const isOuterLink = (url: string) => {
  return !url.includes("/promote/home");
};

/**
 * 替换url的里的参数
 */
export const replaceQueryParam = (
  url: any,
  paramName: string,
  newValue: any
) => {
  const [baseUrl, queryString] = url.split("?");
  if (!queryString) {
    return url;
  }

  const params = queryString.split("&").map((param: any) => {
    const [key] = param.split("=");
    if (key === paramName) {
      return `${key}=${newValue}`;
    }

    return param;
  });

  return `${baseUrl}?${params.join("&")}`;
};
