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'
import { roleShow } from '@/utils/roleShow'

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 STATUS_QUANTITY_UNIT: Record<string, string> = {
    PENDING_SCHEDULE: '件',
    PENDING_PICK: '件',
    PENDING_REPLENISH: '件',
    IN_PRODUCTION: '件',
    PENDING_PACKING: '件',
    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(),
        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()
      const GROUP_MARK = new Set(['PICKING']) // 所有分组容器
      const filterTree = (nodes: StatusTreeNode[]): StatusTreeNode[] => {
        const result: StatusTreeNode[] = []
        for (const node of nodes) {
          let filteredChildren: StatusTreeNode[] = []
          if (node.children) {
            filteredChildren = filterTree(node.children)
          }
          const hasPermission = roleShow(node.status)
          const isGroupContainer = GROUP_MARK.has(node.status)
          if (
            hasPermission ||
            (isGroupContainer && filteredChildren.length > 0)
          ) {
            result.push({
              ...node,
              children: filteredChildren,
              unit: STATUS_QUANTITY_UNIT[node.status] ?? '单',
            })
          }
        }
        return result
      }

      const filteredData = filterTree(res.data)
      statusTree.value = [
        {
          status: 'ALL',
          statusName: '全部',
          quantity: 0,
          children: filteredData,
        },
      ]
      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,
  }
}
