// 去掉小数点后面无用的0
const trimZero = (num: any) => {
  if (num === undefined || num === null) return ''
  let str = `${num}`
  if (!str.includes('.')) {
    // 没有小数点，直接返回
    return str
  }
  while (str.endsWith('0')) {
    str = str.slice(0, -1)
  }
  if (str.endsWith('.')) {
    str = str.slice(0, -1)
  }
  return str
}

const toFixed2 = (num: any) => {
  num = Number(num)
  if (Number.isNaN(num)) return ''
  return trimZero(num.toFixed(2))
}

const toPercent = (val: any) => {
  val = Number(val)
  if (Number.isNaN(val)) return ''
  return `${toFixed2(val * 100)}%`
}

/**
 * 是否为正整数
 */
const isPositiveInt = (val: any) => {
  val = String(val)
  if (val.includes('.')) return false
  const numVal = Number(val)
  return !Number.isNaN(numVal) && numVal > 0
}

// 数字相关
const default_sep = ','
/**
 * 金额格式化
 * 比如 3412000000.34 格式化后为 34_1200_0000.34
 */
const formatMoney = (num: any, sep = default_sep) => {
  const newVal = String(num).replaceAll(/[^\d.]/g, '')
  const cmps = newVal.split('.') as any
  const len = cmps?.length
  if (!len) return num
  // 先把所有下划线替换掉
  cmps[0] = cmps[0].replaceAll(sep, '')

  // 从右到左每4位添加下划线
  const formattedInteger = cmps[0].replaceAll(
    /(\d)(?=(\d{4})+(?!\d))/g,
    `$1${sep}`,
  )

  return len > 1 ? `${formattedInteger}.${cmps[1]}` : formattedInteger
}

const deFormatMoney = (num: any) => {
  if (!num) return num
  return num.replaceAll(default_sep, '')
}

export default {
  trimZero,
  toFixed2,
  toPercent,
  isPositiveInt,
  formatMoney,
  deFormatMoney,
}
