/**
 * 请求工具所使用的工具函数
 *
 * 功能介绍：
 *  提供了一些处理工具函数，方便使用。
 *
 * Author: imengyu
 * Date: 2022/03/25
 *
 * Copyright (c) 2021 imengyu.top. Licensed under the MIT License.
 * See License.txt in the project root for license information.
 */

/* eslint-disable no-bitwise */
import type { KeyValue } from "@imengyu/js-request-transform/dist/DataUtils";
import type { TypeSaveable } from "./AllType";
import { FormData } from "../implementer/Uniapp";

export function isNullOrEmpty(val: unknown) {
  return !val || typeof val === 'undefined' || val === '';
}
export function simpleClone<T>(obj: T) : T {
  let temp: KeyValue|Array<KeyValue>|null = null;
  if (obj instanceof Array) {
    temp = obj.concat();
  }
  else if (typeof obj === 'object') {
    temp = {} as KeyValue;
    for (const item in obj) {
      const val = (obj as unknown as KeyValue)[item];
      if (val === null) temp[item] = null;
      else (temp as KeyValue)[item] = simpleClone(val) as TypeSaveable;
    }
  } else {
    temp = obj as unknown as KeyValue;
  }
  return temp as unknown as T;
}
/**
 * 计算字符串的哈希值
 * @param {string} str
 */
export function stringHashCode(str: string) {
  return '' + (str.split("").reduce(function(a, b) {
    a = (a << 5) - a + b.charCodeAt(0);
    return (a & a);
  }, 0));
}

export function checkIfStringAllEnglish(str: string) {
  return /^[\x00-\x7F]+$/.test(str)
}

export function appendGetUrlParams(url: string, key: string, value: any) {
  if (!url.includes(`?${key}`) && !url.includes(`&${key}`)) {
    if (url.includes('?'))
      url = url + '&' + key + '=' + value;
    else
      url = url + '?' + key + '=' + value;
  }
  return url;
}
export function appendPostParams(source: any, key: string, value: any) {
  if (source instanceof FormData && !source.has(key))
    source.append(key, value);
  else if (typeof source === 'object' && source[key] === undefined)
    source = { ...source, [key]: value };
  return source;
}

export function transformSomeToArray(source: any) {
  if (typeof source === 'string') 
    return source.split(','); 
  if (typeof source === 'object') {
    if (source instanceof Array)
      return source; 
    else {
      const arr = [];
      for (const key in source)
        arr.push(source[key]);
      return arr;
    }
  }
  return source;
}