import dayjs from 'dayjs'
import { de } from 'element-plus/es/locales.mjs'

export function formatIsoToDateTime(isoStr) {
  // 处理 null/undefined 情况，避免报错
  if (!isoStr) return undefined
  // 替换 T 为空格，返回 "YYYY-MM-DD HH:mm:ss"
  return isoStr.replace('T', ' ')
}

const DATE_TIME_FORMAT = 'YYYY-MM-DD HH:mm:ss'
const DATE_FORMAT = 'YYYY-MM-DD'

export function formatToDateTime(date, format = DATE_TIME_FORMAT) {
  if (!date) return ''
  return dayjs(date).format(format)
}

export function formatToDate(date, format = DATE_FORMAT) {
  if (!date) return ''
  return dayjs(date).format(format)
}
export const getNowTime = (format = DATE_TIME_FORMAT) => {
  if (!date) return ''
  return dayjs().format(format)
}
/**
 * 更精确的年龄计算（精确到月日）
 * @param {string|Date} birthDate - 出生日期
 * @returns {number} 年龄
 */
export const calculateExactAge = birthDate => {
  if (!birthDate) return 0

  try {
    const birth = dayjs(birthDate)
    const today = dayjs()

    if (!birth.isValid() || birth.isAfter(today)) {
      return 0
    }

    let age = today.diff(birth, 'year')
    const remainder = today.diff(birth.add(age, 'year'), 'month')

    // 如果还没到今年的生日，年龄减1
    if (remainder < 0) {
      age--
    }

    return age > 0 ? age : 0
  } catch (error) {
    console.error('计算精确年龄时出错:', error)
    return 0
  }
}
export default {
  formatIsoToDateTime,
  formatToDateTime,
  formatToDate,
  getNowTime
}
