showNativeFastPrinterDebugModal.ts 2.95 KB
import { getNativeFastPrinterDebugInfo, getNativeFastPrinterState } from './nativeFastPrinter'

type NativeFastPrinterDebugSnapshot = {
  available?: boolean
  pluginVersion?: string
  backend?: string
  stage?: string
  lastAction?: string
  lastError?: string
  commandBytes?: number
  buildMs?: number
  writeMs?: number
  elementCount?: number
  imagePatchCount?: number
  nativeTextCount?: number
  rasterTextCount?: number
  qrCodeCount?: number
  barcodeCount?: number
  lineCount?: number
  connected?: boolean
  deviceId?: string
  deviceName?: string
}

function isPresent (v: unknown): boolean {
  if (v === undefined || v === null) return false
  if (typeof v === 'string' && v.trim() === '') return false
  return true
}

function formatScalar (v: unknown): string {
  if (typeof v === 'boolean') return v ? 'true' : 'false'
  return String(v)
}

const FIELD_LINES: { key: keyof NativeFastPrinterDebugSnapshot; label: string }[] = [
  { key: 'available', label: 'Available' },
  { key: 'pluginVersion', label: 'Plugin version' },
  { key: 'backend', label: 'Backend' },
  { key: 'stage', label: 'Stage' },
  { key: 'lastAction', label: 'Last action' },
  { key: 'lastError', label: 'Last error' },
  { key: 'commandBytes', label: 'Command bytes' },
  { key: 'buildMs', label: 'Build ms' },
  { key: 'writeMs', label: 'Write ms' },
  { key: 'elementCount', label: 'Element count' },
  { key: 'imagePatchCount', label: 'Image patch count' },
  { key: 'nativeTextCount', label: 'Native text count' },
  { key: 'rasterTextCount', label: 'Raster text count' },
  { key: 'qrCodeCount', label: 'QR code count' },
  { key: 'barcodeCount', label: 'Barcode count' },
  { key: 'lineCount', label: 'Line count' },
  { key: 'connected', label: 'Connected' },
  { key: 'deviceId', label: 'Device ID' },
  { key: 'deviceName', label: 'Device name' },
]

export function formatNativeFastPrinterDebugContent (snapshot: NativeFastPrinterDebugSnapshot): string {
  const lines: string[] = []
  for (const { key, label } of FIELD_LINES) {
    const v = snapshot[key]
    if (!isPresent(v)) continue
    lines.push(`${label}: ${formatScalar(v)}`)
  }
  return lines.length ? lines.join('\n') : '(No debug fields available)'
}

/**
 * 一体机无 console 时,用系统弹框展示 native-fast-printer 关键状态(先尝试 getDebugInfo 刷新,失败则用内存快照)。
 */
export async function showNativeFastPrinterDebugModal (options?: {
  title?: string
}): Promise<void> {
  let merged: NativeFastPrinterDebugSnapshot = {
    ...(getNativeFastPrinterState() || {}),
  }
  try {
    const fresh = await getNativeFastPrinterDebugInfo()
    merged = { ...merged, ...(fresh as NativeFastPrinterDebugSnapshot) }
  } catch {
    /* 仍展示内存态 */
  }

  const modalTitle = (options?.title && options.title.trim()) || 'native-fast-printer'
  const content = formatNativeFastPrinterDebugContent(merged)

  uni.showModal({
    title: modalTitle,
    content,
    showCancel: false,
    confirmText: 'OK',
  })
}