diff --git a/package-lock.json b/package-lock.json index ed5eb19..0a16b22 100644 --- a/package-lock.json +++ b/package-lock.json @@ -24,6 +24,7 @@ "@dcloudio/uni-mp-weixin": "3.0.0-5020420260813003", "@dcloudio/uni-mp-xhs": "3.0.0-5020420260813003", "@dcloudio/uni-quickapp-webview": "3.0.0-5020420260813003", + "element-china-area-data": "^6.1.0", "vue": "^3.4.21", "vue-i18n": "^9.1.9" }, @@ -6856,6 +6857,12 @@ "node": ">=10" } }, + "node_modules/china-division": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/china-division/-/china-division-2.7.0.tgz", + "integrity": "sha512-4uUPAT+1WfqDh5jytq7omdCmHNk3j+k76zEG/2IqaGcYB90c2SwcixttcypdsZ3T/9tN1TTpBDoeZn+Yw/qBEA==", + "license": "MIT" + }, "node_modules/chokidar": { "version": "3.6.0", "resolved": "https://registry.npmmirror.com/chokidar/-/chokidar-3.6.0.tgz", @@ -7413,6 +7420,15 @@ "integrity": "sha512-vUNKPrUzw8ByEMOxloq0a71iD/mPuPxVkbDm3G5YhnxTzOw/I6qAg2MUS0cYj/c267lWmw26yW4Vv7foxTxPLg==", "license": "ISC" }, + "node_modules/element-china-area-data": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/element-china-area-data/-/element-china-area-data-6.1.0.tgz", + "integrity": "sha512-IkpcjwQv2A/2AxFiSoaISZ+oMw1rZCPUSOg5sOCwT5jKc96TaawmKZeY81xfxXsO0QbKxU5LLc6AirhG52hUmg==", + "license": "MIT", + "dependencies": { + "china-division": "^2.7.0" + } + }, "node_modules/emittery": { "version": "0.8.1", "resolved": "https://registry.npmmirror.com/emittery/-/emittery-0.8.1.tgz", diff --git a/package.json b/package.json index 2871fdc..6edc36d 100644 --- a/package.json +++ b/package.json @@ -53,6 +53,7 @@ "@dcloudio/uni-mp-weixin": "3.0.0-5020420260813003", "@dcloudio/uni-mp-xhs": "3.0.0-5020420260813003", "@dcloudio/uni-quickapp-webview": "3.0.0-5020420260813003", + "element-china-area-data": "^6.1.0", "vue": "^3.4.21", "vue-i18n": "^9.1.9" }, diff --git a/src/App.vue b/src/App.vue index 7e1ae94..7992e57 100644 --- a/src/App.vue +++ b/src/App.vue @@ -1,6 +1,11 @@ diff --git a/src/api/auth.ts b/src/api/auth.ts index 3bf25aa..c654a69 100644 --- a/src/api/auth.ts +++ b/src/api/auth.ts @@ -31,3 +31,11 @@ export function logout() { method: 'POST', }) } + +/** POST /app/auth/cancelAccount — 注销账号 */ +export function cancelAccount() { + return request({ + url: '/app/auth/cancelAccount', + method: 'POST', + }) +} diff --git a/src/hooks/use-message-inbox.ts b/src/hooks/use-message-inbox.ts index 431878a..4b0dfd4 100644 --- a/src/hooks/use-message-inbox.ts +++ b/src/hooks/use-message-inbox.ts @@ -1,14 +1,30 @@ -import { ref } from 'vue' +import { computed, ref } from 'vue' import { fetchUnreadMessageCount } from '@/api/message' -import { connectMessageSocket, disconnectMessageSocket, onMessagePush } from '@/utils/message-socket' +import { + connectMessageSocket, + disconnectMessageSocket, + isMessageSocketConnected, + isMessageSocketConnecting, + onMessagePush, +} from '@/utils/message-socket' +import { + clearPushCache, + getCachedPushCount, + pushCacheCount, + rememberPushPayload, +} from '@/utils/message-push-cache' export const unreadMessageCount = ref(0) +export const hasUnreadMessages = computed( + () => unreadMessageCount.value > 0 || pushCacheCount.value > 0, +) let inboxInitialized = false let refreshingUnread = false let lastUnreadRefreshAt = 0 +let pendingPushUnread = 0 -const UNREAD_REFRESH_MIN_GAP_MS = 5000 +const UNREAD_REFRESH_MIN_GAP_MS = 15000 export async function refreshUnreadMessageCount(force = false): Promise { const now = Date.now() @@ -19,30 +35,48 @@ export async function refreshUnreadMessageCount(force = false): Promise refreshingUnread = true try { const count = await fetchUnreadMessageCount() - unreadMessageCount.value = typeof count === 'number' ? count : Number(count) || 0 + const serverCount = typeof count === 'number' ? count : Number(count) || 0 + const cached = getCachedPushCount() + if (serverCount > 0) { + pendingPushUnread = 0 + unreadMessageCount.value = serverCount + } else { + pendingPushUnread = cached + unreadMessageCount.value = Math.max(serverCount, cached) + } lastUnreadRefreshAt = Date.now() } catch { - unreadMessageCount.value = 0 + unreadMessageCount.value = pendingPushUnread } finally { refreshingUnread = false } return unreadMessageCount.value } +function handleIncomingPush(payload: Parameters[0]) { + if (!rememberPushPayload(payload)) return + pendingPushUnread = getCachedPushCount() + unreadMessageCount.value = Math.max(unreadMessageCount.value, pendingPushUnread) +} + export function setupMessageInbox() { - connectMessageSocket() if (!inboxInitialized) { inboxInitialized = true - onMessagePush(() => { - void refreshUnreadMessageCount() + onMessagePush((payload) => { + handleIncomingPush(payload) }) void refreshUnreadMessageCount(true) - return + } + + if (!isMessageSocketConnected() && !isMessageSocketConnecting()) { + connectMessageSocket() } } export function teardownMessageInbox() { disconnectMessageSocket() + clearPushCache() unreadMessageCount.value = 0 + pendingPushUnread = 0 inboxInitialized = false } diff --git a/src/manifest.json b/src/manifest.json index 36cb0f4..fe2b659 100644 --- a/src/manifest.json +++ b/src/manifest.json @@ -39,6 +39,7 @@ "", "", "", + "", "", "", "", @@ -69,6 +70,9 @@ }, "scope.userLocation" : { "desc" : "你的位置信息将用于在地图上选择家庭位置" + }, + "scope.record" : { + "desc" : "你的麦克风将用于在线客服语音输入" } }, "requiredPrivateInfos" : [ diff --git a/src/pages/change-password/index.vue b/src/pages/change-password/index.vue index 99b1cda..44aa38c 100644 --- a/src/pages/change-password/index.vue +++ b/src/pages/change-password/index.vue @@ -7,6 +7,8 @@ + 8-20位字符,须包含字母、数字、符号中的至少2种。 + @@ -38,6 +40,14 @@ const { password, confirmPassword, submit } = useChangePassword() margin-bottom: 48rpx; } +.auth-form-page__hint { + display: block; + margin-top: 16rpx; + font-size: 24rpx; + color: $color-text-secondary; + line-height: 1.5; +} + .auth-form-page__btn { margin-top: 16rpx; } diff --git a/src/pages/change-password/use-change-password.ts b/src/pages/change-password/use-change-password.ts index 2b34937..28633ee 100644 --- a/src/pages/change-password/use-change-password.ts +++ b/src/pages/change-password/use-change-password.ts @@ -1,18 +1,20 @@ import { onLoad } from '@dcloudio/uni-app' import { ref } from 'vue' import { getErrorMessage } from '@/utils/api-error' -import { isValidPassword } from '@/utils/validate' +import { isValidStrongPassword } from '@/utils/validate' import { resetPasswordByToken } from './change-password.api' export function useChangePassword() { const password = ref('') const confirmPassword = ref('') const resetToken = ref('') + const fromPrivacy = ref(false) const loading = ref(false) onLoad((query) => { const raw = (query?.resetToken as string) || '' resetToken.value = raw ? decodeURIComponent(raw) : '' + fromPrivacy.value = query?.from === 'privacy' if (!resetToken.value) { uni.showToast({ title: '请先完成验证码校验', icon: 'none' }) setTimeout(() => uni.navigateBack(), 1500) @@ -24,8 +26,11 @@ export function useChangePassword() { uni.showToast({ title: '重置令牌无效', icon: 'none' }) return } - if (!isValidPassword(password.value)) { - uni.showToast({ title: '密码至少 6 位', icon: 'none' }) + if (!isValidStrongPassword(password.value)) { + uni.showToast({ + title: '密码需8-20位,且包含字母、数字、符号中至少2种', + icon: 'none', + }) return } if (password.value !== confirmPassword.value) { @@ -40,8 +45,12 @@ export function useChangePassword() { newPassword: password.value, confirmPassword: confirmPassword.value, }) - uni.showToast({ title: '修改成功', icon: 'success' }) + uni.showToast({ title: '密码修改成功', icon: 'success' }) setTimeout(() => { + if (fromPrivacy.value) { + uni.navigateBack({ delta: 2 }) + return + } uni.reLaunch({ url: '/pages/login/index' }) }, 800) } catch (err) { diff --git a/src/pages/device/components/device-header/index.vue b/src/pages/device/components/device-header/index.vue index 5fc6c9c..0f22abf 100644 --- a/src/pages/device/components/device-header/index.vue +++ b/src/pages/device/components/device-header/index.vue @@ -49,6 +49,7 @@ :src="staticAssets.iconNotify" mode="aspectFit" /> + @@ -72,6 +73,7 @@ diff --git a/src/pages/mine/edit/components/region-picker/region-data.ts b/src/pages/mine/edit/components/region-picker/region-data.ts new file mode 100644 index 0000000..8bc5db9 --- /dev/null +++ b/src/pages/mine/edit/components/region-picker/region-data.ts @@ -0,0 +1,61 @@ +import { regionData } from 'element-china-area-data' + +export interface RegionNode { + label: string + children?: RegionNode[] +} + +export const CHINA_REGION_TREE: RegionNode[] = regionData.map((province) => ({ + label: province.label, + children: province.children?.map((city) => ({ + label: city.label, + children: city.children?.map((district) => ({ + label: district.label, + })), + })), +})) + +export function getProvinceList(tree: RegionNode[] = CHINA_REGION_TREE): string[] { + return tree.map((item) => item.label) +} + +export function getCityList(provinceIndex: number, tree: RegionNode[] = CHINA_REGION_TREE): string[] { + return tree[provinceIndex]?.children?.map((item) => item.label) ?? [] +} + +export function getDistrictList( + provinceIndex: number, + cityIndex: number, + tree: RegionNode[] = CHINA_REGION_TREE, +): string[] { + return tree[provinceIndex]?.children?.[cityIndex]?.children?.map((item) => item.label) ?? [] +} + +export function findRegionIndexes( + province: string, + city: string, + district: string, + tree: RegionNode[] = CHINA_REGION_TREE, +): [number, number, number] { + const provinceIndex = Math.max( + 0, + tree.findIndex((item) => item.label === province), + ) + const cities = tree[provinceIndex]?.children ?? [] + const cityIndex = Math.max(0, cities.findIndex((item) => item.label === city)) + const districts = cities[cityIndex]?.children ?? [] + const districtIndex = Math.max(0, districts.findIndex((item) => item.label === district)) + return [provinceIndex, cityIndex, districtIndex] +} + +export function getRegionByIndexes( + indexes: [number, number, number], + tree: RegionNode[] = CHINA_REGION_TREE, +): { province: string; city: string; district: string } { + const [provinceIndex, cityIndex, districtIndex] = indexes + const province = tree[provinceIndex]?.label ?? '' + const city = tree[provinceIndex]?.children?.[cityIndex]?.label ?? '' + const district = + tree[provinceIndex]?.children?.[cityIndex]?.children?.[districtIndex]?.label ?? '' + return { province, city, district } +} diff --git a/src/pages/mine/edit/index.vue b/src/pages/mine/edit/index.vue index 0b9c23e..2b3678c 100644 --- a/src/pages/mine/edit/index.vue +++ b/src/pages/mine/edit/index.vue @@ -84,26 +84,24 @@ - - - 所在地 - - - {{ locationText }} - - - + + 所在地 + + + {{ locationText }} + + - + @@ -144,6 +142,14 @@ :value="form.nickName" @confirm="onConfirmNickname" /> + + @@ -151,6 +157,7 @@ import { staticAssets } from '@/utils/static-assets' import AvatarActionSheet from './components/avatar-action-sheet/index.vue' import NicknameDialog from './components/nickname-dialog/index.vue' +import RegionPicker from './components/region-picker/index.vue' import { useEditProfile } from './use-edit-profile' const today = new Date().toISOString().slice(0, 10) @@ -162,7 +169,7 @@ const { maskedPhone, genderText, locationText, - regionValue, + regionPickerVisible, avatarSheetVisible, nicknameDialogVisible, onOpenAvatarSheet, @@ -173,7 +180,8 @@ const { onConfirmNickname, onPickGender, onBirthdayChange, - onRegionChange, + onOpenRegionPicker, + onConfirmRegion, onChangePhone, onSave, } = useEditProfile() diff --git a/src/pages/mine/edit/use-edit-profile.ts b/src/pages/mine/edit/use-edit-profile.ts index 0d9a527..e1e9cdf 100644 --- a/src/pages/mine/edit/use-edit-profile.ts +++ b/src/pages/mine/edit/use-edit-profile.ts @@ -49,18 +49,13 @@ export function useEditProfile() { const form = ref(createEmptyForm()) const avatarSheetVisible = ref(false) const nicknameDialogVisible = ref(false) + const regionPickerVisible = ref(false) const maskedPhone = computed(() => maskPhone(form.value.phonenumber)) const genderText = computed(() => GENDER_LABELS[form.value.gender] || '未知') const locationText = computed(() => formatLocation(form.value.province, form.value.city, form.value.district), ) - const regionValue = computed(() => { - const { province, city, district } = form.value - if (province && city && district) return [province, city, district] - return [] - }) - async function loadProfile() { if (loading.value) return loading.value = true @@ -158,11 +153,14 @@ export function useEditProfile() { form.value.birthday = e.detail.value } - function onRegionChange(e: { detail: { value: string[] } }) { - const [province, city, district] = e.detail.value - form.value.province = province || '' - form.value.city = city || '' - form.value.district = district || '' + function onOpenRegionPicker() { + regionPickerVisible.value = true + } + + function onConfirmRegion(value: { province: string; city: string; district: string }) { + form.value.province = value.province + form.value.city = value.city + form.value.district = value.district } function onChangePhone() { @@ -214,7 +212,7 @@ export function useEditProfile() { maskedPhone, genderText, locationText, - regionValue, + regionPickerVisible, avatarSheetVisible, nicknameDialogVisible, onOpenAvatarSheet, @@ -225,7 +223,8 @@ export function useEditProfile() { onConfirmNickname, onPickGender, onBirthdayChange, - onRegionChange, + onOpenRegionPicker, + onConfirmRegion, onChangePhone, onSave, } diff --git a/src/pages/mine/index.vue b/src/pages/mine/index.vue index 825116b..4a8ce5b 100644 --- a/src/pages/mine/index.vue +++ b/src/pages/mine/index.vue @@ -27,35 +27,6 @@ - - - {{ item.value }} - {{ item.label }} - - - - - - - - - {{ action.label }} - - - @@ -270,6 +287,7 @@ import { computed, nextTick, ref, watch } from 'vue' import { staticAssets } from '@/utils/static-assets' import { useSupport } from './use-support' +import { useSupportVoice } from './use-support-voice' import type { DiagnosisItem } from './support.types' const { @@ -290,8 +308,29 @@ const { onSend, } = useSupport() +const { + inputMode, + voiceHolding, + voiceRecognizing, + toggleInputMode, + onVoiceTouchStart, + onVoiceTouchEnd, + onVoiceTouchCancel, +} = useSupportVoice({ + onRecognized: (text) => { + inputValue.value = text + onSend() + }, +}) + const humanAvatarText = computed(() => headerInfo.value.avatarText || '服') +const voiceButtonText = computed(() => { + if (voiceRecognizing.value && !voiceHolding.value) return '识别中...' + if (voiceHolding.value) return '松手 发送' + return '按住 说话' +}) + const scrollIntoView = ref('chat-bottom') watch( diff --git a/src/pages/mine/support/support.scss b/src/pages/mine/support/support.scss index f6d6cda..802bbfb 100644 --- a/src/pages/mine/support/support.scss +++ b/src/pages/mine/support/support.scss @@ -209,7 +209,7 @@ $support-danger: #f04438; } &--user { - border-radius: 16rpx; + border-radius: 50%; background: #d0d5dd; color: #fff; } @@ -259,13 +259,6 @@ $support-danger: #f04438; } } -.support-page__bubble-time { - margin-top: 8rpx; - font-size: 22rpx; - color: $support-text-secondary; - line-height: 1.2; -} - .support-page__quick { display: flex; flex-wrap: wrap; @@ -637,6 +630,34 @@ $support-danger: #f04438; height: 56rpx; } +.support-page__keyboard-icon { + font-size: 40rpx; + line-height: 1; + color: $support-text-muted; +} + +.support-page__voice-btn { + flex: 1; + height: 72rpx; + border-radius: 36rpx; + background: #f5f6f8; + display: flex; + align-items: center; + justify-content: center; + user-select: none; + + &--holding, + &--recognizing { + background: rgba(30, 198, 113, 0.12); + } +} + +.support-page__voice-btn-text { + font-size: 28rpx; + color: $support-text; + line-height: 1; +} + .support-page__input-wrap { flex: 1; height: 72rpx; @@ -687,7 +708,9 @@ $support-danger: #f04438; } .support-page__secure { - margin-top: 12rpx; + display: block; + margin: 0 0 16rpx; + padding: 0 16rpx; text-align: center; font-size: 22rpx; color: $support-text-secondary; diff --git a/src/pages/mine/support/support.types.ts b/src/pages/mine/support/support.types.ts index cbaab06..c4f9b40 100644 --- a/src/pages/mine/support/support.types.ts +++ b/src/pages/mine/support/support.types.ts @@ -128,7 +128,7 @@ export type SupportMessage = type: 'text' role: ChatRole content: string - time?: string + createTime?: string } | { id: string @@ -165,7 +165,7 @@ export type SupportMessage = type: 'image' role: 'user' src: string - time?: string + createTime?: string } export interface SupportHeaderInfo { diff --git a/src/pages/mine/support/support.utils.ts b/src/pages/mine/support/support.utils.ts index 2c48a0d..302020a 100644 --- a/src/pages/mine/support/support.utils.ts +++ b/src/pages/mine/support/support.utils.ts @@ -91,11 +91,62 @@ export function getQueueEstimate(session: CsSessionVo): string { return session.estimateWaitTime?.trim() || '正在为您分配人工客服' } -function formatMessageTime(value?: string): string | undefined { - if (!value) return undefined +const TIME_DIVIDER_GAP_MS = 5 * 60 * 1000 + +function parseMessageTimestamp(value?: string): number | null { + if (!value) return null const date = new Date(value) - if (Number.isNaN(date.getTime())) return undefined - return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}` + const ts = date.getTime() + return Number.isNaN(ts) ? null : ts +} + +function formatTimeDividerText(value: string): string { + const date = new Date(value) + if (Number.isNaN(date.getTime())) return '' + const hm = `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}` + const now = new Date() + if (date.toDateString() === now.toDateString()) return hm + + const yesterday = new Date(now) + yesterday.setDate(now.getDate() - 1) + if (date.toDateString() === yesterday.toDateString()) return `昨天 ${hm}` + + return `${date.getMonth() + 1}月${date.getDate()}日 ${hm}` +} + +function getMessageCreateTime(item: SupportMessage): string | undefined { + if (item.type === 'text' || item.type === 'image') return item.createTime + return undefined +} + +export function injectTimeDividers(messages: SupportMessage[]): SupportMessage[] { + const result: SupportMessage[] = [] + let lastTimestamp = 0 + + for (const item of messages) { + const createTime = getMessageCreateTime(item) + const timestamp = parseMessageTimestamp(createTime) + const shouldInsertDivider = timestamp !== null + && (lastTimestamp === 0 || timestamp - lastTimestamp >= TIME_DIVIDER_GAP_MS) + + if (shouldInsertDivider && createTime) { + const text = formatTimeDividerText(createTime) + if (text) { + result.push({ + id: `time-${timestamp}`, + type: 'time', + text, + }) + } + lastTimestamp = timestamp + } else if (timestamp !== null) { + lastTimestamp = timestamp + } + + result.push(item) + } + + return result } function resolveSenderRole(senderType?: string | number): ChatRole | null { @@ -183,7 +234,7 @@ function mapStructuredMessage(message: CsMessageVo, payload: Record void +} + +interface SpeechRecognitionInstance { + lang: string + continuous: boolean + interimResults: boolean + start: () => void + stop: () => void + abort: () => void + onresult: ((event: { results: Array> }) => void) | null + onerror: ((event: { error?: string }) => void) | null + onend: (() => void) | null +} + +const MAX_VOICE_DURATION_MS = 60000 + +export function useSupportVoice(options: UseSupportVoiceOptions) { + const inputMode = ref('text') + const voiceHolding = ref(false) + const voiceRecognizing = ref(false) + + let touchCanceled = false + let recordStopTimer: ReturnType | null = null + let h5Recognition: SpeechRecognitionInstance | null = null + + // #ifdef MP-WEIXIN + let mpRecoManager: { + start: (opts: { duration: number; lang: string }) => void + stop: () => void + onStop?: (res: { result?: string }) => void + onError?: () => void + } | null = null + + try { + const plugin = requirePlugin('WechatSI') as { + getRecordRecognitionManager: () => NonNullable + } + mpRecoManager = plugin.getRecordRecognitionManager() + mpRecoManager.onStop = (res) => { + voiceRecognizing.value = false + const text = res.result?.trim() + if (text) { + options.onRecognized(text) + return + } + uni.showToast({ title: '未识别到语音内容', icon: 'none' }) + } + mpRecoManager.onError = () => { + voiceRecognizing.value = false + uni.showToast({ title: '语音识别失败', icon: 'none' }) + } + } catch { + mpRecoManager = null + } + // #endif + + function clearRecordStopTimer() { + if (recordStopTimer) clearTimeout(recordStopTimer) + recordStopTimer = null + } + + function resetVoiceState() { + voiceHolding.value = false + voiceRecognizing.value = false + touchCanceled = false + clearRecordStopTimer() + } + + function isVoiceSupported(): boolean { + // #ifdef H5 + const win = window as Window & { + SpeechRecognition?: new () => SpeechRecognitionInstance + webkitSpeechRecognition?: new () => SpeechRecognitionInstance + } + return !!(win.SpeechRecognition || win.webkitSpeechRecognition) + // #endif + + // #ifdef APP-PLUS + return typeof plus !== 'undefined' && !!plus.speech + // #endif + + // #ifdef MP-WEIXIN + return !!mpRecoManager + // #endif + + return false + } + + function ensureRecordPermission(): Promise { + return new Promise((resolve) => { + uni.getSetting({ + success: (res) => { + if (res.authSetting['scope.record']) { + resolve(true) + return + } + uni.authorize({ + scope: 'scope.record', + success: () => resolve(true), + fail: () => { + uni.showModal({ + title: '需要麦克风权限', + content: '请在设置中开启麦克风权限后使用语音输入', + confirmText: '去设置', + success: (modalRes) => { + if (modalRes.confirm) { + uni.openSetting({}) + } + }, + }) + resolve(false) + }, + }) + }, + fail: () => resolve(false), + }) + }) + } + + function cleanupH5Recognition() { + if (!h5Recognition) return + try { + h5Recognition.abort() + } catch { + // ignore + } + h5Recognition.onresult = null + h5Recognition.onerror = null + h5Recognition.onend = null + h5Recognition = null + } + + async function startH5Voice() { + const win = window as Window & { + SpeechRecognition?: new () => SpeechRecognitionInstance + webkitSpeechRecognition?: new () => SpeechRecognitionInstance + } + const Ctor = win.SpeechRecognition || win.webkitSpeechRecognition + if (!Ctor) { + uni.showToast({ title: '当前浏览器不支持语音输入', icon: 'none' }) + resetVoiceState() + return + } + + cleanupH5Recognition() + const recognition = new Ctor() + h5Recognition = recognition + recognition.lang = 'zh-CN' + recognition.continuous = false + recognition.interimResults = false + voiceRecognizing.value = true + + recognition.onresult = (event) => { + const text = event.results[0]?.[0]?.transcript?.trim() + if (text) options.onRecognized(text) + } + recognition.onerror = (event) => { + if (event.error !== 'aborted') { + uni.showToast({ title: '语音识别失败', icon: 'none' }) + } + } + recognition.onend = () => { + voiceRecognizing.value = false + h5Recognition = null + } + + try { + recognition.start() + } catch { + voiceRecognizing.value = false + h5Recognition = null + uni.showToast({ title: '无法启动语音识别', icon: 'none' }) + } + } + + function stopH5Voice() { + if (!h5Recognition) return + try { + h5Recognition.stop() + } catch { + h5Recognition.abort() + } + } + + function startAppVoice() { + if (!plus.speech) { + uni.showToast({ title: '当前环境不支持语音输入', icon: 'none' }) + return + } + voiceRecognizing.value = true + plus.speech.startRecognize( + { + engine: 'baidu', + lang: 'zh-cn', + punctuation: false, + timeout: 10000, + }, + (text) => { + voiceRecognizing.value = false + const result = String(text || '').trim() + if (result) { + options.onRecognized(result) + return + } + uni.showToast({ title: '未识别到语音内容', icon: 'none' }) + }, + () => { + voiceRecognizing.value = false + uni.showToast({ title: '语音识别失败', icon: 'none' }) + }, + ) + } + + async function startMpVoice() { + if (!mpRecoManager) { + uni.showToast({ title: '未配置同声传译插件,暂无法使用语音输入', icon: 'none' }) + resetVoiceState() + return + } + const granted = await ensureRecordPermission() + if (!granted) { + resetVoiceState() + return + } + voiceRecognizing.value = true + mpRecoManager.start({ duration: MAX_VOICE_DURATION_MS, lang: 'zh_CN' }) + } + + function stopMpVoice() { + mpRecoManager?.stop() + } + + function cancelVoiceCapture() { + // #ifdef H5 + cleanupH5Recognition() + // #endif + + // #ifdef APP-PLUS + if (voiceRecognizing.value) { + plus.speech.stopRecognize() + } + // #endif + + // #ifdef MP-WEIXIN + mpRecoManager?.stop() + // #endif + + voiceRecognizing.value = false + } + + function toggleInputMode() { + if (inputMode.value === 'text') { + if (!isVoiceSupported()) { + uni.showToast({ title: '当前环境不支持语音输入', icon: 'none' }) + return + } + inputMode.value = 'voice' + return + } + cancelVoiceCapture() + resetVoiceState() + inputMode.value = 'text' + } + + async function onVoiceTouchStart() { + if (voiceRecognizing.value) return + touchCanceled = false + voiceHolding.value = true + + // #ifdef H5 + await startH5Voice() + // #endif + + // #ifdef MP-WEIXIN + await startMpVoice() + // #endif + + clearRecordStopTimer() + recordStopTimer = setTimeout(() => { + if (voiceHolding.value) { + onVoiceTouchEnd() + } + }, MAX_VOICE_DURATION_MS) + } + + function onVoiceTouchEnd() { + if (!voiceHolding.value) return + voiceHolding.value = false + clearRecordStopTimer() + + if (touchCanceled) { + cancelVoiceCapture() + return + } + + // #ifdef H5 + stopH5Voice() + // #endif + + // #ifdef APP-PLUS + startAppVoice() + // #endif + + // #ifdef MP-WEIXIN + stopMpVoice() + // #endif + } + + function onVoiceTouchCancel() { + touchCanceled = true + voiceHolding.value = false + clearRecordStopTimer() + cancelVoiceCapture() + } + + onBeforeUnmount(() => { + cancelVoiceCapture() + clearRecordStopTimer() + }) + + return { + inputMode, + voiceHolding, + voiceRecognizing, + toggleInputMode, + onVoiceTouchStart, + onVoiceTouchEnd, + onVoiceTouchCancel, + } +} diff --git a/src/pages/mine/support/use-support.ts b/src/pages/mine/support/use-support.ts index afb5040..f9c837c 100644 --- a/src/pages/mine/support/use-support.ts +++ b/src/pages/mine/support/use-support.ts @@ -39,6 +39,7 @@ import { getMaxSeq, getQueueEstimate, getQueuePosition, + injectTimeDividers, mapCsMessage, mergeSupportMessages, normalizeSessionId, @@ -124,7 +125,7 @@ export function useSupport() { estimateText: queueEstimate.value, }) } - return list + return injectTimeDividers(list) }) function clearQueueTimer() { diff --git a/src/pages/mine/use-mine.ts b/src/pages/mine/use-mine.ts index a8e32e2..f59c121 100644 --- a/src/pages/mine/use-mine.ts +++ b/src/pages/mine/use-mine.ts @@ -1,29 +1,14 @@ import { onShow } from '@dcloudio/uni-app' import { computed, ref } from 'vue' import { getErrorMessage } from '@/utils/api-error' -import { staticAssets } from '@/utils/static-assets' import { fetchMineOverview } from './mine.api' -import type { MineMenuItem, MineQuickAction } from './mine.types' - -const APP_VERSION = 'v3.2.0' - -const QUICK_ACTIONS: MineQuickAction[] = [ - { id: 'notify', label: '消息通知', icon: staticAssets.iconMineNotify }, - { id: 'order', label: '我的订单', icon: staticAssets.iconMineOrder }, - { id: 'coupon', label: '优惠券', icon: staticAssets.iconMineCoupon }, - { id: 'address', label: '收货地址', icon: staticAssets.iconMineAddress }, -] +import type { MineMenuItem } from './mine.types' const MENU_ITEMS: MineMenuItem[] = [ { id: 'devices', title: '我的设备' }, - { id: 'members', title: '家庭成员' }, - { id: 'scene', title: '场景与自动化' }, - { id: 'service', title: '售后服务' }, { id: 'support', title: '在线客服' }, - { id: 'feedback', title: '帮助与反馈' }, - { id: 'settings', title: '通用设置' }, + { id: 'storage', title: '储存空间' }, { id: 'privacy', title: '隐私与安全' }, - { id: 'about', title: '关于我们', value: APP_VERSION }, ] export function useMine() { @@ -32,32 +17,13 @@ export function useMine() { const phone = ref('') const avatarUrl = ref('') const deviceCount = ref(0) - const memberCount = ref(0) - const warrantyCount = ref(0) - const sceneCount = ref(0) - const statusBarHeight = ref(0) - const stats = computed(() => [ - { label: '我的设备', value: deviceCount.value }, - { label: '家庭成员', value: memberCount.value }, - { label: '保修中', value: warrantyCount.value }, - ]) - const menuList = computed(() => MENU_ITEMS.map((item) => { if (item.id === 'devices') { return { ...item, value: `已绑定 ${deviceCount.value} 台` } } - if (item.id === 'members') { - return { ...item, value: `${memberCount.value} 位成员` } - } - if (item.id === 'scene') { - return { ...item, value: `${sceneCount.value} 个场景` } - } - if (item.id === 'service') { - return { ...item, value: '报修 / 退换' } - } return item }), ) @@ -82,14 +48,6 @@ export function useMine() { uni.navigateTo({ url: '/pages/mine/edit/index' }) } - function onQuickAction(action: MineQuickAction) { - if (action.id === 'notify') { - uni.navigateTo({ url: '/pages/mine/notify/index' }) - return - } - uni.showToast({ title: `${action.label}功能开发中`, icon: 'none' }) - } - function onMenuTap(item: MineMenuItem) { if (item.id === 'devices') { uni.reLaunch({ url: '/pages/device/index' }) @@ -99,16 +57,13 @@ export function useMine() { uni.navigateTo({ url: '/pages/mine/support/index' }) return } - if (item.id === 'settings') { + if (item.id === 'storage') { uni.navigateTo({ url: '/pages/mine/storage/index' }) return } if (item.id === 'privacy') { uni.navigateTo({ url: '/pages/mine/privacy/index' }) - return } - if (item.id === 'about') return - uni.showToast({ title: `${item.title}功能开发中`, icon: 'none' }) } onShow(() => { @@ -122,11 +77,8 @@ export function useMine() { nickName, phone, avatarUrl, - stats, - quickActions: QUICK_ACTIONS, menuList, onEditNickname, - onQuickAction, onMenuTap, } } diff --git a/src/static/通知 (1).png b/src/static/通知 (1).png new file mode 100644 index 0000000..aa6a730 Binary files /dev/null and b/src/static/通知 (1).png differ diff --git a/src/utils/message-push-cache.ts b/src/utils/message-push-cache.ts new file mode 100644 index 0000000..01decc4 --- /dev/null +++ b/src/utils/message-push-cache.ts @@ -0,0 +1,58 @@ +import { ref } from 'vue' +import type { AppMessageVo, MessagePushPayload } from '@/types/message' +import { buildMessageFromPush, normalizeMessageId } from '@/utils/message-push' + +const cachedPushes = new Map() +export const pushCacheCount = ref(0) + +function syncCacheCount() { + pushCacheCount.value = cachedPushes.size +} + +function resolveCacheId(payload: MessagePushPayload, message: AppMessageVo): string { + const messageId = normalizeMessageId(message) + if (messageId) return messageId + if (payload.alertId != null && payload.alertId !== '') return String(payload.alertId) + const stamp = payload.timestamp || Date.now() + const title = payload.title || payload.content || 'push' + return `${title}-${stamp}` +} + +export function rememberPushPayload(payload: MessagePushPayload): AppMessageVo | null { + if (!payload.title && !payload.content && payload.messageId == null && payload.alertId == null) { + return null + } + + const message = buildMessageFromPush(payload) + const id = resolveCacheId(payload, message) + message.messageId = id + cachedPushes.set(id, message) + syncCacheCount() + return message +} + +export function mergeCachedMessages(rows: AppMessageVo[]): AppMessageVo[] { + const map = new Map() + for (const item of rows) { + const id = normalizeMessageId(item) + if (id) map.set(id, item) + } + for (const [id, item] of cachedPushes) { + if (!map.has(id)) map.set(id, item) + } + return Array.from(map.values()) +} + +export function forgetCachedMessage(messageId: string) { + cachedPushes.delete(messageId) + syncCacheCount() +} + +export function clearPushCache() { + cachedPushes.clear() + syncCacheCount() +} + +export function getCachedPushCount(): number { + return pushCacheCount.value +} diff --git a/src/utils/message-push.ts b/src/utils/message-push.ts new file mode 100644 index 0000000..3930bc3 --- /dev/null +++ b/src/utils/message-push.ts @@ -0,0 +1,114 @@ +import type { AppMessageVo, MessagePushPayload } from '@/types/message' + +export function normalizeMessageId(message: AppMessageVo): string { + const raw = message.messageId + if (raw === undefined || raw === null || raw === '') return '' + return String(raw) +} + +export function buildMessageFromPush(payload: MessagePushPayload): AppMessageVo { + return { + messageId: payload.messageId, + alertId: payload.alertId, + alertType: payload.alertType, + title: payload.title, + content: payload.content, + deviceId: payload.deviceId, + timestamp: payload.timestamp, + readFlag: '0', + } +} + +function asRecord(value: unknown): Record | null { + if (!value || typeof value !== 'object' || Array.isArray(value)) return null + return value as Record +} + +function pickString(obj: Record, keys: string[]): string | undefined { + for (const key of keys) { + const value = obj[key] + if (value !== undefined && value !== null && value !== '') { + return String(value) + } + } + return undefined +} + +function pickId(obj: Record, keys: string[]): string | number | undefined { + for (const key of keys) { + const value = obj[key] + if (value !== undefined && value !== null && value !== '') { + return typeof value === 'number' ? value : String(value) + } + } + return undefined +} + +export function normalizeMessagePushPayload( + source: Record, +): MessagePushPayload { + return { + messageId: pickId(source, ['messageId', 'id', 'msgId']), + alertId: pickId(source, ['alertId', 'alert_id']), + alertType: pickString(source, ['alertType', 'alert_type', 'type']), + title: pickString(source, ['title', 'msgTitle', 'subject']), + content: pickString(source, ['content', 'msgContent', 'body', 'message']), + deviceId: pickId(source, ['deviceId', 'device_id']), + timestamp: pickString(source, ['timestamp', 'createTime', 'time']), + } +} + +export function parseMessagePushPayload(raw: string): MessagePushPayload | null { + if (!raw || raw === 'ping' || raw === 'pong') return null + + try { + const parsed = JSON.parse(raw) as Record + const type = String(parsed.type ?? '').toLowerCase() + + if (type === 'message' || type === 'push' || type === 'notify') { + const nested = asRecord(parsed.data) ?? asRecord(parsed.message) ?? asRecord(parsed.msg) + if (nested) return normalizeMessagePushPayload(nested) + } + + const nested = asRecord(parsed.data) ?? asRecord(parsed.message) ?? asRecord(parsed.msg) + if (nested) { + const payload = normalizeMessagePushPayload(nested) + if (payload.title || payload.content || payload.messageId) return payload + } + + const direct = normalizeMessagePushPayload(parsed) + if (direct.title || direct.content || direct.messageId || direct.alertId) { + return direct + } + + if (import.meta.env.DEV) { + console.log('[Message WS] unknown payload', parsed) + } + return null + } catch { + if (import.meta.env.DEV) { + console.log('[Message WS] invalid json', raw) + } + return null + } +} + +export function decodeSocketMessageData(data: unknown): string { + if (typeof data === 'string') return data + if (data instanceof ArrayBuffer) { + return new TextDecoder('utf-8').decode(data) + } + if (ArrayBuffer.isView(data)) { + return new TextDecoder('utf-8').decode(data.buffer) + } + return '' +} + +export function getMessagePushToastText(payload: MessagePushPayload): string | null { + const title = payload.title?.trim() + if (title) return title + const content = payload.content?.trim() + if (content) return content.length > 30 ? `${content.slice(0, 30)}...` : content + if (payload.messageId || payload.alertId) return '您有新消息' + return null +} diff --git a/src/utils/message-socket.ts b/src/utils/message-socket.ts index ee4f977..874e204 100644 --- a/src/utils/message-socket.ts +++ b/src/utils/message-socket.ts @@ -1,4 +1,9 @@ import { getStoredToken } from '@/utils/auth-token' +import { + decodeSocketMessageData, + getMessagePushToastText, + parseMessagePushPayload, +} from '@/utils/message-push' import type { MessagePushPayload } from '@/types/message' const HEARTBEAT_INTERVAL_MS = 25000 @@ -9,6 +14,8 @@ let heartbeatTimer: ReturnType | null = null let reconnectTimer: ReturnType | null = null let connecting = false let manualClosed = false +let socketOpened = false +let disconnectHandled = false const listeners = new Set<(payload: MessagePushPayload) => void>() @@ -35,11 +42,15 @@ function stopHeartbeat() { heartbeatTimer = null } +function sendPing() { + if (!socketOpened || !socketTask) return + socketTask.send({ data: 'ping' }) +} + function startHeartbeat() { stopHeartbeat() - heartbeatTimer = setInterval(() => { - socketTask?.send({ data: 'ping' }) - }, HEARTBEAT_INTERVAL_MS) + sendPing() + heartbeatTimer = setInterval(sendPing, HEARTBEAT_INTERVAL_MS) } function clearReconnectTimer() { @@ -58,20 +69,45 @@ function scheduleReconnect() { function cleanupSocketTask() { stopHeartbeat() socketTask = null + socketOpened = false connecting = false + disconnectHandled = false +} + +function handleDisconnect(reason: string) { + if (disconnectHandled) return + disconnectHandled = true + if (import.meta.env.DEV) { + console.log(`[Message WS] ${reason}`) + } + cleanupSocketTask() + if (!manualClosed) { + scheduleReconnect() + } } function handleSocketMessage(raw: string) { - if (!raw || raw === 'ping' || raw === 'pong') return - try { - const data = JSON.parse(raw) as MessagePushPayload - listeners.forEach((listener) => listener(data)) - if (data.title) { - uni.showToast({ title: data.title, icon: 'none' }) - } - } catch { - // ignore invalid payload + const payload = parseMessagePushPayload(raw) + if (!payload) return + + if (import.meta.env.DEV) { + console.log('[Message WS] push', payload) } + + listeners.forEach((listener) => listener(payload)) + + const toastText = getMessagePushToastText(payload) + if (toastText) { + uni.showToast({ title: toastText, icon: 'none' }) + } +} + +export function isMessageSocketConnected(): boolean { + return socketOpened && !!socketTask +} + +export function isMessageSocketConnecting(): boolean { + return connecting || (!!socketTask && !socketOpened) } export function onMessagePush(listener: (payload: MessagePushPayload) => void) { @@ -81,38 +117,47 @@ export function onMessagePush(listener: (payload: MessagePushPayload) => void) { export function connectMessageSocket() { const token = getStoredToken() - if (!token || connecting || socketTask) return + if (!token || manualClosed) return + if (socketOpened && socketTask) return + // 握手进行中:不要 close,否则 DevTools 会报 "closed before connection is established" + if (isMessageSocketConnecting()) return manualClosed = false connecting = true + disconnectHandled = false clearReconnectTimer() const task = uni.connectSocket({ url: resolveMessageWsUrl(token), - complete: () => { - connecting = false + fail: (err) => { + if (import.meta.env.DEV) { + console.log('[Message WS] connect fail', err) + } + handleDisconnect('connect fail') }, }) socketTask = task task.onOpen(() => { + socketOpened = true + connecting = false + if (import.meta.env.DEV) { + console.log('[Message WS] connected') + } startHeartbeat() }) task.onMessage((res) => { - const raw = typeof res.data === 'string' ? res.data : '' - handleSocketMessage(raw) + handleSocketMessage(decodeSocketMessageData(res.data)) }) task.onClose(() => { - cleanupSocketTask() - scheduleReconnect() + handleDisconnect('closed') }) task.onError(() => { - cleanupSocketTask() - scheduleReconnect() + handleDisconnect('error') }) } @@ -120,9 +165,15 @@ export function disconnectMessageSocket() { manualClosed = true clearReconnectTimer() stopHeartbeat() + disconnectHandled = true if (socketTask) { - socketTask.close({}) + try { + socketTask.close({}) + } catch { + // ignore + } } socketTask = null + socketOpened = false connecting = false } diff --git a/src/utils/static-assets.ts b/src/utils/static-assets.ts index cec7f53..5b53fce 100644 --- a/src/utils/static-assets.ts +++ b/src/utils/static-assets.ts @@ -10,7 +10,7 @@ import iconRunModeInfo from '@/static/组 15227@2x.png' import iconHomeSelector from '@/static/图标 4.png' import iconHomeArrow from '@/static/组 9.png' import iconHomeSelected from '@/static/完成@2x.png' -import iconNotify from '@/static/组 27.png' +import iconNotify from '@/static/通知 (1).png' import iconDeviceEmpty from '@/static/图标 8.png' import iconDeviceNameEdit from '@/static/图标 9.png' import iconBindComplete from '@/static/组 41@2x.png' @@ -57,7 +57,7 @@ export const staticAssets = { iconHomeArrow, /** 完成@2x.png — 「我的家」下拉选中图标 */ iconHomeSelected, - /** 组 27.png — 设备页右上角通知 */ + /** 通知 (1).png — 设备页右上角通知 */ iconNotify, /** 图标 8.png — 设备空状态中心图标 */ iconDeviceEmpty, diff --git a/src/utils/z2-ble-protocol.ts b/src/utils/z2-ble-protocol.ts index 917c3f0..5b3cd25 100644 --- a/src/utils/z2-ble-protocol.ts +++ b/src/utils/z2-ble-protocol.ts @@ -100,6 +100,11 @@ export function splitZ2NotifyRecords(raw: string): string[] { return [text] } + // 实机单包 Q 应答(含 M= 与 B=)整条解析,避免误拆成碎片 + if (text.startsWith('Q;') && /;M=/i.test(text)) { + return [text] + } + // 仅标准多包应答(Q; 开头或独立 FL=/FILTER= 行)才拆分 const isMultiRecord = text.startsWith('Q;') || /(?:^|;)FL=|(?:^|;)FILTER=/.test(text) @@ -196,10 +201,9 @@ function parseBatteryValue(value: string): number | undefined { const raw = Number(matched[1]) if (!Number.isFinite(raw)) return undefined if (raw <= 100) return clampPercent(raw) - // 实机可能上报 731 表示 73.1% - const scaled = Math.round(raw / 10) - if (scaled <= 100) return clampPercent(scaled) - return clampPercent(raw % 100) + // 实机可能上报 731 表示 73.1%,800 表示 80.0% + if (raw <= 1000) return clampPercent(Math.round(raw / 10)) + return undefined } /** 解析单行 Notify,如 `Q;M=L;W=C;A=G` 或 `B=34;P=B` */ @@ -269,11 +273,21 @@ export function mergeZ2DeviceState( export function parseZ2NotifyPayload(lines: string[]): Z2DeviceState { let state: Z2DeviceState = {} + let batteryFromMainLine: number | undefined + for (const line of lines) { for (const record of splitZ2NotifyRecords(line)) { - state = mergeZ2DeviceState(state, parseZ2NotifyLine(record)) + const patch = parseZ2NotifyLine(record) + if (/M=/i.test(record) && patch.battery != null) { + batteryFromMainLine = patch.battery + } + state = mergeZ2DeviceState(state, patch) } } + + if (batteryFromMainLine != null) { + state.battery = batteryFromMainLine + } return state } diff --git a/src/utils/z2-ble.ts b/src/utils/z2-ble.ts index 31e8c80..814e8d8 100644 --- a/src/utils/z2-ble.ts +++ b/src/utils/z2-ble.ts @@ -291,9 +291,12 @@ function writeBleAscii( function appendNotifyText(buffer: string, chunk: string): string { if (!chunk) return buffer - if (!buffer) return chunk - const needsSeparator = !/[;\r\n]$/.test(buffer) && !/^(B=\d|T=\d|FL=|FILTER=|Q;)/.test(chunk) - return needsSeparator ? `${buffer}${chunk}` : `${buffer}${chunk}` + const next = chunk.trim() + if (!next) return buffer + if (!buffer) return next + if (/[;\r\n]$/.test(buffer)) return `${buffer}${next}` + // 分包粘连时补分隔符,避免 B=8 + 0... 被拼成 B=80 + return `${buffer};${next}` } function resolveNotifyRecords(buffer: string): string[] { @@ -307,7 +310,7 @@ async function collectNotifyLines( options: { maxWaitMs?: number; idleMs?: number } = {}, ): Promise { const maxWaitMs = options.maxWaitMs ?? 6000 - const idleMs = options.idleMgs ?? 400 + const idleMs = options.idleMs ?? 400 let buffer = '' let settled = false