/**
 * 表格选择管理 Composable
 */

import { computed, shallowRef } from 'vue'

export function useTableSelection<T = any>() {
  // 选中的行
  const selectedRows = shallowRef<T[]>([])

  // 选中的ID列表
  const selectedIds = computed(() => {
    return selectedRows.value.map((row: any) => row.id)
  })

  // 选中的数量
  const selectedCount = computed(() => selectedRows.value.length)

  // 是否有选中项
  const hasSelected = computed(() => selectedRows.value.length > 0)

  // 处理选择变化
  const handleSelectionChange = (selection: T[]) => {
    selectedRows.value = selection
  }

  // 清空选择
  const clearSelection = () => {
    selectedRows.value = []
  }

  // 判断是否选中指定项
  const isSelected = (row: any) => {
    return selectedIds.value.includes(row.id)
  }

  // 切换选中状态
  const toggleSelection = (row: T) => {
    const index = selectedRows.value.findIndex((item: any) => item.id === (row as any).id)
    if (index > -1) {
      selectedRows.value = selectedRows.value.filter((_, itemIndex) => itemIndex !== index)
    } else {
      selectedRows.value = [...selectedRows.value, row]
    }
  }

  return {
    selectedRows,
    selectedIds,
    selectedCount,
    hasSelected,
    handleSelectionChange,
    clearSelection,
    isSelected,
    toggleSelection
  }
}
