// 格式化工具函数

/**
 * 格式化时间
 * @param {number|string|Date} timestamp 时间戳或时间字符串
 * @param {string} format 格式化模板
 * @returns {string} 格式化后的时间字符串
 */
export function formatTime(timestamp, format = 'YYYY-MM-DD HH:mm:ss') {
  if (!timestamp) return ''
  
  const date = new Date(timestamp)
  
  if (isNaN(date.getTime())) {
    return ''
  }
  
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()
  
  return format
    .replace('YYYY', year)
    .replace('MM', month.toString().padStart(2, '0'))
    .replace('DD', day.toString().padStart(2, '0'))
    .replace('HH', hour.toString().padStart(2, '0'))
    .replace('mm', minute.toString().padStart(2, '0'))
    .replace('ss', second.toString().padStart(2, '0'))
}

/**
 * 格式化日期
 * @param {number|string|Date} timestamp 时间戳或时间字符串
 * @param {string} format 格式化模板
 * @returns {string} 格式化后的日期字符串
 */
export function formatDate(timestamp, format = 'YYYY-MM-DD') {
  return formatTime(timestamp, format)
}

/**
 * 相对时间格式化
 * @param {number|string|Date} timestamp 时间戳
 * @returns {string} 相对时间字符串
 */
export function formatRelativeTime(timestamp) {
  if (!timestamp) return ''
  
  const date = new Date(timestamp)
  const now = new Date()
  const diff = now - date
  
  if (diff < 0) {
    return '未来时间'
  }
  
  const minute = 60 * 1000
  const hour = 60 * minute
  const day = 24 * hour
  const week = 7 * day
  const month = 30 * day
  const year = 365 * day
  
  if (diff < minute) {
    return '刚刚'
  } else if (diff < hour) {
    return `${Math.floor(diff / minute)}分钟前`
  } else if (diff < day) {
    return `${Math.floor(diff / hour)}小时前`
  } else if (diff < week) {
    return `${Math.floor(diff / day)}天前`
  } else if (diff < month) {
    return `${Math.floor(diff / week)}周前`
  } else if (diff < year) {
    return `${Math.floor(diff / month)}个月前`
  } else {
    return `${Math.floor(diff / year)}年前`
  }
}

/**
 * 格式化数字
 * @param {number} number 数字
 * @param {number} decimals 小数位数
 * @param {string} thousandsSeparator 千位分隔符
 * @param {string} decimalSeparator 小数分隔符
 * @returns {string} 格式化后的数字字符串
 */
export function formatNumber(number, decimals = 2, thousandsSeparator = ',', decimalSeparator = '.') {
  if (isNaN(number) || number === null || number === undefined) {
    return '0'
  }
  
  const num = parseFloat(number)
  const parts = num.toFixed(decimals).split('.')
  
  // 添加千位分隔符
  parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, thousandsSeparator)
  
  return parts.join(decimalSeparator)
}

/**
 * 格式化货币
 * @param {number} amount 金额
 * @param {string} currency 货币符号
 * @param {number} decimals 小数位数
 * @returns {string} 格式化后的货币字符串
 */
export function formatCurrency(amount, currency = '¥', decimals = 2) {
  const formattedAmount = formatNumber(amount, decimals)
  return `${currency}${formattedAmount}`
}

/**
 * 格式化百分比
 * @param {number} value 数值
 * @param {number} decimals 小数位数
 * @returns {string} 格式化后的百分比字符串
 */
export function formatPercentage(value, decimals = 2) {
  if (isNaN(value) || value === null || value === undefined) {
    return '0%'
  }
  
  return `${(value * 100).toFixed(decimals)}%`
}

/**
 * 格式化文件大小
 * @param {number} bytes 字节数
 * @param {number} decimals 小数位数
 * @returns {string} 格式化后的文件大小字符串
 */
export function formatFileSize(bytes, decimals = 2) {
  if (bytes === 0) return '0 B'
  
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  
  return `${parseFloat((bytes / Math.pow(k, i)).toFixed(decimals))} ${sizes[i]}`
}

/**
 * 格式化手机号
 * @param {string} phone 手机号
 * @param {string} separator 分隔符
 * @returns {string} 格式化后的手机号
 */
export function formatPhone(phone, separator = ' ') {
  if (!phone) return ''
  
  const cleanPhone = phone.replace(/\D/g, '')
  
  if (cleanPhone.length === 11) {
    return `${cleanPhone.slice(0, 3)}${separator}${cleanPhone.slice(3, 7)}${separator}${cleanPhone.slice(7)}`
  }
  
  return phone
}

/**
 * 隐藏手机号中间4位
 * @param {string} phone 手机号
 * @returns {string} 隐藏后的手机号
 */
export function hidePhone(phone) {
  if (!phone) return ''
  
  const cleanPhone = phone.replace(/\D/g, '')
  
  if (cleanPhone.length === 11) {
    return `${cleanPhone.slice(0, 3)}****${cleanPhone.slice(7)}`
  }
  
  return phone
}

/**
 * 格式化身份证号
 * @param {string} idCard 身份证号
 * @returns {string} 格式化后的身份证号
 */
export function formatIdCard(idCard) {
  if (!idCard) return ''
  
  const cleanIdCard = idCard.replace(/\s/g, '')
  
  if (cleanIdCard.length === 18) {
    return `${cleanIdCard.slice(0, 6)} ${cleanIdCard.slice(6, 14)} ${cleanIdCard.slice(14)}`
  } else if (cleanIdCard.length === 15) {
    return `${cleanIdCard.slice(0, 6)} ${cleanIdCard.slice(6, 12)} ${cleanIdCard.slice(12)}`
  }
  
  return idCard
}

