import { nextTick, ref, watch, type Ref } from 'vue'
import type { TabsPaneContext } from 'element-plus'
import usePageList from '@/utils/hooks/usePageList'
import {
  getFactoryOrderNewDetailApi,
  getFactoryOrderNewListApi,
  getFactoryOrderNewLogApi,
  getSuspendListApi,
} from '@/api/factoryOrderNew'
import type {
  FactoryOrderNewListData,
  LogListData,
  ProductListData,
  operateOrderListData,
} from '@/types/api/order/factoryOrderNew'

interface UseOrderListAndDetailOptions {
  status: Ref<string>
  isCardLayout: Ref<boolean>
  isTableLayout: Ref<boolean>
  getQueryPayload: () => Record<string, unknown>
  getListPageAcceptedSubStatus: () => number | undefined
  suspendedSubTab: Ref<number>
}

export function useOrderListAndDetail(options: UseOrderListAndDetailOptions) {
  const {
    status,
    isCardLayout,
    isTableLayout,
    getQueryPayload,
    getListPageAcceptedSubStatus,
    suspendedSubTab,
  } = options

  const subLoading = ref(false)
  const activeTab = ref<'product' | 'log'>('product')
  const productList = ref<ProductListData[]>([])
  const logList = ref<LogListData[]>([])
  const tableRef = ref()
  const currentRow = ref<FactoryOrderNewListData | null>(null)
  const selectedRowIds = ref<(number | string)[]>([])
  const selectedRows = ref<FactoryOrderNewListData[]>([])
  const cardSelectList = ref<operateOrderListData[]>([])

  const {
    loading,
    currentPage,
    pageSize,
    total,
    data: tableData,
    onCurrentPageChange,
    onPageSizeChange,
    refresh: refreshTableList,
  } = usePageList<FactoryOrderNewListData>({
    query: (page, size) => {
      if (status.value === 'SUSPEND') {
        return getSuspendListApi(
          getQueryPayload(),
          page,
          size,
          suspendedSubTab.value,
        ).then(async (res) => {
          const records = Array.isArray(res.data?.records)
            ? res.data.records
            : []
          await nextTick(() => {
            tableRef.value.setCurrentRow(records[0])
            currentRow.value = records[0] as never
          })
          return res.data
        })
      }
      return getFactoryOrderNewListApi(
        getQueryPayload(),
        page,
        size,
        status.value === 'ALL' ? undefined : status.value,
        getListPageAcceptedSubStatus(),
      ).then(async (res) => {
        const records = res.data.records || []
        await nextTick(() => {
          tableRef.value.setCurrentRow(records[0])
          currentRow.value = (records[0] as never) || null
        })
        return res.data
      })
    },
  })

  const getSelectedIds = (): (number | string)[] => {
    if (isCardLayout.value) return cardSelectList.value.map((item) => item.id)
    return selectedRowIds.value
  }

  const clearTableState = () => {
    selectedRowIds.value = []
    selectedRows.value = []
    cardSelectList.value = []
    productList.value = []
    logList.value = []
    currentRow.value = null
  }

  const handleMainSelectionChange = (rows: FactoryOrderNewListData[]) => {
    selectedRowIds.value = rows.map((row) => row.id)
    selectedRows.value = rows
  }

  const handleCardSelectionChange = (items: operateOrderListData[]) => {
    cardSelectList.value = items
  }

  const getOrderDetailsById = async (tabName?: 'product' | 'log') => {
    if (!currentRow.value) {
      productList.value = []
      logList.value = []
      return
    }
    const id = currentRow.value.id
    // const isSuspend = status.value === 'SUSPEND'
    const effectiveTab = tabName ?? activeTab.value
    subLoading.value = true
    try {
      if (effectiveTab === 'product') {
        productList.value = []
        // const productRes = isSuspend
        //   ? await getSuspendDetailApi(id)
        //   : await getFactoryOrderNewDetailApi(id)
        const productRes = await getFactoryOrderNewDetailApi(id)
        if (productRes.code !== 200) return
        productList.value = Array.isArray(productRes.data)
          ? productRes.data
          : []
      } else {
        logList.value = []
        // const logRes = isSuspend
        //   ? await getSuspendLogApi(id)
        //   : await getFactoryOrderNewLogApi(id)
        const logRes = await getFactoryOrderNewLogApi(id)
        if (logRes.code !== 200) return
        logList.value = Array.isArray(logRes.data) ? logRes.data : []
      }
    } catch (e) {
      console.error(e)
    } finally {
      subLoading.value = false
    }
  }

  watch(currentRow, (row) => {
    if (!row) {
      productList.value = []
      logList.value = []
      return
    }
    if (!isTableLayout.value) return
    void getOrderDetailsById()
  })

  const handleRowClick = (row: FactoryOrderNewListData) => {
    const isSameRow = currentRow.value?.id === row.id
    currentRow.value = row
    if (isSameRow) {
      getOrderDetailsById()
    }
  }

  const handleTabClick = (tab: TabsPaneContext) => {
    if (!currentRow.value) return
    const name = tab?.props?.name as 'product' | 'log' | undefined
    void getOrderDetailsById(name)
  }

  return {
    subLoading,
    activeTab,
    productList,
    logList,
    tableRef,
    currentRow,
    selectedRowIds,
    selectedRows,
    cardSelectList,
    loading,
    currentPage,
    pageSize,
    total,
    tableData,
    onCurrentPageChange,
    onPageSizeChange,
    refreshTableList,
    getSelectedIds,
    clearTableState,
    handleMainSelectionChange,
    handleCardSelectionChange,
    getOrderDetailsById,
    handleRowClick,
    handleTabClick,
  }
}
