const { printA4FromRows } = require('./a4HistoryPrint'); const { openPdf } = require('./jpegPdf'); const { buildThermalBytes } = require('./thermalPrint'); const { loadSavedPrinter, savePrinter, clearPrinter, connectAndWrite } = require('./blePrinter'); const SHEET_ITEMS = ['A4 文档(系统打印机)', '58mm 热敏(蓝牙)']; function choosePrintKind() { return new Promise((resolve) => { wx.showActionSheet({ itemList: SHEET_ITEMS, success: (res) => resolve(res.tapIndex === 1 ? 'thermal' : 'a4'), fail: () => resolve(null), }); }); } async function printA4(component, payload) { wx.showLoading({ title: '正在生成', mask: true }); let filePath = ''; try { filePath = await printA4FromRows(component, payload); } finally { wx.hideLoading(); } await openPdf(filePath); } async function printThermal(component, payload, pickDevice) { let device = loadSavedPrinter(); if (!device) { if (typeof pickDevice !== 'function') { throw new Error('请先在「我的」绑定 BLE 热敏机;A4 激光机请选 A4 文档'); } device = await pickDevice(); if (!device) throw new Error('已取消'); savePrinter(device); } wx.showLoading({ title: '正在打印', mask: true }); try { const bytes = await buildThermalBytes(component, payload); await connectAndWrite(device, bytes); } catch (err) { // deviceId 可能因系统蓝牙重置而失效,下一次打印应允许重新选择。 // 仅连接/协议发现阶段重试,写入阶段失败不能盲目重发,避免重复出单。 if (pickDevice && /连接打印机|未找到可写特征/i.test(err.message || '')) { clearPrinter(); const retry = await pickDevice(); if (retry && retry.deviceId && retry.deviceId !== device.deviceId) { const bytes = await buildThermalBytes(component, payload); await connectAndWrite(retry, bytes); } else { throw err; } } else { throw err; } } finally { wx.hideLoading(); } } async function printHistory(component, payload, pickDevice) { const kind = await choosePrintKind(); if (!kind) return { kind: null }; if (kind === 'a4') { await printA4(component, payload); return { kind: 'a4' }; } await printThermal(component, payload, pickDevice); wx.showToast({ title: '已发送到打印机', icon: 'success' }); return { kind: 'thermal' }; } module.exports = { SHEET_ITEMS, choosePrintKind, printA4, printThermal, printHistory, };