<template>
  <section class="receipt-folder-page">
    <article v-if="!detailMode" class="receipt-folder-list documents-list panel">
      <nav class="status-tabs receipt-status-tabs" aria-label="票据关联状态">
        <button
          v-for="tab in receiptTabs"
          :key="tab.value"
          type="button"
          :class="{ active: activeStatus === tab.value }"
          @click="switchStatus(tab.value)"
        >
          <span>{{ tab.label }}</span>
          <span v-if="tab.count > 0" class="scope-tab-badge">{{ tab.count > 99 ? '99+' : tab.count }}</span>
        </button>
      </nav>

      <div class="document-toolbar">
        <div class="filter-set">
          <div class="list-search">
            <i class="mdi mdi-magnify"></i>
            <input v-model="keyword" type="search" placeholder="搜索文件名、票据类型、金额、关联单号..." />
          </div>
          <DocumentDropdownFilter
            v-for="control in receiptFilterControls"
            :id="control.key"
            :key="control.key"
            :active-filter-key="openReceiptFilterKey"
            :label="resolveReceiptFilterLabel(control)"
            :title="control.label"
            :options="control.options"
            :selected-value="receiptFilters[control.key]"
            @toggle="toggleReceiptFilter"
            @select="selectReceiptFilter(control.key, $event)"
          />
          <button v-if="hasActiveReceiptFilters" class="filter-btn clear-filter-btn" type="button" @click="clearReceiptFilters">
            <i class="mdi mdi-filter-remove-outline"></i>
            <span>清空筛选</span>
          </button>
        </div>

        <div class="document-actions">
          <button
            class="create-request-btn"
            type="button"
            :disabled="!unlinkedReceipts.length"
            @click="openAssociateDialog"
          >
            <i class="mdi mdi-link-variant-plus"></i>
            <span>一键关联票据</span>
          </button>
        </div>
      </div>

      <div class="table-wrap" :class="{ 'is-empty': showEmpty }">
        <div v-if="loading" class="table-state">
          <TableLoadingState
            title="票据夹加载中"
            message="正在读取已上传票据、OCR 信息与关联状态"
            icon="mdi mdi-receipt-text-outline"
            floating
          />
        </div>

        <div v-else-if="error" class="table-state error">
          <i class="mdi mdi-alert-circle-outline"></i>
          <strong>票据夹加载失败</strong>
          <p>{{ error }}</p>
          <button class="retry-btn" type="button" @click="reloadReceipts">重新加载</button>
        </div>

        <TableEmptyState
          v-else-if="showEmpty"
          eyebrow="票据夹"
          :title="emptyTitle"
          :description="emptyDesc"
          icon="mdi mdi-receipt-text-outline"
          tone="theme"
          art-label="RECEIPT"
          :tips="emptyTips"
        />

        <table v-else>
          <colgroup>
            <col class="col-file">
            <col class="col-kind">
            <col class="col-scene">
            <col class="col-money">
            <col class="col-date">
            <col class="col-score">
            <col v-if="showStatusColumn" class="col-status">
            <col class="col-updated">
          </colgroup>
          <thead>
            <tr>
              <th>票据文件</th>
              <th>识别类型</th>
              <th>费用场景</th>
              <th>金额</th>
              <th>票据日期</th>
              <th>置信度</th>
              <th v-if="showStatusColumn">关联状态</th>
              <th>上传时间</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="row in visibleRows" :key="row.id" @click="openDetail(row)">
              <td data-label="票据文件">
                <strong class="doc-id">{{ row.file_name }}</strong>
                <small>{{ row.summary || '暂无摘要' }}</small>
              </td>
              <td data-label="识别类型"><span class="doc-kind-tag reimbursement">{{ row.document_type_label }}</span></td>
              <td data-label="费用场景"><span class="type-tag neutral">{{ row.scene_label }}</span></td>
              <td data-label="金额">{{ row.amount || '待补充' }}</td>
              <td data-label="票据日期">{{ row.document_date || '待补充' }}</td>
              <td data-label="置信度">{{ formatScore(row.avg_score) }}</td>
              <td v-if="showStatusColumn" data-label="关联状态">
                <span class="status-tag" :class="row.status === 'linked' ? 'completed' : 'warning'">
                  {{ row.status_label }}
                </span>
              </td>
              <td data-label="上传时间">{{ formatDateTime(row.uploaded_at) }}</td>
            </tr>
          </tbody>
        </table>
      </div>

      <EnterprisePagination
        v-if="showTable"
        :current-page="currentPage"
        :page-size="pageSize"
        :page-size-options="pageSizeOptions"
        :summary="pageSummary"
        :total-pages="totalPages"
        @page-size-change="changePageSize"
        @update:current-page="currentPage = $event"
      />
    </article>

    <EnterpriseDetailPage
      v-else
      variant="receipt-folder-detail"
      back-label="返回票据夹"
      :loading="detailLoading"
      loading-title="票据详情加载中"
      loading-message="正在读取票据源文件与 OCR 元数据"
      loading-icon="mdi mdi-receipt-text-outline"
      @back="backToList"
    >
      <template #main>
        <EnterpriseDetailCard class="receipt-preview-panel" title="票据预览">
          <div class="receipt-preview-frame">
            <div class="receipt-preview-box">
              <img
                v-if="previewKind === 'image' && previewObjectUrl"
                :src="previewObjectUrl"
                :style="{ transform: previewTransform }"
                alt="票据预览"
              />
              <iframe v-else-if="previewKind === 'pdf' && previewObjectUrl" :src="previewFrameUrl" title="票据 PDF 预览"></iframe>
              <div v-else class="preview-empty">
                <i class="mdi mdi-file-eye-outline"></i>
                <strong>当前文件暂不支持内嵌预览</strong>
                <p>请确认源文件是否支持预览，或重新上传清晰图片/PDF。</p>
              </div>
            </div>
          </div>

          <footer class="receipt-preview-tools" aria-label="票据预览工具">
            <span class="preview-page">{{ previewPageLabel }}</span>
            <div class="preview-tool-group">
              <button type="button" :disabled="previewZoom <= 0.6" aria-label="缩小预览" @click="adjustPreviewZoom(-0.1)">
                <i class="mdi mdi-minus"></i>
              </button>
              <strong>{{ Math.round(previewZoom * 100) }}%</strong>
              <button type="button" :disabled="previewZoom >= 1.8" aria-label="放大预览" @click="adjustPreviewZoom(0.1)">
                <i class="mdi mdi-plus"></i>
              </button>
            </div>
            <div class="preview-tool-group">
              <button type="button" aria-label="重置预览" @click="resetPreviewView">
                <i class="mdi mdi-refresh"></i>
              </button>
              <button type="button" aria-label="旋转预览" @click="rotatePreview">
                <i class="mdi mdi-rotate-right"></i>
              </button>
            </div>
          </footer>

          <section class="receipt-edit-log-section">
            <header>
              <strong>用户编辑操作</strong>
              <span>{{ receiptEditLogs.length }} 条</span>
            </header>
            <ol v-if="receiptEditLogs.length" class="receipt-edit-log-list">
              <li v-for="log in receiptEditLogs" :key="`${log.operated_at}-${log.operator}`">
                <div class="receipt-edit-log-meta">
                  <strong>{{ log.operator || '当前用户' }}</strong>
                  <span>{{ formatDateTime(log.operated_at) }}</span>
                </div>
                <p v-for="change in log.changes" :key="`${change.key}-${change.before}-${change.after}`">
                  <span>{{ change.label || change.key }}</span>
                  <em>{{ change.before || '空' }}</em>
                  <i class="mdi mdi-arrow-right"></i>
                  <strong>{{ change.after || '空' }}</strong>
                </p>
              </li>
            </ol>
            <div v-else class="receipt-edit-log-empty">
              <i class="mdi mdi-history"></i>
              <span>暂无用户修改记录。</span>
            </div>
          </section>
        </EnterpriseDetailCard>
      </template>

      <template #side>
        <EnterpriseDetailCard class="receipt-ticket-info-panel" title="识别票据详情">
          <template #actions>
            <div class="receipt-card-actions">
              <button v-if="!receiptInfoEditing" class="minor-action" type="button" @click="startReceiptInfoEdit">
                <i class="mdi mdi-pencil-outline"></i>
                <span>编辑</span>
              </button>
              <template v-else>
                <button class="minor-action" type="button" :disabled="savingDetail" @click="cancelReceiptInfoEdit">
                  <span>取消</span>
                </button>
                <button class="major-action" type="button" :disabled="savingDetail" @click="saveDetail">
                  <i class="mdi mdi-content-save-outline"></i>
                  <span>{{ savingDetail ? '保存中' : '保存' }}</span>
                </button>
              </template>
            </div>
          </template>

          <div class="receipt-static-grid">
            <div v-for="item in basicInfoItems" :key="item.label" class="receipt-static-item">
              <span>{{ item.label }}</span>
              <strong>{{ item.value }}</strong>
            </div>
          </div>

          <section class="receipt-ticket-section">
            <div class="receipt-section-head">
              <strong>识别字段</strong>
              <small>{{ detailForm.fields.length }} 项</small>
            </div>

            <div v-if="detailForm.fields.length" class="receipt-all-field-grid" :class="{ editing: receiptInfoEditing }">
              <label v-for="field in detailForm.fields" :key="field.key || field.label" class="receipt-ocr-field">
                <span>{{ field.label || field.key }}</span>
                <input
                  v-if="receiptInfoEditing"
                  v-model="field.value"
                  type="text"
                  placeholder="字段值"
                  @input="syncEditableFieldsToTopLevel"
                />
                <strong v-else>{{ field.value || '待补全' }}</strong>
              </label>
            </div>
            <div v-else class="receipt-field-empty">
              <i class="mdi mdi-information-outline"></i>
              <span>暂无可展示的 OCR 识别字段。</span>
            </div>
          </section>
        </EnterpriseDetailCard>
      </template>

      <template #bottom>
        <EnterpriseDetailCard class="receipt-association-panel" title="关联信息">
          <template #actions>
            <button
              v-if="selectedReceipt?.status !== 'linked'"
              class="minor-action"
              type="button"
              @click="openAssociateDialogForCurrentReceipt"
            >
              <i class="mdi mdi-link-variant-plus"></i>
              <span>关联单据</span>
            </button>
          </template>

          <div class="receipt-data-list association">
            <div v-for="item in linkedClaimItems" :key="item.label" class="receipt-data-item">
              <span>{{ item.label }}</span>
              <strong>{{ item.value }}</strong>
            </div>
          </div>
        </EnterpriseDetailCard>
      </template>

      <template #actions>
        <button class="minor-action danger-action" type="button" :disabled="deleting" @click="deleteCurrentReceipt">
          <i class="mdi mdi-delete-outline"></i>
          <span>{{ deleting ? '删除中' : '删除票据' }}</span>
        </button>
      </template>
    </EnterpriseDetailPage>

    <ElDialog
      v-model="associateDialogOpen"
      class="receipt-associate-dialog"
      title="一键关联票据"
      width="680px"
      append-to-body
    >
      <section v-if="associateStep === 1" class="associate-step">
        <p class="associate-hint">选择需要归集的未关联票据。</p>
        <ElCheckboxGroup v-model="selectedReceiptIds" class="receipt-checkbox-list">
          <ElCheckbox v-for="receipt in unlinkedReceipts" :key="receipt.id" :label="receipt.id">
            <span>{{ receipt.file_name }}</span>
            <small>{{ receipt.document_type_label }} · {{ receipt.amount || '金额待补充' }}</small>
          </ElCheckbox>
        </ElCheckboxGroup>
      </section>

      <section v-else class="associate-step">
        <p class="associate-hint">选择未提交草稿，或基于票据新建一张报销单。</p>
        <div class="draft-choice-list">
          <label class="draft-choice" :class="{ active: targetDraftId === NEW_CLAIM_VALUE }">
            <input v-model="targetDraftId" type="radio" :value="NEW_CLAIM_VALUE" />
            <span>
              <strong>新建报销单</strong>
              <small>将选中的票据带入对话，由 AI 辅助填写信息。</small>
            </span>
          </label>
          <label
            v-for="draft in draftClaims"
            :key="draft.claimId"
            class="draft-choice"
            :class="{ active: targetDraftId === draft.claimId }"
          >
            <input v-model="targetDraftId" type="radio" :value="draft.claimId" />
            <span>
              <strong>{{ draft.claimNo }}</strong>
              <small>{{ draft.reason }} · {{ draft.amountDisplay }}</small>
            </span>
          </label>
        </div>
      </section>

      <template #footer>
        <button class="ghost-btn" type="button" @click="closeAssociateDialog">取消</button>
        <button v-if="associateStep === 2" class="ghost-btn" type="button" @click="associateStep = 1">上一步</button>
        <button
          class="apply-btn"
          type="button"
          :disabled="associateBusy || !canProceedAssociate"
          @click="handleAssociatePrimary"
        >
          {{ associatePrimaryLabel }}
        </button>
      </template>
    </ElDialog>
  </section>
