import { reactive, ref } from 'vue'

import { lookupAdminFulfillmentBindingOrder } from '@/services/admin'
import type { AdminFulfillmentLookupItem, AdminFulfillmentLookupResult } from '@/types/admin'

import type { useFulfillmentBindings } from './useFulfillmentBindings'

export function useFulfillmentBindingsLookup(
  bindings: ReturnType<typeof useFulfillmentBindings>,
) {
  const lookupLoading = ref(false)
  const lookupErrorMessage = ref('')
  const lookupResult = ref<AdminFulfillmentLookupResult | null>(null)
  const importedLookupLineIds = ref<string[]>([])
  const lookupForm = reactive({
    shopId: '',
    platformOrderId: '',
  })

  function importLookupProduct(item: AdminFulfillmentLookupItem) {
    bindings.importObservedProduct(item)
    if (!importedLookupLineIds.value.includes(item.lineId)) {
      importedLookupLineIds.value = [...importedLookupLineIds.value, item.lineId]
    }
  }

  function isLookupProductImported(lineId: string) {
    return importedLookupLineIds.value.includes(lineId)
  }

  async function lookupOrderProducts() {
    const shopId = lookupForm.shopId.trim()
    const platformOrderId = lookupForm.platformOrderId.trim()

    if (!shopId || !platformOrderId) {
      lookupErrorMessage.value = '请先填写店铺 ID 和平台订单号'
      return
    }

    lookupLoading.value = true
    lookupErrorMessage.value = ''

    try {
      const response = await lookupAdminFulfillmentBindingOrder({
        provider: 'agiso',
        platform: 'xianyu',
        shopId,
        platformOrderId,
      })
      lookupResult.value = response.data
      importedLookupLineIds.value = []
    } catch (error) {
      lookupResult.value = null
      lookupErrorMessage.value = error instanceof Error ? error.message : '订单商品查询失败'
    } finally {
      lookupLoading.value = false
    }
  }

  return {
    lookupLoading,
    lookupErrorMessage,
    lookupResult,
    importedLookupLineIds,
    lookupForm,
    importLookupProduct,
    isLookupProductImported,
    lookupOrderProducts,
  }
}
