import { computed, ref, nextTick } from 'vue'
import { getPodOrderAcceptedStatisticsApi, getPodOrderStateGroupListApi } from '@/api/factoryOrderNew'
import type { StatusTreeNode } from '@/types/api/order/factoryOrderNew'

interface UseOrderStatusTreeOptions {
  getQueryPayload: () => Record<string, unknown>
  currentPage: { value: number }
  pageSize: { value: number }
  onClearTableState: () => void
  onRefreshCurrentView: () => void
}

export function useOrderStatusTree(options: UseOrderStatusTreeOptions) {
  const { getQueryPayload, currentPage, pageSize, onClearTableState, onRefreshCurrentView } =
    options

  const cardLayoutStatuses = [
    'PENDING_SCHEDULE',
    'PENDING_PICK',
    'PENDING_REPLENISH',
    'IN_PRODUCTION',
    'PENDING_PACKING',
  ]
  const specialLayoutStatuses = ['BATCH_MANAGE', 'AWAITING_RESTOCK']

  const statusTree = ref<StatusTreeNode[]>()
  const status = ref<string>('PENDING_RECEIVE')
  const pendingAcceptSubTab = ref<'PENDING_RECEIVE' | 'ACCEPT_FAIL_OUT_OF_STOCK'>(
    'PENDING_RECEIVE',
  )
  const pendingAcceptCounts = ref<{
    acceptedOutOfStockCount?: number
    pendingCount?: number
    totalCount?: number
  }>({
    pendingCount: 0,
    acceptedOutOfStockCount: 0,
  })
  const suspendedTabs = [
    { label: '客户拦截', value: 'CUSTOMER_INTERCEPT', count: 0 },
    { label: '地址异常', value: 'ADDRESS_EXCEPTION', count: 0 },
    { label: '其他', value: 'OTHER', count: 0 },
  ]
  const suspendedSubTab = ref('CUSTOMER_INTERCEPT')
  const treeRef = ref()

  const isCardLayout = computed(() => cardLayoutStatuses.includes(status.value))
  const isSpecialLayout = computed(() => specialLayoutStatuses.includes(status.value))
  const isTableLayout = computed(
    () => !isCardLayout.value && !isSpecialLayout.value,
  )

  const getListPageAcceptedSubStatus = () =>
    status.value === 'PENDING_RECEIVE'
      ? pendingAcceptSubTab.value === 'PENDING_RECEIVE'
        ? 0
        : 2
      : undefined

  const getPendingReceiveCounts = async () => {
    try {
      const res = await getPodOrderAcceptedStatisticsApi(
        getQueryPayload(),
        currentPage.value,
        pageSize.value,
        status.value,
        getListPageAcceptedSubStatus(),
      )
      if (res.code !== 200) return
      pendingAcceptCounts.value = res.data || {
        pendingCount: 0,
        acceptedOutOfStockCount: 0,
      }
    } catch (e) {
      console.error(e)
    }
  }

  const loadStatusTreeCounts = async () => {
    try {
      const res = await getPodOrderStateGroupListApi()
      statusTree.value = [
        { status: 'ALL', statusName: '全部', quantity: 0, children: res.data },
      ]
      nextTick(() => {
        treeRef.value?.setCurrentKey(status.value, true)
      })
    } catch (e) {
      console.error(e)
    }
  }

  const handleStatusNodeClick = (node: StatusTreeNode) => {
    status.value = node.status
    if (node.status !== 'PENDING_RECEIVE') {
      pendingAcceptSubTab.value = 'PENDING_RECEIVE'
    }
    if (node.status !== 'SUSPEND') {
      suspendedSubTab.value = 'CUSTOMER_INTERCEPT'
    }
    onClearTableState()
    if (!isSpecialLayout.value) {
      onRefreshCurrentView()
    }
  }

  const handlePendingAcceptTabClick = (
    tab: 'PENDING_RECEIVE' | 'ACCEPT_FAIL_OUT_OF_STOCK',
    refreshTableList: () => void,
  ) => {
    if (pendingAcceptSubTab.value === tab) return
    pendingAcceptSubTab.value = tab
    refreshTableList()
  }

  const toggleExpand = (node: { expanded?: boolean }) => {
    node.expanded = !node.expanded
  }

  return {
    cardLayoutStatuses,
    specialLayoutStatuses,
    statusTree,
    status,
    pendingAcceptSubTab,
    pendingAcceptCounts,
    suspendedTabs,
    suspendedSubTab,
    treeRef,
    isCardLayout,
    isSpecialLayout,
    isTableLayout,
    getListPageAcceptedSubStatus,
    getPendingReceiveCounts,
    loadStatusTreeCounts,
    handleStatusNodeClick,
    handlePendingAcceptTabClick,
    toggleExpand,
  }
}
