function toDate(value) {
  if (!value) {
    return null
  }

  const nextDate = new Date(value)
  return Number.isNaN(nextDate.getTime()) ? null : nextDate
}

export function extractDateText(value) {
  const matched = String(value || '').match(/\d{4}-\d{2}-\d{2}/)
  return matched ? matched[0] : ''
}

export function formatDocumentListTime(value) {
  const raw = String(value || '').trim()
  if (!raw || raw === '待补充') {
    return '待补充'
  }

  const date = toDate(raw)
  if (date) {
    const year = String(date.getFullYear())
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hour = String(date.getHours()).padStart(2, '0')
    const minute = String(date.getMinutes()).padStart(2, '0')
    return `${year}-${month}-${day} ${hour}:${minute}`
  }

  return raw.slice(0, 16)
}

export function resolveDocumentSortTime(value) {
  const date = toDate(value)
  return date ? date.getTime() : 0
}

export function formatDocumentDurationSince(value, now = Date.now()) {
  const startAt = toDate(value)
  if (!startAt) {
    return ''
  }

  const diffMs = Math.max(0, Number(now) - startAt.getTime())
  const totalMinutes = Math.floor(diffMs / (60 * 1000))
  if (totalMinutes < 1) {
    return '刚刚'
  }

  const days = Math.floor(totalMinutes / (24 * 60))
  const hours = Math.floor((totalMinutes % (24 * 60)) / 60)
  const minutes = totalMinutes % 60

  if (days > 0) {
    return hours > 0 ? `${days}天${hours}小时` : `${days}天`
  }

  if (hours > 0) {
    return minutes > 0 ? `${hours}小时${minutes}分钟` : `${hours}小时`
  }

  return `${minutes}分钟`
}

export function resolveDocumentStayTimeDisplay(row, now = Date.now()) {
  const currentStep = Array.isArray(row?.progressSteps)
    ? row.progressSteps.find((step) => step?.current)
    : null
  const stepTime = String(currentStep?.time || '').trim()
  if (stepTime.startsWith('停留')) {
    return stepTime.replace(/^停留\s*/, '') || '待计算'
  }

  const startedAt = row?.updatedAt || row?.submittedAt || row?.createdAt || row?.applyTime
  return formatDocumentDurationSince(startedAt, now) || '待计算'
}
