import { computed, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

export interface BatchRow {
  isLock?: boolean
}

export function useWmsBatchActions<T extends BatchRow>() {
  const selected = ref<T[]>([])

  const batchCount = computed(() => selected.value.filter((r) => !r.isLock).length)

  function onSelectionChange(rows: T[]) {
    selected.value = rows
  }

  function selectable(row: T) {
    return !row.isLock
  }

  function clearSelection() {
    selected.value = []
  }

  async function runBatch(opts: {
    actionLabel: string
    confirmMessage: string
    rows?: T[]
    canRun?: (row: T) => boolean
    run: (row: T) => Promise<unknown>
  }) {
    const source = opts.rows ?? selected.value
    const pool = source.filter((r) => !r.isLock && (opts.canRun?.(r as T) ?? true)) as T[]
    if (pool.length === 0) {
      ElMessage.warning('请先选择可操作的记录')
      return { ok: 0, fail: 0 }
    }
    await ElMessageBox.confirm(opts.confirmMessage.replace('{n}', String(pool.length)), '确认操作', { type: 'warning' })

    let ok = 0
    let fail = 0
    for (const row of pool) {
      try {
        await opts.run(row)
        ok += 1
      } catch {
        fail += 1
      }
    }
    clearSelection()
    if (fail === 0) ElMessage.success(`${opts.actionLabel}完成：${ok} 条`)
    else ElMessage.warning(`${opts.actionLabel}完成 ${ok} 条，失败 ${fail} 条`)
    return { ok, fail }
  }

  return reactive({
    selected,
    batchCount,
    onSelectionChange,
    selectable,
    clearSelection,
    runBatch
  })
}
