import { ref } from 'vue' import { ElMessage, ElMessageBox } from 'element-plus' import { pickWavePickComplete } from '@/api/pick/pick' function okCode(code: unknown) { return code === 1 || code === 200 || code === 0 } export function resolveWavePickCompleteWaveId(row: any): number | null { const id = row?.wave_id ?? row?.id ?? row?.batch_id const num = Number(id) return Number.isFinite(num) && num > 0 ? num : null } function getWavePickCompleteLoadingKey(row: any) { return String(row?.id ?? row?.wave_id ?? row?.batch_id ?? '') } export function useWavePickComplete(options: { onSuccess?: () => void | Promise } = {}) { const wavePickCompleteLoadingKey = ref('') function isWavePickCompleteLoading(row: any) { return wavePickCompleteLoadingKey.value === getWavePickCompleteLoadingKey(row) } async function handleWavePickComplete(row: any) { const waveId = resolveWavePickCompleteWaveId(row) if (!waveId) { ElMessage.warning('当前波次缺少可用的波次 ID') return } const waveNo = String(row?.wave_no || row?.wave_code || row?.batch_no || waveId).trim() try { await ElMessageBox.confirm( `确定要对波次「${waveNo}」执行批量拣货(一键完成整个波次拣货)吗?`, '批量拣货', { type: 'warning', buttonSize: 'small', confirmButtonText: '确认拣货', cancelButtonText: '取消' } ) } catch { return } const loadingKey = getWavePickCompleteLoadingKey(row) wavePickCompleteLoadingKey.value = loadingKey try { const res = await pickWavePickComplete({ wave_id: waveId }) as Record if (res?.code !== undefined && res?.code !== null && !okCode(res.code)) { throw new Error(res?.message || res?.tip || '批量拣货失败') } const data = (res?.data && typeof res.data === 'object') ? res.data : res const status = String(data?.status ?? '').trim().toLowerCase() const tip = String(data?.tip || res?.message || '').trim() if (status === 'already_completed') { ElMessage.info(tip || '该波次拣货已完成') } else { ElMessage.success(tip || '批量拣货成功') } await options.onSuccess?.() } catch (error: any) { console.error('wave pick complete failed:', error) ElMessage.error(error?.message || '批量拣货失败') } finally { wavePickCompleteLoadingKey.value = '' } } return { handleWavePickComplete, isWavePickCompleteLoading } }