import Decimal from 'decimal.js'
import numeral from 'numeral'

// 把后端金额转换为实际金额，要除以 100，小数点直接去掉
export function formatFromCents(
  cents: number | undefined,
  precision: number = 0,
  isNumeral: boolean = true
): string | undefined {
  if (typeof cents !== 'number' || isNaN(cents)) return undefined
  const value = new Decimal(cents).div(100).toNumber()

  if (precision > 0) {
    if (isNumeral) {
      return numeral(value).format(`0,0.${new Array(precision).fill('0').join('')}`)
    }
    return value.toFixed(precision)
  }

  const integerValue = Math.floor(value)

  return isNumeral ? numeral(integerValue).format('0,0') : integerValue.toString()
}

export function formatToCents(value?: number): number | undefined {
  if (!value) return 0
  return new Decimal(value).mul(100).toNumber()
}
