export const PercentFormat = (value) => {
  if (value == null) {
    return '+0%'
  } else if (value < 0) {
    return value + '%'
  } else if (value == '+∞') {
    return value
  } else if (value == '-∞') {
    return value
  } else {
    return '+' + value + '%'
  }
}

export const NumberFormat = (value) => {
  if (isNaN(value)) {
    return 0
  }
  const num = value.toString().split('.')
  const interCount = num[0].length
  if (interCount < 3) {
    return value
  }
  let index = 0
  let inter = ''
  for (let i = interCount - 3; i >= 0; i -= 3) {
    inter = num[0].substr(i, 3) + (inter == '' ? '' : ',') + inter
    index = i
  }
  if (index > 0) {
    inter = num[0].substr(0, index) + (inter == '' ? '' : ',') + inter
  }
  return inter + (num.length == 1 ? '' : '.' + num[1])
}

export const PwdFormat = (value) => {
  if (value == null) {
    return 'Null'
  } else {
    const len = value.toString().length
    let val = ''
    for (let i = 0; i < len; i++) {
      val = val + '*'
    }
    return val
  }
}
export const NumberDecimal = (value) => {
  let realVal = ''
  if (!isNaN(value) && value !== '') {
    // 截取当前数据到小数点后两位
    realVal = parseFloat(value).toFixed(2)
  } else {
    realVal = '--'
  }
  return realVal
}
/**
 * 格式化数字，添加千位分隔符
 * @param {string|number} value - 要格式化的值
 * @returns {string} 格式化后的字符串
 */
export const NumberFormatAll = (value) => {
  // 处理特殊值
  if (value === '***') {
    return '***'
  }

  const numValue = Number(value)
  if (isNaN(numValue)) {
    return '0'
  }

  // 处理0
  if (numValue === 0) {
    return '0'
  }

  const isNegative = numValue < 0
  const numStr = Math.abs(numValue).toString()
  const [integerPart, decimalPart] = numStr.split('.')

  // 如果整数部分长度小于3，直接返回
  if (integerPart.length < 3) {
    return (isNegative ? '-' : '') + numStr
  }

  // 格式化整数部分
  const formattedInteger = formatIntegerWithCommas(integerPart)

  // 组合结果
  const result = decimalPart ? `${formattedInteger}.${decimalPart}` : formattedInteger

  return (isNegative ? '-' : '') + result
}

/**
 * 为整数部分添加千位分隔符
 * @param {string} integerStr - 整数部分的字符串
 * @returns {string} 添加了千位分隔符的字符串
 */
const formatIntegerWithCommas = (integerStr) => {
  const parts = []
  let remaining = integerStr

  // 从右向左每3位一组
  while (remaining.length > 3) {
    parts.unshift(remaining.slice(-3))
    remaining = remaining.slice(0, -3)
  }

  // 添加剩余的部分
  if (remaining.length > 0) {
    parts.unshift(remaining)
  }

  return parts.join(',')
}
