/* eslint-disable no-param-reassign */
// 保留2位小数
export const toFixed2 = (num: any) => {
  num = Number(num)
  if (Number.isNaN(num)) return ''
  return trimZero(num.toFixed(2))
}

// 格式化金额
const formatAmount = (amount: any): string => {
  amount = Number(amount)
  if (amount < 10000) {
    // 10000以下的直接显示数字
    return String(amount)
  } else {
    // 10000以上的转换为"W"单位，保留2位小数
    return toFixed2(amount / 10000) + '万'
  }
}

// 去掉小数点后面无用的0
const trimZero = (num: any) => {
  if (num === undefined || num === null) return ''
  let str = String(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 toPercent = (val: any) => {
  val = Number(val)
  if (isNaN(val)) return ''
  return toFixed2(val * 100) + '%'
}

const isNumberValue = (val: any) => {
  val = Number(val)
  return !isNaN(val)
}

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

// 数字相关
const default_sep = ','
/**
 * 金额格式化
 * 比如 3412000000.34 格式化后为 34_1200_0000.34
 */
const formatMoney = (num: any, sep = default_sep) => {
  const val = Number(num)
  if (!val) return num
  const cmps = String(val).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 {
  isNumberValue,
  isPositiveInt,
  toFixed2,
  formatAmount,
  trimZero,
  toPercent,
  formatMoney,
  deFormatMoney,
}
