import {
  DOCUMENT_TYPE_APPLICATION,
  buildOccurredDisplay,
  buildRiskMeta,
  formatDateTime,
  parseNumber,
  parseOptionalAmount,
  resolveApprovalMeta,
  resolveDisplayName,
  resolveDocumentTypeMeta,
  resolveTypeLabel,
  resolveWorkflowNode
} from './requestShared.js'
import { buildExpenseItems } from './requestExpenseItems.js'
import { resolveRelatedApplicationInfo } from './requestRelatedApplication.js'
import {
  buildProgressSteps,
  isApplicationArchivedWorkflow,
  resolveApplicationLinkedReimbursementNo
} from './requestProgressSteps.js'

export function mapExpenseClaimToRequest(claim) {
  const typeCode = String(claim?.expense_type || '').trim() || 'other'
  const typeLabel = resolveTypeLabel(typeCode)
  const documentTypeMeta = resolveDocumentTypeMeta(claim, typeCode)
  const isApplicationDocument = documentTypeMeta.documentTypeCode === DOCUMENT_TYPE_APPLICATION
  const approvalMeta = resolveApprovalMeta(claim?.status)
  const workflowNode = resolveWorkflowNode(claim, approvalMeta, isApplicationDocument)
  const applicationArchived = isApplicationDocument && isApplicationArchivedWorkflow(claim, workflowNode)
  const applicationLinkedReimbursementNo = isApplicationDocument ? resolveApplicationLinkedReimbursementNo(claim) : ''
  const applicationLinkStatusText = applicationLinkedReimbursementNo
    ? `关联中 ${applicationLinkedReimbursementNo}`
    : '未关联'
  const invoiceCount = Math.max(0, parseNumber(claim?.invoice_count))
  const riskMeta = buildRiskMeta(claim?.risk_flags_json)
  const riskSummary = riskMeta.summary
  const relatedApplication = isApplicationDocument ? null : resolveRelatedApplicationInfo(claim, typeLabel)
  const expenseItems = buildExpenseItems(claim, riskMeta)
  const visibleExpenseAmount = expenseItems.reduce((sum, item) => {
    const amount = parseOptionalAmount(item.reimbursableAmount) ?? parseNumber(item.itemAmount)
    return sum + amount
  }, 0)
  const amountValue = relatedApplication
    ? expenseItems.length
      ? visibleExpenseAmount
      : invoiceCount === 0
        ? 0
        : parseNumber(claim?.amount)
    : parseNumber(claim?.amount)
  const applyDateTime = claim?.submitted_at || claim?.created_at
  const employeeId = String(claim?.employee_id || claim?.employeeId || '').trim()
  const employeeName = String(claim?.employee_name || claim?.employeeName || '').trim()

  return {
    id: String(claim?.claim_no || claim?.id || '').trim(),
    claimNo: String(claim?.claim_no || claim?.id || '').trim(),
    claimId: String(claim?.id || '').trim(),
    status: String(claim?.status || '').trim(),
    employeeId,
    employee_id: employeeId,
    profileEmployeeId: employeeId || employeeName,
    person: String(claim?.employee_name || '').trim() || '待补充',
    dept: String(claim?.department_name || '').trim() || '待补充',
    departmentName: String(claim?.department_name || '').trim() || '待补充',
    employeeName: String(claim?.employee_name || '').trim() || '待补充',
    employeePosition: String(claim?.employee_position || '').trim(),
    employeeGrade: String(claim?.employee_grade || '').trim(),
    managerName: resolveDisplayName(claim?.manager_name),
    financeApproverName: resolveDisplayName(claim?.finance_approver_name, claim?.financeApproverName),
    financeOwnerName: resolveDisplayName(claim?.finance_owner_name, claim?.financeOwnerName),
    budgetApproverName: resolveDisplayName(claim?.budget_approver_name, claim?.budgetApproverName),
    budgetApproverGrade: String(claim?.budget_approver_grade || claim?.budgetApproverGrade || '').trim(),
    budgetApproverRoleCode: String(claim?.budget_approver_role_code || claim?.budgetApproverRoleCode || '').trim(),
    roleLabels: Array.isArray(claim?.role_labels) ? claim.role_labels.filter(Boolean) : [],
    entity: '',
    typeCode,
    typeLabel,
    ...documentTypeMeta,
    detailVariant: typeCode === 'travel' || typeCode === 'travel_application' ? 'travel' : 'general',
    title: String(claim?.reason || '').trim() || (isApplicationDocument ? typeLabel : `${typeLabel}报销`),
    sceneLabel: typeLabel,
    sceneTarget: String(claim?.location || '').trim() || '待补充',
    location: String(claim?.location || '').trim() || '待补充',
    relatedCustomer: '',
    occurredDisplay: buildOccurredDisplay(claim),
    occurredAt: claim?.occurred_at || '',
    applyTime: formatDateTime(applyDateTime) || '待补充',
    submittedAt: applyDateTime || '',
    createdAt: claim?.created_at || '',
    updatedAt: claim?.updated_at || '',
    amount: amountValue,
    riskFlags: Array.isArray(claim?.risk_flags_json) ? claim.risk_flags_json : [],
    riskTone: riskMeta.tone,
    riskLabel: riskMeta.label,
    invoiceCount,
    workflowNode,
    approvalKey: approvalMeta.key,
    approvalStatus: approvalMeta.label,
    approvalTone: approvalMeta.tone,
    secondaryStatusLabel: isApplicationDocument ? '申请材料' : (typeCode === 'travel' ? '行程状态' : '票据状态'),
    secondaryStatusValue: isApplicationDocument
      ? approvalMeta.key === 'supplement'
        ? '领导已退回，待重新提交'
        : applicationArchived
          ? '已归档'
          : approvalMeta.key === 'completed'
            ? applicationLinkStatusText
            : '已进入审批流程'
      : (invoiceCount > 0 ? `已关联 ${invoiceCount} 张票据` : '待上传票据'),
    secondaryStatusTone: isApplicationDocument
      ? approvalMeta.key === 'supplement'
        ? 'warning'
        : approvalMeta.key === 'completed' && !applicationArchived && !applicationLinkedReimbursementNo
          ? 'warning'
          : 'success'
      : (invoiceCount > 0 ? 'success' : 'warning'),
    riskSummary,
    attachmentSummary: isApplicationDocument ? '申请单' : (invoiceCount > 0 ? `${invoiceCount} 张票据` : '无'),
    expenseTableSummary: isApplicationDocument
      ? '预计金额已随申请提交'
      : expenseItems.length
      ? (invoiceCount > 0
        ? `共 ${expenseItems.length} 条费用明细，已关联 ${invoiceCount} 张票据`
        : `共 ${expenseItems.length} 条费用明细，待补充票据`)
      : '暂无费用明细',
    note: String(claim?.reason || '').trim(),
    relatedApplication,
    progressSteps: buildProgressSteps(approvalMeta, workflowNode, claim, {
      documentTypeCode: documentTypeMeta.documentTypeCode
    }),
    expenseItems
  }
}
