import { nextTick, ref, watch, type Ref } from 'vue'
import type { TabsPaneContext } from 'element-plus'
import usePageList from '@/utils/hooks/usePageList'
import {
  getFactoryOrderNewDetailApi,
  getFactoryOrderNewListApi,
  getFactoryOrderNewLogApi,
} from '@/api/factoryOrderNew'
import type { SearchForm } from '@/types/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 listSortProp = ref<string | null>(null)
  const listSortOrder = ref<'asc' | 'desc' | null>(null)

  const buildListQueryBody = (): SearchForm => {
    const base = { ...getQueryPayload() } as SearchForm
    if (listSortProp.value && listSortOrder.value) {
      return {
        ...base,
        prop: listSortProp.value,
        order: listSortOrder.value,
      }
    }
    return base
  }

  const {
    loading,
    currentPage,
    pageSize,
    total,
    data: tableData,
    onCurrentPageChange,
    onPageSizeChange,
    refresh: refreshTableList,
  } = usePageList<FactoryOrderNewListData>({
    query: (page, size) => {
      const isSuspend = status.value === 'SUSPEND'
      return getFactoryOrderNewListApi(
        buildListQueryBody(),
        page,
        size,
        status.value === 'ALL' ? undefined : status.value,
        getListPageAcceptedSubStatus(),
        isSuspend ? suspendedSubTab.value : undefined,
      ).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
    listSortProp.value = null
    listSortOrder.value = null
  }

  const SORTABLE_COLUMN_PROPS = [
    'createTime',
    'startStockingTime',
    'finishTime',
  ] as const

  /** 表格列 prop → 后端 list_page 排序字段（如 MyBatis 列别名） */
  const LIST_SORT_PROP_BY_COLUMN: Record<
    (typeof SORTABLE_COLUMN_PROPS)[number],
    string
  > = {
    createTime: 'po.create_time',
    startStockingTime: 'po.start_stocking_time',
    finishTime: 'po.finish_time',
  }

  const handleMainTableSortChange = (data: {
    prop?: string
    order: string | null
  }) => {
    const { prop, order } = data
    if (
      !prop ||
      !SORTABLE_COLUMN_PROPS.includes(
        prop as (typeof SORTABLE_COLUMN_PROPS)[number],
      )
    ) {
      return
    }
    const sortProp = LIST_SORT_PROP_BY_COLUMN[prop as keyof typeof LIST_SORT_PROP_BY_COLUMN]
    if (order === 'ascending') {
      listSortProp.value = sortProp
      listSortOrder.value = 'asc'
    } else if (order === 'descending') {
      listSortProp.value = sortProp
      listSortOrder.value = 'desc'
    } else {
      listSortProp.value = null
      listSortOrder.value = null
    }
    refreshTableList()
  }

  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,
    handleMainTableSortChange,
  }
}