/**
 * 隐藏身份证号中间部分
 * @param {string} idCard 身份证号
 * @returns {string} 隐藏后的身份证号
 */
export function hideIdCard(idCard) {
  if (!idCard) return ''
  
  const cleanIdCard = idCard.replace(/\s/g, '')
  
  if (cleanIdCard.length === 18) {
    return `${cleanIdCard.slice(0, 6)}********${cleanIdCard.slice(14)}`
  } else if (cleanIdCard.length === 15) {
    return `${cleanIdCard.slice(0, 6)}*****${cleanIdCard.slice(11)}`
  }
  
  return idCard
}

/**
 * 格式化银行卡号
 * @param {string} cardNumber 银行卡号
 * @param {string} separator 分隔符
 * @returns {string} 格式化后的银行卡号
 */
export function formatBankCard(cardNumber, separator = ' ') {
  if (!cardNumber) return ''
  
  const cleanNumber = cardNumber.replace(/\D/g, '')
  
  return cleanNumber.replace(/(.{4})/g, `$1${separator}`).trim()
}

/**
 * 隐藏银行卡号中间部分
 * @param {string} cardNumber 银行卡号
 * @returns {string} 隐藏后的银行卡号
 */
export function hideBankCard(cardNumber) {
  if (!cardNumber) return ''
  
  const cleanNumber = cardNumber.replace(/\D/g, '')
  
  if (cleanNumber.length >= 8) {
    return `${cleanNumber.slice(0, 4)} **** **** ${cleanNumber.slice(-4)}`
  }
  
  return cardNumber
}

/**
 * 格式化地址
 * @param {object} address 地址对象
 * @returns {string} 格式化后的地址字符串
 */
export function formatAddress(address) {
  if (!address) return ''
  
  const parts = []
  
  if (address.province) parts.push(address.province)
  if (address.city) parts.push(address.city)
  if (address.district) parts.push(address.district)
  if (address.street) parts.push(address.street)
  if (address.detail) parts.push(address.detail)
  
  return parts.join('')
}

/**
 * 截断文本
 * @param {string} text 文本
 * @param {number} length 最大长度
 * @param {string} suffix 后缀
 * @returns {string} 截断后的文本
 */
export function truncateText(text, length = 50, suffix = '...') {
  if (!text) return ''
  
  if (text.length <= length) {
    return text
  }
  
  return text.slice(0, length) + suffix
}

/**
 * 首字母大写
 * @param {string} str 字符串
 * @returns {string} 首字母大写的字符串
 */
export function capitalize(str) {
  if (!str) return ''
  
  return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase()
}

/**
 * 驼峰转下划线
 * @param {string} str 驼峰字符串
 * @returns {string} 下划线字符串
 */
export function camelToSnake(str) {
  if (!str) return ''
  
  return str.replace(/([A-Z])/g, '_$1').toLowerCase()
}

/**
 * 下划线转驼峰
 * @param {string} str 下划线字符串
 * @returns {string} 驼峰字符串
 */
export function snakeToCamel(str) {
  if (!str) return ''
  
  return str.replace(/_([a-z])/g, (match, letter) => letter.toUpperCase())
}

/**
 * 格式化距离
 * @param {number} distance 距离（米）
 * @returns {string} 格式化后的距离字符串
 */
export function formatDistance(distance) {
  if (isNaN(distance) || distance < 0) {
    return '未知距离'
  }
  
  if (distance < 1000) {
    return `${Math.round(distance)}m`
  } else {
    return `${(distance / 1000).toFixed(1)}km`
  }
}

/**
 * 格式化重量
 * @param {number} weight 重量（克）
 * @param {string} unit 单位
 * @returns {string} 格式化后的重量字符串
 */
export function formatWeight(weight, unit = 'auto') {
  if (isNaN(weight) || weight < 0) {
    return '0g'
  }
  
  if (unit === 'auto') {
    if (weight < 1000) {
      return `${Math.round(weight)}g`
    } else if (weight < 1000000) {
      return `${(weight / 1000).toFixed(1)}kg`
    } else {
      return `${(weight / 1000000).toFixed(1)}t`
    }
  }
  
  switch (unit) {
    case 'g':
      return `${Math.round(weight)}g`
    case 'kg':
      return `${(weight / 1000).toFixed(1)}kg`
    case 't':
      return `${(weight / 1000000).toFixed(1)}t`
    default:
      return `${weight}${unit}`
  }
}

/**
 * 格式化温度
 * @param {number} temperature 温度
 * @param {string} unit 单位（C/F）
 * @returns {string} 格式化后的温度字符串
 */
export function formatTemperature(temperature, unit = 'C') {
  if (isNaN(temperature)) {
    return '--°C'
  }
  
  const temp = parseFloat(temperature).toFixed(1)
  return `${temp}°${unit}`
}

/**
 * 格式化湿度
 * @param {number} humidity 湿度
 * @returns {string} 格式化后的湿度字符串
 */
export function formatHumidity(humidity) {
  if (isNaN(humidity)) {
    return '--%'
  }
  
  return `${Math.round(humidity)}%`
}

// 默认导出所有格式化函数
export default {
  formatTime,
  formatDate,
  formatRelativeTime,
  formatNumber,
  formatCurrency,
  formatPercentage,
  formatFileSize,
  formatPhone,
  hidePhone,
  formatIdCard,
  hideIdCard,
  formatBankCard,
  hideBankCard,
  formatAddress,
  truncateText,
  capitalize,
  camelToSnake,
  snakeToCamel,
  formatDistance,
  formatWeight,
  formatTemperature,
  formatHumidity
}