feat(蓝牙秤): 订单复核页接入蓝牙秤,修复连接切换/扫描问题与老机型弹窗间隔

- 订单复核页 order-review.vue 称重弹窗接入蓝牙秤(复用 bluetoothScale store):
  - 称重行新增「读秤/连秤」按钮,蓝牙秤状态卡(实时重量/自动读秤/连接/断开/设备管理)
  - 新增蓝牙秤连接弹窗(按名称连接/扫描设备列表)与断开二次确认弹窗
  - 导航栏右侧新增「蓝牙秤/已连」入口,复核开始前可提前手动连接
  - 读秤/自动读秤回填(单位 g),带 1g 抖动阈值与编辑保护,回填前先失焦避免输入框不刷新
  - 连接弹窗与按钮样式对齐称重页 weighing.vue

- bluetoothScale store 模块修复:
  - 切换设备改为单连接:连接前先断开旧设备,manualDisconnect 阻止自动重连争抢
  - already-connect 分支改为重新发现服务并重新订阅通知,切回仍连接设备也能稳定收数
  - 扫描列表合并已配对设备 + 本地持久化历史连接设备(WMS_BT_SCALE_HISTORY),
    解决切换设备后扫描找不到之前连接过的设备

- 老机型 flex gap 兼容(改用 margin):
  - order-review.vue 称重/包材/断开确认/扫描数量弹窗底部按钮
  - ReviewDetail.vue 无条码复核弹窗底部按钮
This commit is contained in:
zm2000 2026-10-16 17:59:47 +08:00
parent fb14f89aef
commit 445e4aa209
4 changed files with 856 additions and 68 deletions

View File

