import { ref, onBeforeUnmount } from 'vue'
import { queryOrderPayment, type PaymentOrder } from '../api/orders'

/**
 * 支付轮询 Composable
 * 负责轮询查询支付状态，直到支付完成
 */
export function usePaymentPolling() {
  const activePayment = ref<PaymentOrder | null>(null)
  const checkingPayment = ref(false)
  let paymentPollingTimer: number | undefined

  /**
   * 开始轮询支付状态
   */
  function startPaymentPolling(payment: PaymentOrder, onSuccess?: () => void) {
    activePayment.value = payment
    stopPaymentPolling()
    paymentPollingTimer = window.setInterval(() => checkPaymentStatus(onSuccess), 2000)
  }

  /**
   * 停止轮询
   */
  function stopPaymentPolling() {
    if (paymentPollingTimer !== undefined) {
      clearInterval(paymentPollingTimer)
      paymentPollingTimer = undefined
    }
    activePayment.value = null
  }

  /**
   * 检查支付状态
   */
  async function checkPaymentStatus(onSuccess?: () => void) {
    if (!activePayment.value || checkingPayment.value) return false

    checkingPayment.value = true
    try {
      const updated = await queryOrderPayment(activePayment.value.id)
      if (updated.paid) {
        stopPaymentPolling()
        onSuccess?.()
        return true
      }
    } catch {
      // 忽略轮询错误，继续下次轮询
    } finally {
      checkingPayment.value = false
    }
    return false
  }

  // 组件卸载时停止轮询
  onBeforeUnmount(stopPaymentPolling)

  return {
    activePayment,
    checkingPayment,
    startPaymentPolling,
    stopPaymentPolling,
    checkPaymentStatus,
  }
}
