/**
 * 表格组合式函数
 */
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

export function useTable(fetchApi: any) {
  const loading = ref(false)
  const tableData = ref<any[]>([])
  const selectedRows = ref<any[]>([])

  const filters = reactive<Record<string, any>>({})

  /**
   * 获取数据
   */
  const fetchData = async (params: any = {}) => {
    loading.value = true
    try {
      const data = await fetchApi({
        ...filters,
        ...params
      })
      tableData.value = data.items || []
      return data
    } catch (error) {
      ElMessage.error('获取数据失败')
      throw error
    } finally {
      loading.value = false
    }
  }

  /**
   * 搜索
   */
  const handleSearch = () => {
    return fetchData({ page: 1 })
  }

  /**
   * 重置
   */
  const handleReset = () => {
    Object.keys(filters).forEach(key => {
      filters[key] = undefined
    })
    return fetchData({ page: 1 })
  }

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

  /**
   * 删除确认
   */
  const handleDeleteConfirm = async (callback: () => Promise<void>) => {
    try {
      await ElMessageBox.confirm('确定要删除吗？', '提示', {
        type: 'warning'
      })
      await callback()
      ElMessage.success('删除成功')
      return true
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error('删除失败')
      }
      return false
    }
  }

  return {
    loading,
    tableData,
    selectedRows,
    filters,
    fetchData,
    handleSearch,
    handleReset,
    handleSelectionChange,
    handleDeleteConfirm
  }
}
