import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import type { BaseRespData } from '@/types/api'

interface BatchActionOptions<T = unknown> {
  getIds: () => (number | string)[]
  api: (ids: (number | string)[]) => Promise<BaseRespData<T>>
  confirmText?: string
  successText?: string
  refreshTree?: boolean
  onSuccess?: (res: BaseRespData<T>) => void | Promise<void>
  onAfter?: () => void | Promise<void>
}

interface UseOrderBatchActionsOptions {
  getIds: () => (number | string)[]
  refreshCurrentView: (options?: { isRefreshTree?: boolean }) => void | Promise<void>
}

export function useOrderBatchActions(options: UseOrderBatchActionsOptions) {
  const { getIds, refreshCurrentView } = options

  const ensureSelection = (msg = '请先选择订单'): boolean => {
    const ids = getIds()
    if (!ids.length) {
      ElMessage.warning(msg)
      return false
    }
    return true
  }

  const executeBatchAction = async <T = unknown>(action: BatchActionOptions<T>) => {
    const ids = action.getIds()
    if (!ids.length) {
      ElMessage.warning('请先选择订单')
      return
    }
    if (action.confirmText) {
      try {
        await ElMessageBox.confirm(action.confirmText, '提示', { type: 'warning' })
      } catch {
        return
      }
    }
    const loading = ElLoading.service({
      fullscreen: true,
      text: '操作中...',
      background: 'rgba(0, 0, 0, 0.3)',
    })
    try {
      const res = await action.api(ids)
      if (res.code !== 200) return
      if (action.successText) ElMessage.success(action.successText)
      if (action.onSuccess) await action.onSuccess(res)
      await refreshCurrentView({ isRefreshTree: !!action.refreshTree })
      if (action.onAfter) await action.onAfter()
    } catch (e) {
      console.error(e)
    } finally {
      loading.close()
    }
  }

  return {
    ensureSelection,
    executeBatchAction,
  }
}
