WMS_PDA/src/components/BluetoothPrint/BluetoothPrint.vue
liufumingren 5ae92e0f63 chore(cli): 由 HBuilderX 工程迁移为 uni-app Vue2 CLI 脚手架工程
- 业务源码统一迁入 src/,H5 模板移到 public/index.html
- 新增 @vue/cli 4.5 + @dcloudio 2.0.2-5020620260917001 全套依赖与 scripts
- 保留 vue.config.js 的 ROUTES 注入(uni-simple-router 运行时依赖)
- 新增 scripts/node-compat.cjs 兼容 Node 23+ 移除的 util.isRegExp 等 API
- README 补充构建/运行/回退说明
2026-10-02 19:45:18 +08:00

882 lines
22 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<!-- components/bluetooth-print.vue -->
<template>
<view class="container">
<view class="bluetooth-print" v-if="bluetoothAvailable">
<!-- 内容区域 -->
<view class="section">
<!-- 蓝牙设备选择组件 -->
<BluetoothDeviceSelector :selectedDevice="selectedDevice" :deviceList="deviceList"
@scan="scanBluetoothDevices" :discovering="discovering" @change="confirmSelection" />
<!-- 打印模板选择 -->
<view class="detail-item selectable" @click="showTemplateSelector = true">
<text class="detail-item-label">打印模板:</text>
<view class="detail-item-value">
<text>{{ printRenderData.selectedTemplate ? `${printRenderData.selectedTemplate.template_name}【${printRenderData.selectedTemplate.page_width}mm*${printRenderData.selectedTemplate.page_height}mm】` : "点击选择打印模板" }}</text>
<u-icon name="arrow-right" size="24" color="#666"></u-icon>
</view>
</view>
<view class="detail-item selectable" :prop="printRenderData" :change:prop="printRender.update"
@click="printRender.generateImage">
<text class="detail-item-label">预览</text>
</view>
<view class="view-section">
<scroll-view class="viewer" scroll-x="true" scroll-y="true" >
<image :src="imageUrl" :style="contentStyle"></image>
</scroll-view>
<view class="card-content" id="card-content" :style="contentStyle">1111</view>
</view>
<!-- 操作日志区域 -->
<view class="log-section" v-if="log.length > 0">
<view class="log-header">
<u-icon name="file-text" size="32" color="#2979ff"></u-icon>
<text class="log-title">操作日志</text>
<text class="log-count">({{ log.length }})</text>
<view class="log-actions">
<u-button size="mini" type="primary" @click="clearLogs" :plain="true">
清空
</u-button>
</view>
</view>
<scroll-view scroll-y class="log-container">
<view class="log-list">
<view v-for="(item, index) in log" :key="index" class="log-item"
:class="[`log-${item.type}`]">
<view class="log-item-header">
<u-icon :name="getLogIcon(item.type)" size="24"
:color="getLogColor(item.type)"></u-icon>
<text class="log-type">{{ getLogTypeText(item.type) }}</text>
<text class="log-time">{{ formatTime(item.timestamp) }}</text>
</view>
<view class="log-message">
{{ item.message }}
</view>
<view v-if="item.details" class="log-details">
<text class="details-label">详情:</text>
<text class="details-content">{{ item.details }}</text>
</view>
</view>
</view>
<view v-if="log.length === 0" class="log-empty">
<u-icon name="list" size="60" color="#dcdfe6"></u-icon>
<text class="empty-text">暂无操作日志</text>
</view>
</scroll-view>
</view>
</view>
<!-- 操作按钮 -->
<view class="action-buttons">
<u-button type="primary" :disabled="!selectedDevice || !printRenderData.selectedTemplate"
@click="handlePrint" :loading="printing">
{{ printing ? '打印中...' : '开始打印' }}
</u-button>
</view>
</view>
<u-empty class="bluetoothUnAvailable" mode="address" text="蓝牙未开启" velse>
</u-empty>
<!-- 打印模板选择弹窗 -->
<u-popup :show="showTemplateSelector" mode="bottom" round="20" @close="showTemplateSelector = false">
<view class="template-selector-popup">
<view class="popup-header">
<text class="popup-title">选择打印模板</text>
</view>
<scroll-view scroll-y class="template-list" style="height: 400px;">
<view v-for="template in printTemplateList" :key="template.id" class="template-item"
:class="{ selected: printRenderData.selectedTemplate && printRenderData.selectedTemplate.id === template.id }"
@click="selectTemplate(template)">
<u-icon name="file-text" size="40" color="#19be6b"></u-icon>
<view class="template-info">
<text
class="template-name">{{ template.template_name }}【{{template.page_width}}mm*{{template.page_height}}mm】</text>
</view>
<u-icon
v-if="printRenderData.selectedTemplate && printRenderData.selectedTemplate.id === template.id"
name="checkbox-mark" size="28" color="#2979ff"></u-icon>
</view>
<view v-if="printTemplateList.length === 0" class="empty-state">
<u-icon name="file-text" size="60" color="#ccc"></u-icon>
<text class="empty-text">暂无可用模板</text>
</view>
</scroll-view>
</view>
</u-popup>
</view>
</template>
<script>
export default {
name: 'BluetoothPrint',
props: {
printData: {
type: Object,
default: () => ({})
}
},
data() {
return {
printTemplateList: [],
showTemplateSelector: false,
printing: false,
//bluetoothAvailable: true,
showView: false,
printRenderData: {
selectedTemplate: null,
targetSize: 203.2,
mmToDot: 8,
cardWidthMm: 40,
cardHeightMm: 30,
printImage: "",
},
imageUrl: null,
CanvasData: {}
}
},
mounted() {
this.init();
},
computed: {
contentStyle(){
return {
width:this.printRenderData.selectedTemplate?.page_width+"mm"||0,
height:this.printRenderData.selectedTemplate?.page_height+"mm"||0,
}
},
deviceList() {
return this.$store.state.bluetoothPrint.bluetoothDevices
},
printConfig() {
return this.$store.state.bluetoothPrint.printerConfig
},
printConfig() {
return this.$store.state.bluetoothPrint.printerConfig
},
selectedDevice() {
return this.$store.state.bluetoothPrint.currentDevice
},
discovering() {
return this.$store.state.bluetoothPrint.discovering
},
log() {
return this.$store.state.bluetoothPrint.operationLogs || []
},
bluetoothAvailable() {
return this.$store.state.bluetoothPrint.bluetoothAvailable
}
},
watch: {
printData: {
handler(newVal) {
console.log(newVal)
if (newVal.type) {
this.getPrintTemplate();
}
},
deep: true
},
bluetoothAvailable: {
handler(newVal) {
if (newVal) {
this.init();
}
}
}
},
methods: {
// 初始化
async init() {
console.log(this.deviceList);
await this.getPrintTemplate();
},
//渲染canvas
renderCanvas() {
if (this.selectedTemplate.id) {
this.showView = true;
} else {
uni.showToast({
title: '未选择打印模板',
icon: 'none'
});
}
},
// 获取打印模板
async getPrintTemplate() {
console.log("getPrintTemplate", this.printData.type)
const templates = await this.$store.dispatch("bluetoothPrint/getPrintTemplate", this.printData.type);
console.log("========templates", templates);
if (templates.code == 200) {
this.printTemplateList = templates.data || [];
}
},
// 扫描蓝牙设备
async scanBluetoothDevices(status) {
console.log("搜索设备", status ? "开" : "关");
const devices = await this.$store.dispatch('bluetoothPrint/scanDevices', status);
},
// 选择模板
selectTemplate(template) {
this.printRenderData.selectedTemplate = template;
this.showTemplateSelector = false;
},
// 确认模板选择
confirmTemplate() {
this.showTemplateSelector = false;
},
// 处理打印
async handlePrint() {
if (!this.selectedDevice) {
uni.showToast({
title: '请选择打印设备',
icon: 'none'
})
return
}
this.printing = true;
try {
await this.$store.dispatch('bluetoothPrint/printCanvas', this.CanvasData);
uni.showToast({
title: '打印指令已发送',
icon: 'success'
});
} catch (error) {
console.error('打印失败:', error);
uni.showToast({
title: error.message || '打印失败',
icon: 'none'
});
} finally {
this.printing = false;
}
},
async confirmSelection(device) {
const result = await this.$store.dispatch('bluetoothPrint/connectDevice', device);
console.log(result);
},
// 获取日志图标
getLogIcon(type) {
const icons = {
'success': 'checkmark-circle',
'error': 'close-circle',
'warning': 'error-circle',
'info': 'info-circle',
'default': 'chat'
}
return icons[type] || icons['default'];
},
// 获取日志颜色
getLogColor(type) {
const colors = {
'success': '#19be6b',
'error': '#fa3534',
'warning': '#ff9900',
'info': '#2979ff',
'default': '#909399'
}
return colors[type] || colors['default'];
},
// 获取日志类型文本
getLogTypeText(type) {
const texts = {
'success': '成功',
'error': '错误',
'warning': '警告',
'info': '信息',
'default': '日志'
}
return texts[type] || texts['default'];
},
// 格式化时间
formatTime(timestamp) {
if (!timestamp) return '';
const date = new Date(timestamp);
return `1`;
},
// 清空日志
clearLogs() {
this.$store.dispatch('bluetoothPrint/clearLogs');
},
onImage(src) {
this.imageUrl = src;
},
canvasData(canvas) {
this.CanvasData = canvas;
}
}
}
</script>
<script module="printRender" lang="renderjs">
import html2canvas from 'html2canvas'
import dpiConverter from '@/core/utils/dpi-converter'
let datas = {};
function inArray(arr, key, val) {
for (let i = 0; i < arr.length; i++) {
if (arr[i][key] === val) {
return i;
}
}
return -1;
}
// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
var hexArr = Array.prototype.map.call(
new Uint8Array(buffer),
function (bit) {
return ('00' + bit.toString(16)).slice(-2)
}
)
return hexArr.join('');
}
function convertToGrayscale(data) {
let g = 0
for (let i = 0; i < data.length; i += 4) {
g = (data[i] * 0.3 + data[i + 1] * 0.59 + data[i + 2] * 0.11)
data[i] = g
data[i + 1] = g
data[i + 2] = g
}
return data
}
function setPixel(data, offset, value) {
data[offset] = value;
data[offset + 1] = value;
data[offset + 2] = value;
}
function adjustPixel(data, offset, value) {
data[offset] += value;
}
function convertToMonoImage(width, height, imageData, shake) {
// 创建新的数据数组,避免修改原数据
const data = new Uint8ClampedArray(imageData.data);
let g = 0;
let e = 0;
// 第一步:转为灰度(只修改R通道作为灰度值)
for (let i = 0; i < data.length; i += 4) {
// 计算灰度值
g = Math.round(data[i] * 0.3 + data[i + 1] * 0.59 + data[i + 2] * 0.11);
// 设置所有通道为相同的灰度值
data[i] = g; // R
data[i + 1] = g; // G
data[i + 2] = g; // B
// data[i + 3] 保持原alpha不变
}
if (!shake) {
// 如果不抖动,直接二值化
for (let i = 0; i < data.length; i += 4) {
const gray = data[i];
const value = gray >= 150 ? 255 : 0;
data[i] = value;
data[i + 1] = value;
data[i + 2] = value;
}
return new ImageData(data, width, height);
}
// 第二步:Floyd-Steinberg抖动
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const idx = (y * width + x) * 4;
const oldPixel = data[idx]; // 当前像素的灰度值
// 量化
const newPixel = oldPixel >= 150 ? 255 : 0;
const error = oldPixel - newPixel;
// 设置量化后的值
data[idx] = newPixel;
data[idx + 1] = newPixel;
data[idx + 2] = newPixel;
if (error !== 0) {
// 向右传播 7/16
if (x + 1 < width) {
const rightIdx = (y * width + (x + 1)) * 4;
data[rightIdx] = Math.min(255, Math.max(0, data[rightIdx] + error * 7 / 16));
}
// 向左下传播 3/16
if (y + 1 < height && x > 0) {
const bottomLeftIdx = ((y + 1) * width + (x - 1)) * 4;
data[bottomLeftIdx] = Math.min(255, Math.max(0, data[bottomLeftIdx] + error * 3 / 16));
}
// 向下传播 5/16
if (y + 1 < height) {
const bottomIdx = ((y + 1) * width + x) * 4;
data[bottomIdx] = Math.min(255, Math.max(0, data[bottomIdx] + error * 5 / 16));
}
// 向右下传播 1/16
if (y + 1 < height && x + 1 < width) {
const bottomRightIdx = ((y + 1) * width + (x + 1)) * 4;
data[bottomRightIdx] = Math.min(255, Math.max(0, data[bottomRightIdx] + error * 1 / 16));
}
}
}
}
return new ImageData(data, width, height);
}
export default {
methods: {
async update(newval) {
datas = newval;
},
async generateImage(event, ownerInstance) {
console.log("点击预览", datas);
try {
if (!datas.selectedTemplate.id) {
throw new Error('未选择模板');
}
const element = document.getElementById('card-content')
console.log("element", element);
// 获取当前元素实际渲染尺寸
const rect = element.getBoundingClientRect();
console.log("rect", rect);
const currentWidthPx = rect.width
const currentHeightPx = rect.height
console.log("currentWidthPx", currentWidthPx);
datas.selectedTemplate.page_width
console.log('当前尺寸:', currentWidthPx, 'px');
const scaleFactor = datas.selectedTemplate.page_width*8/currentWidthPx;
const targetSize = {
width:datas.selectedTemplate.page_width*8,
height:datas.selectedTemplate.page_height*8
};
console.log('目标尺寸:', datas.selectedTemplate.page_width*8, 'px');
console.log('缩放比例:', datas.selectedTemplate.page_width*8/currentWidthPx)
console.log('目标尺寸:', targetSize, 'px')
// 生成高精度画布
html2canvas(element, {
backgroundColor: '#ffffff',
useCORS: true,
allowTaint: false,
logging: true,
width: rect.width,
height: rect.height
}).then(sourceCanvas => {
// 创建两个 canvas:一个用于图像处理,一个用于显示测试
const imageCanvas = document.createElement('canvas');
imageCanvas.width = sourceCanvas.width;
imageCanvas.height = sourceCanvas.height;
const imageCtx = imageCanvas.getContext('2d', { willReadFrequently: true });
const displayCanvas = document.createElement('canvas');
displayCanvas.width = sourceCanvas.width;
displayCanvas.height = sourceCanvas.height;
const displayCtx = displayCanvas.getContext('2d', { willReadFrequently: true });
// 复制源内容到两个 canvas
imageCtx.drawImage(sourceCanvas, 0, 0);
displayCtx.drawImage(sourceCanvas, 0, 0);
// 处理图像数据
const imgData = imageCtx.getImageData(0, 0, sourceCanvas.width, sourceCanvas.height);
const processedImgData = convertToMonoImage(
sourceCanvas.width,
sourceCanvas.height,
imgData,
true
);
// 将处理后的数据写入两个 canvas
imageCtx.putImageData(processedImgData, 0, 0);
displayCtx.putImageData(processedImgData, 0, 0);
// 在显示用的 canvas 上添加测试标记
displayCtx.fillStyle = 'red';
displayCtx.fillRect(10, 10, 50, 50);
// 等待一帧确保所有绘制完成
requestAnimationFrame(() => {
// 验证处理后的图像数据
const testImagePixel = imageCtx.getImageData(15, 15, 1, 1);
console.log('处理后图像像素 (应该是黑白):', testImagePixel.data);
// 验证显示用的测试标记
const testDisplayPixel = displayCtx.getImageData(15, 15, 1, 1);
console.log('显示用 canvas 像素 (应该是红色):', testDisplayPixel.data);
// 返回处理后的图像数据(不包含测试标记)
const finalImgData = imageCtx.getImageData(0, 0, sourceCanvas.width, sourceCanvas.height);
// 生成图片(使用 imageCanvas,不包含测试标记)
const src = imageCanvas.toDataURL('image/png');
ownerInstance.callMethod('onImage', src);
// 返回处理后的数据
ownerInstance.callMethod('canvasData', {
data: processedImgData.data,
width: imageCanvas.width,
height: imageCanvas.height
});
// 可以临时显示测试用的 canvas 来验证
// document.body.appendChild(displayCanvas);
});
});
} catch (error) {
console.error('生成失败:', error)
}
},
/**
* 保存为打印文件
*/
savePrintFile() {
if (!this.printImage) return
const link = document.createElement('a')
link.download = `print-card-${this.cardWidthMm}x${this.cardHeightMm}mm-${this.targetDpi}dpi.png`
link.href = this.printImage
link.click()
},
}
}
</script>
<style scoped lang="scss">
.container {
width: 100%;
height: 100%;
}
.bluetooth-print {
height: 100%;
padding: 20rpx;
display: flex;
flex-direction: column;
box-sizing: border-box;
.section {
display: flex;
flex-direction: column;
flex: 1;
height: 100rpx;
gap: 24rpx;
}
.view-section {
width: 100%;
height: 300rpx;
.viewer {
width: 100%;
height: 100%;
}
.card-content {
position: fixed;
top: 100%;
width: 40mm;
height: 30mm;
font-size: 1mm;
color:#ff0000;
}
}
// 日志区域样式
.log-section {
background: #fff;
border-radius: 12rpx;
border: 1rpx solid #e4e7ed;
overflow: hidden;
margin-top: 16rpx;
flex: 1;
display: flex;
flex-direction: column;
.log-header {
display: flex;
align-items: center;
padding: 24rpx 32rpx;
border-bottom: 1rpx solid #f0f0f0;
background: #f8f9fa;
.log-title {
font-size: 32rpx;
font-weight: 600;
color: #303133;
margin-left: 12rpx;
}
.log-count {
font-size: 24rpx;
color: #909399;
margin-left: 8rpx;
}
.log-actions {
margin-left: auto;
}
}
.log-container {
flex: 1;
height: 400rpx;
.log-list {
padding: 16rpx 24rpx;
}
.log-item {
padding: 20rpx;
margin-bottom: 16rpx;
border-radius: 8rpx;
background: #f8f9fa;
border-left: 4rpx solid;
&.log-success {
border-left-color: #19be6b;
background: linear-gradient(135deg, #f0f9eb 0%, #e8f5e9 100%);
}
&.log-error {
border-left-color: #fa3534;
background: linear-gradient(135deg, #fef0f0 0%, #fde2e2 100%);
}
&.log-warning {
border-left-color: #ff9900;
background: linear-gradient(135deg, #fdf6ec 0%, #fef8e8 100%);
}
&.log-info {
border-left-color: #2979ff;
background: linear-gradient(135deg, #ecf5ff 0%, #e8f3ff 100%);
}
.log-item-header {
display: flex;
align-items: center;
margin-bottom: 12rpx;
.log-type {
font-size: 24rpx;
font-weight: 500;
margin-left: 8rpx;
color: #303133;
}
.log-time {
margin-left: auto;
font-size: 22rpx;
color: #909399;
}
}
.log-message {
font-size: 28rpx;
color: #606266;
line-height: 1.5;
word-break: break-all;
}
.log-details {
margin-top: 8rpx;
padding-top: 8rpx;
border-top: 1rpx dashed #dcdfe6;
.details-label {
font-size: 24rpx;
color: #909399;
font-weight: 500;
}
.details-content {
font-size: 24rpx;
color: #606266;
margin-left: 4rpx;
}
}
}
.log-empty {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 80rpx 0;
color: #c0c4cc;
.empty-text {
margin-top: 16rpx;
font-size: 28rpx;
color: #909399;
}
}
}
}
.detail-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 24rpx 0;
border-bottom: 1rpx solid #f5f5f5;
&.selectable {
cursor: pointer;
&:active {
background-color: #f9f9f9;
}
}
.detail-item-label {
font-size: 32rpx;
color: #333;
font-weight: 500;
}
.detail-item-value {
display: flex;
align-items: center;
gap: 16rpx;
font-size: 28rpx;
color: #666;
max-width: 60%;
text-align: right;
text {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
}
}
.action-buttons {
margin-top: auto;
padding-top: 30rpx;
border-top: 1rpx solid #eee;
}
}
.template-selector-popup {
background-color: #fff;
border-radius: 20rpx 20rpx 0 0;
height: 60vh;
.popup-header {
padding: 40rpx 32rpx 24rpx;
border-bottom: 1rpx solid #f0f0f0;
.popup-title {
font-size: 36rpx;
font-weight: bold;
color: #333;
}
}
.template-list {
padding: 24rpx 32rpx;
.template-item {
display: flex;
align-items: center;
padding: 24rpx;
margin-bottom: 16rpx;
border-radius: 16rpx;
border: 2rpx solid #eee;
&:active {
background-color: #f9f9f9;
}
&.selected {
border-color: #2979ff;
background-color: #f0f7ff;
}
.template-info {
flex: 1;
margin-left: 24rpx;
display: flex;
flex-direction: column;
.template-name {
font-size: 32rpx;
color: #333;
font-weight: 500;
margin-bottom: 8rpx;
}
.template-desc {
font-size: 24rpx;
color: #999;
}
}
}
.empty-state {
display: flex;
flex-direction: column;
align-items: center;
padding: 80rpx 0;
.empty-text {
margin-top: 24rpx;
font-size: 28rpx;
color: #999;
}
}
}
.popup-actions {
display: flex;
padding: 24rpx 32rpx;
border-top: 1rpx solid #f0f0f0;
gap: 24rpx;
.u-button {
flex: 1;
}
}
}
.bluetoothUnAvailable {
width: 100%;
height: 100%;
}
</style>