diff --git a/src/core/active-view.js b/src/core/active-view.js new file mode 100644 index 0000000..1f38b87 --- /dev/null +++ b/src/core/active-view.js @@ -0,0 +1,68 @@ +/** + * 当前激活的功能视图(菜单页 / 独立页路由) + * + * 背景:布局壳 pages/index/index.vue 用 切换页面 + * (App 端退化为普通动态组件),被缓存的页面实例在切页瞬间仍可能持有全局扫码接收者, + * 生命周期时序(activated / deactivated / mounted / beforeUnmount)在某些情况下不足以 + * 判断「此刻真正展示的是哪一页」——表现为:在退件页扫码,称重页的「扫描记录」也被写入。 + * + * 因此把「当前展示的视图」提到全局单例里: + * - 布局壳每次切换菜单写入(权威来源,覆盖所有菜单页) + * - 各页 onShow / activated / mounted 写入自身路径(独立页 / URL 直达兜底) + * - 需要区分页面的全局能力(如称重页扫描记录)读取 isActiveView() 判断 + * + * 注意:这里只做「标记 + 读取」,不触发任何跳转或响应式更新。 + */ + +// 后端菜单短路径 <-> 本地页面路径 统一成同一个「视图标识」 +const VIEW_ALIASES = { + '/order': '/order', + '/pages/order/index': '/order', + '/catchWeight': '/catchWeight', + '/pages/weighing/index': '/catchWeight', + '/returns': '/returns', + '/pages/returns/index': '/returns', + '/packaging': '/packaging', + '/pages/packaging/index': '/packaging', + '/index': '/index', + '/pages/index/index': '/index', + '/login': '/login', + '/pages/login/login': '/login', +} + +let activeView = '' + +/** 归一化:去 query、去结尾斜杠、保证以 / 开头、映射成本地视图标识 */ +function canonicalViewPath(path) { + const raw = String(path || '').trim() + if (!raw) { + return '' + } + const trimmed = raw.split('?')[0].replace(/\/+$/, '') + const normalized = trimmed.startsWith('/') ? trimmed : `/${trimmed}` + return VIEW_ALIASES[normalized] || normalized +} + +/** 写入当前展示的视图(布局壳切换菜单 / 页面 onShow 时调用) */ +export function setActiveView(path) { + activeView = canonicalViewPath(path) +} + +/** 读取当前展示的视图标识(未记录时返回空串) */ +export function getActiveView() { + return activeView +} + +/** 当前展示的视图是否为给定路径之一(短路径与页面路径等价) */ +export function isActiveView(...paths) { + const current = activeView + if (!current) { + return false + } + return paths.some((path) => canonicalViewPath(path) === current) +} + +/** 清空当前视图标记(退出登录 / 离开布局壳时调用) */ +export function clearActiveView() { + activeView = '' +} diff --git a/src/core/camera-live.js b/src/core/camera-live.js new file mode 100644 index 0000000..ac3712a --- /dev/null +++ b/src/core/camera-live.js @@ -0,0 +1,433 @@ +/** + * 真机(APP-PLUS)摄像头实时预览:直连海康 NVR 轮询 ISAPI 快照 + * + * 背景:桌面端(Electron)由内置取流服务 127.0.0.1:17320 把 NVR 快照合成为 MJPEG, + * 前端 即可播放;真机上既没有本地取流服务, + * localhost 也访问不到电脑,因此改为端内直连录像机: + * 1) ISAPI sessionLogin(SHA-256 摘要)建立会话 + * —— App 端 uni.request 是原生网络层,会自动保存/回传 Cookie(WebSession), + * 因此这里只需自行带上登录响应里的 SessionTag 头; + * 2) 定时 GET /ISAPI/Streaming/channels/{100*通道+码流}/picture 取 JPEG 快照; + * 3) 转成 data:image/jpeg;base64 交给 渲染(约 2fps 的伪实时画面)。 + * + * 与 electron/hikvision-live.js 的登录/取图流程保持一致(同一套海康接口)。 + */ + +const LOGIN_TIMEOUT_MS = 4000 +const FRAME_TIMEOUT_MS = 4000 +const MIN_FRAME_BYTES = 500 +// 连续取图失败次数:达到后重新登录 / 切主码流 +const RELOGIN_AFTER_FAILS = 5 +const SWITCH_STREAM_AFTER_FAILS = 6 +// 码流候选:2=子码流(体积小、流畅),1=主码流(子码流不可用时兜底) +const STREAM_SUFFIXES = [2, 1] + +const B64_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' + +// ==================== SHA-256(真机逻辑层没有 crypto.subtle / node crypto) ==================== + +const SHA256_K = [ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, +] + +function rotr(x, n) { + return (x >>> n) | (x << (32 - n)) +} + +/** 字符串 → UTF-8 字节数组 */ +function utf8Bytes(str) { + const bytes = [] + for (let i = 0; i < str.length; i++) { + const code = str.charCodeAt(i) + if (code < 0x80) { + bytes.push(code) + } else if (code < 0x800) { + bytes.push(0xc0 | (code >> 6), 0x80 | (code & 0x3f)) + } else if (code >= 0xd800 && code <= 0xdbff && i + 1 < str.length) { + const cp = 0x10000 + ((code - 0xd800) << 10) + (str.charCodeAt(i + 1) - 0xdc00) + bytes.push(0xf0 | (cp >> 18), 0x80 | ((cp >> 12) & 0x3f), 0x80 | ((cp >> 6) & 0x3f), 0x80 | (cp & 0x3f)) + i++ + } else { + bytes.push(0xe0 | (code >> 12), 0x80 | ((code >> 6) & 0x3f), 0x80 | (code & 0x3f)) + } + } + return bytes +} + +/** SHA-256 → 64 位小写十六进制(海康 sessionLogin 摘要用) */ +export function sha256Hex(message) { + const bytes = utf8Bytes(String(message)) + const bitLen = bytes.length * 8 + bytes.push(0x80) + while (bytes.length % 64 !== 56) bytes.push(0) + // 64 位长度(高 32 位恒为 0,本场景消息远小于 2^32 位) + bytes.push(0, 0, 0, 0, (bitLen >>> 24) & 0xff, (bitLen >>> 16) & 0xff, (bitLen >>> 8) & 0xff, bitLen & 0xff) + + let h0 = 0x6a09e667 + let h1 = 0xbb67ae85 + let h2 = 0x3c6ef372 + let h3 = 0xa54ff53a + let h4 = 0x510e527f + let h5 = 0x9b05688c + let h6 = 0x1f83d9ab + let h7 = 0x5be0cd19 + const w = new Array(64) + + for (let offset = 0; offset < bytes.length; offset += 64) { + for (let t = 0; t < 16; t++) { + const j = offset + t * 4 + w[t] = ((bytes[j] << 24) | (bytes[j + 1] << 16) | (bytes[j + 2] << 8) | bytes[j + 3]) >>> 0 + } + for (let t = 16; t < 64; t++) { + const s0 = (rotr(w[t - 15], 7) ^ rotr(w[t - 15], 18) ^ (w[t - 15] >>> 3)) >>> 0 + const s1 = (rotr(w[t - 2], 17) ^ rotr(w[t - 2], 19) ^ (w[t - 2] >>> 10)) >>> 0 + w[t] = (w[t - 16] + s0 + w[t - 7] + s1) >>> 0 + } + let a = h0 + let b = h1 + let c = h2 + let d = h3 + let e = h4 + let f = h5 + let g = h6 + let h = h7 + for (let t = 0; t < 64; t++) { + const S1 = (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) >>> 0 + const ch = ((e & f) ^ (~e & g)) >>> 0 + const t1 = (h + S1 + ch + SHA256_K[t] + w[t]) >>> 0 + const S0 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) >>> 0 + const maj = ((a & b) ^ (a & c) ^ (b & c)) >>> 0 + const t2 = (S0 + maj) >>> 0 + h = g + g = f + f = e + e = (d + t1) >>> 0 + d = c + c = b + b = a + a = (t1 + t2) >>> 0 + } + h0 = (h0 + a) >>> 0 + h1 = (h1 + b) >>> 0 + h2 = (h2 + c) >>> 0 + h3 = (h3 + d) >>> 0 + h4 = (h4 + e) >>> 0 + h5 = (h5 + f) >>> 0 + h6 = (h6 + g) >>> 0 + h7 = (h7 + h) >>> 0 + } + + const hex = (n) => ('00000000' + n.toString(16)).slice(-8) + return hex(h0) + hex(h1) + hex(h2) + hex(h3) + hex(h4) + hex(h5) + hex(h6) + hex(h7) +} + +// ==================== base64(ArrayBuffer → dataURL 用) ==================== + +function bytesToBase64(bytes) { + const len = bytes.length + let out = '' + let i = 0 + for (; i + 2 < len; i += 3) { + const n = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2] + out += + B64_CHARS[(n >> 18) & 63] + + B64_CHARS[(n >> 12) & 63] + + B64_CHARS[(n >> 6) & 63] + + B64_CHARS[n & 63] + } + const rest = len - i + if (rest === 1) { + const n = bytes[i] << 16 + out += B64_CHARS[(n >> 18) & 63] + B64_CHARS[(n >> 12) & 63] + '==' + } else if (rest === 2) { + const n = (bytes[i] << 16) | (bytes[i + 1] << 8) + out += B64_CHARS[(n >> 18) & 63] + B64_CHARS[(n >> 12) & 63] + B64_CHARS[(n >> 6) & 63] + '=' + } + return out +} + +function toUint8(data) { + if (!data) return null + if (typeof Uint8Array !== 'undefined' && data instanceof Uint8Array) return data + if (typeof ArrayBuffer !== 'undefined' && data instanceof ArrayBuffer) return new Uint8Array(data) + if (typeof data === 'object' && typeof data.byteLength === 'number') { + try { + return new Uint8Array(data) + } catch (e) { + return null + } + } + return null +} + +function arrayBufferToBase64(data) { + // 优先用运行时提供的能力(App 端存在 uni.arrayBufferToBase64) + if (typeof uni !== 'undefined' && typeof uni.arrayBufferToBase64 === 'function') { + try { + const base64 = uni.arrayBufferToBase64(data) + if (base64) return base64 + } catch (e) { + // 回退手写实现 + } + } + const bytes = toUint8(data) + return bytes ? bytesToBase64(bytes) : '' +} + +// ==================== 海康 ISAPI 工具 ==================== + +/** XML 文本提取(支持命名空间前缀,与 electron/hikvision-live.js 一致) */ +function xmlText(xml, tag) { + if (!xml) return '' + const re = new RegExp( + '<(?:[\\w.-]+:)?' + tag + '(?:\\s[^>]*)?>([\\s\\S]*?)<\\/(?:[\\w.-]+:)?' + tag + '\\s*>' + ) + const m = String(xml).match(re) + return m ? m[1].trim() : '' +} + +/** + * 统一请求封装:永不 reject,返回 { ok, statusCode, data, header } + * dataType 固定 text(避免 uni 自动 JSON.parse XML 响应),二进制用 responseType arraybuffer + */ +function requestOnce(options) { + return new Promise((resolve) => { + let settled = false + const done = (result) => { + if (settled) return + settled = true + resolve(result) + } + try { + uni.request({ + url: options.url, + method: options.method || 'GET', + data: options.data, + header: options.header || {}, + dataType: 'text', + responseType: options.responseType || 'text', + timeout: options.timeout || 5000, + success: (res) => { + done({ + ok: true, + statusCode: Number(res && res.statusCode) || 0, + data: res && res.data, + header: (res && res.header) || {}, + }) + }, + fail: (err) => { + done({ + ok: false, + statusCode: 0, + error: (err && err.errMsg) || '网络请求失败', + data: '', + header: {}, + }) + }, + }) + } catch (e) { + done({ ok: false, statusCode: 0, error: (e && e.message) || '请求异常', data: '', header: {} }) + } + }) +} + +/** + * 创建快照轮询器 + * @param {Object} options + * @param {string} options.ip 录像机地址(内网/公网) + * @param {number[]} options.ports HTTP(ISAPI) 端口候选,按顺序尝试 + * @param {string} options.user 用户名 + * @param {string} options.pass 密码 + * @param {number} options.channel 摄像头通道号(camera.list 的 channel_id) + * @param {number} [options.interval] 帧间隔 ms(默认 500) + * @param {(dataUrl:string)=>void} options.onFrame 每帧回调(data:image/jpeg;base64) + * @param {(text:string)=>void} [options.onStatus] 状态文案回调(连不上/切码流等) + * @param {(message:string)=>void} [options.onFail] 登录失败、无法连接时回调(页面可回退公网重试) + */ +export function createHikvisionSnapshotPoller(options = {}) { + const cfg = { + ip: String(options.ip || '').trim(), + ports: (Array.isArray(options.ports) ? options.ports : []) + .map((p) => Number(p)) + .filter((p, i, arr) => p > 0 && p < 65536 && arr.indexOf(p) === i), + user: String(options.user || ''), + pass: String(options.pass || ''), + channel: Math.max(1, Number(options.channel) || 1), + interval: Math.max(200, Number(options.interval) || 500), + onFrame: typeof options.onFrame === 'function' ? options.onFrame : () => {}, + onStatus: typeof options.onStatus === 'function' ? options.onStatus : () => {}, + onFail: typeof options.onFail === 'function' ? options.onFail : () => {}, + } + if (!cfg.ports.length) cfg.ports.push(80) + + let stopped = false + let timer = null + // 登录成功后的地址前缀(如 http://192.168.1.64:80),为空表示需要登录 + let base = '' + let sessionTag = '' + let streamIndex = 0 + let failCount = 0 + // 登录成功次数 / 是否已收到过画面:从未出图却反复登录说明会话/通道有问题,及时止损 + let loginCount = 0 + let gotFrame = false + const MAX_LOGIN_WITHOUT_FRAME = 3 + + const channelCode = () => cfg.channel * 100 + STREAM_SUFFIXES[streamIndex] + + /** 单端口登录:capabilities → sessionLogin(SessionTag 从响应体取,Cookie 由原生网络层托管) */ + async function loginOnPort(port) { + const httpBase = `http://${cfg.ip}:${port}` + const capsUrl = + `${httpBase}/ISAPI/Security/sessionLogin/capabilities?username=${encodeURIComponent(cfg.user)}` + + `&random:${String(Date.now()).slice(-8)}` + const capsRes = await requestOnce({ url: capsUrl, timeout: LOGIN_TIMEOUT_MS }) + if (!capsRes.ok) throw new Error(capsRes.error) + if (capsRes.statusCode !== 200) throw new Error(`HTTP ${capsRes.statusCode}`) + + const capsBody = String(capsRes.data || '') + const sid = xmlText(capsBody, 'sessionID') + const challenge = xmlText(capsBody, 'challenge') + const salt = xmlText(capsBody, 'salt') + const iterations = parseInt(xmlText(capsBody, 'iterations'), 10) || 1 + const version = xmlText(capsBody, 'sessionIDVersion') || '1' + const validLongTerm = xmlText(capsBody, 'isSessionIDValidLongTerm') || 'false' + const supportTag = xmlText(capsBody, 'isSupportSessionTag') || 'false' + const irreversible = xmlText(capsBody, 'isIrreversible') === 'true' + if (!sid || !challenge) throw new Error('登录能力解析失败') + + let digest + if (irreversible) { + digest = sha256Hex(cfg.user + salt + cfg.pass) + digest = sha256Hex(digest + challenge) + for (let i = 2; i < iterations; i++) digest = sha256Hex(digest) + } else { + digest = sha256Hex(cfg.pass + challenge) + for (let i = 1; i < iterations; i++) digest = sha256Hex(digest) + } + + const loginXml = + version === '2' + ? `${cfg.user}${digest}${sid}` + + `${validLongTerm}2` + + `${supportTag}` + : `${cfg.user}${digest}${sid}` + + const loginRes = await requestOnce({ + url: `${httpBase}/ISAPI/Security/sessionLogin?timeStamp=${Date.now()}`, + method: 'POST', + data: loginXml, + header: { 'Content-Type': 'text/plain;charset=UTF-8' }, + timeout: LOGIN_TIMEOUT_MS, + }) + if (!loginRes.ok) throw new Error(loginRes.error) + if (loginRes.statusCode !== 200) throw new Error(`登录失败 HTTP ${loginRes.statusCode}`) + + const tag = xmlText(String(loginRes.data || ''), 'sessionTag') + return { httpBase, sessionTag: tag } + } + + /** 依次尝试候选端口登录,任一成功即返回 true */ + async function ensureLogin() { + for (let i = 0; i < cfg.ports.length; i++) { + if (stopped) return false + try { + const result = await loginOnPort(cfg.ports[i]) + base = result.httpBase + sessionTag = result.sessionTag + failCount = 0 + return true + } catch (e) { + console.warn('[camera-live] 登录失败', cfg.ip, cfg.ports[i], (e && e.message) || e) + } + } + return false + } + + /** 取一帧 JPEG 快照并转 dataURL */ + async function fetchFrame() { + const res = await requestOnce({ + url: `${base}/ISAPI/Streaming/channels/${channelCode()}/picture`, + header: sessionTag ? { SessionTag: sessionTag } : {}, + responseType: 'arraybuffer', + timeout: FRAME_TIMEOUT_MS, + }) + if (!res.ok) return { ok: false, status: 0 } + if (res.statusCode !== 200) return { ok: false, status: res.statusCode } + const size = res.data && typeof res.data.byteLength === 'number' ? res.data.byteLength : 0 + if (size < MIN_FRAME_BYTES) return { ok: false, status: res.statusCode } + const base64 = arrayBufferToBase64(res.data) + if (!base64) return { ok: false, status: res.statusCode } + return { ok: true, dataUrl: `data:image/jpeg;base64,${base64}` } + } + + async function tick() { + if (stopped) return + try { + if (!base) { + cfg.onStatus('正在连接录像机…') + const ok = await ensureLogin() + if (stopped) return + if (!ok) { + stopped = true + cfg.onFail(`无法连接录像机(${cfg.ip}),请确认平板与录像机在同一网络`) + return + } + loginCount += 1 + if (!gotFrame && loginCount > MAX_LOGIN_WITHOUT_FRAME) { + stopped = true + cfg.onFail('登录成功但一直取不到画面,请检查摄像头通道号或录像机账号密码') + return + } + cfg.onStatus('已连接,正在取流…') + } + const frame = await fetchFrame() + if (stopped) return + if (frame.ok) { + failCount = 0 + gotFrame = true + cfg.onFrame(frame.dataUrl) + } else { + failCount += 1 + if (frame.status === 401) { + // 会话过期:清空 base,下一轮重新登录 + base = '' + cfg.onStatus('会话失效,正在重连…') + } else if (failCount === 1) { + cfg.onStatus(frame.status ? `取流异常(${frame.status}),正在重试…` : '等待画面…') + } else if (failCount >= SWITCH_STREAM_AFTER_FAILS && streamIndex < STREAM_SUFFIXES.length - 1) { + streamIndex += 1 + failCount = 0 + cfg.onStatus('子码流不可用,切换主码流…') + } else if (failCount === RELOGIN_AFTER_FAILS) { + base = '' + } + } + } catch (e) { + failCount += 1 + } + if (!stopped) { + timer = setTimeout(tick, cfg.interval) + } + } + + return { + start() { + if (stopped) return + tick() + }, + stop() { + stopped = true + if (timer) { + clearTimeout(timer) + timer = null + } + }, + } +} diff --git a/src/core/scan.js b/src/core/scan.js index 832555d..3834315 100644 --- a/src/core/scan.js +++ b/src/core/scan.js @@ -479,11 +479,13 @@ function removePlusListener() { /** * 注册扫码接收者(页面 onShow/onReady 时调用) * receiver: { onScanCode(code, meta), onScanDebug(...args)? } + * @returns {object|null} 本次注册的接收者对象:页面请保存它(每页只建一次), + * 注销时作为 unregisterScanReceiver 的归属凭证传回,避免误清其它页面的接收者 */ export function registerScanReceiver(next) { if (receiver === next) { resetBuffer() - return + return receiver } unregisterScanReceiver(receiver) receiver = next || null @@ -494,12 +496,17 @@ export function registerScanReceiver(next) { diagNote('receiver-registered', { scope: receiverScope() }) debug('receiver-registered') } + return receiver } -/** 注销扫码接收者(页面 onHide/onUnload 时调用) */ +/** 注销扫码接收者(页面 onHide/onUnload 时调用) + * - 传入 target:仅当它正是当前接收者时才注销(页面应传自己保存的接收者对象,避免误清其它页) + * - 不传 target:无条件注销(登录页等整页退出的场景仍可用) + * @returns {boolean} 本次调用是否真的注销了接收者 + */ export function unregisterScanReceiver(target) { if (target && receiver !== target) { - return + return false } const scope = receiverScope() receiver = null @@ -509,6 +516,7 @@ export function unregisterScanReceiver(target) { setScanPaused(false) diagSetGates({ scope, receiver: false, paused: false, buffer: 0 }) diagNote('receiver-unregistered', { scope }) + return true } /** 暂停/恢复捕获(账号/密码等输入框聚焦时暂停,并清空已缓冲的按键) */ diff --git a/src/pages/index/index.vue b/src/pages/index/index.vue index c76b4af..c892747 100644 --- a/src/pages/index/index.vue +++ b/src/pages/index/index.vue @@ -41,6 +41,7 @@ import NoticeBanner from '@/components/notice-banner.vue' import NoticeSendDialog from '@/components/notice-send-dialog.vue' import TopNav from '@/components/top-nav.vue' import { getNoticeCenter } from '@/core/notice' +import { setActiveView } from '@/core/active-view' import { hasMenuView, normalizeMenuPath, resolveMenuView } from '@/router/menuRoutes' export default { @@ -96,6 +97,9 @@ export default { } } this.activeMenuPath = normalizeMenuPath(menu) + // 记录当前展示的视图:后续切菜单由 setActiveMenu 维护, + // 供扫码等全局能力判断「此刻展示的是哪一页」 + setActiveView(this.activeMenuPath) this.loadCurrentUserInfo() }, data() { @@ -214,6 +218,8 @@ export default { } this.activeMenuPath = normalizedPath + // 同步全局激活视图(扫码等全局能力据此判断页面归属) + setActiveView(normalizedPath) if (syncUrl) { this.syncMenuToUrl(normalizedPath) } diff --git a/src/pages/returns/index.vue b/src/pages/returns/index.vue index 197c3e6..f191287 100644 --- a/src/pages/returns/index.vue +++ b/src/pages/returns/index.vue @@ -346,7 +346,7 @@ - + {{ activeCamera ? cameraLabel(activeCamera) : '选择' }} ▾ - {{ floatFullscreen ? '⤡' : '⛶' }} - - + + + + + + + + - {{ previewLoading ? '正在连接录像机…' : previewError || '无信号' }} - APP 端暂不支持实时预览,字幕推送不受影响 + + {{ previewLoading ? '正在连接录像机…' : previewError || '无信号' }} @@ -442,6 +456,8 @@ import { getLiveStreamUrl, } from '@/api/camera' import { registerScanReceiver, unregisterScanReceiver, setScanPaused, setScanMinLength, startScanSelfHeal, stopScanSelfHeal } from '@/core/scan' +import { setActiveView } from '@/core/active-view' +import { createHikvisionSnapshotPoller } from '@/core/camera-live' import ScanDiagPanel from '@/components/scan-diag-panel.vue' import { diagBegin, diagDrop, diagNote, diagPersistNow, diagSetContext } from '@/core/scan-diag' @@ -483,8 +499,11 @@ const DETAIL_PAGE_SIZE = 10 const CAMERA_STORAGE_KEY = 'returnUnpackWork:selectedCameraIds' const ACTIVE_CAMERA_STORAGE_KEY = 'returnUnpackWork:activeCameraId' const OSD_IDLE_TEXT = '无任务' -const FLOAT_WIDTH = 240 -const FLOAT_HEIGHT = 180 +const FLOAT_WIDTH = 300 +const FLOAT_HEIGHT = 225 +// 未拖拽时贴右下角的偏移(px) +const FLOAT_RIGHT = 24 +const FLOAT_BOTTOM = 96 export default { name: 'ReturnsPage', @@ -560,6 +579,7 @@ export default { floatCollapsed: false, // 最小化收起态(拉流停止,设置不变) floatFullscreen: false, // 全屏态 floatPos: { x: 0, y: 0 }, + floatMoved: false, // 已手动拖拽过(未拖拽时用 right/bottom 贴角,保证真机也一定在屏内) // 浮动预览流状态 previewLoading: false, previewError: '', @@ -570,6 +590,7 @@ export default { previewProbeAbort: null, previewTriedPublic: false, _dragStart: null, // APP 触摸拖拽起始状态(非展示数据) + _appPoller: null, // APP 端快照轮询实例(非展示数据) // OSD 推送状态 osdPushing: false, lastOsdText: null, @@ -715,11 +736,16 @@ export default { previewCameraOptions() { return this.selectedCameras.map((c) => ({ id: c.id, label: this.cameraLabel(c) })) }, - /** 浮动窗定位样式(全屏铺满,否则跟随拖拽位置) */ + /** 浮动窗定位样式(全屏铺满;未拖拽过贴右下角;拖拽后跟随位置) */ floatWindowStyle() { if (this.floatFullscreen) { return { left: '0px', top: '0px' } } + // 未拖拽过:用 right/bottom 贴角。APP 逻辑层没有可靠的 window 尺寸, + // 之前用 innerWidth 兜底 1920 会把窗口算到 (1656,980),真机 961×640 下完全在屏外(表现为「无预览窗口」) + if (!this.floatMoved) { + return { left: 'auto', top: 'auto', right: '24px', bottom: `${FLOAT_BOTTOM}px` } + } return { left: this.floatPos.x + 'px', top: this.floatPos.y + 'px' } }, }, @@ -732,6 +758,7 @@ export default { }, onShow() { this.pageActive = true + setActiveView('/pages/returns/index') diagBegin('returns') diagNote('lifecycle', { hook: 'onShow' }) this.registerScanCapture() @@ -763,6 +790,7 @@ export default { // 扫码捕获必须挂在 keep-alive 的 activated/deactivated 上(与订单复核页一致) activated() { this.pageActive = true + setActiveView('/pages/returns/index') diagBegin('returns') diagNote('lifecycle', { hook: 'activated' }) this.registerScanCapture() @@ -787,6 +815,7 @@ export default { return } this.pageActive = true + setActiveView('/pages/returns/index') diagBegin('returns') diagNote('lifecycle', { hook: 'mounted' }) this.registerScanCapture() @@ -916,24 +945,33 @@ export default { registerScanCapture() { setScanMinLength(SCAN_MIN_LENGTH) - registerScanReceiver({ - scope: 'returns', - onScanCode: (code, meta) => { - if (!this.isPageActive()) { - diagDrop('page-inactive-receiver', { source: 'receiver' }) - return - } - this.handleScanCode(code, meta) - }, - onScanDebug: (...args) => { - console.log('[scan-returns]', ...args) - }, - }) + // 接收者对象每页只建一次并复用:注销时作为归属凭证传回, + // 避免本页 onHide/deactivated 把其它页刚注册的接收者一并清掉 + if (!this._scanReceiver) { + this._scanReceiver = { + scope: 'returns', + onScanCode: (code, meta) => { + if (!this.isPageActive()) { + diagDrop('page-inactive-receiver', { source: 'receiver' }) + return + } + this.handleScanCode(code, meta) + }, + onScanDebug: (...args) => { + console.log('[scan-returns]', ...args) + }, + } + } + registerScanReceiver(this._scanReceiver) }, unregisterScanCapture() { - unregisterScanReceiver() - setScanMinLength(SCAN_MIN_LENGTH_DEFAULT) + // 必须带归属凭证:全局同一时刻只保留一个接收者,无参注销会误清其它页面的注册 + const cleared = this._scanReceiver ? unregisterScanReceiver(this._scanReceiver) : false + // 只有真的注销了自己的接收者才恢复默认码长,避免切页时把新页面的最小码长改回去 + if (cleared) { + setScanMinLength(SCAN_MIN_LENGTH_DEFAULT) + } }, /** @@ -1657,6 +1695,12 @@ export default { saveCameraSettings() { this.selectedCameras = this.allCameras.filter((cam) => this.selectedCameraIds.indexOf(cam.id) !== -1) + // 诊断:真机(dev:adb)可在终端看到勾选/浮窗状态 + const view = this.viewportSize() + console.log( + `[returns][camera] 保存 selected=${this.selectedCameras.length} ids=${JSON.stringify(this.selectedCameraIds)} ` + + `all=${this.allCameras.length} viewport=${view.width}x${view.height}` + ) if (this.selectedCameras.length) { const firstId = this.selectedCameras[0].id ?? null if (this.activeCameraId == null || !this.selectedCameras.some((c) => c.id === this.activeCameraId)) { @@ -1715,18 +1759,47 @@ export default { } }, - ensureFloatPos() { - if (this.floatPos.x === 0 && this.floatPos.y === 0) { - const win = typeof window !== 'undefined' ? window : { innerWidth: 1920, innerHeight: 1280 } - this.floatPos.x = Math.max(8, (win.innerWidth || 1920) - FLOAT_WIDTH - 24) - this.floatPos.y = Math.max(8, (win.innerHeight || 1280) - FLOAT_HEIGHT - 120) + /** 视口尺寸(逻辑 px):APP 逻辑层没有可用的 window,优先用 uni.getSystemInfoSync */ + viewportSize() { + try { + const info = uni.getSystemInfoSync() || {} + const w = Number(info.windowWidth || info.screenWidth || 0) + const h = Number(info.windowHeight || info.screenHeight || 0) + if (w > 0 && h > 0) return { width: w, height: h } + } catch (e) { + // 忽略,走 window 兜底 + } + const win = typeof window !== 'undefined' ? window : null + return { + width: (win && win.innerWidth) || 960, + height: (win && win.innerHeight) || 640, } }, + /** 未拖拽时的默认锚点(与 floatWindowStyle 的 right/bottom 一致) */ + defaultFloatPos() { + const view = this.viewportSize() + return { + x: Math.max(0, view.width - FLOAT_WIDTH - FLOAT_RIGHT), + y: Math.max(0, view.height - FLOAT_HEIGHT - FLOAT_BOTTOM), + } + }, + + ensureFloatPos() { + if (this.floatMoved) { + this.clampFloatPos() + return + } + // 未拖拽过:保持贴角定位,同时把坐标同步为锚点值(拖拽起始用) + const pos = this.defaultFloatPos() + this.floatPos.x = pos.x + this.floatPos.y = pos.y + }, + clampFloatPos() { - const win = typeof window !== 'undefined' ? window : { innerWidth: 1920, innerHeight: 1280 } - const maxX = Math.max(0, (win.innerWidth || 1920) - FLOAT_WIDTH) - const maxY = Math.max(0, (win.innerHeight || 1280) - FLOAT_HEIGHT) + const view = this.viewportSize() + const maxX = Math.max(0, view.width - FLOAT_WIDTH) + const maxY = Math.max(0, view.height - FLOAT_HEIGHT) this.floatPos.x = Math.min(maxX, Math.max(0, this.floatPos.x)) this.floatPos.y = Math.min(maxY, Math.max(0, this.floatPos.y)) }, @@ -1757,74 +1830,165 @@ export default { } }, - // ==================== 浮动预览流(H5/桌面,参照散单 CameraLivePreview) ==================== + // ==================== 浮动预览流(H5/桌面 MJPEG;真机 NVR 快照轮询) ==================== async loadPreviewStream() { const cam = this.activeCamera this.stopPreviewStream() if (!cam) return - // #ifdef APP-PLUS - // APP 端浮动窗仅显示提示,不拉流 - return - // #endif this.previewLoading = true this.previewError = '' this.previewReady = false this.previewSrc = '' this.previewTriedPublic = false try { - const sid = cam.server_id - if (!sid) { - this.previewError = '未关联录像服务器' - return - } - let srv = null - const listRes = await cameraServerList({ pagination: { page: 1, pageSize: 999 } }) - if (isReturnUnpackOk(listRes)) { - const listData = pickApiData(listRes) - srv = ((listData && listData.list) || []).find((s) => Number(s.id) === Number(sid)) || null - } - if (!srv) { - this.previewError = '未找到服务器信息' - return - } - let pwd = srv.password - if (!pwd) { - const dRes = await cameraServerDetail({ id: sid }) - if (isReturnUnpackOk(dRes)) { - const d = pickApiData(dRes) - pwd = d && d.password - } - } - if (!pwd) { - this.previewError = '缺少服务器密码' - return - } - const internalIp = String(srv.internal_ip || '').trim() - const publicIp = String(srv.public_ip || '').trim() - this.previewNvr = { - internalIp, - internalPort: srv.internal_port || srv.port, - publicIp, - publicPort: srv.public_port || srv.port, - user: srv.username || '', - pass: pwd, - ip: internalIp || publicIp, - port: internalIp ? srv.internal_port || srv.port : srv.public_port || srv.port, - } - if (!this.previewNvr.ip) { - this.previewError = '服务器未配置 IP' + const ok = await this.resolvePreviewNvr(cam) + if (!ok) { + this.previewLoading = false return } + // #ifdef APP-PLUS + // 真机没有本机取流服务:直连录像机轮询 ISAPI 快照 + this.startAppPreview() + return + // #endif + // #ifndef APP-PLUS await this.probePreviewStream() + this.previewLoading = false + // #endif } catch (e) { console.error('[returns] preview stream error', e) this.previewError = '预览加载失败' - } finally { this.previewLoading = false } }, + /** 解析录像服务器(内网/公网地址、端口、账号密码)写入 previewNvr;失败时设置 previewError */ + async resolvePreviewNvr(cam) { + const sid = cam.server_id + if (!sid) { + this.previewError = '未关联录像服务器' + return false + } + let srv = null + const listRes = await cameraServerList({ pagination: { page: 1, pageSize: 999 } }) + if (isReturnUnpackOk(listRes)) { + const listData = pickApiData(listRes) + srv = ((listData && listData.list) || []).find((s) => Number(s.id) === Number(sid)) || null + } + if (!srv) { + this.previewError = '未找到服务器信息' + return false + } + let pwd = srv.password + if (!pwd) { + const dRes = await cameraServerDetail({ id: sid }) + if (isReturnUnpackOk(dRes)) { + const d = pickApiData(dRes) + pwd = d && d.password + } + } + if (!pwd) { + this.previewError = '缺少服务器密码' + return false + } + const internalIp = String(srv.internal_ip || '').trim() + const publicIp = String(srv.public_ip || '').trim() + this.previewNvr = { + internalIp, + internalPort: srv.internal_port || srv.port, + publicIp, + publicPort: srv.public_port || srv.port, + user: srv.username || '', + pass: pwd, + ip: internalIp || publicIp, + port: internalIp ? srv.internal_port || srv.port : srv.public_port || srv.port, + } + if (!this.previewNvr.ip) { + this.previewError = '服务器未配置 IP' + return false + } + return true + }, + + /** 真机预览:直连 NVR 轮询 ISAPI 快照(约 2fps),逐帧以 dataURL 渲染 */ + startAppPreview() { + const cam = this.activeCamera + const nvr = this.previewNvr + if (this._appPoller) { + try { + this._appPoller.stop() + } catch (e) { + // 忽略停止异常 + } + this._appPoller = null + } + if (!cam || !nvr) return + const channel = Number(cam.channel_id) + if (!channel) { + this.previewError = '摄像头缺少通道号' + this.previewLoading = false + return + } + // 端口候选:服务器端口 → 80(海康 ISAPI 的 HTTP 服务通常在 80,port 常是 RTSP 554) + const ports = [] + ;[nvr.port, nvr.internalPort, nvr.publicPort, 80].forEach((p) => { + const n = Number(p) + if (n > 0 && n < 65536 && ports.indexOf(n) === -1) ports.push(n) + }) + this.previewLoading = true + this.previewError = '' + this.previewReady = false + this.previewSrc = '' + this._appPoller = createHikvisionSnapshotPoller({ + ip: nvr.ip, + ports, + user: nvr.user, + pass: nvr.pass, + channel, + interval: 500, + onStatus: (text) => { + if (this.previewReady || !this._appPoller) return + this.previewError = text + }, + onFrame: (dataUrl) => { + if (!this._appPoller) return + this.previewReady = true + this.previewLoading = false + this.previewError = '' + this.previewSrc = dataUrl + }, + onFail: (message) => { + if (!this._appPoller) return + this.handleAppPreviewFail(message) + }, + }) + this._appPoller.start() + }, + + /** 预览无画面时点击状态文字重试(真机/桌面通用) */ + handlePreviewStatusTap() { + if (this.previewLoading || !this.previewError) return + this.loadPreviewStream() + }, + + /** 真机预览连接失败:内网失败时回退公网地址再试一次 */ + handleAppPreviewFail(message) { + const nvr = this.previewNvr + const canFallback = + nvr && nvr.internalIp && nvr.publicIp && nvr.publicIp !== nvr.internalIp && !this.previewTriedPublic + if (canFallback) { + this.previewTriedPublic = true + nvr.ip = nvr.publicIp + nvr.port = nvr.publicPort + this.startAppPreview() + return + } + this.previewLoading = false + this.previewReady = false + this.previewError = message || '无法连接录像机' + }, + /** fetch 探测流地址:成功才渲染 ;502 走公网回退;网络错误提示本地服务未启动 */ probePreviewStream() { const cam = this.activeCamera @@ -1885,8 +2049,16 @@ export default { this.previewReady = false }, - /** 关闭连接:abort 探测请求 + 清空 src 触发浏览器断开 MJPEG 长连接 */ + /** 关闭连接:停快照轮询 + abort 探测请求 + 清空 src 触发浏览器断开 MJPEG 长连接 */ stopPreviewStream() { + if (this._appPoller) { + try { + this._appPoller.stop() + } catch (e) { + // 忽略停止异常 + } + this._appPoller = null + } if (this.previewProbeAbort) { this.previewProbeAbort.abort() this.previewProbeAbort = null @@ -1916,9 +2088,14 @@ export default { if (this.floatFullscreen) return const startX = e.clientX const startY = e.clientY - const origX = this.floatPos.x - const origY = this.floatPos.y + // 首次拖拽:从贴角锚点接手,拖动时不跳变 + const anchor = this.floatMoved ? { x: this.floatPos.x, y: this.floatPos.y } : this.defaultFloatPos() + const origX = anchor.x + const origY = anchor.y const move = (ev) => { + if (!this.floatMoved) { + this.floatMoved = true + } this.floatPos.x = origX + (ev.clientX - startX) this.floatPos.y = origY + (ev.clientY - startY) this.clampFloatPos() @@ -1938,11 +2115,12 @@ export default { if (this.floatFullscreen) return const touch = e.touches && e.touches[0] if (!touch) return + const anchor = this.floatMoved ? { x: this.floatPos.x, y: this.floatPos.y } : this.defaultFloatPos() this._dragStart = { x: touch.clientX, y: touch.clientY, - origX: this.floatPos.x, - origY: this.floatPos.y, + origX: anchor.x, + origY: anchor.y, } // #endif }, @@ -1951,6 +2129,9 @@ export default { // #ifdef APP-PLUS const touch = e.touches && e.touches[0] if (!touch || !this._dragStart) return + if (!this.floatMoved) { + this.floatMoved = true + } this.floatPos.x = this._dragStart.origX + (touch.clientX - this._dragStart.x) this.floatPos.y = this._dragStart.origY + (touch.clientY - this._dragStart.y) this.clampFloatPos() @@ -3489,33 +3670,53 @@ export default { color: var(--wms-text-tertiary); } -/* 摄像头设置弹窗 */ +/* 摄像头设置弹窗(整体字号/行高加大一档,仅作用于 .rp-camera-popup,不影响其它弹窗) */ .rp-camera-popup { width: 6.4rem; } +.rp-camera-popup .rp-popup-head { + padding: 0.12rem 0.2rem; +} + +.rp-camera-popup .rp-popup-title { + font-size: 0.24rem; + line-height: 0.36rem; +} + +.rp-camera-popup .rp-popup-close { + font-size: 0.28rem; + line-height: 0.36rem; +} + .rp-camera-tip { - padding: 0.05rem 0.15rem 0; - font-size: 0.15rem; + padding: 0.08rem 0.2rem 0; + font-size: 0.2rem; + line-height: 0.32rem; color: var(--wms-text-tertiary); } +.rp-camera-popup .rp-empty { + font-size: 0.2rem; + line-height: 0.32rem; +} + .rp-camera-options { flex: 1; min-height: 0; - max-height: 2.62rem; - margin-top: 0.05rem; + max-height: 3.2rem; + margin-top: 0.06rem; } .rp-camera-option { display: flex; align-items: center; - padding: 0.05rem 0.15rem; + padding: 0.1rem 0.2rem; border-bottom: 1px solid var(--wms-bg-subtle); } .rp-camera-option > * + * { - margin-left: 0.05rem; + margin-left: 0.08rem; } .rp-camera-option--checked { @@ -3524,16 +3725,18 @@ export default { .rp-camera-option-check { flex: 0 0 auto; - font-size: 0.17rem; + font-size: 0.22rem; + line-height: 0.34rem; color: var(--wms-primary-alt); - width: 0.2rem; + width: 0.26rem; text-align: center; } .rp-camera-option-label { flex: 1; min-width: 0; - font-size: 0.17rem; + font-size: 0.22rem; + line-height: 0.34rem; color: var(--wms-text-strong); overflow: hidden; text-overflow: ellipsis; @@ -3543,19 +3746,28 @@ export default { .rp-camera-actions { display: flex; justify-content: flex-end; - padding: 0.1rem 0.15rem; + padding: 0.12rem 0.2rem; border-top: 1px solid var(--wms-border-light); } -.rp-camera-actions > .rp-btn + .rp-btn { - margin-left: 0.05rem; +/* 底部按钮同步放大(覆盖 .rp-btn / .rp-btn--plain 的行高) */ +.rp-camera-actions > .rp-btn { + height: 0.46rem; + line-height: 0.46rem; + padding: 0 0.24rem; + font-size: 0.22rem; + border-radius: 0.08rem; } -/* 浮动摄像头预览窗(px 固定尺寸,与散单 Web 端一致) */ +.rp-camera-actions > .rp-btn + .rp-btn { + margin-left: 0.1rem; +} + +/* 浮动摄像头预览窗(px 固定尺寸;比原 240×180 放大一档,真机好点、画面也更大) */ .rp-float-preview { position: fixed; - width: 240px; - height: 180px; + width: 300px; + height: 225px; background: var(--wms-card-bg); border: 1px solid #d3d9e3; border-radius: 6px; @@ -3567,7 +3779,7 @@ export default { } .rp-float-header { - height: 28px; + height: 34px; flex-shrink: 0; display: flex; align-items: center; @@ -3596,14 +3808,20 @@ export default { align-items: center; } +/* 按钮间距:普通态 10px;全屏(放大)态再加大,见下方 .rp-float-preview--full 规则 */ .rp-float-tools > * + * { - margin-left: 4px; + margin-left: 10px; +} + +/* 显式子选择器兼底:通配符 + 相邻兄弟在某些真机会失效,按钮单独再声明一次 */ +.rp-float-tools > .rp-float-btn { + margin-left: 12px; } .rp-float-select { - max-width: 110px; - height: 20px; - line-height: 20px; + max-width: 88px; + height: 24px; + line-height: 24px; padding: 0 6px; font-size: 11px; color: var(--wms-primary-alt); @@ -3615,23 +3833,125 @@ export default { white-space: nowrap; } +/* 工具按钮:28×28 点击区(原 20×20 偏小),图标全部用 CSS 画,不依赖字体/emoji */ .rp-float-btn { flex: 0 0 auto; - width: 20px; - height: 20px; - line-height: 20px; + position: relative; + width: 28px; + height: 28px; + box-sizing: border-box; text-align: center; - font-size: 13px; color: var(--wms-text-tertiary); background: var(--wms-card-bg); border: 1px solid var(--wms-border); - border-radius: 4px; + border-radius: 5px; } .rp-float-btn:active { background: #ecf5ff; } +.rp-float-icon { + position: absolute; + left: 50%; + top: 50%; + width: 12px; + height: 12px; + margin: -6px 0 0 -6px; +} + +/* 放大:左上/右下外向直角 */ +.rp-float-icon--expand::before, +.rp-float-icon--expand::after, +.rp-float-icon--restore::before, +.rp-float-icon--restore::after { + content: ''; + position: absolute; + width: 5px; + height: 5px; + border: 0 solid #555; +} + +.rp-float-icon--expand::before { + left: 0; + top: 0; + border-left-width: 2px; + border-top-width: 2px; +} + +.rp-float-icon--expand::after { + right: 0; + bottom: 0; + border-right-width: 2px; + border-bottom-width: 2px; +} + +/* 还原:居中方框 */ +.rp-float-icon--restore::before { + left: 1px; + top: 1px; + width: 10px; + height: 10px; + box-sizing: border-box; + border-width: 2px; +} + +.rp-float-icon--restore::after { + display: none; +} + +/* 收起:一条横线 */ +.rp-float-icon--min { + width: 12px; + height: 2px; + margin: -1px 0 0 -6px; + background: #555; + border-radius: 1px; +} + +/* 全屏(放大)态:按钮、图标、间距同步放大一档,全屏下更好点 */ +.rp-float-preview--full .rp-float-header { + height: 40px; + padding: 0 10px; +} + +.rp-float-preview--full .rp-float-tools > * + * { + margin-left: 16px; +} + +.rp-float-preview--full .rp-float-tools > .rp-float-btn { + margin-left: 18px; +} + +.rp-float-preview--full .rp-float-select { + max-width: 140px; + height: 28px; + line-height: 28px; + font-size: 13px; +} + +.rp-float-preview--full .rp-float-btn { + width: 34px; + height: 34px; + border-radius: 6px; +} + +.rp-float-preview--full .rp-float-icon { + width: 14px; + height: 14px; + margin: -7px 0 0 -7px; +} + +.rp-float-preview--full .rp-float-icon--min { + width: 14px; + height: 2px; + margin: -1px 0 0 -7px; +} + +.rp-float-preview--full .rp-float-title { + font-size: 14px; +} + /* 全屏态:铺满视口 */ .rp-float-preview--full { width: 100vw; diff --git a/src/pages/weighing/index.vue b/src/pages/weighing/index.vue index a7ff428..468ba98 100644 --- a/src/pages/weighing/index.vue +++ b/src/pages/weighing/index.vue @@ -125,12 +125,26 @@ import { stopScanSelfHeal, } from '@/core/scan' import { getVoice } from '@/core/voice' +import { getActiveView, isActiveView, setActiveView } from '@/core/active-view' // 扫码最少码长:称重只收运单号,兼容短码;退出页面时恢复默认 5 const SCAN_MIN_LENGTH = 2 const SCAN_MIN_LENGTH_DEFAULT = 5 // 扫描记录本地缓存 key(最多 50 条,最新在前) const SCAN_RECORDS_STORAGE_KEY = 'weighScanRecords' +// 称重页的两种写法(后端菜单短路径 + 本地页面路径),用于判断当前展示的页 +const WEIGHING_VIEW_PATHS = ['/catchWeight', '/pages/weighing/index'] +// 其它功能页:只用来判定「此刻不是在称重页」(未列出的未知路径不拦截) +const OTHER_VIEW_PATHS = [ + '/returns', + '/pages/returns/index', + '/order', + '/pages/order/index', + '/packaging', + '/pages/packaging/index', +] +// 记录的来源标记:只记录称重页自己扫的码(过滤历史遗留的其它页面扫码) +const SCAN_RECORD_SOURCE = 'weighing' function emptyOrderInfo() { return { @@ -185,6 +199,7 @@ export default { }, onShow() { this.pageActive = true + setActiveView('/pages/weighing/index') this.registerScanCapture() startScanSelfHeal() // #ifdef APP-PLUS @@ -204,6 +219,7 @@ export default { // keep-alive 内嵌模式(H5 布局壳菜单切换):页面级 onShow/onHide 不会触发 activated() { this.pageActive = true + setActiveView('/pages/weighing/index') this.registerScanCapture() startScanSelfHeal() // #ifdef APP-PLUS @@ -221,6 +237,7 @@ export default { return } this.pageActive = true + setActiveView('/pages/weighing/index') this.registerScanCapture() startScanSelfHeal() // #ifdef APP-PLUS @@ -244,27 +261,56 @@ export default { return this.pageActive }, + /** 布局壳当前展示的是否为称重页(尚未记录激活视图时按本页为准,避免完全不计记录) */ + isWeighingViewActive() { + if (!getActiveView()) { + return true + } + if (isActiveView(...WEIGHING_VIEW_PATHS)) { + return true + } + // 只有「明确处于其它功能页」时才判定不是在称重页; + // 未知/未映射的视图标识一律放行,避免菜单路径差异误伤正常扫码 + return !isActiveView(...OTHER_VIEW_PATHS) + }, + + /** 是否允许接收扫码:本页 active 且当前展示的确实是称重页 */ + canCaptureScan() { + return this.isPageActive() && this.isWeighingViewActive() + }, + // ==================== 扫码捕获 ==================== registerScanCapture() { setScanMinLength(SCAN_MIN_LENGTH) - registerScanReceiver({ - scope: 'weighing', - onScanCode: (code) => { - if (!this.isPageActive()) { - return - } - this.handleScanCode(code) - }, - onScanDebug: (...args) => { - console.log('[scan-weighing]', ...args) - }, - }) + // 接收者对象每页只建一次并复用:注销时把它作为归属凭证传回, + // 避免本页 onHide/deactivated 把其它页刚注册的接收者一并清掉 + if (!this._scanReceiver) { + this._scanReceiver = { + scope: 'weighing', + onScanCode: (code) => { + // 只有「称重页正在展示」时收到的扫码才算称重页扫码; + // 页面已切走(如在退件页扫码)时直接丢弃,不写扫描记录 + if (!this.canCaptureScan()) { + return + } + this.handleScanCode(code) + }, + onScanDebug: (...args) => { + console.log('[scan-weighing]', ...args) + }, + } + } + registerScanReceiver(this._scanReceiver) }, unregisterScanCapture() { - unregisterScanReceiver() - setScanMinLength(SCAN_MIN_LENGTH_DEFAULT) + // 必须带归属凭证:全局同一时刻只保留一个接收者,无参注销会误清其它页面的注册 + const cleared = this._scanReceiver ? unregisterScanReceiver(this._scanReceiver) : false + // 只有真的注销了自己的接收者才恢复默认码长,避免切页时把新页面的最小码长改回去 + if (cleared) { + setScanMinLength(SCAN_MIN_LENGTH_DEFAULT) + } }, // 恢复窗口软键盘模式:登录页会把窗口设为 ALWAYS_HIDDEN(3)(窗口级、跨页持续), @@ -319,6 +365,10 @@ export default { // ==================== 扫码/查询路由 ==================== handleScanCode(code) { + // 双保险:非称重页展示期间的扫码不进入称重流程 / 扫描记录 + if (!this.canCaptureScan()) { + return + } const barcode = String(code || '').trim() if (!barcode) { return @@ -604,8 +654,10 @@ export default { try { const cached = uni.getStorageSync(SCAN_RECORDS_STORAGE_KEY) if (Array.isArray(cached)) { + // 只保留称重页写入的记录:历史版本可能混入其它页面(如退件页)的扫码, + // 这些记录没有 source 标记,无法区分,一并丢弃 this.scanRecords = cached - .filter((record) => record && record.text) + .filter((record) => record && record.text && record.source === SCAN_RECORD_SOURCE) .slice(0, 50) } } catch (e) { @@ -614,10 +666,18 @@ export default { }, addScanRecord(code) { + // 兜底:只记录称重页自己的扫码(防止缓存实例/生命周期时序导致别的页面扫码被记到这里) + if (!this.isWeighingViewActive()) { + return + } + const text = String(code || '').trim() + if (!text) { + return + } const date = new Date() const pad = (n) => String(n).padStart(2, '0') const time = `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}` - this.scanRecords.unshift({ text: code, time }) + this.scanRecords.unshift({ text, time, source: SCAN_RECORD_SOURCE }) if (this.scanRecords.length > 50) { this.scanRecords = this.scanRecords.slice(0, 50) }