function normalizeText(value) {
  return String(value || '').trim()
}

function isEmailLike(value) {
  return /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(normalizeText(value))
}

function resolveDisplayName(...values) {
  for (const value of values) {
    const normalized = normalizeText(value)
    if (normalized && !isEmailLike(normalized)) {
      return normalized
    }
  }
  return ''
}

function toDate(value) {
  if (!value) {
    return null
  }
  const nextDate = new Date(value)
  return Number.isNaN(nextDate.getTime()) ? null : nextDate
}

function formatDateTime(value) {
  const date = toDate(value)
  if (!date) {
    return ''
  }
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

function formatDateLabel(value) {
  const date = toDate(value)
  if (!date) {
    return ''
  }
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

function formatTimeLabel(value) {
  const date = toDate(value)
  if (!date) {
    return ''
  }
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${hours}:${minutes}`
}

function resolveApprovalRole(event, returned) {
  return resolveDisplayName(
    event?.operator_position,
    event?.operatorPosition,
    event?.operator_title,
    event?.operatorTitle,
    event?.approver_position,
    event?.approverPosition,
    event?.approval_role,
    event?.approvalRole,
    event?.previous_approval_stage,
    event?.previousApprovalStage
  ) || (returned ? '直属领导审批节点' : '直属领导')
}

function getRiskFlags(request) {
  const flags = request?.riskFlags || request?.risk_flags_json || []
  return Array.isArray(flags) ? flags : []
}

function getLatestEvent(events) {
  const sortedEvents = events
    .filter((item) => item && typeof item === 'object')
    .map((item) => ({ ...item, eventDate: toDate(item.created_at || item.createdAt) }))
    .filter((item) => item.eventDate)
    .sort((left, right) => left.eventDate.getTime() - right.eventDate.getTime())
  return sortedEvents.length ? sortedEvents[sortedEvents.length - 1] : null
}

function isLeaderApprovalEvent(flag) {
  const source = normalizeText(flag?.source)
  const eventType = normalizeText(flag?.event_type || flag?.eventType)
  const previousStage = normalizeText(flag?.previous_approval_stage || flag?.previousApprovalStage)
  const nextStage = normalizeText(flag?.next_approval_stage || flag?.nextApprovalStage)
  return (
    source === 'manual_approval'
    && (
      eventType === 'expense_application_approval'
      || previousStage.includes('直属领导')
      || previousStage.includes('领导审批')
      || nextStage.includes('财务')
      || nextStage.includes('审批完成')
    )
  )
}

function isLeaderReturnEvent(flag) {
  const source = normalizeText(flag?.source)
  const eventType = normalizeText(flag?.event_type || flag?.eventType)
  const returnStage = normalizeText(flag?.return_stage || flag?.returnStage || flag?.previous_approval_stage)
  const stageKey = normalizeText(flag?.return_stage_key || flag?.returnStageKey)
  return (
    source === 'manual_return'
    && (
      eventType === 'expense_application_return'
      || stageKey === 'direct_manager'
      || returnStage.includes('直属领导')
      || returnStage.includes('领导审批')
    )
  )
}

export function findLeaderApprovalEvent(request) {
  return getLatestEvent(getRiskFlags(request).filter(isLeaderApprovalEvent))
}

export function buildLeaderApprovalEvents(request) {
  return getRiskFlags(request)
    .filter((flag) => isLeaderApprovalEvent(flag) || isLeaderReturnEvent(flag))
    .map((event) => {
      const returned = isLeaderReturnEvent(event)
      const rawTime = event.created_at || event.createdAt
      const operator = resolveDisplayName(
        event.operator,
        event.operator_name,
        event.operatorName,
        request?.profileManager,
        request?.managerName
      ) || '直属领导'
      const time = formatDateTime(rawTime)
      const dateLabel = formatDateLabel(rawTime) || '待记录'
      const timeLabel = formatTimeLabel(rawTime)
      const opinion = normalizeText(event.opinion)
        || normalizeText(event.leader_opinion || event.leaderOpinion)
        || normalizeText(event.reason)
        || normalizeText(event.message)
        || (returned ? '已退回申请，请申请人补充后重新提交。' : '已审批通过。')
      const returnCount = Number(event.return_count || event.returnCount || 0)
      return {
        id: normalizeText(event.return_event_id || event.returnEventId || event.approval_event_id || event.approvalEventId)
          || `${returned ? 'return' : 'approval'}-${event.created_at || event.createdAt || opinion}`,
        type: returned ? 'returned' : 'approved',
        tone: returned ? 'danger' : 'success',
        title: returned ? '领导退回' : '领导审批通过',
        operator,
        role: resolveApprovalRole(event, returned),
        time,
        dateLabel,
        timeLabel,
        sortAt: rawTime,
        opinion,
        returnCount,
        meta: [operator ? `${operator}${returned ? '退回' : '通过'}` : '', time].filter(Boolean).join(' · ')
      }
    })
    .sort((left, right) => {
      const leftDate = toDate(left.sortAt)
      const rightDate = toDate(right.sortAt)
      if (!leftDate || !rightDate) return 0
      return leftDate.getTime() - rightDate.getTime()
    })
    .map(({ sortAt, ...event }) => event)
}

export function buildLeaderApprovalInfo(request) {
  const event = findLeaderApprovalEvent(request)
  if (!event) {
    return {
      opinion: '',
      operator: '',
      time: '',
      generatedDraftClaimNo: ''
    }
  }

  return {
    opinion: normalizeText(event.opinion) || normalizeText(event.message),
    operator: resolveDisplayName(
      event.operator,
      event.operator_name,
      event.operatorName,
      request?.profileManager,
      request?.managerName
    ),
    time: formatDateTime(event.created_at || event.createdAt),
    generatedDraftClaimNo: normalizeText(event.generated_draft_claim_no || event.generatedDraftClaimNo)
  }
}

export function resolveGeneratedDraftClaimNo(responsePayload) {
  const event = findLeaderApprovalEvent({
    riskFlags: responsePayload?.risk_flags_json || responsePayload?.riskFlags || []
  })
  return normalizeText(event?.generated_draft_claim_no || event?.generatedDraftClaimNo)
}