</template>

<script setup>
import { computed, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue'
import { ElCheckbox, ElCheckboxGroup } from 'element-plus/es/components/checkbox/index.mjs'
import { ElDialog } from 'element-plus/es/components/dialog/index.mjs'

import DocumentDropdownFilter from '../components/shared/DocumentDropdownFilter.vue'
import EnterprisePagination from '../components/shared/EnterprisePagination.vue'
import EnterpriseDetailCard from '../components/shared/EnterpriseDetailCard.vue'
import EnterpriseDetailPage from '../components/shared/EnterpriseDetailPage.vue'
import TableEmptyState from '../components/shared/TableEmptyState.vue'
import TableLoadingState from '../components/shared/TableLoadingState.vue'
import { useToast } from '../composables/useToast.js'
import {
  REIMBURSEMENT_LIST_PREVIEW_PARAMS,
  extractExpenseClaimItems,
  fetchExpenseClaims
} from '../services/reimbursements.js'
import {
  buildReceiptFile,
  deleteReceiptFolderItem,
  fetchReceiptFolderAsset,
  fetchReceiptFolderDetail,
  fetchReceiptFolderItems,
  updateReceiptFolderItem
} from '../services/receiptFolder.js'
import { inferPreviewKindFromBlob } from '../utils/documentPreviewAssets.js'
import { createReceiptDetailDashboardModel } from './scripts/receiptFolderDetailDashboard.js'
import { createReceiptDetailFieldModel } from './scripts/receiptFolderDetailFields.js'
import {
  formatReceiptDateTime as formatDateTime,
  formatReceiptRecognitionScore as formatScore
} from './scripts/receiptFolderFormatting.js'
import { createReceiptFolderListFilterModel } from './scripts/receiptFolderListFilters.js'

const NEW_CLAIM_VALUE = '__new_claim__'
const pageSizeOptions = [10, 20, 50].map((size) => ({ label: `${size} 条/页`, value: size }))
const emit = defineEmits(['open-assistant', 'detail-open-change', 'detail-topbar-change'])
const { toast } = useToast()

const activeStatus = ref('all')
const keyword = ref('')
const receipts = ref([])
const loading = ref(false)
const error = ref('')
const currentPage = ref(1)
const pageSize = ref(20)
const selectedReceipt = ref(null)
const detailLoading = ref(false)
const savingDetail = ref(false)
const deleting = ref(false)
const previewObjectUrl = ref('')
const receiptInfoEditing = ref(false)
const associateDialogOpen = ref(false)
const associateStep = ref(1)
const selectedReceiptIds = ref([])
const targetDraftId = ref(NEW_CLAIM_VALUE)
const draftClaims = ref([])
const associateBusy = ref(false)

const detailForm = reactive({
  file_name: '',
  document_type: '',
  document_type_label: '',
  scene_code: '',
  scene_label: '',
  summary: '',
  amount: '',
  document_date: '',
  merchant_name: '',
  fields: []
})

const detailMode = computed(() => Boolean(selectedReceipt.value))
const unlinkedReceipts = computed(() => receipts.value.filter((item) => item.status !== 'linked'))
const linkedReceipts = computed(() => receipts.value.filter((item) => item.status === 'linked'))
const receiptTabs = computed(() => [
  { value: 'all', label: '全部', count: receipts.value.length },
  { value: 'unlinked', label: '未关联票据', count: unlinkedReceipts.value.length },
  { value: 'linked', label: '已关联票据', count: linkedReceipts.value.length }
])
const activeRows = computed(() => {
  if (activeStatus.value === 'linked') return linkedReceipts.value
  if (activeStatus.value === 'unlinked') return unlinkedReceipts.value
  return receipts.value
})
const showStatusColumn = computed(() => activeStatus.value !== 'linked')
const {
  filteredRows,
  hasActiveReceiptFilters,
  openReceiptFilterKey,
  receiptFilterControls,
  receiptFilters,
  clearReceiptFilters,
  resolveReceiptFilterLabel,
  selectReceiptFilter,
  toggleReceiptFilter
} = createReceiptFolderListFilterModel({ receipts, activeRows, keyword })
const totalPages = computed(() => Math.max(1, Math.ceil(filteredRows.value.length / pageSize.value)))
const pageSummary = computed(() => `共 ${filteredRows.value.length} 条，目前第 ${currentPage.value} / ${totalPages.value} 页`)
const visibleRows = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  return filteredRows.value.slice(start, start + pageSize.value)
})
const showEmpty = computed(() => !loading.value && !error.value && visibleRows.value.length === 0)
const showTable = computed(() => !loading.value && !error.value && visibleRows.value.length > 0)
const activeStatusLabel = computed(() => {
  if (activeStatus.value === 'linked') return '已关联票据'
  if (activeStatus.value === 'unlinked') return '未关联票据'
  return '全部票据'
})
const emptyTitle = computed(() => keyword.value.trim() ? '没有符合条件的票据' : `${activeStatusLabel.value}为空`)
const emptyDesc = computed(() => {
  if (activeStatus.value === 'linked') return '已关联到报销单的票据会显示在这里，方便后续回溯。'
  if (activeStatus.value === 'unlinked') return '上传并完成 OCR 的票据会先进入这里，稍后可以再关联到报销草稿。'
  return '上传并完成 OCR 的票据会统一进入票据夹，可按关联状态继续筛选。'
})
const emptyTips = computed(() => {
  if (activeStatus.value === 'linked') return ['可从报销明细或票据夹关联流程形成已关联票据', '点击票据可查看原始文件与识别字段']
  if (activeStatus.value === 'unlinked') return ['票据不会因为未立即建单而丢失', '可多选票据后一次性带入报销对话']
  return ['全部视图同时展示未关联和已关联票据', '可切换标签快速定位待处理票据']
})
const receiptDetailSubtitle = computed(() => {
  const receipt = selectedReceipt.value || {}
  const documentType = String(detailForm.document_type_label || receipt.document_type_label || '').trim()
  const scene = String(detailForm.scene_label || receipt.scene_label || '').trim()
  const merchant = String(detailForm.merchant_name || receipt.merchant_name || '').trim()
  const sceneLabel = scene && /^[（(].*[）)]$/.test(scene) ? scene : (scene ? `（${scene}）` : '')
  const parts = [documentType, sceneLabel, merchant].filter(Boolean)
  return parts.length
    ? parts.join('；')
    : (selectedReceipt.value?.summary || '核对并修正票据基础信息，后续关联报销单时会带入当前票据。')
})
const receiptDetailTitle = computed(() => (
  String(selectedReceipt.value?.file_name || detailForm.file_name || '').trim() || '票据详情'
))
const isTrainTicket = computed(() => {
  const type = String(detailForm.document_type || selectedReceipt.value?.document_type || '').trim().toLowerCase()
  const label = [
    detailForm.document_type_label,
    selectedReceipt.value?.document_type_label,
    detailForm.scene_label,
    selectedReceipt.value?.scene_label
  ].filter(Boolean).join('')
  return type === 'train_ticket' || /火车|高铁|动车|铁路|电子客票/.test(label)
})
const {
  buildDetailPayload,
  ensureEditableReceiptFields,
  syncEditableFieldsToTopLevel
} = createReceiptDetailFieldModel({ detailForm, isTrainTicket })
const {
  adjustPreviewZoom,
  basicInfoItems,
  linkedClaimItems,
  previewPageLabel,
  previewTransform,
  previewZoom,
  resetPreviewView,
  rotatePreview
} = createReceiptDetailDashboardModel({
  detailForm,
  formatDateTime,
  formatScore,
  selectedReceipt
})
const receiptDetailTopBarPayload = computed(() => (
  detailMode.value
    ? {
        view: {
          eyebrow: '票据详情',
          title: receiptDetailTitle.value,
          desc: receiptDetailSubtitle.value
        },
        alerts: [],
        kpis: []
      }
    : null
))
const previewKind = computed(() => selectedReceipt.value?.preview_kind || '')
const previewFrameUrl = computed(() => (
  previewKind.value === 'pdf' && previewObjectUrl.value
    ? `${previewObjectUrl.value}#toolbar=0&navpanes=0&view=Fit`
    : previewObjectUrl.value
))
const receiptEditLogs = computed(() => {
  const logs = selectedReceipt.value?.edit_logs || selectedReceipt.value?.editLogs || []
  return Array.isArray(logs) ? logs : []
})
const canProceedAssociate = computed(() => (
  associateStep.value === 1
    ? selectedReceiptIds.value.length > 0
    : Boolean(targetDraftId.value)
))
const associatePrimaryLabel = computed(() => {
  if (associateBusy.value) return '处理中'
  return associateStep.value === 1 ? '下一步' : '进入关联对话'
})

