function normalizeSortTime(value) {
  const time = Number(value)
  return Number.isFinite(time) ? time : 0
}

export function compareDocumentRowsByLatestTime(left, right) {
  const latestDiff = normalizeSortTime(right?.sortTime) - normalizeSortTime(left?.sortTime)
  if (latestDiff !== 0) {
    return latestDiff
  }

  const createdDiff = normalizeSortTime(right?.createdSortTime) - normalizeSortTime(left?.createdSortTime)
  if (createdDiff !== 0) {
    return createdDiff
  }

  const rightKey = String(right?.documentKey || right?.documentNo || '').trim()
  const leftKey = String(left?.documentKey || left?.documentNo || '').trim()
  return rightKey.localeCompare(leftKey, 'zh-CN')
}

export function sortDocumentRowsByLatestTime(rows) {
  return (Array.isArray(rows) ? [...rows] : []).sort(compareDocumentRowsByLatestTime)
}
