import { computed, ref } from 'vue'

import {
  createExpenseClaimActionRequestId,
  payExpenseClaim
} from '../../services/reimbursements.js'
import {
  canManageExpenseClaims,
  isFinanceUser
} from '../../utils/accessControl.js'

export function useTravelRequestPaymentFlow({
  request,
  currentUser,
  isApplicationDocument,
  isCurrentApplicant,
  toast,
  emit
}) {
  const payBusy = ref(false)
  const payConfirmDialogOpen = ref(false)
  const payRequestId = ref('')
  const payExpectedStatus = ref('')
  const payExpectedStage = ref('')

  const isPendingPaymentStage = computed(() => {
    const node = String(request.value.node || request.value.approvalStage || '').trim()
    return (
      !isApplicationDocument.value
      && Boolean(request.value.claimId)
      && (
        request.value.approvalKey === 'pending_payment'
        || String(request.value.status || '').trim().toLowerCase() === 'pending_payment'
        || node === '待付款'
      )
    )
  })

  const canPayRequest = computed(() =>
    isPendingPaymentStage.value
    && !isCurrentApplicant.value
    && (
      isFinanceUser(currentUser.value)
      || canManageExpenseClaims(currentUser.value)
    )
  )

  function handlePayRequest() {
    if (!request.value.claimId) {
      toast('当前单据缺少 claimId，暂时无法确认付款。')
      return
    }

    if (!canPayRequest.value) {
      toast('只有待付款状态的报销单可以确认付款。')
      return
    }

    payRequestId.value = createExpenseClaimActionRequestId('pay', request.value.claimId)
    payExpectedStatus.value = String(request.value.status || '').trim()
    payExpectedStage.value = String(request.value.node || request.value.approvalStage || '').trim()
    payConfirmDialogOpen.value = true
  }

  function closePayConfirmDialog() {
    if (payBusy.value) {
      return
    }

    payConfirmDialogOpen.value = false
    payRequestId.value = ''
    payExpectedStatus.value = ''
    payExpectedStage.value = ''
  }

  async function confirmPayRequest() {
    if (!request.value.claimId) {
      toast('当前单据缺少 claimId，暂时无法确认付款。')
      payConfirmDialogOpen.value = false
      return
    }

    if (!canPayRequest.value) {
      toast('只有待付款状态的报销单可以确认付款。')
      payConfirmDialogOpen.value = false
      return
    }

    payBusy.value = true
    try {
      await payExpenseClaim(request.value.claimId, {
        request_id: payRequestId.value,
        expected_status: payExpectedStatus.value,
        expected_approval_stage: payExpectedStage.value
      })
      payConfirmDialogOpen.value = false
      payRequestId.value = ''
      payExpectedStatus.value = ''
      payExpectedStage.value = ''
      toast(`${request.value.id} 已确认付款。`)
      emit('request-updated', { claimId: request.value.claimId })
    } catch (error) {
      toast(error?.message || '确认付款失败，请稍后重试。')
    } finally {
      payBusy.value = false
    }
  }

  return {
    canPayRequest,
    closePayConfirmDialog,
    confirmPayRequest,
    handlePayRequest,
    payBusy,
    payConfirmDialogOpen
  }
}