watch([
  activeStatus,
  keyword,
  pageSize,
  () => receiptFilters.documentType,
  () => receiptFilters.scene,
  () => receiptFilters.month,
  () => receiptFilters.quality
], () => {
  currentPage.value = 1
})

watch(detailMode, (value) => {
  emit('detail-open-change', value)
}, { immediate: true })

watch(receiptDetailTopBarPayload, (payload) => {
  emit('detail-topbar-change', payload)
}, { immediate: true })

onMounted(() => {
  void reloadReceipts()
})

onBeforeUnmount(() => {
  revokePreviewUrl()
})

function switchStatus(status) {
  activeStatus.value = status
}

function changePageSize(size) {
  pageSize.value = Number(size) || pageSize.value
  currentPage.value = 1
}

async function reloadReceipts() {
  loading.value = true
  error.value = ''
  try {
    receipts.value = await fetchReceiptFolderItems('all')
  } catch (err) {
    error.value = err?.message || '票据夹加载失败。'
  } finally {
    loading.value = false
  }
}

async function openDetail(row) {
  selectedReceipt.value = row
  detailLoading.value = true
  revokePreviewUrl()
  try {
    const detail = await fetchReceiptFolderDetail(row.id)
    selectedReceipt.value = detail
    fillDetailForm(detail)
    await loadPreview(detail)
  } catch (err) {
    error.value = err?.message || '票据详情加载失败。'
    selectedReceipt.value = null
  } finally {
    detailLoading.value = false
  }
}