@ -37,6 +37,30 @@ function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// ---------------- 历史连接设备持久化 ----------------
const HISTORY_KEY = 'WMS_BT_SCALE_HISTORY';
function loadHistoryDevices() {
try {
const list = uni.getStorageSync(HISTORY_KEY);
return Array.isArray(list) ? list : [];
} catch (e) {
return [];
}
}
function saveHistoryDevice(device) {
if (!device || !device.deviceId) return;
try {
const list = loadHistoryDevices().filter(d => d && d.deviceId !== device.deviceId);
list.unshift({ deviceId: device.deviceId, name: device.name || '' });
if (list.length > 20) list.length = 20;
uni.setStorageSync(HISTORY_KEY, list);
} catch (e) {
// ignore
}
}
function normalizeBluetoothError(error) {
const raw = error && (error.message || error.errMsg || String(error));
const text = String(raw || '').trim();
@ -92,6 +116,8 @@ let reconnectTimer = null;
let disconnectDebounceTimer = null;
let scanStopTimer = null;
let manualDisconnect = false;
// 连接互斥锁:避免手动连接与自动重连并发执行
let connectLock = false;
const SCAN_TIMEOUT_MS = 12000;
@ -267,6 +293,27 @@ function parseIncoming(commit, state, res) {
}
}
// 发现可订阅(notify/indicate)的重量特征值,返回 { service, characteristic, error }
async function discoverNotifyCharacteristic(deviceId) {
const [srvErr, srvRes] = await uni.getBLEDeviceServices({ deviceId });
if (srvErr || !srvRes || !srvRes.services || !srvRes.services.length) {
return { service: null, characteristic: null, error: new Error('未发现设备服务') };
}
for (const service of srvRes.services) {
const [chErr, chRes] = await uni.getBLEDeviceCharacteristics({
deviceId,
serviceId: service.uuid
});
if (chErr || !chRes || !chRes.characteristics) continue;
for (const ch of chRes.characteristics) {
if (ch.properties && (ch.properties.notify || ch.properties.indicate)) {
return { service, characteristic: ch, error: null };
}
}
}
return { service: null, characteristic: null, error: new Error('未找到可订阅的重量数据特征') };
}
const actions = {
/**
* 初始化蓝牙适配器并注册全局监听
@ -365,6 +412,11 @@ const actions = {
*/
async startScan({ commit, dispatch }) {
commit('RESET_DEVICES');
// 已配对/已连接设备不会出现在 discovery 结果中,先并入列表;
// 并加载历史连接过的设备,避免切换设备后扫描找不到之前连接过的设备名称
const bonded = await dispatch('getBondedDevices');
(Array.isArray(bonded) ? bonded : []).forEach(d => commit('ADD_DEVICE', d));
loadHistoryDevices().forEach(d => commit('ADD_DEVICE', d));
const [err] = await uni.startBluetoothDevicesDiscovery({ allowDuplicatesKey: false });
commit('DISCOVERING', true);
if (err) {
@ -428,7 +480,7 @@ const actions = {
commit('SET_CONNECTION_STATUS', 'scanning');
await dispatch('startScan');
const timeout = 15000;
const timeout = SCAN_TIMEOUT_MS;
const startAt = Date.now();
try {
while (Date.now() - startAt < timeout) {
@ -458,6 +510,12 @@ const actions = {
return;
}
if (connectLock) {
commit('ADD_LOG', { type: 'info', message: '正在连接设备,跳过本次自动重连' });
return;
}
connectLock = true;
commit('SET_RECONNECTING', true);
commit('SET_RECONNECT_MESSAGE', '正在恢复蓝牙连接...');
commit('SET_CONNECTION_STATUS', 'connecting');
@ -485,15 +543,27 @@ const actions = {
throw connErr;
}
if (state.currentDevice.serviceId && state.currentDevice.characteristicId) {
const [notifyErr] = await uni.notifyBLECharacteristicValueChange({
deviceId: state.currentDevice.id,
serviceId: state.currentDevice.serviceId,
characteristicId: state.currentDevice.characteristicId,
state: true
});
if (notifyErr) throw notifyErr;
}
// 连接建立后部分安卓机型服务可用存在延时,短暂等待再重新发现服务
await delay(400);
// 重连后重新发现服务/特征,避免直接复用旧特征实例导致 notify 失败
const discovered = await discoverNotifyCharacteristic(state.currentDevice.id);
if (discovered.error) throw discovered.error;
const [notifyErr] = await uni.notifyBLECharacteristicValueChange({
deviceId: state.currentDevice.id,
serviceId: discovered.service.uuid,
characteristicId: discovered.characteristic.uuid,
state: true
});
if (notifyErr) throw notifyErr;
commit('SET_CURRENT_DEVICE', {
id: state.currentDevice.id,
name: state.currentDevice.name || '未知设备',
serviceId: discovered.service.uuid,
characteristicId: discovered.characteristic.uuid
});
clearReconnectTimer();
commit('SET_RECONNECT_ATTEMPTS', 0);
@ -516,6 +586,8 @@ const actions = {
});
}
throw e;
} finally {
connectLock = false;
}
},
@ -525,14 +597,30 @@ const actions = {
commit('ADD_LOG', { type: 'info', message: `设备已连接,继续读取重量: ${device.name || device.deviceId}` });
return true;
}
if (manualDisconnect) {
commit('ADD_LOG', { type: 'info', message: `已手动断开,忽略重复连接: ${device.name || device.deviceId}` });
return false;
if (connectLock) {
commit('ADD_LOG', { type: 'info', message: '正在连接其他设备,请稍候' });
throw new Error('正在连接中,请稍候');
}
connectLock = true;
clearReconnectTimer();
clearDisconnectDebounceTimer();
manualDisconnect = false;
// 单连接:切换设备前先显式断开旧设备,避免旧设备残留连接;
// 断开期间置 manualDisconnect=true,阻止全局监听对旧设备触发自动重连
const prev = state.currentDevice;
const prevId = prev && prev.id;
if (prevId && prevId !== device.deviceId) {
manualDisconnect = true;
try {
await uni.closeBLEConnection({ deviceId: prevId });
} catch (e) {
// ignore
}
commit('ADD_LOG', { type: 'info', message: `已断开旧设备: ${prev.name || prevId}` });
}
commit('SET_CONNECTION_STATUS', 'connecting');
commit('ADD_LOG', { type: 'info', message: `正在连接: ${device.name || device.deviceId}` });
@ -541,61 +629,48 @@ const actions = {
deviceId: device.deviceId,
timeout: 10000
});
if (connErr) {
const errText = String(connErr.message || connErr.errMsg || '');
if (/already connect|已连接|already connected/i.test(errText)) {
if (!state.currentDevice || state.currentDevice.id !== device.deviceId) {
commit('SET_CURRENT_DEVICE', {
id: device.deviceId,
name: device.name || '未知设备',
serviceId: (state.currentDevice && state.currentDevice.serviceId) || '',
characteristicId: (state.currentDevice && state.currentDevice.characteristicId) || ''
});
}
commit('SET_RECONNECTING', false);
commit('SET_RECONNECT_MESSAGE', '');
commit('SET_CONNECTION_STATUS', 'connected');
commit('SET_RECONNECT_ATTEMPTS', 0);
dispatch('stopScan');
commit('ADD_LOG', { type: 'warning', message: `设备已处于连接状态,继续读取重量: ${device.name || device.deviceId}` });
return true;
}
throw connErr;
}
const [srvErr, srvRes] = await uni.getBLEDeviceServices({ deviceId: device.deviceId });
if (srvErr || !srvRes || !srvRes.services || !srvRes.services.length) {
throw new Error('未发现设备服务');
}
// already-connect 兜底:设备已处于系统连接状态,重新发现服务并重新订阅通知,
// 避免复用旧特征实例导致收不到重量数据
if (connErr && /already connect|已连接|already connected/i.test(String(connErr.message || connErr.errMsg || ''))) {
// 连接已建立,短暂等待服务可用后重新发现服务/特征
await delay(400);
const discovered = await discoverNotifyCharacteristic(device.deviceId);
if (discovered.error) throw discovered.error;
// 遍历服务,找到具备 notify/indicate 的特征值(电子秤重量数据通常通过通知推送)
let notifyChar = null;
let notifyService = null;
for (const service of srvRes.services) {
const [chErr, chRes] = await uni.getBLEDeviceCharacteristics({
const [notifyErr] = await uni.notifyBLECharacteristicValueChange({
deviceId: device.deviceId,
serviceId: service.uuid
serviceId: discovered.service.uuid,
characteristicId: discovered.characteristic.uuid,
state: true
});
if (chErr || !chRes || !chRes.characteristics) continue;
if (notifyErr) throw notifyErr;
for (const ch of chRes.characteristics) {
if (ch.properties && (ch.properties.notify || ch.properties.indicate)) {
notifyChar = ch;
notifyService = service;
break;
}
}
if (notifyChar) break;
commit('SET_CURRENT_DEVICE', {
id: device.deviceId,
name: device.name || '未知设备',
serviceId: discovered.service.uuid,
characteristicId: discovered.characteristic.uuid
});
saveHistoryDevice({ deviceId: device.deviceId, name: device.name || '' });
manualDisconnect = false;
commit('SET_RECONNECTING', false);
commit('SET_RECONNECT_MESSAGE', '');
commit('SET_CONNECTION_STATUS', 'connected');
commit('SET_RECONNECT_ATTEMPTS', 0);
dispatch('stopScan');
commit('ADD_LOG', { type: 'warning', message: `设备已处于连接状态,已重新订阅重量数据: ${device.name || device.deviceId}` });
return true;
}
if (connErr) throw connErr;
if (!notifyChar || !notifyService) {
throw new Error('未找到可订阅的重量数据特征');
}
const discovered = await discoverNotifyCharacteristic(device.deviceId);
if (discovered.error) throw discovered.error;
const [notifyErr] = await uni.notifyBLECharacteristicValueChange({
deviceId: device.deviceId,
serviceId: notifyService.uuid,
characteristicId: notifyChar.uuid,
serviceId: discovered.service.uuid,
characteristicId: discovered.characteristic.uuid,
state: true
});
if (notifyErr) throw notifyErr;
@ -603,9 +678,10 @@ const actions = {
commit('SET_CURRENT_DEVICE', {
id: device.deviceId,
name: device.name || '未知设备',
serviceId: notifyService.uuid,
characteristicId: notifyChar.uuid
serviceId: discovered.service.uuid,
characteristicId: discovered.characteristic.uuid
});
saveHistoryDevice({ deviceId: device.deviceId, name: device.name || '' });
clearReconnectTimer();
manualDisconnect = false;
commit('SET_RECONNECT_ATTEMPTS', 0);
@ -616,6 +692,7 @@ const actions = {
commit('ADD_LOG', { type: 'success', message: `连接成功: ${device.name || device.deviceId}` });
return true;
} catch (e) {
manualDisconnect = false;
commit('SET_RECONNECTING', false);
commit('SET_RECONNECT_MESSAGE', '连接失败,可手动重连');
commit('SET_CONNECTION_STATUS', 'error');
@ -625,6 +702,8 @@ const actions = {
message: `连接失败: ${e.message || e.errMsg || '未知错误'}`
});
throw e;
} finally {
connectLock = false;
}
},

View File

@ -1695,7 +1695,10 @@ import voice from '@/core/utils/voice';
.no-barcode-popup__actions {
display: flex;
align-items: center;
gap: 20rpx;
}
.no-barcode-popup__btn + .no-barcode-popup__btn {
margin-left: 20rpx;
}
.no-barcode-popup__btn {

View File

@ -8,6 +8,13 @@
</view>
</template>
<template #right>
<view
class="nav-scale-btn"
:class="{ 'nav-scale-btn--connected': isScaleConnected }"
@click="openScalePopup"
>
<text class="nav-scale-btn__text">{{ isScaleConnected ? '已连' : '蓝牙秤' }}</text>
</view>
<view class="nav-settings-btn" @click="showSettingsPopup = true">
<text class="nav-settings-btn__text">设置</text>
</view>
@ -168,16 +175,70 @@
class="weigh-input"
type="number"
:value="weighWeight > 0 ? String(weighWeight) : ''"
:focus="true"
:focus="weighInputFocused"
:adjust-position="false"
placeholder="请输入重量(g)"
placeholder-style="color:#c0c4cc;font-size:36rpx"
@input="handleWeighInput"
@focus="onWeighInputFocus"
@blur="onWeighInputBlur"
/>
<view class="weigh-btn weigh-btn--plus" @click="weighWeight += 1">+</view>
<text class="weigh-unit">g</text>
<view
class="weigh-read-btn"
:class="{ 'weigh-read-btn--connected': isScaleConnected }"
@click="handleReadScale"
>
<text class="weigh-read-btn-text">{{ isScaleConnected ? '读秤' : '连秤' }}</text>
</view>
</view>
</view>
<!-- 蓝牙秤 -->
<view class="weigh-section-divider"></view>
<view class="weigh-scale-line">
<text class="weigh-scale-label">蓝牙秤</text>
<view class="weigh-scale-right">
<text class="weigh-scale-status" :class="'weigh-scale-status--' + scaleConnectionStatus">{{ scaleStatusText }}</text>
<text v-if="scaleCurrentDevice" class="weigh-scale-device">{{ scaleCurrentDevice.name }}</text>
</view>
</view>
<view class="weigh-scale-line" v-if="isScaleConnected">
<text class="weigh-scale-label">实时重量</text>
<view class="weigh-live-wrap">
<text class="weigh-scale-value">{{ scaleWeightDisplay }}</text>
<text class="weigh-scale-unit">g</text>
<text class="weigh-scale-stable">{{ scaleStable ? '稳定' : '读数中' }}</text>
</view>
</view>
<view class="weigh-scale-line">
<text class="weigh-scale-label">自动读秤</text>
<u-switch v-model="autoReadScale" size="20" activeColor="#2979ff"></u-switch>
</view>
<view class="weigh-scale-actions">
<u-button
v-if="!isScaleConnected"
type="primary"
size="mini"
:customStyle="{ color: '#2979ff', backgroundColor: '#eaf3ff', borderColor: '#b3d8ff' }"
@click="openScalePopup"
>连接蓝牙秤</u-button>
<u-button
v-if="isScaleConnected"
type="error"
size="mini"
:customStyle="{ color: '#fa3534', backgroundColor: '#fef0f0', borderColor: '#fbc4c4' }"
@click="handleScaleDisconnect"
>断开</u-button>
<u-button
v-if="isScaleConnected"
type="info"
size="mini"
:customStyle="{ color: '#909399', backgroundColor: '#f4f4f5', borderColor: '#dcdfe6' }"
@click="openScalePopup"
>设备管理</u-button>
</view>
</view>
<view class="weigh-popup-footer">
<view class="weigh-footer-btn weigh-footer-btn--cancel" @click="handleWeighCancel">取消</view>
@ -186,6 +247,76 @@
</view>
</u-popup>
<!-- 蓝牙秤连接弹窗 -->
<u-popup :show="showScalePopup" mode="bottom" :closeable="true" :closeOnClickOverlay="false" round="20" :z-index="10100" @close="closeScalePopup">
<view class="scale-popup">
<view class="scale-popup-header">
<text class="scale-popup-title">连接蓝牙秤</text>
</view>
<view class="scale-popup-input">
<u-input
v-model="scaleFilterName"
placeholder="电子秤蓝牙名称(完整名称)"
border="surround"
fontSize="32rpx"
></u-input>
<u-button
type="primary"
size="mini"
:disabled="!scaleFilterName"
:loading="scaleConnectionStatus === 'connecting'"
:customStyle="{ width: '200rpx', height: '72rpx', padding: '0', fontSize: '32rpx', flexShrink: '0' }"
@click="handleScaleConnectByName"
>按名称连接</u-button>
</view>
<scroll-view scroll-y class="scale-popup-list" v-if="scaleDevices.length">
<view class="scale-popup-list-inner">
<view
v-for="d in scaleDevices"
:key="d.deviceId"
class="scale-device-item"
:class="{ 'scale-device-item--active': isScaleCurrentDevice(d) }"
@click="handleScaleConnectDevice(d)"
>
<view class="scale-device-info">
<view class="scale-device-name">{{ d.name || '未知设备' }}</view>
<view class="scale-device-id">{{ d.deviceId }}</view>
</view>
<view class="scale-device-connect">{{ isScaleCurrentDevice(d) ? '已连接' : '连接' }}</view>
</view>
</view>
</scroll-view>
<u-empty v-else class="scale-popup-list" mode="list" text="暂无设备,点击扫描"></u-empty>
<view class="scale-popup-actions">
<view class="scale-popup-close-btn" @click="closeScalePopup">关闭</view>
<view
class="scale-popup-scan-btn"
:class="{ 'scale-popup-scan-btn--loading': scaleDiscovering }"
@click="handleScaleScan"
>
<text>{{ scaleDiscovering ? '扫描中...' : '扫描' }}</text>
</view>
</view>
</view>
</u-popup>
<!-- 断开蓝牙秤二次确认弹窗 -->
<u-popup :show="showDisconnectConfirm" mode="center" :closeable="true" :closeOnClickOverlay="false" border-radius="20" :z-index="10110" @close="cancelScaleDisconnect">
<view class="weigh-disconnect-popup">
<view class="weigh-disconnect-popup__title">断开蓝牙秤</view>
<view class="weigh-disconnect-popup__body">
<text class="weigh-disconnect-popup__text">确定要断开当前蓝牙秤连接吗?</text>
</view>
<view class="weigh-disconnect-popup__actions">
<view class="weigh-disconnect-popup__btn weigh-disconnect-popup__btn--cancel" @click="cancelScaleDisconnect">取消</view>
<view class="weigh-disconnect-popup__btn weigh-disconnect-popup__btn--confirm" @click="confirmScaleDisconnect">断开</view>
</view>
</view>
</u-popup>
<!-- 包材绑定弹窗 -->
<u-popup :show="showPackageBindingPopup" mode="bottom" :closeable="true" :closeOnClickOverlay="false" border-radius="20" :z-index="10080" @close="handlePackageBindingSkip">
<view class="package-popup" :style="{ paddingBottom: keyboardHeight ? keyboardHeight + 'px' : '' }">
@ -464,6 +595,15 @@ import ReviewDetail from './order-review-comps/ReviewDetail.vue';
weighWeight: 0,
weighAfterReview: false,
weighCancelled: false,
weighInputFocused: true,
showScalePopup: false,
scaleFilterName: '',
autoReadScale: true,
autoReadThresholdG: 1,
lastAutoWeight: '',
weightEditing: false,
_programmaticFocus: false,
showDisconnectConfirm: false,
packageInputCode: '',
scannedPackageCode: '',
scannedPackageId: '',
@ -600,6 +740,37 @@ import ReviewDetail from './order-review-comps/ReviewDetail.vue';
console.log('[refWeightG] itemsWeight:', this.detailInfo?.itemsWeight, 'kg:', kg, 'g:', g);
return g;
},
scaleWeight() {
return this.$store.state.bluetoothScale.weight;
},
scaleWeightUnit() {
return this.$store.state.bluetoothScale.weightUnit;
},
scaleStable() {
return this.$store.state.bluetoothScale.stable;
},
scaleConnectionStatus() {
return this.$store.state.bluetoothScale.connectionStatus;
},
scaleCurrentDevice() {
return this.$store.state.bluetoothScale.currentDevice;
},
scaleDevices() {
return this.$store.state.bluetoothScale.devices;
},
scaleDiscovering() {
return this.$store.state.bluetoothScale.discovering;
},
isScaleConnected() {
return this.scaleConnectionStatus === 'connected';
},
scaleStatusText() {
return this.$store.getters['bluetoothScale/statusText'];
},
scaleWeightDisplay() {
const g = this.scaleWeightInGrams();
return g === '' ? '--' : g;
},
isIntercepted() {
// 散单模式:波次内任一订单被拦截即显示拦截信息按钮(waveHasIntercept)
// 其它模式:直接看当前订单/波次的拦截状态
@ -635,6 +806,46 @@ import ReviewDetail from './order-review-comps/ReviewDetail.vue';
return list.some(item => String(item.waveNo || '').startsWith('D'));
}
},
watch: {
showWeighPopup(val) {
if (!val) return;
// 打开称重弹窗:重置自动读秤抖动阈值状态
this.lastAutoWeight = '';
this.weightEditing = false;
// 蓝牙秤已连接且开启自动读秤时不聚焦输入框,避免键盘反复弹出闪烁;其余情况保持历史聚焦行为
if (this.isScaleConnected && this.autoReadScale) {
this.weighInputFocused = false;
} else {
this._programmaticFocus = true;
this.weighInputFocused = false;
this.$nextTick(() => {
this.weighInputFocused = true;
});
setTimeout(() => {
this._programmaticFocus = false;
}, 600);
}
},
scaleWeight(val) {
if (!this.autoReadScale || !this.showWeighPopup || !this.isScaleConnected || val === null || val === undefined) return;
// 用户正在手动编辑时不打断输入
if (this.weightEditing) return;
const g = this.scaleWeightInGrams();
if (g === '') return;
const gNum = Math.round(Number(g));
if (String(gNum) === String(this.weighWeight)) return;
// 阈值保护:重量变化未超过阈值时不回填,避免秤抖动反复覆盖
if (this.lastAutoWeight !== '' && !isNaN(gNum) && Math.abs(gNum - Number(this.lastAutoWeight)) < this.autoReadThresholdG) {
return;
}
this.lastAutoWeight = String(g);
// App 端聚焦中的原生 input 不响应数据更新,先失焦再回填
this.weighInputFocused = false;
this.$nextTick(() => {
this.weighWeight = gNum;
});
}
},
onLoad(options) {
this.initKeyboardHeightListener();
this.safeDispatchBroadcast('setCallbacks', {
@ -642,6 +853,10 @@ import ReviewDetail from './order-review-comps/ReviewDetail.vue';
});
this.safeDispatchBroadcast('start');
// 蓝牙秤:初始化并尝试恢复已有连接(失败不阻塞正常复核流程)
this.$store.dispatch('bluetoothScale/initialize').catch(() => {});
this.$store.dispatch('bluetoothScale/reconnectIfNeeded').catch(() => {});
this.currentUserId = String(this.$store?.getters?.user?.id || this.$store?.getters?.user?.user_id || '');
const hasGrabCountParam = options && Object.prototype.hasOwnProperty.call(options, 'grabCount');
const parsedGrabCount = Number(options?.grabCount || 0);
@ -681,6 +896,7 @@ import ReviewDetail from './order-review-comps/ReviewDetail.vue';
onUnload() {
this.destroyKeyboardHeightListener();
this.safeDispatchBroadcast('stop');
this.$store.dispatch('bluetoothScale/stopScan').catch(() => {});
uni.$off('orderInterceptCompleted', this.handleInterceptCompleted);
if (this.debugMode) {
this.flushDebugLogs();
@ -3114,6 +3330,95 @@ import ReviewDetail from './order-review-comps/ReviewDetail.vue';
const num = parseInt(val, 10);
this.weighWeight = Number.isFinite(num) && num >= 0 ? num : 0;
},
onWeighInputFocus() {
if (this._programmaticFocus) {
this._programmaticFocus = false;
return;
}
this.weightEditing = true;
},
onWeighInputBlur() {
this.weightEditing = false;
},
scaleWeightInGrams() {
const raw = this.scaleWeight;
if (raw === null || raw === undefined || raw === '') return '';
const num = Number(raw);
if (isNaN(num)) return '';
const unit = String(this.scaleWeightUnit || '').toLowerCase();
// 仅当单位明确为 g 时才原样返回,其余(kg 或未识别)按 kg ×1000
const grams = unit === 'g' ? num : num * 1000;
return Math.round(grams * 1000) / 1000;
},
openScalePopup() {
this.showScalePopup = true;
this.$store.dispatch('bluetoothScale/scanDevices', true).catch(() => {});
},
closeScalePopup() {
this.showScalePopup = false;
this.$store.dispatch('bluetoothScale/stopScan').catch(() => {});
},
handleScaleScan() {
this.$store.dispatch('bluetoothScale/scanDevices', true).catch(e => {
uni.showToast({ title: (e && e.message) || '扫描失败', icon: 'none' });
});
},
async handleScaleConnectByName() {
if (!this.scaleFilterName) {
uni.showToast({ title: '请输入电子秤蓝牙名称', icon: 'none' });
return;
}
try {
await this.$store.dispatch('bluetoothScale/connectDeviceByName', this.scaleFilterName);
uni.showToast({ title: '连接成功', icon: 'success' });
this.showScalePopup = false;
this.speakVoice('蓝牙秤连接成功');
} catch (e) {
uni.showToast({ title: (e && e.message) || '连接失败', icon: 'none' });
}
},
async handleScaleConnectDevice(device) {
try {
await this.$store.dispatch('bluetoothScale/connectDevice', device);
uni.showToast({ title: '连接成功', icon: 'success' });
this.showScalePopup = false;
this.speakVoice('蓝牙秤连接成功');
} catch (e) {
uni.showToast({ title: (e && e.message) || '连接失败', icon: 'none' });
}
},
handleScaleDisconnect() {
this.showDisconnectConfirm = true;
},
cancelScaleDisconnect() {
this.showDisconnectConfirm = false;
},
async confirmScaleDisconnect() {
this.showDisconnectConfirm = false;
await this.$store.dispatch('bluetoothScale/disconnect').catch(() => {});
uni.showToast({ title: '已断开', icon: 'none' });
},
handleReadScale() {
if (!this.isScaleConnected) {
this.openScalePopup();
return;
}
const grams = this.scaleWeightInGrams();
if (grams === '') {
uni.showToast({ title: '未读取到重量,请确认物品已放上秤', icon: 'none' });
return;
}
this.lastAutoWeight = String(grams);
// App 端聚焦中的原生 input 不响应数据更新,先失焦再回填
this.weighInputFocused = false;
this.$nextTick(() => {
this.weighWeight = Math.round(Number(grams));
this.speakVoice('已读取重量');
});
},
isScaleCurrentDevice(device) {
return !!(this.scaleCurrentDevice && device && this.scaleCurrentDevice.id === device.deviceId);
},
async handlePackageCodeConfirm(e) {
const code = e?.detail?.value ?? this.packageInputCode ?? '';
const trimmed = String(code).trim();
@ -4134,6 +4439,35 @@ import ReviewDetail from './order-review-comps/ReviewDetail.vue';
white-space: nowrap;
}
.nav-scale-btn {
padding: 8rpx 18rpx;
display: flex;
align-items: center;
justify-content: center;
border: 1rpx solid #2979ff;
border-radius: 6rpx;
margin-right: 12rpx;
&--connected {
border-color: #07c160;
background: #f0f9eb;
}
.nav-scale-btn__text {
font-size: 30rpx;
color: #2979ff;
line-height: 1.4;
}
&--connected .nav-scale-btn__text {
color: #07c160;
}
}
.nav-scale-btn:active {
opacity: 0.7;
}
.nav-settings-btn {
padding: 8rpx 18rpx;
display: flex;
@ -4514,7 +4848,7 @@ import ReviewDetail from './order-review-comps/ReviewDetail.vue';
border: 2rpx solid #dcdfe6;
border-radius: 12rpx;
text-align: center;
font-size: 40rpx;
font-size: 50rpx;
color: #303133;
}
@ -4537,9 +4871,334 @@ import ReviewDetail from './order-review-comps/ReviewDetail.vue';
margin-left: 4rpx;
}
.weigh-read-btn {
display: flex;
align-items: center;
justify-content: center;
height: 64rpx;
padding: 0 20rpx;
margin-left: 20rpx;
background: #fa8c16;
border-radius: 8rpx;
flex-shrink: 0;
&--connected {
background: #2979ff;
}
.weigh-read-btn-text {
font-size: 30rpx;
color: #fff;
white-space: nowrap;
}
}
.weigh-scale-line {
display: flex;
align-items: center;
justify-content: space-between;
padding: 20rpx 24rpx;
border-bottom: 1rpx solid #f0f0f0;
}
.weigh-scale-label {
font-size: 32rpx;
color: #333;
}
.weigh-scale-right {
display: flex;
align-items: center;
}
.weigh-live-wrap {
display: flex;
align-items: baseline;
}
.weigh-scale-status {
font-size: 32rpx;
font-weight: 500;
color: #909399;
&--connected {
color: #19be6b;
}
&--connecting,
&--scanning {
color: #2979ff;
}
&--error {
color: #fa3534;
}
}
.weigh-scale-device {
font-size: 34rpx;
color: #999;
margin-left: 12rpx;
}
.weigh-scale-value {
font-size: 50rpx;
color: #000000;
}
.weigh-scale-unit {
font-size: 30rpx;
color: #999;
margin-left: 10rpx;
}
.weigh-scale-stable {
font-size: 28rpx;
color: #19be6b;
margin-left: 16rpx;
}
.weigh-scale-actions {
display: flex;
align-items: center;
justify-content: flex-start;
margin-top: 12rpx;
::v-deep .u-button {
height: 72rpx;
min-height: 72rpx;
padding: 0 32rpx;
border-radius: 8rpx;
font-size: 32rpx !important;
}
::v-deep .u-button__text {
font-size: 32rpx !important;
}
::v-deep .u-button + .u-button {
margin-left: 16rpx;
}
}
/* 蓝牙秤连接弹窗 */
.scale-popup {
display: flex;
flex-direction: column;
height: 60vh;
.scale-popup-header {
display: flex;
align-items: center;
justify-content: center;
padding: 48rpx 32rpx 0;
.scale-popup-title {
font-size: 38rpx;
font-weight: 600;
color: #303133;
text-align: center;
white-space: nowrap;
}
}
.scale-popup-input {
display: flex;
align-items: center;
padding: 32rpx 32rpx 0;
::v-deep .u-input {
flex: 1;
min-width: 0;
height: 72rpx;
box-sizing: border-box;
padding-top: 0 !important;
padding-bottom: 0 !important;
}
::v-deep .u-button {
margin-left: 16rpx;
flex-shrink: 0;
}
}
.scale-popup-list {
flex: 1;
width: 100%;
box-sizing: border-box;
overflow: hidden;
.scale-popup-list-inner {
padding: 12rpx 32rpx 8rpx;
}
.scale-device-item {
display: flex;
align-items: center;
justify-content: space-between;
box-sizing: border-box;
padding: 28rpx 24rpx;
margin-bottom: 16rpx;
border-radius: 16rpx;
border: 2rpx solid #eee;
background-color: #fff;
&--active {
border-color: #2979ff;
background-color: #f0f7ff;
}
.scale-device-info {
flex: 1;
min-width: 0;
overflow: hidden;
display: flex;
flex-direction: column;
.scale-device-name {
font-size: 36rpx;
color: #333;
font-weight: 500;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.scale-device-id {
font-size: 24rpx;
color: #999;
margin-top: 6rpx;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
}
.scale-device-connect {
flex-shrink: 0;
margin-left: 16rpx;
padding: 12rpx 32rpx;
font-size: 34rpx;
color: #2979ff;
background-color: #eaf3ff;
border-radius: 30rpx;
white-space: nowrap;
}
&--active .scale-device-connect {
color: #19be6b;
background-color: #e8f9f0;
}
}
}
.scale-popup-actions {
display: flex;
align-items: center;
padding: 24rpx 32rpx calc(24rpx + env(safe-area-inset-bottom));
border-top: 1rpx solid #f0f0f0;
}
.scale-popup-close-btn {
flex: 1;
height: 88rpx;
display: flex;
align-items: center;
justify-content: center;
font-size: 34rpx;
color: #909399;
border: 2rpx solid #dcdfe6;
border-radius: 16rpx;
background: #f5f5f5;
&:active {
opacity: 0.88;
}
}
.scale-popup-scan-btn {
flex: 1;
height: 88rpx;
display: flex;
align-items: center;
justify-content: center;
font-size: 34rpx;
color: #ffffff;
background: #2979ff;
border: 2rpx solid #2979ff;
border-radius: 16rpx;
margin-left: 20rpx;
&:active {
opacity: 0.9;
}
&--loading {
opacity: 0.6;
pointer-events: none;
}
}
}
/* 断开蓝牙秤确认弹窗 */
.weigh-disconnect-popup {
width: 580rpx;
padding: 40rpx 32rpx;
background: #ffffff;
border-radius: 20rpx;
&__title {
font-size: 36rpx;
font-weight: 600;
color: #303133;
text-align: center;
margin-bottom: 24rpx;
}
&__body {
text-align: center;
margin-bottom: 32rpx;
}
&__text {
font-size: 30rpx;
color: #606266;
}
&__actions {
display: flex;
}
&__btn + &__btn {
margin-left: 20rpx;
}
&__btn {
flex: 1;
height: 80rpx;
line-height: 80rpx;
text-align: center;
border-radius: 12rpx;
font-size: 32rpx;
&--cancel {
background: #f5f5f5;
color: #909399;
}
&--confirm {
background: #fa3534;
color: #ffffff;
}
}
}
.weigh-popup-footer {
display: flex;
gap: 20rpx;
}
.weigh-footer-btn + .weigh-footer-btn {
margin-left: 20rpx;
}
.weigh-footer-btn {
@ -4628,7 +5287,10 @@ import ReviewDetail from './order-review-comps/ReviewDetail.vue';
.package-popup-footer {
display: flex;
gap: 20rpx;
}
.package-footer-btn + .package-footer-btn {
margin-left: 20rpx;
}
.package-footer-btn {
@ -4718,7 +5380,10 @@ import ReviewDetail from './order-review-comps/ReviewDetail.vue';
.scan-qty-popup-footer {
display: flex;
justify-content: space-between;
gap: 20rpx;
}
.scan-qty-footer-btn + .scan-qty-footer-btn {
margin-left: 20rpx;
}
.scan-qty-footer-btn {

View File

@ -56,6 +56,8 @@
:customStyle="{ flex: 1 }"
:focus="weightFocused"
class="weigh-input"
@focus="onWeightFocus"
@blur="onWeightBlur"
></u-input>
<text class="info-unit">g</text>
<view
@ -232,6 +234,10 @@ import voice from '@/core/utils/voice';
showScalePopup: false,
scaleFilterName: '',
autoReadScale: true,
autoReadThresholdG: 1,
lastAutoWeight: '',
weightEditing: false,
_programmaticFocus: false,
showDisconnectConfirm: false
};
},
@ -271,8 +277,16 @@ import voice from '@/core/utils/voice';
watch: {
scaleWeight(val) {
if (!this.autoReadScale || !this.isScaleConnected || val === null || val === undefined) return;
// 用户正在手动编辑时不打断输入
if (this.weightEditing) return;
const g = this.scaleWeightInGrams();
if (g === '' || String(g) === this.manualWeight) return;
const gNum = Number(g);
// 阈值保护:重量变化未超过阈值时不回填,避免秤抖动反复覆盖
if (this.lastAutoWeight !== '' && !isNaN(gNum) && Math.abs(gNum - Number(this.lastAutoWeight)) < this.autoReadThresholdG) {
return;
}
this.lastAutoWeight = String(g);
// App 端聚焦中的原生 input 不响应数据更新,先失焦再回填
this.weightFocused = false;
this.$nextTick(() => {
@ -413,9 +427,11 @@ import voice from '@/core/utils/voice';
}
this.showOrderInfo = true;
// 自动聚焦称重重量输入框
// 自动聚焦称重重量输入框(蓝牙秤已连接且自动读秤开启时不聚焦,避免键盘闪烁)
this.$nextTick(() => {
this.weightFocused = true;
if (!(this.isScaleConnected && this.autoReadScale)) {
this.focusWeightInput();
}
});
} catch (e) {
uni.showToast({ title: '网络异常', icon: 'none' });
@ -434,6 +450,8 @@ import voice from '@/core/utils/voice';
this.netWeight = '';
this.manualWeight = '';
this.isGroupOrder = false;
this.lastAutoWeight = '';
this.weightEditing = false;
},
handleSubmitWeight() {
if (!this.manualWeight) {
@ -483,6 +501,8 @@ import voice from '@/core/utils/voice';
this.weightFocused = false;
this.showOrderInfo = false;
this.isGroupOrder = false;
this.lastAutoWeight = '';
this.weightEditing = false;
this.scanFocused = true;
},
scaleWeightInGrams() {
@ -553,6 +573,7 @@ import voice from '@/core/utils/voice';
uni.showToast({ title: '未读取到重量,请确认物品已放上秤', icon: 'none' });
return;
}
this.lastAutoWeight = String(grams);
// App 端聚焦中的原生 input 不响应数据更新,先失焦再回填
this.weightFocused = false;
this.$nextTick(() => {
@ -560,6 +581,26 @@ import voice from '@/core/utils/voice';
this.speakVoice('已读取重量');
});
},
focusWeightInput() {
// 程序化聚焦不视为用户编辑
this._programmaticFocus = true;
this.weightEditing = false;
this.weightFocused = true;
// 兜底:无论 focus 事件是否触发,短暂后清除程序化标志
setTimeout(() => {
this._programmaticFocus = false;
}, 500);
},
onWeightFocus() {
if (this._programmaticFocus) {
this._programmaticFocus = false;
return;
}
this.weightEditing = true;
},
onWeightBlur() {
this.weightEditing = false;
},
isScaleCurrentDevice(device) {
return !!(this.scaleCurrentDevice && device && this.scaleCurrentDevice.id === device.deviceId);
}