const textWidthMap = new Map()
textWidthMap.set(3, 42)

/**
 * @description 根据
 * @param {string} text 变更后的文字
 */
export const getTextWidth = (text) => {
  function calcContainerWidth(text) {
    const tempSpan = document.createElement('span')
    tempSpan.style.visibility = 'hidden'
    tempSpan.style.whiteSpace = 'nowrap'
    tempSpan.innerText = text
    document.body.appendChild(tempSpan)
    const containerWidth = tempSpan.offsetWidth
    document.body.removeChild(tempSpan)
    return containerWidth
  }

  text = text + ''
  const len = text.length
  const cacheWidth = textWidthMap.get(len)
  return (cacheWidth || calcContainerWidth(text)) + 48
}



/**
 * 大数转换
 * @param {number} 要转换的数字
 */
export const formatBigNumber = (number, decimalPlaces = 2) => {
  if (typeof number !== 'number' && typeof number !== 'string') {
    return console.warn(`Input must be a number or a string representation of a number. but get ${typeof number}`)
  }
  number = parseFloat(number)
  if (Math.abs(number) < 10000) {
    return { count: number.toFixed(decimalPlaces), unit: '' }
  }
  const units = ['', '万', '亿']
  const unitIndex = Math.floor((parseInt(number).toString().length - 1) / 4)
  const unit = units[Math.min(unitIndex, 2)]
  let result
  if (unitIndex > 0) {
    result = (number / Math.pow(10, unitIndex * 4)).toFixed(decimalPlaces)
  } else {
    result = number.toFixed(decimalPlaces)
  }
  return {
    count: result,
    unit
  }
}

/**
 * 简单生成id
 */
const uniqueIds = new Set()

export const generateUniqueId = () => {
  let id
  do {
    id = 'id-' + Math.random().toString(36).substr(2, 9)
  } while (uniqueIds.has(id))
  uniqueIds.add(id)
  return id
}