import PrinterJobs from '@/components/print/printerjobs.js' import printerUtil from '@/components/print/printerutil.js' import util from '@/components/print/util.js' import drawQrcode from '@/components/print/weapp.qrcode.esm.js' import Bluetooth from '@/components/print/bluetooth.js' let bluetooth = new Bluetooth(); let isPrint= false let data1 = {} export default { // onDone: 打印完成(或失败/跳过)后执行的回调,用于队列驱动 getData(onDone) { var that = this; if(uni.getStorageSync('bluetoothDeviceId')){ let id = uni.getStorageSync('bluetoothDeviceId') const baseUrl = getApp().globalData.mainurl uni.request({ url: baseUrl + "/mall/order/detail/"+ getApp().globalData.printData[0].order_id, data: {}, method:'GET', header: { "content-type": 'application/x-www-form-urlencoded', 'accessToken':uni.getStorageSync('hiver_token') }, success: function(res) { if (res.data.code == 200) { data1 = res.data.result that.bindViewTap(id, false, onDone) } else { uni.showToast({ title: res.data.message, icon: 'none' }); // 请求失败也需要通知队列继续处理下一条 if (typeof onDone === 'function') onDone(); return; } uni.hideLoading(); }, fail: function(err) { uni.hideLoading(); // 请求失败也需要通知队列继续处理下一条 if (typeof onDone === 'function') onDone(); } }) }else{ uni.showModal({ title: '提示', content: '您还没有连接打印机,将无法为您打印小票!', confirmText:'连接蓝牙', cancelText:'暂不连接', success: function (res) { if (res.confirm) { uni.navigateTo({ url:'/pages/myCenter/setPrint' }) } // 未连接打印机也通知队列继续(跳过当前条) if (typeof onDone === 'function') onDone(); } }); } }, async bindViewTap(deviceId, state, onDone) { var _this = this; try { //1.链接设备 await bluetooth.createBLEConnection(deviceId).then((res) => { bluetooth.deviceId = deviceId; }).catch((e) => { throw e; }); let server = []; //2.寻找服务 await bluetooth.getBLEDeviceServices().then((res) => { bluetooth.notifyId = ''; bluetooth.writeId = ''; bluetooth.num = 0; bluetooth.serviceList = res }).catch((e) => { throw e; }); //3.获取蓝牙设备所有服务 let result3 = await bluetooth.getBLEDeviceCharacteristics().then(res => { uni.setStorageSync('bluetoothDeviceId', deviceId); this.pickUpOnce(onDone) }).catch((e) => { throw e; }); } catch (e) { // 蓝牙连接异常也需要通知队列继续 if (typeof onDone === 'function') onDone(); } }, //打印一次 pickUpOnce(onDone) { isPrint = true; bluetooth.notifyBLECharacteristicValue(); let self = this; setTimeout(() => { self.writeBLECharacteristicValue(onDone); }, 500); }, //写入控制命令 async writeBLECharacteristicValue(onDone) { if(data1.receiverName == null){ data1.receiverName = "***" } if(data1.receiverAddress == null){ data1.receiverAddress = '***' } if(data1.deliveryInfo == null){ data1.deliveryInfo = { mustFinishTime:"***" } } let printerJobs = new PrinterJobs(); printerJobs.setAlign('ct').setSize(2, 2).setLineSpacing(80).print(data1.numberCode + ((data1.status == 7 || data1.status == 11)? '待退款' :data1.deliveryType == 1?'配送':data1.isPack== 0?'自取-堂食':data1.isPack== 1?'自取-打包':'自取')) .setAlign('lt').setSize(1, 1).setLineSpacing(40).print('预计时间:'+ data1.deliveryInfo == null?'暂无':data1.deliveryInfo.mustFinishTime) .setAlign('lt').setSize(1, 1).setLineSpacing(40).print(data1.shopName) .print(printerUtil.fillLine('-', 1, 50)) .setAlign('lt').setSize(2, 2).setLineSpacing(80).print(data1.receiverName == null?'暂无':data1.receiverName) .setAlign('lt').setSize(1, 1).setLineSpacing(40).print('联系电话: '+data1.receiverPhone) .setAlign('lt').setSize(2, 2).setLineSpacing(80).print('地址:'+(data1.receiverAddress == null?'暂无':data1.receiverAddress)) .setAlign('lt').setSize(1, 1).setLineSpacing(40).print('为保护隐私,顾客电话及地址已被隐藏,您可登录商家端或骑手端查看') .print(printerUtil.fillLine('-', 1, 50)); for (var i = 0; i < data1.goodsList.length; i++) { printerJobs.setAlign('lt').setSize(1, 1).setLineSpacing(40).print(data1.goodsList[i].productName) printerJobs.setAlign('lt').setSize(1, 1).setLineSpacing(40).print(this.delNode(data1.goodsList[i].specs)) let setLineSpacing = 40 printerJobs.setLineSpacing(setLineSpacing).print(printerUtil.inlineArr([{ 'text': data1.goodsList[i].price, 'width': 10, }, { 'text': 'X' + data1.goodsList[i].quantity, 'width': 20, }], 1, 50)); } printerJobs.print(printerUtil.fillLine('-', 1, 50)) .setAlign('lt').setSize(1, 1).setLineSpacing(40).print('配送费:'+ data1.deliveryFee) .setAlign('lt').setSize(1, 1).setLineSpacing(40).print('合计金额:'+ data1.totalAmount) .print(printerUtil.fillLine('-', 1, 50)) .setAlign('lt').setSize(1, 1).setLineSpacing(40).print('商品取到后,如有任何商品问题,请及时联系商家和平台,客服将为您服务,客服电话15533910775,谢谢您的惠顾') .println(); let buffer = printerJobs.buffer(); this.sendPrint(buffer, onDone); }, delNode(data) { // 1. 统一转为字符串 let str; if (typeof data === 'object' && data !== null) { // 对象或数组 → JSON 字符串 str = JSON.stringify(data); } else if (typeof data === 'string') { str = data; } else { // 其他类型(数字、布尔等)先转字符串 str = String(data); } // 2. 删除所有大括号 { } 和双引号 " const result = str.replace(/[{}"]/g, ''); return result; }, sendPrint(buffer, onDone) { // 1.并行调用多次会存在写失败的可能性 // 2.建议每次写入不超过20字节 // 分包处理,延时调用 let that = this const maxChunk = 20; const delay = 20; isPrint = true; const totalPackages = Math.ceil(buffer.byteLength / maxChunk); for (let i = 0, j = 0, length = buffer.byteLength; i < length; i += maxChunk, j++) { let subPackage = buffer.slice(i, i + maxChunk <= length ? (i + maxChunk) : length); // 最后一个分包发送完成后,标记打印结束并触发回调 if (j === totalPackages - 1) { setTimeout(() => { that.sendPrintData(subPackage); isPrint = false; if (typeof onDone === 'function') onDone(); }, j * delay); } else { setTimeout(this.sendPrintData, j * delay, subPackage); } } }, sendPrintData(buffer) { bluetooth.writeBLECharacteristicValue(buffer).then(res => {}); }, startSearch(state) { let that = this bluetooth.openBluetoothAdapter().then(e => { uni.startBluetoothDevicesDiscovery({ success: res => { uni.onBluetoothDeviceFound(result => { let arr = that.list; let devices = []; let list = result.devices; for (let i = 0; i < list.length; ++i) { if (list[i].name && list[i].name != "未知设备") { let arrNew = arr.filter((item) => { return item.deviceId == list[i].deviceId; }); if (arrNew.length == 0) { devices.push(list[i]); } if (uni.getStorageSync('bluetoothDeviceId') == list[i] .deviceId) { // that.bindViewTap(list[i].deviceId, state) } } } that.list = arr.concat(devices); }); }, fail: res => { uni.hideLoading(); uni.showToast({ title: `搜索设备失败` + JSON.stringify(err) }) } }) }).catch(e => {}); }, // 停止搜索 stopSearch() { uni.hideLoading(); bluetooth.stopBluetoothDevicesDiscovery(); } }