function fillDetailForm(detail) {
  detailForm.file_name = detail.file_name || ''
  detailForm.document_type = detail.document_type || ''
  detailForm.document_type_label = detail.document_type_label || ''
  detailForm.scene_code = detail.scene_code || ''
  detailForm.scene_label = detail.scene_label || ''
  detailForm.summary = detail.summary || ''
  detailForm.amount = detail.amount || ''
  detailForm.document_date = detail.document_date || ''
  detailForm.merchant_name = detail.merchant_name || ''
  detailForm.fields = Array.isArray(detail.fields)
    ? detail.fields.map((field) => ({ ...field }))
    : []
  receiptInfoEditing.value = false
  resetPreviewView()
  ensureEditableReceiptFields()
  syncEditableFieldsToTopLevel()
}

async function loadPreview(detail) {
  if (!detail?.preview_url) return
  try {
    const blob = await fetchReceiptFolderAsset(detail.preview_url)
    const resolvedPreviewKind = inferPreviewKindFromBlob(blob)
    if (resolvedPreviewKind && selectedReceipt.value?.id === detail.id) {
      selectedReceipt.value = {
        ...selectedReceipt.value,
        preview_kind: resolvedPreviewKind
      }
    }
    previewObjectUrl.value = URL.createObjectURL(blob)
  } catch {
    previewObjectUrl.value = ''
  }
}

