feat(广播): 新增工作台语音广播一期(原声录制,storage mock 先行)
背景:仓库现场需要"管理工作台 → 所有工作台"的实时通知。管理员在任意工作台
录一段原声(或输入文字),其它工作台实时收到后横幅显示 + 播放原声。
后端接口尚未确定,一期用本地 storage 模拟,先跑通完整交互。
新增文件:
- notice.js 广播开关(NOTICE_MOCK)/长轮询/录音时长/存储键配置
- notice.ts 真实接口封装 send/poll/ack/uploadAudio(待后端就绪)
- notice-mock.js storage 模拟"消息表 + 长轮询"
- notice.js 消息中心单例:轮询/去重/游标补发/过期丢弃/横幅通知/播报调度
- recorder.js 录音封装(App: getRecorderManager aac 16k 单声道;H5: MediaRecorder)
- notice-banner.vue 顶部广播横幅(通知/紧急、重播、关闭、自动收起)
- notice-send-dialog.vue 广播发送弹窗(语音/文字、录音计时、试听、优先级)
- notice-voice-broadcast.md 接口契约 + 验证步骤 + 已知限制
修改文件:
- voice.js 播报队列项改为 {kind:'tts'|'audio'},新增 playAudio/playUrgent/
playAudioUrgent/clear,加 token 打断计数避免旧回调推进新队列;
对外 play(text) 行为不变
- top-nav.vue 右上角新增"广播"入口(uni.$emit('notice:open-send'),预留
canBroadcast 权限 prop);退出登录前 reset 消息中心;右侧容器改 flex
- index.vue 布局壳挂广播横幅 + 发送弹窗,onShow 启动接收,onUnload 清理,
用户信息加载后同步发送人名称
- index.vue 打包模式页顶栏新增广播按钮 + 横幅(compact 12.5px 边距) + 弹窗,
onShow 启动接收,退出登录 reset
- manifest.json 新增 android.permission.RECORD_AUDIO
- AndroidManifest.xml
同步声明 RECORD_AUDIO(离线打包不读 manifest.json 的 permissions,
不补会导至真机录音权限申请被拒)
说明:
- NOTICE_MOCK=true 时不发任何网络请求,消息只落本地 storage;同一浏览器多标签页可模拟多台工作台
(游标只放内存、启动跳过历史,互不抢占);NOTICE_MOCK_SELF_PLAY=true 便于单机验证播报
- 两条登录路径都挂载横幅:账号登录走 pages/index 布局壳,工作台绑定登录走 pages/packaging
- 播报优先原声,未上传音频时回落现有 HTTP TTS;priority=1 插队并打断当前播报
- 老 WebView 兼容:组件内一律用 margin 代替 flex gap、控件 height+line-height 成对、
广播按钮用 view(避开 APP-PLUS uni-button 内置样式),弹窗 z-index 990(低于内置 toast 999)
- 验证:npm run build:h5 / npm run build:app 均编译通过
This commit is contained in:
parent
b422bfad08
commit
d75e4e8a74
@ -7,6 +7,9 @@
|
||||
REQUEST_INSTALL_PACKAGES 为 Android 8+ 未知来源安装授权,7.x 及以下仅依赖全局未知来源开关 -->
|
||||
<uses-permission android:name="android.permission.INSTALL_PACKAGES" />
|
||||
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
|
||||
<!-- 语音广播:工作台录制原声。(离线打包不读 uni-app manifest.json 的 permissions,
|
||||
必须在壳工程 AndroidManifest 声明,否则真机 plus.android.requestPermissions 会直接被拒) -->
|
||||
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
||||
|
||||
<application
|
||||
android:allowBackup="true"
|
||||
|
||||
143
docs/notice-voice-broadcast.md
Normal file
143
docs/notice-voice-broadcast.md
Normal file
@ -0,0 +1,143 @@
|
||||
# 语音广播(一期:原声广播)
|
||||
|
||||
仓库现场「管理工作台 → 所有工作台」的单向通知:管理工作台录一段原声(或输入文字),
|
||||
其它工作台实时收到后**横幅显示 + 播放原声**。
|
||||
|
||||
> 一期不依赖任何语音识别(ASR)与后端接口:消息走本地 storage 模拟,先把交互跑通。
|
||||
> 后端就绪后把 `src/config/notice.js` 的 `NOTICE_MOCK` 改为 `false` 即可切换真实接口。
|
||||
|
||||
---
|
||||
|
||||
## 1. 文件清单
|
||||
|
||||
| 文件 | 说明 |
|
||||
|---|---|
|
||||
| `src/config/notice.js` | 开关(`NOTICE_MOCK`)、长轮询时长、录音时长上限、弹窗/横幅时长、存储键 |
|
||||
| `src/api/notice.ts` | 真实接口封装:`sendNotice` / `pollNotice` / `ackNotice` / `uploadNoticeAudio` |
|
||||
| `src/core/notice-mock.js` | 本地 storage 模拟的「消息表 + 长轮询」 |
|
||||
| `src/core/notice.js` | 消息中心单例:长轮询、去重、游标补发、横幅通知、播报调度 |
|
||||
| `src/core/recorder.js` | 录音封装(App 走 `getRecorderManager`,H5/Electron 走 `MediaRecorder`) |
|
||||
| `src/components/notice-banner.vue` | 顶部广播横幅(发送人 + 内容 + 重播 + 关闭) |
|
||||
| `src/components/notice-send-dialog.vue` | 广播发送弹窗(语音 / 文字、优先级) |
|
||||
| `src/core/voice.js` | 队列升级:支持 `playAudio()` 原声播放、`playUrgent()` 紧急插队、`clear()` |
|
||||
|
||||
接入位置:
|
||||
|
||||
- `src/components/top-nav.vue`:右上角「广播」按钮(`uni.$emit('notice:open-send')`)
|
||||
- `src/pages/index/index.vue`:账号登录后的布局壳 → 横幅 + 发送弹窗
|
||||
- `src/pages/packaging/index.vue`:工作台绑定登录后的打包模式页 → 顶栏「广播」按钮 + 横幅 + 弹窗
|
||||
- `src/manifest.json`:新增 `android.permission.RECORD_AUDIO`
|
||||
|
||||
> 两条登录路径都要挂横幅,否则绑定登录的工作台收不到广播。
|
||||
|
||||
---
|
||||
|
||||
## 2. 一期怎么验证(mock)
|
||||
|
||||
1. `npm run dev` 启动 H5,账号登录进入工作台。
|
||||
2. 点右上角「广播」→「语音通知」→ 开始录音 → 停止 → 试听 → 发送广播。
|
||||
3. 本机立刻出现横幅并播放刚录的原声(mock 下 `NOTICE_MOCK_SELF_PLAY = true`)。
|
||||
4. **模拟其它工作台**:同一浏览器再开一个标签页登录同一账号,
|
||||
在 A 页发送,B 页也会收到横幅并播放(两个标签页各自维护内存游标,互不抢)。
|
||||
5. 「文字通知」走现有 HTTP TTS 接口播报(`http://tbdata.gztbyc.com/voice/`)。
|
||||
|
||||
真机(APP-PLUS):
|
||||
- 首次点「开始录音」会申请 `RECORD_AUDIO` 权限;
|
||||
- mock 只有本机 storage,**跨设备不通**,需要后端接口才能多机互发;
|
||||
- 真机录音格式为 `aac`(Android MediaRecorder 不支持 mp3 输出),播放走 `innerAudioContext`。
|
||||
|
||||
---
|
||||
|
||||
## 3. 真实后端接口契约
|
||||
|
||||
统一走现有 `BASE_URL/system?method=xxx&v=1.0`(POST JSON),音频上传单独走 multipart。
|
||||
|
||||
### 3.1 `notice.uploadAudio`(multipart/form-data)
|
||||
|
||||
```
|
||||
file : 音频文件(aac/m4a,16kHz 单声道)
|
||||
duration : 秒
|
||||
workbench_id: 发起工作台 id
|
||||
→ { url: "http://.../uploads/notice/xxx.aac", duration: 8.2 }
|
||||
```
|
||||
|
||||
### 3.2 `notice.send`
|
||||
|
||||
```
|
||||
{
|
||||
content: "B区波次已到货,抓紧复核", // 可空(纯语音通知时为空)
|
||||
audio_url: "/uploads/notice/xxx.aac", // 可空(纯文字通知时为空)
|
||||
duration: 8.2,
|
||||
priority: 0, // 0 普通 / 1 紧急(接收端插队打断当前播报)
|
||||
target_type: "all", // all 全场(后续可扩展 group / workbench)
|
||||
target_ids: [],
|
||||
sender_name: "张三",
|
||||
sender_workbench_id: 8
|
||||
}
|
||||
→ { id: 1024, seq: 1024 }
|
||||
```
|
||||
|
||||
### 3.3 `notice.poll`(长轮询)
|
||||
|
||||
```
|
||||
{ since_id: 1023, workbench_id: 8, timeout: 25 }
|
||||
→ 有新消息立即返回:{ list: [ {id, content, audio_url, duration, priority, sender_name,
|
||||
sender_workbench_id, created_at, expire_at} ], last_id: 1024 }
|
||||
→ 25 秒内无消息:{ list: [], last_id: 1023 }
|
||||
```
|
||||
|
||||
要点:
|
||||
- 服务端 hold 25s;前端请求超时设成 30s(`NOTICE_POLL_TIMEOUT + 5000`);
|
||||
- `since_id` 由客户端持久化,断线/熄屏/重启后补发,保证不丢;
|
||||
- 返回字段按 `id` 升序。
|
||||
|
||||
### 3.4 `notice.ack`(可选)
|
||||
|
||||
```
|
||||
{ ids: [1024, 1025], workbench_id: 8 }
|
||||
```
|
||||
|
||||
用于「必达」统计(哪台工作台没收到/没播)。前端失败静默,不影响播报。
|
||||
|
||||
---
|
||||
|
||||
## 4. 已内置的行为
|
||||
|
||||
- **去重**:同一 `id` 只处理一次(内存 `seenIds` 滚动 200 条)
|
||||
- **离线补发**:真实接口下 `since_id` 落 storage,重连后自动补拉
|
||||
- **过期丢弃**:`expire_at` 已过期的消息只入游标、不播报(避免开机念旧通知)
|
||||
- **自己发的不播**:`sender_workbench_id === 本机` 时只显示横幅(mock 下可用
|
||||
`NOTICE_MOCK_SELF_PLAY` 打开,方便单机验证)
|
||||
- **原声优先**:有 `audio_url` 播原声;没有则用 `content` 走 HTTP TTS
|
||||
- **紧急插播**:`priority=1` 时插到播报队首并打断当前播报,横幅不自动消失
|
||||
- **录音前静音**:开始录音先 `getVoice().clear()`,避免把播报声录进麦克风
|
||||
- **退避重连**:拉取失败按 3s/6s/9s…(上限 15s)重试
|
||||
|
||||
---
|
||||
|
||||
## 5. 注意事项 / 已知限制
|
||||
|
||||
1. **mock 不跨设备**:storage 是设备本地的,多机互发必须接后端。
|
||||
2. **H5/Electron 录音**:走 `MediaRecorder`(webm/opus),mock 下用 blob URL 播放;
|
||||
接入真实上传时 H5 需后端支持 `FormData` 文件(`uni.uploadFile` 的 `filePath` 用 blob 受限)。
|
||||
3. **H5 需要安全上下文**:非 `localhost` 的 `http://` 页面调不到麦克风(浏览器限制)。
|
||||
4. **老 WebView 兼容**:组件内一律 `margin` 代替 flex `gap`;控件都写了 `height` + `line-height`;
|
||||
APP-PLUS 的 `<button>` 会被渲染成 `<uni-button>`(自带高特异性样式),广播按钮统一用 `view`。
|
||||
5. **层级**:发送弹窗 `z-index: 990`(低于内置 toast 的 999);横幅在正常文档流中,
|
||||
不遮挡页面的称重/包材等弹窗。
|
||||
6. **未做权限控制**:目前所有登录用户都能发广播。若需限制为管理人员,
|
||||
前端按 `user.info` 的角色/menus 传 `canBroadcast` 给 `top-nav`(已预留 prop),
|
||||
服务端 `notice.send` 必须二次校验。
|
||||
7. **未做历史列表/未读**:一期只有当前横幅,二期可加 `notice.history` + 未读数角标。
|
||||
8. **二期语音识别**:管理员说话 → ASR 文本。只需把识别文本填入 `content`,
|
||||
音频仍可一并上传(原声播放 + 文字留痕),接收端逻辑无需改动。
|
||||
|
||||
---
|
||||
|
||||
## 6. 切换到真实接口
|
||||
|
||||
1. `src/config/notice.js`:`NOTICE_MOCK = false`;
|
||||
2. 后端按第 3 节补 4 个方法;
|
||||
3. 若接口名不同,改 `NOTICE_METHOD` 即可(`send/poll/ack/upload`);
|
||||
4. 若返回包裹层不同,调整 `notice.js` 的 `fetchList` / `send` 解包逻辑
|
||||
(当前兼容 `data` / `result` / 根三级)。
|
||||
102
src/api/notice.ts
Normal file
102
src/api/notice.ts
Normal file
@ -0,0 +1,102 @@
|
||||
import { request, type ApiBody } from './request'
|
||||
import { API_URL } from '@/config/api'
|
||||
import { appEnv } from '@/config/env'
|
||||
import { NOTICE_METHOD } from '@/config/notice'
|
||||
|
||||
/** 广播消息(服务端 → 工作台) */
|
||||
export type NoticeMessagePayload = {
|
||||
id: number | string
|
||||
content?: string
|
||||
audio_url?: string
|
||||
duration?: number
|
||||
priority?: number
|
||||
target_type?: string
|
||||
target_ids?: (string | number)[]
|
||||
sender_name?: string
|
||||
sender_workbench_id?: string | number
|
||||
created_at?: string
|
||||
expire_at?: string
|
||||
}
|
||||
|
||||
export type NoticePollResponse = {
|
||||
list?: NoticeMessagePayload[]
|
||||
last_id?: number | string
|
||||
}
|
||||
|
||||
/** 发送广播(文本 / 已上传的音频 URL) */
|
||||
export function sendNotice(data: Record<string, unknown>) {
|
||||
return request<ApiBody>(NOTICE_METHOD.send, data)
|
||||
}
|
||||
|
||||
/**
|
||||
* 长轮询拉取广播
|
||||
* - 服务端无新消息时 hold(建议 25s)后返回空列表
|
||||
* - 客户端超时需比服务端 hold 时间长,这里多留 5s
|
||||
*/
|
||||
export function pollNotice(data: Record<string, unknown>, timeout?: number) {
|
||||
return request<ApiBody>(NOTICE_METHOD.poll, data, {
|
||||
timeout: timeout != null ? timeout : 30000,
|
||||
})
|
||||
}
|
||||
|
||||
/** 回报已播(必达统计用,可选接口;失败静默) */
|
||||
export function ackNotice(data: Record<string, unknown>) {
|
||||
return request<ApiBody>(NOTICE_METHOD.ack, data, { timeout: 8000 })
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传录音文件(multipart/form-data)
|
||||
* - 走独立的文件通道(统一 request 通道只支持 JSON)
|
||||
* - 后端返回 { url } 供其它工作台下载播放
|
||||
*/
|
||||
export function uploadNoticeAudio(options: {
|
||||
filePath: string
|
||||
duration?: number
|
||||
workbenchId?: string
|
||||
}): Promise<{ url: string; duration: number }> {
|
||||
const { filePath, duration = 0, workbenchId = '' } = options
|
||||
const query = `method=${encodeURIComponent(NOTICE_METHOD.upload)}&v=1.0×tamp=${Date.now()}`
|
||||
const token = uni.getStorageSync('token')
|
||||
const header: Record<string, string> = {
|
||||
platform: 'workerstation',
|
||||
project: 'warehouse',
|
||||
'app-version': appEnv.version,
|
||||
'pack-type': appEnv.packType,
|
||||
}
|
||||
if (token) {
|
||||
header.token = String(token)
|
||||
header.Authorization = `Bearer ${token}`
|
||||
}
|
||||
|
||||
return new Promise<{ url: string; duration: number }>((resolve, reject) => {
|
||||
uni.uploadFile({
|
||||
url: `${API_URL}?${query}`,
|
||||
filePath,
|
||||
name: 'file',
|
||||
formData: {
|
||||
duration: String(duration),
|
||||
workbench_id: String(workbenchId || ''),
|
||||
},
|
||||
header,
|
||||
timeout: 30000,
|
||||
success: (res) => {
|
||||
let body: any = res.data
|
||||
try {
|
||||
body = typeof res.data === 'string' ? JSON.parse(res.data) : res.data
|
||||
} catch (e) {
|
||||
// 非 JSON 响应时保留原始字符串,下方按失败处理
|
||||
}
|
||||
const data = body?.data || body?.result || body || {}
|
||||
const url = data.url || data.audio_url || data.path || ''
|
||||
if (url) {
|
||||
resolve({ url: String(url), duration: Number(data.duration || duration) || 0 })
|
||||
return
|
||||
}
|
||||
reject(new Error(body?.message || body?.msg || '音频上传失败'))
|
||||
},
|
||||
fail: (err) => {
|
||||
reject(err instanceof Error ? err : new Error((err as any)?.errMsg || '音频上传失败'))
|
||||
},
|
||||
})
|
||||
})
|
||||
}
|
||||
247
src/components/notice-banner.vue
Normal file
247
src/components/notice-banner.vue
Normal file
@ -0,0 +1,247 @@
|
||||
<template>
|
||||
<view
|
||||
v-if="notice"
|
||||
:class="[
|
||||
'notice-banner',
|
||||
notice.priority === 1 ? 'notice-banner--urgent' : '',
|
||||
compact ? 'notice-banner--compact' : '',
|
||||
]"
|
||||
>
|
||||
<view class="notice-banner-flag">
|
||||
<text class="notice-banner-flag-text">{{ notice.priority === 1 ? '紧急' : '通知' }}</text>
|
||||
</view>
|
||||
|
||||
<view class="notice-banner-main">
|
||||
<view class="notice-banner-meta">
|
||||
<text class="notice-banner-sender">{{ notice.senderName || '管理端' }}</text>
|
||||
<text v-if="notice.self" class="notice-banner-self">本机</text>
|
||||
<text v-if="notice.createdAt" class="notice-banner-time">{{ notice.createdAt }}</text>
|
||||
</view>
|
||||
<text class="notice-banner-text">{{ displayText }}</text>
|
||||
</view>
|
||||
|
||||
<view class="notice-banner-actions">
|
||||
<view v-if="notice.audioUrl" class="notice-banner-btn" @click.stop="handleReplay">
|
||||
<text class="notice-banner-btn-text">重播</text>
|
||||
</view>
|
||||
<view
|
||||
:class="['notice-banner-btn', 'notice-banner-btn--primary']"
|
||||
@click.stop="handleDismiss"
|
||||
>
|
||||
<text class="notice-banner-btn-text">{{ notice.priority === 1 ? '知道了' : '关闭' }}</text>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
/**
|
||||
* 广播横幅:显示最近一条广播(发送人 + 文字/语音提示),可重播、可关闭。
|
||||
* 挂载位置:布局壳 pages/index/index.vue 与打包模式页 pages/packaging/index.vue 的顶栏下方,
|
||||
* 因为两处是两条登录路径(账号登录 / 工作台绑定登录),都要能收到广播。
|
||||
*/
|
||||
import { NOTICE_BANNER_MS, NOTICE_URGENT_BANNER_MS } from '@/config/notice'
|
||||
import { getNoticeCenter } from '@/core/notice'
|
||||
import { getVoice } from '@/core/voice'
|
||||
|
||||
export default {
|
||||
name: 'NoticeBanner',
|
||||
props: {
|
||||
// 紧凑模式:左右边距改为 0.125rem(打包模式页的页边距是 12.5px)
|
||||
compact: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
},
|
||||
},
|
||||
data() {
|
||||
return {
|
||||
notice: null,
|
||||
closeTimer: null,
|
||||
}
|
||||
},
|
||||
computed: {
|
||||
displayText() {
|
||||
if (!this.notice) {
|
||||
return ''
|
||||
}
|
||||
if (this.notice.content) {
|
||||
return this.notice.content
|
||||
}
|
||||
return this.notice.audioUrl ? '(语音通知,点击「重播」收听)' : ''
|
||||
},
|
||||
},
|
||||
mounted() {
|
||||
this.closeTimer = null
|
||||
this._unsubscribe = getNoticeCenter().onBanner((notice) => {
|
||||
this.notice = notice
|
||||
this.scheduleAutoClose()
|
||||
})
|
||||
},
|
||||
beforeUnmount() {
|
||||
if (typeof this._unsubscribe === 'function') {
|
||||
this._unsubscribe()
|
||||
this._unsubscribe = null
|
||||
}
|
||||
this.clearAutoClose()
|
||||
},
|
||||
methods: {
|
||||
scheduleAutoClose() {
|
||||
this.clearAutoClose()
|
||||
if (!this.notice) {
|
||||
return
|
||||
}
|
||||
const delay = this.notice.priority === 1 ? NOTICE_URGENT_BANNER_MS : NOTICE_BANNER_MS
|
||||
if (!delay) {
|
||||
return
|
||||
}
|
||||
this.closeTimer = setTimeout(() => {
|
||||
this.closeTimer = null
|
||||
this.handleDismiss()
|
||||
}, delay)
|
||||
},
|
||||
clearAutoClose() {
|
||||
if (this.closeTimer) {
|
||||
clearTimeout(this.closeTimer)
|
||||
this.closeTimer = null
|
||||
}
|
||||
},
|
||||
handleDismiss() {
|
||||
this.clearAutoClose()
|
||||
getNoticeCenter().dismiss()
|
||||
},
|
||||
handleReplay() {
|
||||
if (!this.notice) {
|
||||
return
|
||||
}
|
||||
const voice = getVoice()
|
||||
if (this.notice.audioUrl) {
|
||||
voice.playAudio(this.notice.audioUrl)
|
||||
return
|
||||
}
|
||||
if (this.notice.content) {
|
||||
voice.play(this.notice.content)
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
/* 间距一律用 margin(真机 WebView 为 Chromium 52,flex gap 不生效) */
|
||||
.notice-banner {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
box-sizing: border-box;
|
||||
margin: 0 var(--wms-page-pad) 0.075rem;
|
||||
padding: 0.09rem 0.15rem;
|
||||
background-color: var(--wms-card-bg);
|
||||
border-radius: var(--wms-radius-sm);
|
||||
border-left: 0.06rem solid var(--wms-primary);
|
||||
box-shadow: 0 0.02rem 0.06rem rgba(0, 0, 0, 0.08);
|
||||
}
|
||||
|
||||
.notice-banner--urgent {
|
||||
border-left-color: var(--wms-danger-strong);
|
||||
background-color: #fff5f4;
|
||||
}
|
||||
|
||||
.notice-banner--compact {
|
||||
margin-left: 0.125rem;
|
||||
margin-right: 0.125rem;
|
||||
}
|
||||
|
||||
.notice-banner-flag {
|
||||
flex-shrink: 0;
|
||||
height: 0.32rem;
|
||||
line-height: 0.32rem;
|
||||
padding: 0 0.1rem;
|
||||
border-radius: 0.05rem;
|
||||
background-color: var(--wms-primary);
|
||||
margin-right: 0.15rem;
|
||||
}
|
||||
|
||||
.notice-banner--urgent .notice-banner-flag {
|
||||
background-color: var(--wms-danger-strong);
|
||||
}
|
||||
|
||||
.notice-banner-flag-text {
|
||||
font-size: 0.18rem;
|
||||
color: var(--wms-white);
|
||||
}
|
||||
|
||||
.notice-banner-main {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.notice-banner-meta {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
margin-bottom: 0.03rem;
|
||||
}
|
||||
|
||||
.notice-banner-sender {
|
||||
font-size: 0.18rem;
|
||||
color: var(--wms-text-secondary);
|
||||
margin-right: 0.12rem;
|
||||
}
|
||||
|
||||
.notice-banner-self {
|
||||
font-size: 0.16rem;
|
||||
color: var(--wms-primary);
|
||||
border: 0.01rem solid var(--wms-primary);
|
||||
border-radius: 0.04rem;
|
||||
padding: 0 0.06rem;
|
||||
margin-right: 0.12rem;
|
||||
}
|
||||
|
||||
.notice-banner-time {
|
||||
font-size: 0.16rem;
|
||||
color: var(--wms-text-placeholder);
|
||||
}
|
||||
|
||||
.notice-banner-text {
|
||||
font-size: 0.2rem;
|
||||
color: var(--wms-text);
|
||||
line-height: 0.28rem;
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.notice-banner-actions {
|
||||
flex-shrink: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
margin-left: 0.15rem;
|
||||
}
|
||||
|
||||
.notice-banner-btn {
|
||||
height: 0.34rem;
|
||||
line-height: 0.34rem;
|
||||
padding: 0 0.16rem;
|
||||
margin-left: 0.1rem;
|
||||
border-radius: 0.05rem;
|
||||
border: 0.01rem solid var(--wms-border);
|
||||
background-color: var(--wms-bg-subtle);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.notice-banner-btn--primary {
|
||||
background-color: var(--wms-primary);
|
||||
border-color: var(--wms-primary);
|
||||
}
|
||||
|
||||
.notice-banner-btn-text {
|
||||
font-size: 0.18rem;
|
||||
color: var(--wms-text);
|
||||
line-height: 0.34rem;
|
||||
}
|
||||
|
||||
.notice-banner-btn--primary .notice-banner-btn-text {
|
||||
color: var(--wms-white);
|
||||
}
|
||||
</style>
|
||||
698
src/components/notice-send-dialog.vue
Normal file
698
src/components/notice-send-dialog.vue
Normal file
@ -0,0 +1,698 @@
|
||||
<template>
|
||||
<view v-if="visible" :class="['ns-mask', mode === 'text' ? 'ns-mask--top' : '']" @click.self="handleMaskClick">
|
||||
<view class="ns-dialog">
|
||||
<view class="ns-head">
|
||||
<text class="ns-title">广播通知</text>
|
||||
<text v-if="isMock" class="ns-mock-tag">本地模拟</text>
|
||||
<view class="ns-close" @click="handleClose">
|
||||
<text class="ns-close-text">×</text>
|
||||
</view>
|
||||
</view>
|
||||
|
||||
<view class="ns-seg">
|
||||
<view
|
||||
:class="['ns-seg-item', mode === 'voice' ? 'ns-seg-item--on' : '']"
|
||||
@click="switchMode('voice')"
|
||||
>
|
||||
<text class="ns-seg-text">语音通知</text>
|
||||
</view>
|
||||
<view
|
||||
:class="['ns-seg-item', mode === 'text' ? 'ns-seg-item--on' : '']"
|
||||
@click="switchMode('text')"
|
||||
>
|
||||
<text class="ns-seg-text">文字通知</text>
|
||||
</view>
|
||||
</view>
|
||||
|
||||
<view v-if="mode === 'voice'" class="ns-body">
|
||||
<text class="ns-tip">{{ recordTip }}</text>
|
||||
<view
|
||||
:class="['ns-record-btn', recording ? 'ns-record-btn--on' : '']"
|
||||
@click="handleRecordToggle"
|
||||
>
|
||||
<text class="ns-record-btn-text">{{ recordButtonText }}</text>
|
||||
</view>
|
||||
<view v-if="recording" class="ns-record-status">
|
||||
<text class="ns-record-time">{{ recordSecondsText }}</text>
|
||||
<text class="ns-record-status-text">正在录音,点击上方按钮结束</text>
|
||||
</view>
|
||||
<view v-else-if="recordResult" class="ns-record-result">
|
||||
<text class="ns-record-result-text">已录制 {{ formatDuration(recordResult.duration) }}</text>
|
||||
<view class="ns-small-btn" @click="handlePreview">
|
||||
<text class="ns-small-btn-text">试听</text>
|
||||
</view>
|
||||
</view>
|
||||
<text class="ns-sub-tip">录音最长 {{ maxRecordSeconds }} 秒;发送后其它工作台会直接播放这段原声</text>
|
||||
</view>
|
||||
|
||||
<view v-else class="ns-body">
|
||||
<textarea
|
||||
v-model="text"
|
||||
class="ns-textarea"
|
||||
:maxlength="maxTextLength"
|
||||
placeholder="输入通知内容(接收端用语音播报)"
|
||||
placeholder-class="ns-textarea-placeholder"
|
||||
/>
|
||||
<text class="ns-count">{{ text.length }}/{{ maxTextLength }}</text>
|
||||
</view>
|
||||
|
||||
<view class="ns-row">
|
||||
<text class="ns-row-label">优先级</text>
|
||||
<view class="ns-inline-seg">
|
||||
<view
|
||||
:class="['ns-inline-item', priority === 0 ? 'ns-inline-item--on' : '']"
|
||||
@click="priority = 0"
|
||||
>
|
||||
<text class="ns-inline-text">普通</text>
|
||||
</view>
|
||||
<view
|
||||
:class="['ns-inline-item', priority === 1 ? 'ns-inline-item--on' : '']"
|
||||
@click="priority = 1"
|
||||
>
|
||||
<text class="ns-inline-text">紧急插播</text>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
|
||||
<view class="ns-row">
|
||||
<text class="ns-row-label">接收范围</text>
|
||||
<view class="ns-inline-seg">
|
||||
<view class="ns-inline-item ns-inline-item--on">
|
||||
<text class="ns-inline-text">全场工作台</text>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
|
||||
<view class="ns-footer">
|
||||
<view class="ns-btn ns-btn--ghost" @click="handleClose">
|
||||
<text class="ns-btn-text">取消</text>
|
||||
</view>
|
||||
<view
|
||||
:class="['ns-btn', canSend && !sending ? '' : 'ns-btn--disabled']"
|
||||
@click="handleSend"
|
||||
>
|
||||
<text class="ns-btn-text ns-btn-text--primary">{{ sending ? '发送中…' : '发送广播' }}</text>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
/**
|
||||
* 广播发送弹窗(一期:原声广播)
|
||||
* - 语音通知:录一段原声,发送后其它工作台播放这段音频
|
||||
* - 文字通知:发送文本,接收端走现有 HTTP TTS 播报
|
||||
* - 录音前先清空本机播报队列,避免把播报声录进麦克风
|
||||
*/
|
||||
import {
|
||||
NOTICE_MAX_RECORD_MS,
|
||||
NOTICE_MAX_TEXT,
|
||||
NOTICE_MIN_RECORD_MS,
|
||||
NOTICE_MOCK,
|
||||
NOTICE_PRIORITY,
|
||||
} from '@/config/notice'
|
||||
import { getNoticeCenter } from '@/core/notice'
|
||||
import { VoiceRecorder, isRecorderSupported } from '@/core/recorder'
|
||||
import { getVoice } from '@/core/voice'
|
||||
|
||||
export default {
|
||||
name: 'NoticeSendDialog',
|
||||
props: {
|
||||
visible: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
},
|
||||
},
|
||||
emits: ['update:visible', 'sent'],
|
||||
data() {
|
||||
return {
|
||||
mode: 'voice',
|
||||
text: '',
|
||||
priority: NOTICE_PRIORITY.normal,
|
||||
recording: false,
|
||||
recordSeconds: 0,
|
||||
recordResult: null,
|
||||
sending: false,
|
||||
maxTextLength: NOTICE_MAX_TEXT,
|
||||
maxRecordSeconds: Math.round(NOTICE_MAX_RECORD_MS / 1000),
|
||||
}
|
||||
},
|
||||
computed: {
|
||||
isMock() {
|
||||
return NOTICE_MOCK
|
||||
},
|
||||
canSend() {
|
||||
if (this.mode === 'voice') {
|
||||
return !!this.recordResult
|
||||
}
|
||||
return !!this.text.trim()
|
||||
},
|
||||
recordButtonText() {
|
||||
if (this.recording) {
|
||||
return '停止录音'
|
||||
}
|
||||
return this.recordResult ? '重新录音' : '开始录音'
|
||||
},
|
||||
recordTip() {
|
||||
if (this.recording) {
|
||||
return '正在录音…'
|
||||
}
|
||||
return this.recordResult ? '录音已完成,可试听后发送' : '点击开始录音,录一段要广播的通知'
|
||||
},
|
||||
recordSecondsText() {
|
||||
const seconds = Math.max(0, Math.floor(this.recordSeconds))
|
||||
return `${seconds}s / ${this.maxRecordSeconds}s`
|
||||
},
|
||||
},
|
||||
watch: {
|
||||
visible(val) {
|
||||
if (val) {
|
||||
this.resetState()
|
||||
} else {
|
||||
this.cleanup()
|
||||
}
|
||||
},
|
||||
},
|
||||
beforeUnmount() {
|
||||
this.cleanup()
|
||||
},
|
||||
methods: {
|
||||
switchMode(mode) {
|
||||
if (this.mode === mode) {
|
||||
return
|
||||
}
|
||||
if (this.recording) {
|
||||
this.cancelRecord()
|
||||
}
|
||||
this.mode = mode
|
||||
},
|
||||
resetState() {
|
||||
this.text = ''
|
||||
this.priority = NOTICE_PRIORITY.normal
|
||||
this.recordSeconds = 0
|
||||
this.recordResult = null
|
||||
this.sending = false
|
||||
},
|
||||
async handleRecordToggle() {
|
||||
if (this.recording) {
|
||||
await this.stopRecord()
|
||||
return
|
||||
}
|
||||
await this.startRecord()
|
||||
},
|
||||
async startRecord() {
|
||||
if (!isRecorderSupported()) {
|
||||
this.toast('当前环境不支持录音')
|
||||
return
|
||||
}
|
||||
try {
|
||||
this.recordResult = null
|
||||
this.recordSeconds = 0
|
||||
// 录音前清空本机播报,避免把自己/别人的播报录进去
|
||||
getVoice().clear()
|
||||
this.recorder = new VoiceRecorder({
|
||||
maxDuration: NOTICE_MAX_RECORD_MS,
|
||||
minDuration: NOTICE_MIN_RECORD_MS,
|
||||
})
|
||||
await this.recorder.start()
|
||||
this.recording = true
|
||||
this.startTick()
|
||||
this.maxTimer = setTimeout(() => {
|
||||
if (this.recording) {
|
||||
this.stopRecord()
|
||||
}
|
||||
}, NOTICE_MAX_RECORD_MS)
|
||||
} catch (err) {
|
||||
this.recording = false
|
||||
this.clearRecordTimers()
|
||||
this.recorder = null
|
||||
this.toast((err && err.message) || '录音启动失败')
|
||||
}
|
||||
},
|
||||
async stopRecord() {
|
||||
if (!this.recording || !this.recorder) {
|
||||
return
|
||||
}
|
||||
const recorder = this.recorder
|
||||
this.recording = false
|
||||
this.clearRecordTimers()
|
||||
try {
|
||||
const result = await recorder.stop()
|
||||
this.recordResult = result
|
||||
console.log('[notice-send] 录音完成:', JSON.stringify({ duration: result.duration, size: result.size }))
|
||||
} catch (err) {
|
||||
this.recordResult = null
|
||||
this.toast((err && err.message) || '录音失败')
|
||||
}
|
||||
},
|
||||
cancelRecord() {
|
||||
if (this.recorder) {
|
||||
this.recorder.cancel()
|
||||
}
|
||||
this.recording = false
|
||||
this.recordResult = null
|
||||
this.clearRecordTimers()
|
||||
},
|
||||
startTick() {
|
||||
this.clearTickTimer()
|
||||
this.recordStartAt = Date.now()
|
||||
this.tickTimer = setInterval(() => {
|
||||
if (!this.recording) {
|
||||
return
|
||||
}
|
||||
this.recordSeconds = (Date.now() - this.recordStartAt) / 1000
|
||||
}, 200)
|
||||
},
|
||||
clearTickTimer() {
|
||||
if (this.tickTimer) {
|
||||
clearInterval(this.tickTimer)
|
||||
this.tickTimer = null
|
||||
}
|
||||
},
|
||||
clearRecordTimers() {
|
||||
this.clearTickTimer()
|
||||
if (this.maxTimer) {
|
||||
clearTimeout(this.maxTimer)
|
||||
this.maxTimer = null
|
||||
}
|
||||
},
|
||||
handlePreview() {
|
||||
const result = this.recordResult
|
||||
if (!result || !result.filePath) {
|
||||
return
|
||||
}
|
||||
this.stopPreview()
|
||||
try {
|
||||
const audio = uni.createInnerAudioContext()
|
||||
audio.src = result.filePath
|
||||
audio.onEnded(() => this.stopPreview())
|
||||
audio.onError((err) => {
|
||||
console.log('[notice-send] 试听失败:', err)
|
||||
this.stopPreview()
|
||||
this.toast('试听失败')
|
||||
})
|
||||
audio.play()
|
||||
this.previewAudio = audio
|
||||
} catch (e) {
|
||||
this.toast('试听失败')
|
||||
}
|
||||
},
|
||||
stopPreview() {
|
||||
if (this.previewAudio) {
|
||||
try {
|
||||
this.previewAudio.stop()
|
||||
this.previewAudio.destroy()
|
||||
} catch (e) {
|
||||
// 忽略
|
||||
}
|
||||
this.previewAudio = null
|
||||
}
|
||||
},
|
||||
async handleSend() {
|
||||
if (this.sending || !this.canSend) {
|
||||
return
|
||||
}
|
||||
this.sending = true
|
||||
this.stopPreview()
|
||||
const center = getNoticeCenter()
|
||||
try {
|
||||
let audioUrl = ''
|
||||
let duration = 0
|
||||
if (this.mode === 'voice') {
|
||||
duration = Number(this.recordResult.duration) || 0
|
||||
audioUrl = await center.uploadAudio(this.recordResult.filePath, duration)
|
||||
}
|
||||
await center.send({
|
||||
content: this.mode === 'text' ? this.text.trim() : '',
|
||||
audioUrl,
|
||||
duration,
|
||||
priority: this.priority,
|
||||
})
|
||||
this.toast('广播已发送')
|
||||
this.$emit('sent')
|
||||
this.close()
|
||||
} catch (err) {
|
||||
this.toast((err && err.message) || '发送失败')
|
||||
} finally {
|
||||
this.sending = false
|
||||
}
|
||||
},
|
||||
handleMaskClick() {
|
||||
// 录音中不允许点遮罩关闭,避免误触丢录音
|
||||
if (this.recording || this.sending) {
|
||||
return
|
||||
}
|
||||
this.handleClose()
|
||||
},
|
||||
handleClose() {
|
||||
if (this.sending) {
|
||||
return
|
||||
}
|
||||
if (this.recording) {
|
||||
this.cancelRecord()
|
||||
}
|
||||
this.close()
|
||||
},
|
||||
close() {
|
||||
this.cleanup()
|
||||
this.$emit('update:visible', false)
|
||||
},
|
||||
cleanup() {
|
||||
this.clearRecordTimers()
|
||||
if (this.recorder) {
|
||||
this.recorder.destroy()
|
||||
this.recorder = null
|
||||
}
|
||||
this.recording = false
|
||||
this.stopPreview()
|
||||
},
|
||||
formatDuration(duration) {
|
||||
const seconds = Math.max(0, Math.round(Number(duration) || 0))
|
||||
return `${seconds} 秒`
|
||||
},
|
||||
toast(title) {
|
||||
uni.showToast({
|
||||
title: String(title || ''),
|
||||
icon: 'none',
|
||||
silentVoice: true,
|
||||
})
|
||||
},
|
||||
},
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
/* 间距一律用 margin(真机 WebView Chromium 52 不支持 flex gap) */
|
||||
.ns-mask {
|
||||
position: fixed;
|
||||
left: 0;
|
||||
top: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
/* 990:低于 uni-app 内置 toast(999),避免弹窗内提示被遮住;
|
||||
高于页面内容;订单页/打包页的遮罩(998/999)覆盖全屏时本弹窗本就点不开 */
|
||||
z-index: 990;
|
||||
background-color: rgba(0, 0, 0, 0.45);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
/* 文字模式需要软键盘:弹窗靠上,避免被键盘遮住(不用 adjust-position,老 WebView 会失焦) */
|
||||
.ns-mask--top {
|
||||
align-items: flex-start;
|
||||
}
|
||||
|
||||
.ns-dialog {
|
||||
width: 6rem;
|
||||
box-sizing: border-box;
|
||||
padding: 0.2rem;
|
||||
margin-top: 0.3rem;
|
||||
margin-bottom: 0.3rem;
|
||||
background-color: var(--wms-card-bg);
|
||||
border-radius: var(--wms-radius-md);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.ns-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
margin-bottom: 0.15rem;
|
||||
}
|
||||
|
||||
.ns-title {
|
||||
font-size: 0.24rem;
|
||||
color: var(--wms-text-strong);
|
||||
line-height: 0.32rem;
|
||||
}
|
||||
|
||||
.ns-mock-tag {
|
||||
margin-left: 0.12rem;
|
||||
padding: 0 0.08rem;
|
||||
height: 0.26rem;
|
||||
line-height: 0.26rem;
|
||||
font-size: 0.16rem;
|
||||
color: var(--wms-warning);
|
||||
border: 0.01rem solid var(--wms-warning);
|
||||
border-radius: 0.04rem;
|
||||
}
|
||||
|
||||
.ns-close {
|
||||
margin-left: auto;
|
||||
width: 0.4rem;
|
||||
height: 0.4rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.ns-close-text {
|
||||
font-size: 0.32rem;
|
||||
line-height: 0.4rem;
|
||||
color: var(--wms-text-muted);
|
||||
}
|
||||
|
||||
.ns-seg {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
margin-bottom: 0.15rem;
|
||||
}
|
||||
|
||||
.ns-seg-item {
|
||||
flex: 1;
|
||||
height: 0.4rem;
|
||||
line-height: 0.4rem;
|
||||
margin-right: 0.15rem;
|
||||
border-radius: 0.05rem;
|
||||
border: 0.02rem solid #dcdfe6;
|
||||
background-color: #f5f7fa;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.ns-seg-item:last-child {
|
||||
margin-right: 0;
|
||||
}
|
||||
|
||||
.ns-seg-item--on {
|
||||
background-color: #2f7dff;
|
||||
border-color: #2f7dff;
|
||||
}
|
||||
|
||||
.ns-seg-text {
|
||||
font-size: 0.2rem;
|
||||
line-height: 0.4rem;
|
||||
color: var(--wms-text-secondary);
|
||||
}
|
||||
|
||||
.ns-seg-item--on .ns-seg-text {
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.ns-body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
margin-bottom: 0.1rem;
|
||||
}
|
||||
|
||||
.ns-tip {
|
||||
font-size: 0.18rem;
|
||||
color: var(--wms-text-muted);
|
||||
line-height: 0.26rem;
|
||||
margin-bottom: 0.12rem;
|
||||
}
|
||||
|
||||
.ns-record-btn {
|
||||
height: 0.56rem;
|
||||
line-height: 0.56rem;
|
||||
border-radius: 0.07rem;
|
||||
background-color: #2f7dff;
|
||||
border: 0.02rem solid #2f7dff;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.ns-record-btn--on {
|
||||
background-color: #e64340;
|
||||
border-color: #e64340;
|
||||
}
|
||||
|
||||
.ns-record-btn-text {
|
||||
font-size: 0.22rem;
|
||||
line-height: 0.56rem;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.ns-record-status {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
margin-top: 0.12rem;
|
||||
}
|
||||
|
||||
.ns-record-time {
|
||||
font-size: 0.2rem;
|
||||
color: #e64340;
|
||||
margin-right: 0.15rem;
|
||||
}
|
||||
|
||||
.ns-record-status-text {
|
||||
font-size: 0.18rem;
|
||||
color: var(--wms-text-muted);
|
||||
}
|
||||
|
||||
.ns-record-result {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
margin-top: 0.12rem;
|
||||
}
|
||||
|
||||
.ns-record-result-text {
|
||||
font-size: 0.2rem;
|
||||
color: var(--wms-success-alt);
|
||||
margin-right: 0.15rem;
|
||||
}
|
||||
|
||||
.ns-small-btn {
|
||||
height: 0.32rem;
|
||||
line-height: 0.32rem;
|
||||
padding: 0 0.14rem;
|
||||
border-radius: 0.05rem;
|
||||
border: 0.02rem solid #dcdfe6;
|
||||
background-color: #f5f7fa;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.ns-small-btn-text {
|
||||
font-size: 0.18rem;
|
||||
line-height: 0.32rem;
|
||||
color: var(--wms-text-secondary);
|
||||
}
|
||||
|
||||
.ns-sub-tip {
|
||||
margin-top: 0.1rem;
|
||||
font-size: 0.16rem;
|
||||
color: var(--wms-text-placeholder);
|
||||
line-height: 0.24rem;
|
||||
}
|
||||
|
||||
.ns-textarea {
|
||||
width: 100%;
|
||||
height: 1.4rem;
|
||||
box-sizing: border-box;
|
||||
padding: 0.1rem;
|
||||
font-size: 0.2rem;
|
||||
line-height: 0.3rem;
|
||||
color: var(--wms-text);
|
||||
background-color: #f7f8fa;
|
||||
border: 0.02rem solid #dcdfe6;
|
||||
border-radius: 0.05rem;
|
||||
}
|
||||
|
||||
.ns-textarea-placeholder {
|
||||
font-size: 0.18rem;
|
||||
color: #999;
|
||||
}
|
||||
|
||||
.ns-count {
|
||||
align-self: flex-end;
|
||||
margin-top: 0.06rem;
|
||||
font-size: 0.16rem;
|
||||
color: var(--wms-text-placeholder);
|
||||
}
|
||||
|
||||
.ns-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
margin-bottom: 0.12rem;
|
||||
}
|
||||
|
||||
.ns-row-label {
|
||||
width: 1.1rem;
|
||||
flex-shrink: 0;
|
||||
font-size: 0.2rem;
|
||||
color: var(--wms-text-secondary);
|
||||
}
|
||||
|
||||
.ns-inline-seg {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.ns-inline-item {
|
||||
height: 0.36rem;
|
||||
line-height: 0.36rem;
|
||||
padding: 0 0.18rem;
|
||||
margin-right: 0.12rem;
|
||||
border-radius: 0.05rem;
|
||||
border: 0.02rem solid #dcdfe6;
|
||||
background-color: #f5f7fa;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.ns-inline-item--on {
|
||||
background-color: #2f7dff;
|
||||
border-color: #2f7dff;
|
||||
}
|
||||
|
||||
.ns-inline-text {
|
||||
font-size: 0.18rem;
|
||||
line-height: 0.36rem;
|
||||
color: var(--wms-text-secondary);
|
||||
}
|
||||
|
||||
.ns-inline-item--on .ns-inline-text {
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.ns-footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
margin-top: 0.1rem;
|
||||
}
|
||||
|
||||
.ns-btn {
|
||||
height: 0.42rem;
|
||||
line-height: 0.42rem;
|
||||
padding: 0 0.3rem;
|
||||
margin-left: 0.15rem;
|
||||
border-radius: 0.07rem;
|
||||
background-color: #2f7dff;
|
||||
border: 0.02rem solid #2f7dff;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.ns-btn--ghost {
|
||||
background-color: #f5f7fa;
|
||||
border-color: #dcdfe6;
|
||||
}
|
||||
|
||||
.ns-btn--disabled {
|
||||
background-color: #f2f2f2;
|
||||
border-color: #dcdfe6;
|
||||
}
|
||||
|
||||
.ns-btn-text {
|
||||
font-size: 0.2rem;
|
||||
line-height: 0.42rem;
|
||||
color: var(--wms-text-secondary);
|
||||
}
|
||||
|
||||
.ns-btn-text--primary {
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.ns-btn--disabled .ns-btn-text--primary {
|
||||
color: #999;
|
||||
}
|
||||
</style>
|
||||
@ -15,6 +15,10 @@
|
||||
</view>
|
||||
|
||||
<view class="top-nav-right" @click.stop>
|
||||
<view v-if="canBroadcast" class="top-nav-broadcast" @click="handleBroadcast">
|
||||
<text class="top-nav-broadcast-text">广播</text>
|
||||
</view>
|
||||
|
||||
<view class="top-nav-user" @click="openMinePopup">
|
||||
<view class="top-nav-mine-icon" aria-hidden="true">
|
||||
<view class="top-nav-mine-icon-head"></view>
|
||||
@ -46,6 +50,7 @@
|
||||
|
||||
<script>
|
||||
import { changeUserRole, fetchUserInfo, logout } from '@/api/index'
|
||||
import { getNoticeCenter } from '@/core/notice'
|
||||
|
||||
export default {
|
||||
name: 'TopNav',
|
||||
@ -77,6 +82,11 @@ export default {
|
||||
type: Boolean,
|
||||
default: true,
|
||||
},
|
||||
// 是否显示「广播」入口(角色/权限就绪后由父页面传入;一期默认展示)
|
||||
canBroadcast: {
|
||||
type: Boolean,
|
||||
default: true,
|
||||
},
|
||||
},
|
||||
data() {
|
||||
return {
|
||||
@ -405,6 +415,12 @@ export default {
|
||||
})
|
||||
},
|
||||
finishLogout() {
|
||||
// 先停广播接收并清游标,避免换账号后补发上一个人的消息
|
||||
try {
|
||||
getNoticeCenter().reset()
|
||||
} catch (e) {
|
||||
// 忽略
|
||||
}
|
||||
uni.removeStorageSync('token')
|
||||
uni.removeStorageSync('workbench_token')
|
||||
uni.removeStorageSync('workbench_id')
|
||||
@ -438,6 +454,11 @@ export default {
|
||||
this.finishLogout()
|
||||
})
|
||||
},
|
||||
/** 广播入口:由布局壳监听事件打开发送弹窗(top-nav 不持有弹窗状态) */
|
||||
handleBroadcast() {
|
||||
this.closeMinePopup()
|
||||
uni.$emit('notice:open-send')
|
||||
},
|
||||
},
|
||||
}
|
||||
</script>
|
||||
@ -467,6 +488,28 @@ export default {
|
||||
.top-nav-right {
|
||||
position: relative;
|
||||
margin-left: auto;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
/* 广播入口:白描边按钮(APP-PLUS 的 view 不受 uni-button 内置样式影响) */
|
||||
.top-nav-broadcast {
|
||||
height: 0.36rem;
|
||||
line-height: 0.36rem;
|
||||
padding: 0 0.16rem;
|
||||
margin-right: 0.2rem;
|
||||
border: 0.02rem solid rgba(255, 255, 255, 0.85);
|
||||
border-radius: 0.07rem;
|
||||
box-sizing: border-box;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.top-nav-broadcast-text {
|
||||
font-size: 0.2rem;
|
||||
line-height: 0.36rem;
|
||||
color: var(--wms-white);
|
||||
}
|
||||
|
||||
.top-nav-menu-wrap {
|
||||
|
||||
59
src/config/notice.js
Normal file
59
src/config/notice.js
Normal file
@ -0,0 +1,59 @@
|
||||
/**
|
||||
* 语音广播(一期:原声广播)配置
|
||||
*
|
||||
* 一期不接后端:NOTICE_MOCK = true,消息走本地 storage 模拟,
|
||||
* 用于先跑通「录音 → 发送 → 横幅显示 → 播报」的完整交互。
|
||||
* 后端接口就绪后把 NOTICE_MOCK 改为 false 即可切换到真实接口,
|
||||
* 接口语义见 docs/notice-voice-broadcast.md。
|
||||
*/
|
||||
|
||||
/** 是否使用本地 storage 模拟后端(一期默认 true) */
|
||||
export const NOTICE_MOCK = true
|
||||
|
||||
/**
|
||||
* mock 模式下「自己发的消息」是否也播一遍
|
||||
* - true:单机即可验证播报链路(调试用)
|
||||
* - false:真实后端应为此值语义,避免自己录的音又从自己的音箱放出来(自播自听)
|
||||
*/
|
||||
export const NOTICE_MOCK_SELF_PLAY = true
|
||||
|
||||
/** 接口方法名(真实后端,走 BASE_URL/system?method=xxx) */
|
||||
export const NOTICE_METHOD = {
|
||||
send: 'notice.send',
|
||||
poll: 'notice.poll',
|
||||
ack: 'notice.ack',
|
||||
upload: 'notice.uploadAudio',
|
||||
}
|
||||
|
||||
/** 长轮询挂起时长(毫秒):服务端没有新消息时 hold 这么久再返回空 */
|
||||
export const NOTICE_POLL_TIMEOUT = 25000
|
||||
/** 拉取失败后的重试基数(毫秒),按失败次数退避,最长 15s */
|
||||
export const NOTICE_POLL_RETRY_MS = 3000
|
||||
|
||||
/** 录音最长时长(毫秒),到时自动停止 */
|
||||
export const NOTICE_MAX_RECORD_MS = 20000
|
||||
/** 录音最短时长(毫秒),低于此值视为误触 */
|
||||
export const NOTICE_MIN_RECORD_MS = 700
|
||||
/** 文字通知最大字数 */
|
||||
export const NOTICE_MAX_TEXT = 200
|
||||
|
||||
/** 普通通知横幅自动关闭时间(毫秒) */
|
||||
export const NOTICE_BANNER_MS = 12000
|
||||
/** 紧急通知横幅自动关闭时间(0 = 不自动关闭,需手动「知道了」) */
|
||||
export const NOTICE_URGENT_BANNER_MS = 0
|
||||
|
||||
/** 接收范围(一期只做全场;后端就绪后扩展分组/指定工作台) */
|
||||
export const NOTICE_TARGET_ALL = 'all'
|
||||
|
||||
/** 本地存储键 */
|
||||
export const NOTICE_STORAGE = {
|
||||
lastId: 'notice_last_id',
|
||||
seenIds: 'notice_seen_ids',
|
||||
mockDb: 'notice_mock_db',
|
||||
}
|
||||
|
||||
/** 优先级 */
|
||||
export const NOTICE_PRIORITY = {
|
||||
normal: 0,
|
||||
urgent: 1,
|
||||
}
|
||||
110
src/core/notice-mock.js
Normal file
110
src/core/notice-mock.js
Normal file
@ -0,0 +1,110 @@
|
||||
/**
|
||||
* 广播消息本地模拟后端(一期用,NOTICE_MOCK = true 生效)
|
||||
*
|
||||
* 用 storage 模拟「服务端消息表 + 长轮询」:
|
||||
* - mockSend 写入一条消息
|
||||
* - mockPoll 在 since_id 之后找新消息,没有就每 200ms 轮询一次,
|
||||
* 直到有新消息(模拟服务端 hold 立即返回)或到达挂起上限
|
||||
*
|
||||
* 限制:一台设备一份 storage,所以只能在同一浏览器(多标签页共享)
|
||||
* 或同一台设备内验证;真实跨设备收发需后端就绪。
|
||||
*/
|
||||
import { NOTICE_STORAGE } from '@/config/notice'
|
||||
|
||||
const MAX_ROWS = 100
|
||||
|
||||
function readDb() {
|
||||
try {
|
||||
const rows = uni.getStorageSync(NOTICE_STORAGE.mockDb)
|
||||
return Array.isArray(rows) ? rows : []
|
||||
} catch (e) {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
function writeDb(rows) {
|
||||
try {
|
||||
uni.setStorageSync(NOTICE_STORAGE.mockDb, rows)
|
||||
} catch (e) {
|
||||
// storage 写入失败不阻断交互
|
||||
}
|
||||
}
|
||||
|
||||
function formatTime(date) {
|
||||
const pad = (n) => (n < 10 ? `0${n}` : String(n))
|
||||
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(
|
||||
date.getHours()
|
||||
)}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
|
||||
}
|
||||
|
||||
function nextId(rows) {
|
||||
const maxId = rows.reduce((max, row) => Math.max(max, Number(row.id) || 0), 0)
|
||||
// 用时间戳做 id,保证与 since_id 单调递增
|
||||
return Math.max(Date.now(), maxId + 1)
|
||||
}
|
||||
|
||||
/** 模拟服务端「发送广播」 */
|
||||
export function mockSend(payload = {}) {
|
||||
const rows = readDb()
|
||||
const msg = {
|
||||
id: nextId(rows),
|
||||
content: payload.content || '',
|
||||
audio_url: payload.audio_url || '',
|
||||
duration: Number(payload.duration || 0),
|
||||
priority: Number(payload.priority || 0) === 1 ? 1 : 0,
|
||||
target_type: payload.target_type || 'all',
|
||||
target_ids: payload.target_ids || [],
|
||||
sender_name: payload.sender_name || '本机',
|
||||
sender_workbench_id: payload.sender_workbench_id || '',
|
||||
created_at: formatTime(new Date()),
|
||||
expire_at: '',
|
||||
}
|
||||
rows.unshift(msg)
|
||||
writeDb(rows.slice(0, MAX_ROWS))
|
||||
console.log('[notice-mock] 已写入消息:', JSON.stringify(msg))
|
||||
return msg
|
||||
}
|
||||
|
||||
/**
|
||||
* 模拟服务端「长轮询」
|
||||
* - 有新消息:立即返回(模拟服务端 hold 到新消息即回)
|
||||
* - 无新消息:每 200ms 检查一次,直到达到挂起上限(mock 上限 5s,避免调试等太久)
|
||||
*/
|
||||
export function mockPoll(sinceId = 0, timeout = 0) {
|
||||
const deadline = Date.now() + Math.min(Number(timeout) || 0, 5000)
|
||||
const from = Number(sinceId) || 0
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const tick = () => {
|
||||
const rows = readDb()
|
||||
const list = rows
|
||||
.filter((row) => Number(row.id) > from)
|
||||
.sort((a, b) => Number(a.id) - Number(b.id))
|
||||
if (list.length) {
|
||||
resolve({ list, last_id: list[list.length - 1].id })
|
||||
return
|
||||
}
|
||||
if (Date.now() >= deadline) {
|
||||
resolve({ list: [], last_id: from })
|
||||
return
|
||||
}
|
||||
setTimeout(tick, 200)
|
||||
}
|
||||
tick()
|
||||
})
|
||||
}
|
||||
|
||||
/** 当前模拟消息表里最大的消息 id(mock 启动时用它跳过历史,避免刷新后重播旧消息) */
|
||||
export function mockLatestId() {
|
||||
const rows = readDb()
|
||||
return rows.reduce((max, row) => Math.max(max, Number(row.id) || 0), 0)
|
||||
}
|
||||
|
||||
/** 清空模拟消息表 */
|
||||
export function mockReset() {
|
||||
try {
|
||||
uni.removeStorageSync(NOTICE_STORAGE.mockDb)
|
||||
} catch (e) {
|
||||
// 忽略
|
||||
}
|
||||
}
|
||||
415
src/core/notice.js
Normal file
415
src/core/notice.js
Normal file
@ -0,0 +1,415 @@
|
||||
/**
|
||||
* 广播消息中心(工作台接收端)
|
||||
*
|
||||
* 职责:
|
||||
* 1) 长轮询拉取广播消息(mock / 真实接口由 config/notice.js 的 NOTICE_MOCK 切换)
|
||||
* 2) 去重 + last_id 游标持久化(断线/熄屏重连后补发,保证不丢消息)
|
||||
* 3) 收到消息 → 通知横幅组件 → 交 voice 播放(原声优先,无音频时 TTS 兜底)
|
||||
* 4) 回报 ack(可选接口,失败静默)
|
||||
*
|
||||
* 生命周期:由页面 onShow 调 start()(幂等),退出登录调 reset()。
|
||||
*/
|
||||
import { ackNotice, pollNotice, sendNotice, uploadNoticeAudio } from '@/api/notice'
|
||||
import {
|
||||
NOTICE_MOCK,
|
||||
NOTICE_MOCK_SELF_PLAY,
|
||||
NOTICE_POLL_RETRY_MS,
|
||||
NOTICE_POLL_TIMEOUT,
|
||||
NOTICE_PRIORITY,
|
||||
NOTICE_STORAGE,
|
||||
NOTICE_TARGET_ALL,
|
||||
} from '@/config/notice'
|
||||
import { getVoice } from './voice'
|
||||
import { mockPoll, mockLatestId, mockReset, mockSend } from './notice-mock'
|
||||
|
||||
let instance = null
|
||||
|
||||
function readStorage(key, fallback) {
|
||||
try {
|
||||
const value = uni.getStorageSync(key)
|
||||
if (value === '' || value === undefined || value === null) {
|
||||
return fallback
|
||||
}
|
||||
return value
|
||||
} catch (e) {
|
||||
return fallback
|
||||
}
|
||||
}
|
||||
|
||||
class NoticeCenter {
|
||||
constructor() {
|
||||
this.started = false
|
||||
this.polling = false
|
||||
this.timer = null
|
||||
this.lastId = 0
|
||||
this.seenIds = []
|
||||
this.banner = null
|
||||
this.listeners = []
|
||||
this.pollFailCount = 0
|
||||
// 本机身份(用于「自己发的不播」与 ack 上报)
|
||||
this.self = {
|
||||
workbenchId: '',
|
||||
userName: '',
|
||||
}
|
||||
}
|
||||
|
||||
get isMock() {
|
||||
return NOTICE_MOCK
|
||||
}
|
||||
|
||||
/** 记录本机身份(workbench_id 用于区分自己发的消息) */
|
||||
setSelf(info = {}) {
|
||||
if (info.workbenchId !== undefined) {
|
||||
this.self.workbenchId = String(info.workbenchId || '')
|
||||
}
|
||||
if (info.userName !== undefined && info.userName) {
|
||||
this.self.userName = String(info.userName)
|
||||
}
|
||||
}
|
||||
|
||||
/** 开始接收(幂等;未登录时直接跳过) */
|
||||
start() {
|
||||
if (this.started) {
|
||||
return
|
||||
}
|
||||
let token = ''
|
||||
try {
|
||||
token = String(uni.getStorageSync('token') || '')
|
||||
} catch (e) {
|
||||
token = ''
|
||||
}
|
||||
if (!token) {
|
||||
console.log('[notice] 未登录,跳过广播接收')
|
||||
return
|
||||
}
|
||||
if (!this.self.workbenchId) {
|
||||
this.self.workbenchId = String(readStorage('workbench_id', ''))
|
||||
}
|
||||
this.started = true
|
||||
this.pollFailCount = 0
|
||||
if (NOTICE_MOCK) {
|
||||
// mock:游标只放内存(同一浏览器多标签页可模拟多台工作台,互不抢游标)
|
||||
// 启动时跳过历史消息,避免每次刷新把旧广播重播一遍
|
||||
this.lastId = mockLatestId()
|
||||
this.seenIds = []
|
||||
} else {
|
||||
this.lastId = Number(readStorage(NOTICE_STORAGE.lastId, 0)) || 0
|
||||
const seen = readStorage(NOTICE_STORAGE.seenIds, [])
|
||||
this.seenIds = Array.isArray(seen) ? seen.slice(-200) : []
|
||||
}
|
||||
console.log('[notice] 开始接收广播 lastId =', this.lastId, 'mock =', NOTICE_MOCK)
|
||||
this.schedulePoll(0)
|
||||
}
|
||||
|
||||
/** 回到前台时催一下:立即重新发起一次拉取(已 started 时幂等,不新建循环) */
|
||||
kick() {
|
||||
if (!this.started) {
|
||||
return
|
||||
}
|
||||
this.schedulePoll(0)
|
||||
}
|
||||
|
||||
/** 停止接收(页面销毁/退出登录) */
|
||||
stop(reason = '') {
|
||||
if (!this.started && !this.timer) {
|
||||
return
|
||||
}
|
||||
this.started = false
|
||||
if (this.timer) {
|
||||
clearTimeout(this.timer)
|
||||
this.timer = null
|
||||
}
|
||||
console.log('[notice] 停止接收广播', reason)
|
||||
}
|
||||
|
||||
/** 退出登录:停止 + 清游标 + 清模拟消息(避免换账号后补发上一个人的消息) */
|
||||
reset() {
|
||||
this.stop('reset')
|
||||
this.lastId = 0
|
||||
this.seenIds = []
|
||||
this.pollFailCount = 0
|
||||
try {
|
||||
uni.removeStorageSync(NOTICE_STORAGE.lastId)
|
||||
uni.removeStorageSync(NOTICE_STORAGE.seenIds)
|
||||
} catch (e) {
|
||||
// 忽略
|
||||
}
|
||||
if (NOTICE_MOCK) {
|
||||
mockReset()
|
||||
}
|
||||
this.notifyBanner(null)
|
||||
}
|
||||
|
||||
/** 横幅订阅:回调会立刻收到当前消息(可能是 null),返回取消订阅函数 */
|
||||
onBanner(handler) {
|
||||
if (typeof handler !== 'function') {
|
||||
return () => {}
|
||||
}
|
||||
this.listeners.push(handler)
|
||||
handler(this.banner)
|
||||
return () => {
|
||||
this.listeners = this.listeners.filter((fn) => fn !== handler)
|
||||
}
|
||||
}
|
||||
|
||||
notifyBanner(banner) {
|
||||
this.banner = banner
|
||||
this.listeners.forEach((fn) => {
|
||||
try {
|
||||
fn(banner)
|
||||
} catch (e) {
|
||||
console.error('[notice] 横幅回调异常:', e)
|
||||
}
|
||||
})
|
||||
if (typeof uni.$emit === 'function') {
|
||||
uni.$emit('notice:banner', banner)
|
||||
}
|
||||
}
|
||||
|
||||
/** 手动关闭横幅 */
|
||||
dismiss() {
|
||||
this.notifyBanner(null)
|
||||
}
|
||||
|
||||
/** 重播当前横幅(不插队、不打断其它播报) */
|
||||
replay() {
|
||||
if (this.banner) {
|
||||
this.playMessage(this.banner)
|
||||
}
|
||||
}
|
||||
|
||||
schedulePoll(delay = 0) {
|
||||
if (!this.started) {
|
||||
return
|
||||
}
|
||||
if (this.timer) {
|
||||
clearTimeout(this.timer)
|
||||
}
|
||||
this.timer = setTimeout(() => {
|
||||
this.timer = null
|
||||
this.pollOnce()
|
||||
}, delay)
|
||||
}
|
||||
|
||||
async pollOnce() {
|
||||
if (!this.started || this.polling) {
|
||||
return
|
||||
}
|
||||
this.polling = true
|
||||
try {
|
||||
const result = await this.fetchList(this.lastId)
|
||||
if (!this.started) {
|
||||
return
|
||||
}
|
||||
const list = result && Array.isArray(result.list) ? result.list : []
|
||||
list.forEach((item) => this.handleMessage(item))
|
||||
this.pollFailCount = 0
|
||||
this.schedulePoll(0)
|
||||
} catch (err) {
|
||||
this.pollFailCount = Math.min(this.pollFailCount + 1, 5)
|
||||
const delay = Math.min(NOTICE_POLL_RETRY_MS * this.pollFailCount, 15000)
|
||||
console.log('[notice] 拉取广播失败:', (err && (err.message || err.errMsg)) || err, '→', delay, 'ms 后重试')
|
||||
this.schedulePoll(delay)
|
||||
} finally {
|
||||
this.polling = false
|
||||
}
|
||||
}
|
||||
|
||||
async fetchList(sinceId) {
|
||||
if (NOTICE_MOCK) {
|
||||
return mockPoll(sinceId, NOTICE_POLL_TIMEOUT)
|
||||
}
|
||||
const body = await pollNotice(
|
||||
{
|
||||
since_id: sinceId,
|
||||
workbench_id: this.self.workbenchId || undefined,
|
||||
timeout: Math.round(NOTICE_POLL_TIMEOUT / 1000),
|
||||
},
|
||||
NOTICE_POLL_TIMEOUT + 5000
|
||||
)
|
||||
const data = (body && (body.data || body.result)) || body || {}
|
||||
const list = Array.isArray(data.list) ? data.list : Array.isArray(data) ? data : []
|
||||
return { list, last_id: Number(data.last_id || data.lastId || 0) || 0 }
|
||||
}
|
||||
|
||||
normalizeMessage(raw) {
|
||||
if (!raw || typeof raw !== 'object') {
|
||||
return null
|
||||
}
|
||||
const id = Number(raw.id || raw.msg_id || raw.seq || 0)
|
||||
if (!id) {
|
||||
return null
|
||||
}
|
||||
const msg = {
|
||||
id,
|
||||
content: String(raw.content || raw.text || '').trim(),
|
||||
audioUrl: String(raw.audio_url || raw.audioUrl || ''),
|
||||
duration: Number(raw.duration || 0) || 0,
|
||||
priority: Number(raw.priority || 0) === NOTICE_PRIORITY.urgent ? NOTICE_PRIORITY.urgent : NOTICE_PRIORITY.normal,
|
||||
senderName: String(raw.sender_name || raw.senderName || ''),
|
||||
senderWorkbenchId: String(raw.sender_workbench_id != null ? raw.sender_workbench_id : raw.workbench_id || ''),
|
||||
createdAt: String(raw.created_at || raw.createdAt || ''),
|
||||
expireAt: String(raw.expire_at || raw.expireAt || ''),
|
||||
self: false,
|
||||
}
|
||||
msg.self = this.isSelfMessage(msg)
|
||||
return msg
|
||||
}
|
||||
|
||||
isSelfMessage(msg) {
|
||||
if (!this.self.workbenchId || !msg.senderWorkbenchId) {
|
||||
return false
|
||||
}
|
||||
return String(msg.senderWorkbenchId) === String(this.self.workbenchId)
|
||||
}
|
||||
|
||||
isExpired(msg) {
|
||||
if (!msg.expireAt) {
|
||||
return false
|
||||
}
|
||||
// iOS/部分 WebView 对 'YYYY-MM-DD HH:mm:ss' 解析不稳定,统一替换成 '/'
|
||||
const time = Date.parse(msg.expireAt.replace(/-/g, '/'))
|
||||
if (!time) {
|
||||
return false
|
||||
}
|
||||
return time < Date.now()
|
||||
}
|
||||
|
||||
handleMessage(raw) {
|
||||
const msg = this.normalizeMessage(raw)
|
||||
if (!msg) {
|
||||
return
|
||||
}
|
||||
if (this.seenIds.indexOf(msg.id) >= 0) {
|
||||
return
|
||||
}
|
||||
this.seenIds.push(msg.id)
|
||||
if (this.seenIds.length > 200) {
|
||||
this.seenIds = this.seenIds.slice(-200)
|
||||
}
|
||||
if (msg.id > this.lastId) {
|
||||
this.lastId = msg.id
|
||||
}
|
||||
this.persistCursor()
|
||||
|
||||
if (this.isExpired(msg)) {
|
||||
console.log('[notice] 消息已过期,跳过播报:', msg.id)
|
||||
return
|
||||
}
|
||||
|
||||
console.log('[notice] 收到广播:', JSON.stringify(msg))
|
||||
this.notifyBanner(msg)
|
||||
if (this.shouldPlay(msg)) {
|
||||
this.playMessage(msg)
|
||||
}
|
||||
this.ack([msg.id])
|
||||
}
|
||||
|
||||
shouldPlay(msg) {
|
||||
if (!msg.self) {
|
||||
return true
|
||||
}
|
||||
// 自己发的:mock 下可配置为也播一遍(单机调试),真实后端应为 false
|
||||
return NOTICE_MOCK ? NOTICE_MOCK_SELF_PLAY : false
|
||||
}
|
||||
|
||||
playMessage(msg) {
|
||||
const voice = getVoice()
|
||||
const urgent = msg.priority === NOTICE_PRIORITY.urgent
|
||||
if (msg.audioUrl) {
|
||||
if (urgent) {
|
||||
voice.playAudioUrgent(msg.audioUrl)
|
||||
} else {
|
||||
voice.playAudio(msg.audioUrl)
|
||||
}
|
||||
return
|
||||
}
|
||||
if (msg.content) {
|
||||
if (urgent) {
|
||||
voice.playUrgent(msg.content)
|
||||
} else {
|
||||
voice.play(msg.content)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
persistCursor() {
|
||||
// mock 模式游标不落盘(见 start 注释),只有真实接口才需要断线补发游标
|
||||
if (NOTICE_MOCK) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
uni.setStorageSync(NOTICE_STORAGE.lastId, this.lastId)
|
||||
uni.setStorageSync(NOTICE_STORAGE.seenIds, this.seenIds)
|
||||
} catch (e) {
|
||||
// 忽略
|
||||
}
|
||||
}
|
||||
|
||||
ack(ids) {
|
||||
if (NOTICE_MOCK || !Array.isArray(ids) || !ids.length) {
|
||||
return
|
||||
}
|
||||
ackNotice({
|
||||
ids,
|
||||
workbench_id: this.self.workbenchId || undefined,
|
||||
}).catch(() => {
|
||||
// 必达统计接口失败不影响播报
|
||||
})
|
||||
}
|
||||
|
||||
/** 上传录音:mock 下直接返回本地路径(同机可播) */
|
||||
async uploadAudio(localPath, duration = 0) {
|
||||
if (!localPath) {
|
||||
throw new Error('没有录音文件')
|
||||
}
|
||||
if (NOTICE_MOCK) {
|
||||
return localPath
|
||||
}
|
||||
const res = await uploadNoticeAudio({
|
||||
filePath: localPath,
|
||||
duration,
|
||||
workbenchId: this.self.workbenchId,
|
||||
})
|
||||
return res.url
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送广播
|
||||
* @param {{content?: string, audioUrl?: string, duration?: number, priority?: number, targetType?: string, targetIds?: (string|number)[]}} payload
|
||||
*/
|
||||
async send(payload = {}) {
|
||||
const data = {
|
||||
content: String(payload.content || '').trim(),
|
||||
audio_url: payload.audioUrl || '',
|
||||
duration: Number(payload.duration || 0) || 0,
|
||||
priority: Number(payload.priority || 0) === NOTICE_PRIORITY.urgent ? NOTICE_PRIORITY.urgent : NOTICE_PRIORITY.normal,
|
||||
target_type: payload.targetType || NOTICE_TARGET_ALL,
|
||||
target_ids: Array.isArray(payload.targetIds) ? payload.targetIds : [],
|
||||
sender_name: this.self.userName || '',
|
||||
sender_workbench_id: this.self.workbenchId || '',
|
||||
}
|
||||
if (!data.content && !data.audio_url) {
|
||||
throw new Error('通知内容不能为空')
|
||||
}
|
||||
if (NOTICE_MOCK) {
|
||||
return mockSend(data)
|
||||
}
|
||||
const body = await sendNotice(data)
|
||||
const result = (body && (body.data || body.result)) || body || {}
|
||||
if (body && (body.flag === 'failure' || Number(body.code) === 500)) {
|
||||
throw new Error(body.message || body.msg || '发送失败')
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
/** 获取广播消息中心单例 */
|
||||
export function getNoticeCenter() {
|
||||
if (!instance) {
|
||||
instance = new NoticeCenter()
|
||||
}
|
||||
return instance
|
||||
}
|
||||
|
||||
export default NoticeCenter
|
||||
301
src/core/recorder.js
Normal file
301
src/core/recorder.js
Normal file
@ -0,0 +1,301 @@
|
||||
/**
|
||||
* 录音封装(语音广播「原声录制」用)
|
||||
*
|
||||
* - APP-PLUS:uni.getRecorderManager(aac / 16kHz / 单声道),需 RECORD_AUDIO 权限
|
||||
* - H5 / Electron:MediaRecorder(webm/opus),走浏览器麦克风权限
|
||||
*
|
||||
* 说明:App 端用 aac 而不是 mp3 —— Android MediaRecorder 不支持直接输出 mp3,
|
||||
* aac(m4a) 各端 innerAudioContext 都能播放。
|
||||
*/
|
||||
import { NOTICE_MAX_RECORD_MS, NOTICE_MIN_RECORD_MS } from '@/config/notice'
|
||||
|
||||
function isAppPlus() {
|
||||
// #ifdef APP-PLUS
|
||||
return true
|
||||
// #endif
|
||||
// #ifndef APP-PLUS
|
||||
return false
|
||||
// #endif
|
||||
}
|
||||
|
||||
let appRecorder = null
|
||||
|
||||
function getAppRecorder() {
|
||||
if (!appRecorder) {
|
||||
appRecorder = uni.getRecorderManager()
|
||||
}
|
||||
return appRecorder
|
||||
}
|
||||
|
||||
/** 当前环境是否支持录音 */
|
||||
export function isRecorderSupported() {
|
||||
if (isAppPlus()) {
|
||||
return true
|
||||
}
|
||||
return (
|
||||
typeof navigator !== 'undefined' &&
|
||||
!!navigator.mediaDevices &&
|
||||
typeof navigator.mediaDevices.getUserMedia === 'function' &&
|
||||
typeof window !== 'undefined' &&
|
||||
typeof window.MediaRecorder === 'function'
|
||||
)
|
||||
}
|
||||
|
||||
/** 申请麦克风权限(App 端为运行时权限;H5 由 getUserMedia 触发) */
|
||||
export function requestRecordPermission() {
|
||||
if (!isAppPlus()) {
|
||||
return Promise.resolve(true)
|
||||
}
|
||||
return new Promise((resolve, reject) => {
|
||||
try {
|
||||
plus.android.requestPermissions(
|
||||
['android.permission.RECORD_AUDIO'],
|
||||
(result) => {
|
||||
const granted = (result && result.granted) || []
|
||||
if (granted.length > 0) {
|
||||
resolve(true)
|
||||
return
|
||||
}
|
||||
reject(new Error('未获得麦克风权限,请在系统设置中开启'))
|
||||
},
|
||||
(error) => {
|
||||
reject(new Error((error && (error.message || error.errMsg)) || '麦克风权限申请失败'))
|
||||
}
|
||||
)
|
||||
} catch (e) {
|
||||
reject(e instanceof Error ? e : new Error('麦克风权限申请异常'))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 录音器:start() 开始 / stop() 结束并拿到文件 / cancel() 丢弃
|
||||
* stop() 的结果:{ filePath, duration(秒), size, mime, blob?(H5) }
|
||||
*/
|
||||
export class VoiceRecorder {
|
||||
constructor(options = {}) {
|
||||
this.maxDuration = Number(options.maxDuration || NOTICE_MAX_RECORD_MS)
|
||||
this.minDuration = Number(options.minDuration || NOTICE_MIN_RECORD_MS)
|
||||
this.recording = false
|
||||
this.startedAt = 0
|
||||
this._settleStop = null
|
||||
this._stopTimer = null
|
||||
// H5
|
||||
this._mediaRecorder = null
|
||||
this._stream = null
|
||||
this._chunks = []
|
||||
this._blobUrl = ''
|
||||
}
|
||||
|
||||
/** 当前已录时长(秒) */
|
||||
get elapsed() {
|
||||
return this.recording ? (Date.now() - this.startedAt) / 1000 : 0
|
||||
}
|
||||
|
||||
async start() {
|
||||
if (this.recording) {
|
||||
return true
|
||||
}
|
||||
await requestRecordPermission()
|
||||
if (isAppPlus()) {
|
||||
this.startApp()
|
||||
} else {
|
||||
await this.startWeb()
|
||||
}
|
||||
this.recording = true
|
||||
this.startedAt = Date.now()
|
||||
console.log('[recorder] 开始录音')
|
||||
return true
|
||||
}
|
||||
|
||||
startApp() {
|
||||
const rm = getAppRecorder()
|
||||
try {
|
||||
// 清理上一次的回调,避免多次录音后 onStop 被重复触发
|
||||
if (typeof rm.offStart === 'function') rm.offStart()
|
||||
if (typeof rm.offStop === 'function') rm.offStop()
|
||||
if (typeof rm.offError === 'function') rm.offError()
|
||||
} catch (e) {
|
||||
// 忽略
|
||||
}
|
||||
rm.onStart(() => {
|
||||
console.log('[recorder] recorder onStart')
|
||||
})
|
||||
rm.onStop((res) => {
|
||||
const duration = Number(res && res.duration) || (Date.now() - this.startedAt) / 1000
|
||||
const payload = {
|
||||
filePath: res && res.tempFilePath,
|
||||
duration,
|
||||
size: Number((res && res.fileSize) || 0),
|
||||
mime: 'audio/aac',
|
||||
}
|
||||
console.log('[recorder] 录音结束:', JSON.stringify({ duration, size: payload.size, hasPath: !!payload.filePath }))
|
||||
this.settleStop(payload, null)
|
||||
})
|
||||
rm.onError((err) => {
|
||||
console.log('[recorder] 录音失败:', err)
|
||||
this.settleStop(null, new Error((err && (err.errMsg || err.message)) || '录音失败'))
|
||||
})
|
||||
rm.start({
|
||||
duration: this.maxDuration,
|
||||
sampleRate: 16000,
|
||||
numberOfChannels: 1,
|
||||
encodeBitRate: 48000,
|
||||
format: 'aac',
|
||||
})
|
||||
}
|
||||
|
||||
async startWeb() {
|
||||
const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
|
||||
const supported =
|
||||
typeof window.MediaRecorder.isTypeSupported === 'function' &&
|
||||
window.MediaRecorder.isTypeSupported('audio/webm;codecs=opus')
|
||||
const mediaRecorder = supported
|
||||
? new window.MediaRecorder(stream, { mimeType: 'audio/webm;codecs=opus' })
|
||||
: new window.MediaRecorder(stream)
|
||||
this._chunks = []
|
||||
mediaRecorder.ondataavailable = (e) => {
|
||||
if (e.data && e.data.size) {
|
||||
this._chunks.push(e.data)
|
||||
}
|
||||
}
|
||||
mediaRecorder.start()
|
||||
this._mediaRecorder = mediaRecorder
|
||||
this._stream = stream
|
||||
}
|
||||
|
||||
/** 结束录音并返回文件信息 */
|
||||
stop() {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!this.recording) {
|
||||
reject(new Error('当前没有在录音'))
|
||||
return
|
||||
}
|
||||
const seconds = (Date.now() - this.startedAt) / 1000
|
||||
this._settleStop = (payload, error) => {
|
||||
this._settleStop = null
|
||||
if (this._stopTimer) {
|
||||
clearTimeout(this._stopTimer)
|
||||
this._stopTimer = null
|
||||
}
|
||||
if (error) {
|
||||
reject(error)
|
||||
} else {
|
||||
resolve(payload)
|
||||
}
|
||||
}
|
||||
this.recording = false
|
||||
|
||||
// 时间太短视为误触,直接丢弃
|
||||
if (seconds * 1000 < this.minDuration) {
|
||||
this.cancel()
|
||||
reject(new Error('录音时间太短'))
|
||||
return
|
||||
}
|
||||
|
||||
if (isAppPlus()) {
|
||||
try {
|
||||
getAppRecorder().stop()
|
||||
} catch (e) {
|
||||
this.settleStop(null, e)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
this.stopWeb()
|
||||
}
|
||||
|
||||
// 兜底:部分机型 onStop 不回调,避免界面一直卡在「录音中」
|
||||
this._stopTimer = setTimeout(() => {
|
||||
this.settleStop(null, new Error('录音结束回调超时'))
|
||||
}, 8000)
|
||||
})
|
||||
}
|
||||
|
||||
stopWeb() {
|
||||
const mediaRecorder = this._mediaRecorder
|
||||
if (!mediaRecorder) {
|
||||
this.settleStop(null, new Error('录音器未就绪'))
|
||||
return
|
||||
}
|
||||
mediaRecorder.onstop = () => {
|
||||
this.releaseStream()
|
||||
const blob = new Blob(this._chunks, { type: mediaRecorder.mimeType || 'audio/webm' })
|
||||
this._chunks = []
|
||||
if (this._blobUrl) {
|
||||
try {
|
||||
URL.revokeObjectURL(this._blobUrl)
|
||||
} catch (e) {
|
||||
// 忽略
|
||||
}
|
||||
}
|
||||
const url = URL.createObjectURL(blob)
|
||||
this._blobUrl = url
|
||||
const duration = (Date.now() - this.startedAt) / 1000
|
||||
this.settleStop({ filePath: url, duration, size: blob.size, mime: blob.type, blob }, null)
|
||||
}
|
||||
try {
|
||||
mediaRecorder.stop()
|
||||
} catch (e) {
|
||||
this.settleStop(null, e)
|
||||
}
|
||||
}
|
||||
|
||||
/** 放弃本次录音(不发、不保存) */
|
||||
cancel() {
|
||||
this.recording = false
|
||||
if (this._stopTimer) {
|
||||
clearTimeout(this._stopTimer)
|
||||
this._stopTimer = null
|
||||
}
|
||||
this._settleStop = null
|
||||
if (isAppPlus()) {
|
||||
try {
|
||||
getAppRecorder().stop()
|
||||
} catch (e) {
|
||||
// 忽略
|
||||
}
|
||||
return
|
||||
}
|
||||
try {
|
||||
if (this._mediaRecorder && this._mediaRecorder.state !== 'inactive') {
|
||||
this._mediaRecorder.stop()
|
||||
}
|
||||
} catch (e) {
|
||||
// 忽略
|
||||
}
|
||||
this.releaseStream()
|
||||
}
|
||||
|
||||
settleStop(payload, error) {
|
||||
this.recording = false
|
||||
if (this._settleStop) {
|
||||
this._settleStop(payload, error)
|
||||
}
|
||||
}
|
||||
|
||||
releaseStream() {
|
||||
try {
|
||||
if (this._stream && typeof this._stream.getTracks === 'function') {
|
||||
this._stream.getTracks().forEach((track) => track.stop())
|
||||
}
|
||||
} catch (e) {
|
||||
// 忽略
|
||||
}
|
||||
this._stream = null
|
||||
}
|
||||
|
||||
/** 组件销毁时调用 */
|
||||
destroy() {
|
||||
this.cancel()
|
||||
if (this._blobUrl) {
|
||||
try {
|
||||
URL.revokeObjectURL(this._blobUrl)
|
||||
} catch (e) {
|
||||
// 忽略
|
||||
}
|
||||
this._blobUrl = ''
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default VoiceRecorder
|
||||
@ -12,9 +12,13 @@ class Voice {
|
||||
// 每次播放都会重建音频实例,这里仅占位
|
||||
this.audio = null
|
||||
// 播报队列:FIFO 串行播放,避免连续提示(称重成功/所有订单复核完成等)互相打断交叉播报
|
||||
// 队列元素:{ kind: 'tts', text } 文本播报 / { kind: 'audio', url } 原声播报
|
||||
this.queue = []
|
||||
this.playing = false
|
||||
this.finishTimer = null
|
||||
// 打断计数:interrupt() 自增。旧音频的异步回调(请求返回/onCanplay/兜底定时器)
|
||||
// 携带旧 token,比对不一致直接丢弃,避免打断后旧回调把新队列又推进一格
|
||||
this.token = 0
|
||||
}
|
||||
|
||||
/** 仅播放语音(不弹 toast,避免与全局 showToast 拦截器互相递归);多条按 FIFO 串行 */
|
||||
@ -22,20 +26,110 @@ class Voice {
|
||||
if (!msg) {
|
||||
return
|
||||
}
|
||||
this.queue.push(String(msg))
|
||||
this.enqueue({ kind: 'tts', text: String(msg) })
|
||||
}
|
||||
|
||||
/** 播放原声音频(语音广播):本地路径直接播,http(s) 先下载到本地再播 */
|
||||
playAudio(url) {
|
||||
if (!url) {
|
||||
return
|
||||
}
|
||||
this.enqueue({ kind: 'audio', url: String(url) })
|
||||
}
|
||||
|
||||
/** 紧急插播(文本):插到队首并打断当前播放 */
|
||||
playUrgent(msg) {
|
||||
if (!msg) {
|
||||
return
|
||||
}
|
||||
this.enqueue({ kind: 'tts', text: String(msg) }, true)
|
||||
}
|
||||
|
||||
/** 紧急插播(原声):插到队首并打断当前播放 */
|
||||
playAudioUrgent(url) {
|
||||
if (!url) {
|
||||
return
|
||||
}
|
||||
this.enqueue({ kind: 'audio', url: String(url) }, true)
|
||||
}
|
||||
|
||||
/** 入队;urgent=true 时插队首并打断当前播放 */
|
||||
enqueue(item, urgent = false) {
|
||||
if (urgent) {
|
||||
this.queue.unshift(item)
|
||||
this.interrupt()
|
||||
} else {
|
||||
this.queue.push(item)
|
||||
}
|
||||
this.scheduleNext()
|
||||
}
|
||||
|
||||
/** 打断当前播放(不影响队列里其它条目,由 scheduleNext 继续取) */
|
||||
interrupt() {
|
||||
this.token++
|
||||
if (this.finishTimer) {
|
||||
clearTimeout(this.finishTimer)
|
||||
this.finishTimer = null
|
||||
}
|
||||
if (this.audio) {
|
||||
try {
|
||||
this.audio.stop()
|
||||
this.audio.destroy()
|
||||
} catch (e) {
|
||||
// 忽略旧实例释放异常
|
||||
}
|
||||
this.audio = null
|
||||
}
|
||||
this.playing = false
|
||||
}
|
||||
|
||||
/** 清空队列并停止播放(录音前调用,避免把播报声录进麦克风) */
|
||||
clear() {
|
||||
this.queue = []
|
||||
this.interrupt()
|
||||
}
|
||||
|
||||
/** 从队列取一条播放;正在播放时直接返回,播完再取下一条 */
|
||||
scheduleNext() {
|
||||
if (this.playing) {
|
||||
return
|
||||
}
|
||||
const text = this.queue.shift()
|
||||
if (!text) {
|
||||
const item = this.queue.shift()
|
||||
if (!item) {
|
||||
return
|
||||
}
|
||||
this.playing = true
|
||||
const token = this.token
|
||||
// 播完/失败统一走 done:期间被 interrupt() 打断(token 变化)则丢弃,
|
||||
// 避免旧音频的回调把新队列提前推进
|
||||
const done = () => {
|
||||
if (token !== this.token) {
|
||||
return
|
||||
}
|
||||
this.onPlayFinish()
|
||||
}
|
||||
|
||||
// 原声播放:本地文件直接播,远程地址先下载(复用 TTS 的下载+播放链路)
|
||||
if (item.kind === 'audio') {
|
||||
if (!item.url) {
|
||||
done()
|
||||
return
|
||||
}
|
||||
if (/^https?:/i.test(item.url)) {
|
||||
this.downloadVoiceAudio(item.url)
|
||||
.then((localSrc) => this.playVoiceAudio(localSrc, done))
|
||||
.catch(() => this.playVoiceAudio(item.url, done))
|
||||
} else {
|
||||
this.playVoiceAudio(item.url, done)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
const text = String(item.text || '')
|
||||
if (!text) {
|
||||
done()
|
||||
return
|
||||
}
|
||||
// 末字补句号(两个以加长停顿)+ 下载到本地再播:与打包页 speakViaHttp 行为一致,
|
||||
// 避免部分 Android 设备播放远程 MP3 时解码丢尾帧导致末字截断
|
||||
const ttsText = text + '。。'
|
||||
@ -45,18 +139,21 @@ class Voice {
|
||||
timeout: 3000,
|
||||
header: { 'content-type': 'text/xml; charset=utf-8' },
|
||||
success: (res) => {
|
||||
if (token !== this.token) {
|
||||
return
|
||||
}
|
||||
if (!res || !res.data || !res.data.audio) {
|
||||
this.onPlayFinish()
|
||||
done()
|
||||
return
|
||||
}
|
||||
const src = VOICE_BASE + res.data.audio
|
||||
this.downloadVoiceAudio(src)
|
||||
.then((localSrc) => this.playVoiceAudio(localSrc, () => this.onPlayFinish()))
|
||||
.catch(() => this.playVoiceAudio(src, () => this.onPlayFinish()))
|
||||
.then((localSrc) => this.playVoiceAudio(localSrc, done))
|
||||
.catch(() => this.playVoiceAudio(src, done))
|
||||
},
|
||||
fail: (err) => {
|
||||
console.log('[voice] request fail:', err)
|
||||
this.onPlayFinish()
|
||||
done()
|
||||
},
|
||||
})
|
||||
}
|
||||
@ -144,7 +241,7 @@ class Voice {
|
||||
if (this.finishTimer) {
|
||||
clearTimeout(this.finishTimer)
|
||||
}
|
||||
this.finishTimer = setTimeout(() => this.onPlayFinish(), Math.min(15000, audio.duration * 1000 + 3000))
|
||||
this.finishTimer = setTimeout(finish, Math.min(15000, audio.duration * 1000 + 3000))
|
||||
}
|
||||
doPlay()
|
||||
})
|
||||
|
||||
@ -33,6 +33,7 @@
|
||||
"<uses-feature android:name=\"android.hardware.camera.autofocus\"/>",
|
||||
"<uses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\"/>",
|
||||
"<uses-permission android:name=\"android.permission.CAMERA\"/>",
|
||||
"<uses-permission android:name=\"android.permission.RECORD_AUDIO\"/>",
|
||||
"<uses-permission android:name=\"android.permission.GET_ACCOUNTS\"/>",
|
||||
"<uses-permission android:name=\"android.permission.READ_PHONE_STATE\"/>",
|
||||
"<uses-permission android:name=\"android.permission.CHANGE_WIFI_STATE\"/>",
|
||||
|
||||
@ -10,6 +10,9 @@
|
||||
@user-changed="handleUserChanged"
|
||||
/>
|
||||
|
||||
<!-- 广播横幅:挂在布局壳上,切菜单不会丢;打包模式页另有一份(两条登录路径) -->
|
||||
<notice-banner />
|
||||
|
||||
<view class="layout-main">
|
||||
<!-- keep-alive 仅 H5/Electron 支持(App 端不支持,缓存子组件视图不会被隐藏,
|
||||
导致切换导航后多个页面内容叠在一起);App 端退化为普通动态组件,一次只渲染一个 -->
|
||||
@ -26,17 +29,25 @@
|
||||
<text v-if="activeMenuPath" class="module-placeholder-desc">该菜单页面尚未配置({{ activeMenuPath }})</text>
|
||||
</view>
|
||||
</view>
|
||||
|
||||
<!-- 广播发送弹窗(顶栏「广播」按钮通过 uni.$emit('notice:open-send') 打开) -->
|
||||
<notice-send-dialog v-model:visible="noticeSendVisible" />
|
||||
</view>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import { fetchUserInfo } from '@/api/index'
|
||||
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 { hasMenuView, normalizeMenuPath, resolveMenuView } from '@/router/menuRoutes'
|
||||
|
||||
export default {
|
||||
components: {
|
||||
TopNav,
|
||||
NoticeBanner,
|
||||
NoticeSendDialog,
|
||||
},
|
||||
onReady() {
|
||||
uni.hideKeyboard?.()
|
||||
@ -57,6 +68,11 @@ export default {
|
||||
uni.hideKeyboard?.()
|
||||
}, delay)
|
||||
})
|
||||
// 启动广播接收(幂等;从后台回来时也会在这里补拉未收到的消息)
|
||||
this.initNoticeCenter()
|
||||
},
|
||||
onUnload() {
|
||||
this.teardownNoticeCenter()
|
||||
},
|
||||
onLoad(options) {
|
||||
// reLaunch 重建 WebView 后立即锁定横屏+全屏:登录进入布局壳(订单复核页)时
|
||||
@ -86,6 +102,7 @@ export default {
|
||||
return {
|
||||
currentUser: null,
|
||||
activeMenuPath: '',
|
||||
noticeSendVisible: false,
|
||||
}
|
||||
},
|
||||
computed: {
|
||||
@ -113,6 +130,38 @@ export default {
|
||||
},
|
||||
},
|
||||
methods: {
|
||||
/** 启动广播接收(单例幂等)+ 监听顶栏「广播」按钮 */
|
||||
initNoticeCenter() {
|
||||
const center = getNoticeCenter()
|
||||
center.setSelf({
|
||||
workbenchId: uni.getStorageSync('workbench_id'),
|
||||
userName: this.getSelfDisplayName(),
|
||||
})
|
||||
center.start()
|
||||
center.kick()
|
||||
if (!this._noticeOpenHandler) {
|
||||
this._noticeOpenHandler = () => {
|
||||
this.noticeSendVisible = true
|
||||
}
|
||||
uni.$on('notice:open-send', this._noticeOpenHandler)
|
||||
}
|
||||
},
|
||||
teardownNoticeCenter() {
|
||||
if (this._noticeOpenHandler) {
|
||||
uni.$off('notice:open-send', this._noticeOpenHandler)
|
||||
this._noticeOpenHandler = null
|
||||
}
|
||||
},
|
||||
/** 本机显示名:广播横幅/消息里的发送人 */
|
||||
getSelfDisplayName() {
|
||||
const user = this.currentUser
|
||||
if (!user) {
|
||||
return '工作台'
|
||||
}
|
||||
const employee =
|
||||
Array.isArray(user.employees) && user.employees.length ? user.employees[0] : null
|
||||
return user.real_name || (employee && employee.real_name) || user.username || '工作台'
|
||||
},
|
||||
// 强制锁定横屏:真机 reLaunch 后横屏锁可能丢失,这里只做 lockOrientation 兜底。
|
||||
// setStyle 已禁用:reLaunch/热恢复时 WebView 视图未就绪,setStyle 触发原生层
|
||||
// ViewOptions.updateViewData NPE 导致白屏(打包页实验对照验证);横屏尺寸由
|
||||
@ -230,6 +279,8 @@ export default {
|
||||
.then((body) => {
|
||||
const user = body?.data || body?.result || body || null
|
||||
this.currentUser = user
|
||||
// 同步广播发送人名称
|
||||
getNoticeCenter().setSelf({ userName: this.getSelfDisplayName() })
|
||||
// 持久化用户上下文 store_id / warehouse_id(面单补打团单模式按接口约定 warehouse_id 须与 store_id 一致)
|
||||
this.persistUserContext(user)
|
||||
this.ensureActiveMenuValid()
|
||||
|
||||
@ -10,6 +10,9 @@
|
||||
</view>
|
||||
</view>
|
||||
<view class="topbar-actions">
|
||||
<view class="pack-broadcast-btn" @click="handleBroadcastOpen">
|
||||
<text class="pack-broadcast-btn-text">广播</text>
|
||||
</view>
|
||||
<button
|
||||
class="operator-btn"
|
||||
:class="workbenchMembers.length > 0 ? 'operator-btn--bound' : ''"
|
||||
@ -23,6 +26,8 @@
|
||||
</button>
|
||||
</view>
|
||||
</view>
|
||||
<!-- 广播横幅:与布局壳各挂一份(工作台绑定登录进的是本页,不走 pages/index) -->
|
||||
<notice-banner compact />
|
||||
<view class="mode-main">
|
||||
<view v-if="infoLoading" class="mode-card mode-card--center">
|
||||
<text class="mode-card-desc">正在获取工作台信息...</text>
|
||||
@ -353,6 +358,9 @@
|
||||
|
||||
<!-- 扫码诊断面板(隐藏入口:3 秒内连点标题 5 次) -->
|
||||
<scan-diag-panel :visible="diagPanelVisible" @close="diagPanelVisible = false" />
|
||||
|
||||
<!-- 广播发送弹窗 -->
|
||||
<notice-send-dialog v-model:visible="noticeSendVisible" />
|
||||
</view>
|
||||
</template>
|
||||
|
||||
@ -368,6 +376,9 @@ import {
|
||||
finishPack,
|
||||
} from '@/api/index'
|
||||
import ScanDiagPanel from '@/components/scan-diag-panel.vue'
|
||||
import NoticeBanner from '@/components/notice-banner.vue'
|
||||
import NoticeSendDialog from '@/components/notice-send-dialog.vue'
|
||||
import { getNoticeCenter } from '@/core/notice'
|
||||
import {
|
||||
diagAnomaly,
|
||||
diagBegin,
|
||||
@ -430,12 +441,13 @@ const VOICE_API_PATH = 'http://tbdata.gztbyc.com'
|
||||
|
||||
export default {
|
||||
name: 'PackagingPage',
|
||||
components: { ScanDiagPanel },
|
||||
components: { ScanDiagPanel, NoticeBanner, NoticeSendDialog },
|
||||
data() {
|
||||
return {
|
||||
workbenchInfo: null,
|
||||
infoLoading: false,
|
||||
infoError: '',
|
||||
noticeSendVisible: false,
|
||||
keyword: '',
|
||||
currentWaveNo: '',
|
||||
waveTotalOrders: '',
|
||||
@ -719,6 +731,8 @@ export default {
|
||||
this.startScanWatchdog()
|
||||
this.suppressSoftKeyboardBurst()
|
||||
this.scheduleIdleAutoLogout()
|
||||
// 广播接收(幂等;从后台回来在这里补拉)
|
||||
this.initNoticeCenter()
|
||||
} catch (e) {
|
||||
console.error('[packaging] onShow 异常:', e)
|
||||
}
|
||||
@ -734,7 +748,38 @@ export default {
|
||||
diagSetGates({ pageActive: false })
|
||||
diagPersistNow()
|
||||
},
|
||||
onUnload() {
|
||||
getNoticeCenter().stop('packaging unload')
|
||||
},
|
||||
methods: {
|
||||
/** 广播入口:打开发送弹窗 */
|
||||
handleBroadcastOpen() {
|
||||
this.noticeSendVisible = true
|
||||
},
|
||||
/** 启动广播接收(单例幂等) */
|
||||
initNoticeCenter() {
|
||||
const center = getNoticeCenter()
|
||||
center.setSelf({
|
||||
workbenchId: uni.getStorageSync('workbench_id'),
|
||||
userName: this.getSelfDisplayName(),
|
||||
})
|
||||
center.start()
|
||||
center.kick()
|
||||
},
|
||||
/** 本机显示名:广播横幅里的发送人 */
|
||||
getSelfDisplayName() {
|
||||
const info = this.workbenchInfo || {}
|
||||
const member =
|
||||
Array.isArray(this.workbenchMembers) && this.workbenchMembers.length
|
||||
? this.workbenchMembers[0]
|
||||
: null
|
||||
return (
|
||||
(member && (member.real_name || member.name)) ||
|
||||
info.name ||
|
||||
uni.getStorageSync('workbench_name') ||
|
||||
'工作台'
|
||||
)
|
||||
},
|
||||
// 强制锁定横屏 + 全屏重排:
|
||||
// 实验:暂时禁用所有 native 调用,验证白屏是否与 lockOrientation/setStyle 相关。
|
||||
lockLandscape() {
|
||||
@ -3534,6 +3579,12 @@ export default {
|
||||
},
|
||||
exitToLogin(message) {
|
||||
this.clearIdleAutoLogoutTimer()
|
||||
// 停止广播接收并清游标(避免换账号后补发上一个人的消息)
|
||||
try {
|
||||
getNoticeCenter().reset()
|
||||
} catch (e) {
|
||||
// 忽略
|
||||
}
|
||||
if (message) {
|
||||
uni.showToast({
|
||||
title: message,
|
||||
@ -4510,6 +4561,26 @@ export default {
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
/* 广播入口:白描边(APP-PLUS 的 view 不受 uni-button 内置样式影响,无需 !important) */
|
||||
.pack-broadcast-btn {
|
||||
height: 0.36rem;
|
||||
line-height: 0.36rem;
|
||||
padding: 0 0.16rem;
|
||||
margin-right: 0.15rem;
|
||||
border: 0.02rem solid rgba(255, 255, 255, 0.85);
|
||||
border-radius: 0.07rem;
|
||||
box-sizing: border-box;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.pack-broadcast-btn-text {
|
||||
font-size: 0.2rem;
|
||||
line-height: 0.36rem;
|
||||
color: var(--wms-white);
|
||||
}
|
||||
|
||||
.operator-btn {
|
||||
min-width: 1.31rem;
|
||||
height: 0.36rem;
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user