export function useTravelReimbursementCreateViewControls({
  activeSessionType,
  attachedFiles,
  clearAssistantSessionSnapshot,
  closeAfterBusy,
  conversationId,
  deleteConversation,
  deleteSessionBusy,
  deleteSessionDialogOpen,
  draftClaimId,
  emitClose,
  getExpenseQueryActivePage,
  getExpenseQueryTotalPages,
  persistSessionState,
  resetCurrentSessionState,
  reviewActionBusy,
  router,
  resolveCurrentUserId,
  sessionSwitchBusy,
  submitComposer,
  submitting,
  toast,
  workbenchVisible
}) {
  function isWorkbenchBusy() {
    return submitting.value || reviewActionBusy.value || sessionSwitchBusy.value
  }

  function maybeFinalizeDeferredClose() {
    if (!closeAfterBusy.value || workbenchVisible.value || isWorkbenchBusy()) return
    closeAfterBusy.value = false
    emitClose()
  }

  function requestCloseWorkbench() {
    persistSessionState()
    closeAfterBusy.value = isWorkbenchBusy()
    workbenchVisible.value = false
  }

  function emitCloseAfterLeave() {
    if (workbenchVisible.value) return
    if (closeAfterBusy.value && isWorkbenchBusy()) return
    closeAfterBusy.value = false
    emitClose()
  }

  function openExpenseQueryRecord(record) {
    const claimId = String(record?.claimId || '').trim()
    if (!claimId) return
    router.push({ name: 'app-document-detail', params: { requestId: claimId } })
    emitClose()
  }

  async function handleExpenseQueryRecordClick(message, record) {
    if (message?.queryPayload?.selectionMode !== 'draft_association') {
      openExpenseQueryRecord(record)
      return
    }
    if (message.querySelectionLocked || message.queryPayload.selectionLocked || submitting.value || reviewActionBusy.value) return

    const claimId = String(record?.claimId || '').trim()
    if (!claimId) return
    const files = Array.from(attachedFiles.value || [])
    if (!files.length) {
      toast('本次上传的附件已不在当前会话中，请重新选择附件后再关联草稿。')
      return
    }

    message.querySelectionLocked = true
    message.selectedQueryRecordId = claimId
    message.queryPayload.selectionLocked = true
    message.queryPayload.selectedClaimId = claimId
    draftClaimId.value = claimId
    persistSessionState()

    await submitComposer({
      rawText: `将本次上传的 ${files.length} 份票据关联到报销草稿 ${record.claimNo}`,
      userText: `关联到草稿 ${record.claimNo}`,
      pendingText: `已选择草稿 ${record.claimNo}，正在识别并归集附件...`,
      files,
      uploadDisposition: 'continue_existing',
      skipDraftAssociationPrompt: true,
      associationConfirmed: true,
      extraContext: {
        review_action: 'link_to_existing_draft',
        draft_claim_id: claimId,
        selected_claim_id: claimId,
        selected_claim_no: String(record?.claimNo || '').trim(),
        attachment_association_confirmed: true
      }
    })
  }

  function setExpenseQueryPage(message, page) {
    if (!message?.queryPayload) return
    const totalPages = getExpenseQueryTotalPages(message.queryPayload)
    message.queryPayload.currentPage = Math.min(Math.max(1, Number(page || 1)), totalPages)
  }

  function shiftExpenseQueryPage(message, delta) {
    if (!message?.queryPayload) return
    setExpenseQueryPage(message, getExpenseQueryActivePage(message.queryPayload) + Number(delta || 0))
  }

  function openDeleteSessionDialog() {
    if (submitting.value || reviewActionBusy.value || deleteSessionBusy.value || sessionSwitchBusy.value) return
    deleteSessionDialogOpen.value = true
  }

  function closeDeleteSessionDialog() {
    if (deleteSessionBusy.value) return
    deleteSessionDialogOpen.value = false
  }

  async function confirmDeleteCurrentSession() {
    if (deleteSessionBusy.value || sessionSwitchBusy.value) return

    deleteSessionBusy.value = true
    try {
      if (conversationId.value) {
        await deleteConversation(conversationId.value, resolveCurrentUserId())
      }
      clearAssistantSessionSnapshot(resolveCurrentUserId(), activeSessionType.value)
      resetCurrentSessionState()
      deleteSessionDialogOpen.value = false
      toast('当前会话已删除。')
    } catch (error) {
      toast(error?.message || '删除当前会话失败，请稍后重试。')
    } finally {
      deleteSessionBusy.value = false
    }
  }

  return {
    emitCloseAfterLeave,
    handleExpenseQueryRecordClick,
    maybeFinalizeDeferredClose,
    openDeleteSessionDialog,
    openExpenseQueryRecord,
    closeDeleteSessionDialog,
    confirmDeleteCurrentSession,
    requestCloseWorkbench,
    setExpenseQueryPage,
    shiftExpenseQueryPage
  }
}