function revokePreviewUrl() {
  if (previewObjectUrl.value) {
    URL.revokeObjectURL(previewObjectUrl.value)
    previewObjectUrl.value = ''
  }
}

function backToList() {
  selectedReceipt.value = null
  receiptInfoEditing.value = false
  revokePreviewUrl()
}

async function reloadCurrentReceipt() {
  if (!selectedReceipt.value?.id || detailLoading.value) return
  await openDetail(selectedReceipt.value)
}

function startReceiptInfoEdit() {
  receiptInfoEditing.value = true
}

function cancelReceiptInfoEdit() {
  if (selectedReceipt.value) {
    fillDetailForm(selectedReceipt.value)
  }
  receiptInfoEditing.value = false
}

async function saveDetail() {
  if (!selectedReceipt.value?.id || savingDetail.value) return
  savingDetail.value = true
  try {
    const updated = await updateReceiptFolderItem(selectedReceipt.value.id, buildDetailPayload())
    selectedReceipt.value = updated
    fillDetailForm(updated)
    await reloadReceipts()
  } finally {
    savingDetail.value = false
  }
}

async function deleteCurrentReceipt() {
  if (!selectedReceipt.value?.id || deleting.value) return
  deleting.value = true
  try {
    await deleteReceiptFolderItem(selectedReceipt.value.id)
    backToList()
    await reloadReceipts()
    toast('已从票据夹删除；已关联到报销单的附件副本会保留。')
  } finally {
    deleting.value = false
  }
}

