import { computed, ref } from 'vue'

import { showConfirm, showError, showSuccess } from '@/lib/feedback'
import {
  failAdminNinetyoneOrder,
  fetchAdminNinetyoneOrders,
  retryAdminNinetyoneOrder,
} from '@/services/admin'
import type { AdminNinetyoneOrderItem, AdminNinetyoneOrderListResult } from '@/types/admin'

export function useAdminNinetyonePlatform() {
  const ninetyoneLoading = ref(false)
  const ninetyoneActionLoadingId = ref<number | null>(null)
  const ninetyoneResultError = ref('')
  const ninetyoneStatus = ref<'pending_config' | 'all' | 'manual_failed'>('pending_config')
  const ninetyoneOrders = ref<AdminNinetyoneOrderListResult>({
    page: 1,
    pageSize: 20,
    total: 0,
    items: [],
  })

  const ninetyoneStats = computed(() => {
    const pendingCount = ninetyoneOrders.value.items.filter(
      (item) => item.orderStatus === 'pending_config',
    ).length
    const failedCount = ninetyoneOrders.value.items.filter(
      (item) => item.orderStatus === 'manual_failed',
    ).length
    const taskReadyCount = ninetyoneOrders.value.items.filter((item) => item.taskCount > 0).length

    return {
      total: ninetyoneOrders.value.total,
      currentCount: ninetyoneOrders.value.items.length,
      pendingCount,
      failedCount,
      taskReadyCount,
    }
  })

  async function loadNinetyoneOrders(page = 1) {
    ninetyoneLoading.value = true
    ninetyoneResultError.value = ''

    try {
      const response = await fetchAdminNinetyoneOrders({
        page,
        pageSize: ninetyoneOrders.value.pageSize || 20,
        status: ninetyoneStatus.value,
      })
      ninetyoneOrders.value = response.data
    } catch (error) {
      ninetyoneResultError.value = error instanceof Error ? error.message : '91卡券订单读取失败'
      showError(ninetyoneResultError.value)
    } finally {
      ninetyoneLoading.value = false
    }
  }

  async function handleNinetyoneStatusChange(status: 'pending_config' | 'all' | 'manual_failed') {
    ninetyoneStatus.value = status
    await loadNinetyoneOrders(1)
  }

  async function handleNinetyoneRetryOrder(item: AdminNinetyoneOrderItem) {
    ninetyoneActionLoadingId.value = item.orderId
    ninetyoneResultError.value = ''

    try {
      const response = await retryAdminNinetyoneOrder(item.orderId)
      showSuccess(`91卡券订单已重试，生成任务 ${response.data.taskCount} 个`)
      await loadNinetyoneOrders(ninetyoneOrders.value.page || 1)
    } catch (error) {
      ninetyoneResultError.value = error instanceof Error ? error.message : '91卡券订单重试失败'
      showError(ninetyoneResultError.value)
    } finally {
      ninetyoneActionLoadingId.value = null
    }
  }

  async function handleNinetyoneFailOrder(item: AdminNinetyoneOrderItem) {
    try {
      await showConfirm(
        `确认把 91卡券订单 ${item.orderNo} 标记为无法履约吗？查询接口会返回失败状态。`,
        '确认标记失败',
        {
          type: 'warning',
          confirmButtonText: '标记失败',
          cancelButtonText: '取消',
        },
      )
    } catch {
      return
    }

    ninetyoneActionLoadingId.value = item.orderId
    ninetyoneResultError.value = ''

    try {
      await failAdminNinetyoneOrder(item.orderId, {
        reason: '商家后台手动标记无法履约',
      })
      showSuccess('91卡券订单已标记失败')
      await loadNinetyoneOrders(ninetyoneOrders.value.page || 1)
    } catch (error) {
      ninetyoneResultError.value = error instanceof Error ? error.message : '91卡券订单标记失败失败'
      showError(ninetyoneResultError.value)
    } finally {
      ninetyoneActionLoadingId.value = null
    }
  }

  return {
    ninetyoneLoading,
    ninetyoneActionLoadingId,
    ninetyoneResultError,
    ninetyoneStatus,
    ninetyoneOrders,
    ninetyoneStats,
    loadNinetyoneOrders,
    handleNinetyoneStatusChange,
    handleNinetyoneRetryOrder,
    handleNinetyoneFailOrder,
  }
}
