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

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

export function useOrderStatusTree(options: UseOrderStatusTreeOptions) {
  const {
    getQueryPayload,
    currentPage,
    pageSize,
  } = 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: 'materialExceptionCount', value: 3, count: 0 },
    { label: '其他', key: 'otherReasonCount', value: 4, count: 0 },
  ])
  const suspendedSubTab = ref(1)
  /** 已取消：子 tab 与 list_page 的 cancelSubType 取值 1/2/3 对应 */
  const cancelledTabs = ref([
    { label: '客户拦截', key: 'customerInterceptCount', value: 1, count: 0 },
    { label: '协商取消', key: 'mutualAgreeCancelCount', value: 2, count: 0 },
    { label: '其他', key: 'otherReasonCount', value: 3, count: 0 },
  ])
  const cancelledSubTab = 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 getCancelledCounts = async () => {
    try {
      const res = await getCancelledOrderStatisticsApi(
        getQueryPayload() as SearchForm,
        currentPage.value,
        pageSize.value,
        cancelledSubTab.value,
      )
      if (res.code !== 200 || !res.data) return
      const data = res.data || {}
      cancelledTabs.value = cancelledTabs.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 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,
    cancelledTabs,
    cancelledSubTab,
    treeRef,
    isCardLayout,
    isSpecialLayout,
    isTableLayout,
    getListPageAcceptedSubStatus,
    getPendingReceiveCounts,
    getSuspendCounts,
    getCancelledCounts,
    loadStatusTreeCounts,
    handlePendingAcceptTabClick,
    toggleExpand
  }
}
