import { ATTACHMENT_ASSOCIATION_CONFIRM_HREF } from './travelReimbursementAttachmentModel.js'

export function useTravelReimbursementCreateViewMessageHandlers({
  APPLICATION_SUBMIT_HREF,
  REVIEW_NEXT_STEP_HREF,
  REVIEW_QUICK_EDIT_HREF,
  REVIEW_RISK_PANEL_HREF_PREFIX,
  REVIEW_DRAWER_MODE_REVIEW,
  REVIEW_DRAWER_MODE_RISK,
  activeReviewPayload,
  buildReviewPlainFollowupCopy,
  confirmPendingAttachmentAssociationInternal,
  draftClaimId,
  handleApplicationSubmitConfirmationText,
  handleGuidedComposerSubmit,
  handleReviewActionInternal,
  handleSaveDraftDirectlyInternal,
  handleStewardRuntimeDecision,
  handleInlineSaveDraftDirectly,
  handleGuidedStewardPlan,
  isKnowledgeSession,
  isStewardSession,
  messages,
  openApplicationSubmitConfirm,
  openReviewNextStepConfirm,
  reviewActionBusy,
  reviewHasUnsavedChanges,
  reviewOverviewDrawerAvailable,
  reviewRiskDrawerAvailable,
  resolveActiveClaimId,
  resolveReviewSaveDraftAction,
  router,
  saveInlineReviewChangesInternal,
  scrollToBottom,
  sessionSwitchBusy,
  submitComposerInternal,
  submitting,
  switchReviewDrawerMode,
  toast
}) {
  function saveInlineReviewChanges() {
    if (!activeReviewPayload.value || !reviewHasUnsavedChanges.value || submitting.value || reviewActionBusy.value || sessionSwitchBusy.value) return
    return saveInlineReviewChangesInternal()
  }

  function askHotKnowledgeQuestion(question) {
    const normalizedQuestion = String(question || '').trim()
    if (!normalizedQuestion || !isKnowledgeSession.value || submitting.value || reviewActionBusy.value || sessionSwitchBusy.value) return
    submitComposer({
      rawText: normalizedQuestion,
      userText: normalizedQuestion,
      pendingText: '正在整理财务知识答案...'
    })
  }

  async function submitComposer(options = {}) {
    if (await handleStewardRuntimeDecision(options)) return null
    if (await handleApplicationSubmitConfirmationText(options)) return null
    if (await handleGuidedStewardPlan(options)) return null
    if (await handleGuidedComposerSubmit(options)) return null
    return submitComposerInternal(options)
  }

  async function handleAssistantMarkdownClick(event, message) {
    const anchor = event?.target?.closest?.('a')
    if (!anchor || !message || submitting.value || reviewActionBusy.value || sessionSwitchBusy.value) return

    const href = String(anchor.getAttribute('href') || '').trim()
    if (href === APPLICATION_SUBMIT_HREF) {
      event.preventDefault()
      openApplicationSubmitConfirm(message)
      return
    }
    if (href === REVIEW_NEXT_STEP_HREF) {
      event.preventDefault()
      openReviewNextStepConfirm(message)
      return
    }
    if (href.startsWith(REVIEW_RISK_PANEL_HREF_PREFIX)) {
      event.preventDefault()
      if (reviewRiskDrawerAvailable.value) {
        switchReviewDrawerMode(REVIEW_DRAWER_MODE_RISK)
      } else {
        toast('当前没有需要额外处理的风险信息。')
      }
      return
    }
    if (href === REVIEW_QUICK_EDIT_HREF) {
      event.preventDefault()
      if (reviewOverviewDrawerAvailable.value) {
        switchReviewDrawerMode(REVIEW_DRAWER_MODE_REVIEW)
        toast('已打开右侧核对信息，可以直接修改当前单据。')
      }
      return
    }
    if (href.startsWith('/app/')) {
      event.preventDefault()
      router.push(href)
      return
    }
    if (href !== ATTACHMENT_ASSOCIATION_CONFIRM_HREF) return

    event.preventDefault()
    reviewActionBusy.value = true
    try {
      await confirmPendingAttachmentAssociationInternal(message)
    } finally {
      reviewActionBusy.value = false
    }
  }

  async function handleReviewAction(message, action) {
    const actionType = String(action?.action_type || '').trim()
    if (!actionType || submitting.value || reviewActionBusy.value || sessionSwitchBusy.value) return
    return handleReviewActionInternal(message, action)
  }

  async function handleSaveDraftDirectly(message, actionType = 'save_draft') {
    return handleSaveDraftDirectlyInternal(message, actionType)
  }

  function isDraftSavedReviewMessage(message) {
    if (!message?.reviewPayload) return false
    return Boolean(
      String(message?.draftPayload?.claim_no || message?.draftPayload?.claim_id || '').trim()
        || String(draftClaimId.value || '').trim()
        || String(resolveActiveClaimId() || '').trim()
    )
  }

  function buildReviewPlainFollowupForMessage(message) {
    return buildReviewPlainFollowupCopy(message?.reviewPayload, {
      savedDraft: isDraftSavedReviewMessage(message)
    })
  }

  function canUseInlineSaveDraft(message) {
    if (!message?.reviewPayload || isDraftSavedReviewMessage(message)) return false
    return Boolean(resolveReviewSaveDraftAction(message.reviewPayload))
  }

  async function handleInlineSaveDraft(message) {
    if (!canUseInlineSaveDraft(message) || submitting.value || reviewActionBusy.value || sessionSwitchBusy.value) return
    await handleInlineSaveDraftDirectly(message, 'save_draft')
  }

  return {
    askHotKnowledgeQuestion,
    buildReviewPlainFollowupForMessage,
    canUseInlineSaveDraft,
    handleAssistantMarkdownClick,
    handleInlineSaveDraft,
    handleReviewAction,
    handleSaveDraftDirectly,
    isDraftSavedReviewMessage,
    saveInlineReviewChanges,
    submitComposer
  }
}
