/* eslint-disable import/prefer-default-export */
export const replaceAll = (FindText: RegExp | string, RepText: string, str: string): string => {
  const regExp = new RegExp(FindText, 'g');
  return str.replace(regExp, RepText);
};

// 全局替换 字符串（处理字符串内有需要转义的字符 如：'()'）
export const replaceStrAll = (replaceThis: string, withThis: string, inThis: string): string => {
  withThis = withThis.replace(/\$/g, '$$$$');
  return inThis.replace(
    // eslint-disable-next-line no-useless-escape
    new RegExp(replaceThis.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|<>\-\&])/g, '\\$&'), 'g'),
    withThis
  );
};

// 是否未定义
export const isDef = (value: any): boolean => {
  return value !== undefined && value !== null;
};

// 是否为空值
export const isEmptyVal = (val: any): boolean => {
  return val === null || val === undefined || val === '';
};

export const getPatten = (decimal: number) => {
  const header = '0,0.';
  return header + '00000000'.substr(0, decimal);
};

// 判断是否数字
export const isNumeric = (n: any) => {
  /* eslint-disable */
  var t = typeof n;

  return t == 'number'
    ? !isNaN(n) && isFinite(n)
    : t == 'string'
    ? !n.length
      ? false
      : n.length == 1
      ? /\d/.test(n)
      : /^\s*[+-]?\s*(?:(?:\d+(?:\.\d+)?(?:e[+-]?\d+)?)|(?:0x[a-f\d]+))\s*$/i.test(n)
    : t == 'object'
    ? !!n && typeof n.valueOf() == 'number' && !(n instanceof Date)
    : false;
};

// 判断数据库中的某个字段是否为空
export const isEmptyForDB = (obj: any) => {
  return obj == null || obj === -1 || obj === '';
};

// 判断是否过期
export const isExpired = (deadline:number)=> {
  // deadline 为 0 表示无限制
  if (deadline !== 0) {
    return Date.now() >= deadline + 24 * 60 * 60 * 1000;
  }
  return false;
}

const canvas = document.createElement("canvas");

export const getTextWidth = (text:string, font :string)=> {
  const context = canvas.getContext("2d") as CanvasRenderingContext2D;
  context.font = font;
  const metrics = context.measureText(text);
  return metrics.width;
}


