import { computed, ref } from 'vue'

export function createReceiptDetailDashboardModel({
  detailForm,
  formatDateTime,
  formatScore,
  selectedReceipt
}) {
  const previewZoom = ref(1)
  const previewRotation = ref(0)
  const previewTransform = computed(() => `scale(${previewZoom.value}) rotate(${previewRotation.value}deg)`)
  const previewPageLabel = computed(() => {
    const pageCount = Number(selectedReceipt.value?.page_count || 1)
    return `1 / ${Number.isFinite(pageCount) && pageCount > 0 ? pageCount : 1}`
  })
  const basicInfoItems = computed(() => [
    { label: '票据类型', value: fallback(detailForm.document_type_label) },
    { label: '票据名称', value: fallback(detailForm.file_name) },
    { label: '金额', value: fallback(detailForm.amount) },
    { label: '票据日期', value: fallback(detailForm.document_date) },
    { label: '提交人', value: fallback(selectedReceipt.value?.owner_name || selectedReceipt.value?.owner || '当前用户') },
    { label: '上传时间', value: formatDateTime(selectedReceipt.value?.uploaded_at) },
    { label: '所属单据编号', value: fallback(selectedReceipt.value?.linked_claim_no, '未关联') },
    { label: 'OCR 置信度', value: formatScore(selectedReceipt.value?.avg_score) }
  ])
  const linkedClaimItems = computed(() => [
    { label: '关联状态', value: selectedReceipt.value?.status === 'linked' ? '已关联' : '未关联' },
    { label: '报销单编号', value: fallback(selectedReceipt.value?.linked_claim_no, '未关联') },
    { label: '报销单名称', value: linkedClaimName.value },
    { label: '费用类型', value: fallback(detailForm.scene_label) },
    { label: '关联时间', value: formatDateTime(selectedReceipt.value?.linked_at) },
    { label: '关联附件数量', value: selectedReceipt.value?.status === 'linked' ? '1' : '0' }
  ])
  const linkedClaimName = computed(() => (
    selectedReceipt.value?.linked_claim_no
      ? `${fallback(detailForm.scene_label)}票据归集`
      : '暂未关联报销单'
  ))

  function adjustPreviewZoom(delta) {
    previewZoom.value = Math.min(1.8, Math.max(0.6, Number((previewZoom.value + delta).toFixed(2))))
  }

  function resetPreviewView() {
    previewZoom.value = 1
    previewRotation.value = 0
  }

  function rotatePreview() {
    previewRotation.value = (previewRotation.value + 90) % 360
  }

  return {
    adjustPreviewZoom,
    basicInfoItems,
    linkedClaimItems,
    previewPageLabel,
    previewRotation,
    previewTransform,
    previewZoom,
    resetPreviewView,
    rotatePreview
  }
}

function fallback(value, empty = '待补充') {
  const text = String(value || '').trim()
  return text || empty
}
