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

function isProvided(value) {
  const text = normalizeText(value)
  return Boolean(text) && !['待补充', '暂无', '无', '未知'].includes(text)
}

function resolveApplicationDetailPayload(request = {}) {
  const flags = Array.isArray(request.risk_flags_json)
    ? request.risk_flags_json
    : Array.isArray(request.riskFlags)
      ? request.riskFlags
      : []
  const detailFlag = flags.find((flag) =>
    flag &&
    typeof flag === 'object' &&
    normalizeText(flag.source) === 'application_detail'
  )
  const detail = detailFlag?.application_detail || detailFlag?.applicationDetail || {}
  return detail && typeof detail === 'object' ? detail : {}
}

function pickDetailValue(detail, request, keys = [], fallback = '') {
  for (const key of keys) {
    const value = normalizeText(detail[key] ?? request[key])
    if (isProvided(value)) return value
  }
  return normalizeText(fallback)
}

function isTravelApplicationDetail(detail = {}, request = {}) {
  const typeText = [
    detail.application_type,
    detail.applicationType,
    request.typeCode,
    request.typeLabel,
    request.documentTypeLabel
  ].map(normalizeText).join(' ')
  return /travel_application|差旅|出差/.test(typeText)
}

function isEntertainmentApplicationDetail(detail = {}, request = {}) {
  const typeText = [
    detail.application_type,
    detail.applicationType,
    request.typeCode,
    request.typeLabel
  ].map(normalizeText).join(' ')
  return /entertainment|招待/.test(typeText)
}

function extractDateRange(value) {
  const dates = normalizeText(value).match(/\d{4}-\d{2}-\d{2}/g) || []
  return {
    startDate: dates[0] || '',
    endDate: dates[dates.length - 1] || ''
  }
}

function extractDayCount(value) {
  const match = normalizeText(value).replace(/\s+/g, '').match(/(\d{1,2})天/)
  return match ? Number(match[1]) || 0 : 0
}

function addDays(dateText, days) {
  if (!dateText || days <= 1) {
    return dateText
  }
  const date = new Date(`${dateText}T00:00:00`)
  if (Number.isNaN(date.getTime())) {
    return dateText
  }
  date.setDate(date.getDate() + days - 1)
  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 buildApplicationTimeRows(detail, request) {
  const timeValue = pickDetailValue(detail, request, ['time', 'occurredDisplay', 'period'], request.occurredDisplay)
  if (!isProvided(timeValue)) {
    return []
  }

  if (isTravelApplicationDetail(detail, request)) {
    const days = extractDayCount(pickDetailValue(detail, request, ['days']))
    const range = extractDateRange(timeValue)
    const startDate = range.startDate || timeValue
    const endDate = range.endDate && range.endDate !== range.startDate
      ? range.endDate
      : addDays(range.startDate, days)

    return [
      {
        key: 'trip_start_time',
        label: '出发时间',
        value: startDate
      },
      {
        key: 'trip_return_time',
        label: '返回时间',
        value: endDate
      }
    ]
  }

  return [
    {
      key: 'time',
      label: isEntertainmentApplicationDetail(detail, request) ? '招待时间' : '申请时间',
      value: timeValue
    }
  ]
}

export function buildApplicationDetailFactItems(request = {}) {
  const detail = resolveApplicationDetailPayload(request)
  const amountDisplay = normalizeText(request.amountDisplay || request.amount)
  const rows = [
    {
      key: 'application_type',
      label: '申请类型',
      value: pickDetailValue(detail, request, ['application_type', 'typeLabel'], request.typeLabel)
    },
    ...buildApplicationTimeRows(detail, request),
    {
      key: 'location',
      label: '地点',
      value: pickDetailValue(detail, request, ['location', 'sceneTarget', 'city'], request.sceneTarget)
    },
    {
      key: 'reason',
      label: '事由',
      value: pickDetailValue(detail, request, ['reason'], request.reason)
    },
    {
      key: 'days',
      label: '天数',
      value: pickDetailValue(detail, request, ['days'])
    },
    {
      key: 'transport_mode',
      label: '出行方式',
      value: pickDetailValue(detail, request, ['transport_mode'])
    },
    {
      key: 'grade',
      label: '职级',
      value: pickDetailValue(detail, request, ['grade', 'profileGrade', 'employee_grade'], request.profileGrade),
      highlight: true
    },
    {
      key: 'lodging_daily_cap',
      label: '住宿上限/天',
      value: pickDetailValue(detail, request, ['lodging_daily_cap']),
      highlight: true
    },
    {
      key: 'subsidy_daily_cap',
      label: '补贴标准/天',
      value: pickDetailValue(detail, request, ['subsidy_daily_cap']),
      highlight: true
    },
    {
      key: 'transport_policy',
      label: '交通费用口径',
      value: pickDetailValue(detail, request, ['transport_policy'], '车票、机票暂无实时价格接口，按真实票据实报实销')
    },
    {
      key: 'policy_estimate',
      label: '规则测算参考',
      value: pickDetailValue(detail, request, ['policy_estimate']),
      highlight: true
    },
    {
      key: 'amount',
      label: '用户预估费用',
      value: pickDetailValue(detail, request, ['amount'], amountDisplay),
      highlight: true,
      emphasis: true
    }
  ]

  return rows.filter((row) => isProvided(row.value))
}

export function buildRelatedApplicationFactItems(request = {}) {
  const related = request.relatedApplication || {}
  const relatedRange = extractDateRange(related.time)
  const relatedStartDate = normalizeText(related.tripStartDate) || relatedRange.startDate
  const relatedEndDate = normalizeText(related.tripEndDate) || relatedRange.endDate || addDays(
    relatedStartDate,
    extractDayCount(related.days)
  )
  const rows = [
    {
      key: 'claim_no',
      label: '关联单据单号',
      value: related.claimNo,
      highlight: true
    },
    {
      key: 'content',
      label: '申请内容',
      value: related.content
    },
    {
      key: 'trip_start_date',
      label: '出发时间',
      value: relatedStartDate
    },
    {
      key: 'trip_end_date',
      label: '返回时间',
      value: relatedEndDate
    },
    {
      key: 'days',
      label: '申请天数',
      value: related.days
    },
    {
      key: 'reason',
      label: '申请事由',
      value: related.reason
    },
    {
      key: 'location',
      label: '申请地点',
      value: related.location
    },
    {
      key: 'transport_mode',
      label: '出行方式',
      value: related.transportMode
    },
    {
      key: 'lodging_daily_cap',
      label: '住宿上限/天',
      value: related.lodgingDailyCap,
      highlight: true
    },
    {
      key: 'subsidy_daily_cap',
      label: '补贴标准/天',
      value: related.subsidyDailyCap,
      highlight: true
    },
    {
      key: 'transport_policy',
      label: '交通费用口径',
      value: related.transportPolicy
    },
    {
      key: 'policy_estimate',
      label: '规则测算参考',
      value: related.policyEstimate,
      highlight: true
    },
    {
      key: 'rule',
      label: '规则依据',
      value: related.ruleLabel
    },
    {
      key: 'amount',
      label: '预计金额',
      value: related.amountLabel,
      highlight: true,
      emphasis: true
    }
  ]

  return rows.filter((row) => isProvided(row.value))
}
