import { computed, ref, nextTick } from 'vue'
import {
  getPodOrderAcceptedStatisticsApi,
  getPodOrderStateGroupListApi,
  getSuspendStatisticsApi,
} 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 = ref([
    { label: '客户拦截', key: 'customerInterceptCount', value: 1, count: 0 },
    { label: '地址异常', key: 'addressExceptionCount', value: 2, count: 0 },
    { label: '其他', key: 'otherReasonCount', value: 4, count: 0 },
  ])
  const suspendedSubTab = ref(1)
  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 getSuspendCounts = async () => {
    try {
      const res = await getSuspendStatisticsApi(
        getQueryPayload(),
        currentPage.value,
        pageSize.value,
        suspendedSubTab.value,
      )
      if (res.code !== 200 || !res.data) return
      const data = res.data || {}
      suspendedTabs.value = suspendedTabs.value.map((tab) => ({
        ...tab,
        count: data[String(tab.key)] ?? 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 = 1
    }
    onClearTableState()
    if (!isSpecialLayout.value) {
      onRefreshCurrentView()
    }
    if (node.status === 'SUSPEND') {
      void getSuspendCounts()
    }
  }

  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,
    getSuspendCounts,
    loadStatusTreeCounts,
    handleStatusNodeClick,
    handlePendingAcceptTabClick,
    toggleExpand,
  }
}
