function parseRequestDateFromId(id) {
  const match = String(id || '').match(/^REQ-(\d{4})-(\d{2})(\d{2})$/)

  if (!match) {
    return ''
  }

  const [, year, month, day] = match
  return `${year}-${month}-${day}`
}

function formatTripWindow(range) {
  const normalized = String(range || '')

  if (!normalized) {
    return '待补充'
  }

  if (normalized.includes('本月')) {
    return '本月申请'
  }

  if (normalized.includes('本周')) {
    return '本周申请'
  }

  if (normalized.includes('今天')) {
    return '今日申请'
  }

  return normalized
}

function mapApproval(status) {
  if (status === 'success') {
    return {
      node: '已完成归档',
      approval: '已完成',
      approvalTone: 'success',
      travel: '已完成行程',
      travelTone: 'success'
    }
  }

  if (status === 'danger') {
    return {
      node: '异常待复核',
      approval: '待处理',
      approvalTone: 'danger',
      travel: '存在异常',
      travelTone: 'danger'
    }
  }

  return {
    node: '财务审核中',
    approval: '审批中',
    approvalTone: 'info',
    travel: '待安排行程',
    travelTone: 'warning'
  }
}

export function normalizeRequestForUi(request) {
  if (!request) {
    return null
  }

  const applyTime = parseRequestDateFromId(request.id) || '2026-04-18'
  const reason = `${request.category || '差旅'}申请`
  const city = request.entity || '待补充'
  const period = formatTripWindow(request.range)
  const approvalState = mapApproval(request.status)

  return {
    ...request,
    reason,
    city,
    period,
    applyTime,
    node: approvalState.node,
    approval: approvalState.approval,
    approvalTone: approvalState.approvalTone,
    travel: approvalState.travel,
    travelTone: approvalState.travelTone
  }
}