async function openAssociateDialog() {
  selectedReceiptIds.value = []
  targetDraftId.value = NEW_CLAIM_VALUE
  associateStep.value = 1
  associateDialogOpen.value = true
  await loadDraftClaims()
}

async function openAssociateDialogForCurrentReceipt() {
  if (!selectedReceipt.value?.id || selectedReceipt.value.status === 'linked') return
  selectedReceiptIds.value = [selectedReceipt.value.id]
  targetDraftId.value = NEW_CLAIM_VALUE
  associateStep.value = 2
  associateDialogOpen.value = true
  await loadDraftClaims()
}

function closeAssociateDialog() {
  if (associateBusy.value) return
  associateDialogOpen.value = false
}

async function loadDraftClaims() {
  try {
    const claims = extractExpenseClaimItems(await fetchExpenseClaims(REIMBURSEMENT_LIST_PREVIEW_PARAMS))
    draftClaims.value = claims
      .filter((claim) => String(claim.status || '').trim().toLowerCase() === 'draft')
      .map((claim) => ({
        raw: claim,
        claimId: String(claim.id || '').trim(),
        claimNo: String(claim.claim_no || '').trim(),
        reason: String(claim.reason || '待补充事由').trim(),
        amountDisplay: `${Number(claim.amount || 0).toFixed(2)} ${claim.currency || 'CNY'}`
      }))
      .filter((claim) => claim.claimId)
  } catch {
    draftClaims.value = []
  }
}

