import { ElMessage, ElMessageBox } from 'element-plus'
import { setVehicleMaintenance, type VehicleMaintenanceMode } from '@/api/vehicleOps'

export const MAINTENANCE_OPTIONS: { value: VehicleMaintenanceMode; label: string }[] = [
  { value: 'online', label: '上线' },
  { value: 'offline', label: '下线维护' },
  { value: 'repair', label: '现场检修' },
  { value: 'blown', label: '返厂检修' }
]

export function maintenanceModeLabel(mode?: VehicleMaintenanceMode): string {
  return MAINTENANCE_OPTIONS.find((o) => o.value === mode)?.label ?? '上线'
}

export async function confirmAndApplyMaintenance(
  rawId: number | undefined,
  mode: VehicleMaintenanceMode,
  prevMode: VehicleMaintenanceMode
): Promise<boolean> {
  if (!Number.isFinite(rawId)) return false
  if (mode === prevMode) return false

  try {
    if (mode === 'blown') {
      await ElMessageBox.confirm('返厂检修将停止调度并清空站点，确认？', '危险操作', {
        type: 'error',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
    } else if (mode === 'repair') {
      await ElMessageBox.confirm('现场检修：不调度但仍刷新状态，确认？', '维护确认', {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
    } else if (mode === 'online' || mode === 'offline') {
      await ElMessageBox.confirm(
        mode === 'online' ? '确认将车辆上线？' : '确认将车辆下线维护？',
        '维护确认',
        { type: 'warning', confirmButtonText: '确定', cancelButtonText: '取消' }
      )
    }

    const ok = await setVehicleMaintenance(rawId!, mode)
    if (ok) {
      ElMessage.success('维护状态已更新')
      return true
    }
    ElMessage.error('维护操作失败')
    return false
  } catch {
    return false
  }
}