async function handleAssociatePrimary() {
  if (associateStep.value === 1) {
    associateStep.value = 2
    return
  }
  await openAssociationConversation()
}

async function openAssociationConversation() {
  if (associateBusy.value || !selectedReceiptIds.value.length) return
  associateBusy.value = true
  try {
    const selected = receipts.value.filter((item) => selectedReceiptIds.value.includes(item.id))
    const files = await Promise.all(selected.map((item) => buildReceiptFile(item)))
    const selectedDraft = draftClaims.value.find((item) => item.claimId === targetDraftId.value)
    const prompt = selectedDraft
      ? `请把票据夹中选中的 ${files.length} 份票据关联到报销草稿 ${selectedDraft.claimNo}，并继续核对填写信息。`
      : `请基于票据夹中选中的 ${files.length} 份票据新建一张报销草稿，并继续核对填写信息。`
    associateDialogOpen.value = false
    emit('open-assistant', {
      source: selectedDraft ? 'detail' : 'receipt-folder',
      request: selectedDraft
        ? {
            ...selectedDraft.raw,
            claimId: selectedDraft.claimId,
            documentNo: selectedDraft.claimNo
          }
        : null,
      prompt,
      files
    })
  } finally {
    associateBusy.value = false
  }
}

</script>

<style scoped src="../assets/styles/components/document-list-shared.css"></style>
<style scoped src="../assets/styles/views/receipt-folder-view.css"></style>
