feat:客服
This commit is contained in:
16
package-lock.json
generated
16
package-lock.json
generated
@@ -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",
|
||||
|
||||
@@ -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"
|
||||
},
|
||||
|
||||
10
src/App.vue
10
src/App.vue
@@ -1,6 +1,11 @@
|
||||
<script setup lang="ts">
|
||||
import { onLaunch, onShow } from '@dcloudio/uni-app'
|
||||
import { setupMessageInbox } from '@/hooks/use-message-inbox'
|
||||
import {
|
||||
connectMessageSocket,
|
||||
isMessageSocketConnected,
|
||||
isMessageSocketConnecting,
|
||||
} from '@/utils/message-socket'
|
||||
import { getStoredToken } from '@/utils/auth-token'
|
||||
|
||||
onLaunch(() => {
|
||||
@@ -10,8 +15,9 @@ onLaunch(() => {
|
||||
})
|
||||
|
||||
onShow(() => {
|
||||
if (getStoredToken()) {
|
||||
setupMessageInbox()
|
||||
if (!getStoredToken()) return
|
||||
if (!isMessageSocketConnected() && !isMessageSocketConnecting()) {
|
||||
connectMessageSocket()
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
@@ -31,3 +31,11 @@ export function logout() {
|
||||
method: 'POST',
|
||||
})
|
||||
}
|
||||
|
||||
/** POST /app/auth/cancelAccount — 注销账号 */
|
||||
export function cancelAccount() {
|
||||
return request<void>({
|
||||
url: '/app/auth/cancelAccount',
|
||||
method: 'POST',
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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<number> {
|
||||
const now = Date.now()
|
||||
@@ -19,30 +35,48 @@ export async function refreshUnreadMessageCount(force = false): Promise<number>
|
||||
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<typeof rememberPushPayload>[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
|
||||
}
|
||||
|
||||
@@ -39,6 +39,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\"/>",
|
||||
@@ -69,6 +70,9 @@
|
||||
},
|
||||
"scope.userLocation" : {
|
||||
"desc" : "你的位置信息将用于在地图上选择家庭位置"
|
||||
},
|
||||
"scope.record" : {
|
||||
"desc" : "你的麦克风将用于在线客服语音输入"
|
||||
}
|
||||
},
|
||||
"requiredPrivateInfos" : [
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
<base-input v-model="password" icon="lock" type="password" placeholder="请输入密码" />
|
||||
<base-input v-model="confirmPassword" icon="lock" type="password" placeholder="确认密码" />
|
||||
|
||||
<text class="auth-form-page__hint">8-20位字符,须包含字母、数字、符号中的至少2种。</text>
|
||||
|
||||
<view class="auth-form-page__btn">
|
||||
<primary-button text="确认修改" @click="submit" />
|
||||
</view>
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -49,6 +49,7 @@
|
||||
:src="staticAssets.iconNotify"
|
||||
mode="aspectFit"
|
||||
/>
|
||||
<view v-if="hasUnreadNotify" class="device-header__notify-badge" />
|
||||
</view>
|
||||
<view class="device-header__add-wrap">
|
||||
<view class="device-header__add-btn" @tap.stop="toggleAddMenu">
|
||||
@@ -72,6 +73,7 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import { hasUnreadMessages } from '@/hooks/use-message-inbox'
|
||||
import { staticAssets } from '@/utils/static-assets'
|
||||
|
||||
defineProps<{
|
||||
@@ -87,6 +89,7 @@ const emit = defineEmits<{
|
||||
|
||||
const pickerOpen = ref(false)
|
||||
const addMenuOpen = ref(false)
|
||||
const hasUnreadNotify = hasUnreadMessages
|
||||
|
||||
const sys = uni.getSystemInfoSync()
|
||||
const statusBarHeight = sys.statusBarHeight ?? 0
|
||||
@@ -242,10 +245,31 @@ function onScan() {
|
||||
gap: 16rpx;
|
||||
}
|
||||
|
||||
.device-header__notify-icon {
|
||||
.device-header__notify-wrap {
|
||||
position: relative;
|
||||
width: 72rpx;
|
||||
height: 72rpx;
|
||||
flex-shrink: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.device-header__notify-icon {
|
||||
width: 33rpx;
|
||||
height: 33rpx;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.device-header__notify-badge {
|
||||
position: absolute;
|
||||
top: 12rpx;
|
||||
right: 12rpx;
|
||||
width: 16rpx;
|
||||
height: 16rpx;
|
||||
border-radius: 50%;
|
||||
background: #ff4d4f;
|
||||
z-index: 2;
|
||||
}
|
||||
|
||||
.device-header__add-wrap {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { onUnload } from '@dcloudio/uni-app'
|
||||
import { ref } from 'vue'
|
||||
import { getErrorMessage } from '@/utils/api-error'
|
||||
import {
|
||||
closeBleConnection,
|
||||
ensureBleConnection,
|
||||
@@ -130,22 +131,32 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
|
||||
|
||||
const runtimePatch = context.getRuntimePatch()
|
||||
const signalLevel = rssiToSignalLevel(foundDevice?.RSSI)
|
||||
const hasBleData = Object.keys(blePayload).length > 0
|
||||
|
||||
await updateDeviceRuntime({
|
||||
deviceId,
|
||||
...runtimePatch,
|
||||
...blePayload,
|
||||
status: '1',
|
||||
bluetoothConnected: '1',
|
||||
signalLevel,
|
||||
})
|
||||
|
||||
if (!Object.keys(blePayload).length) {
|
||||
setSyncText('蓝牙已连接,等待设备上报数据…')
|
||||
} else {
|
||||
setSyncText('刚刚更新 · 数据实时同步中')
|
||||
try {
|
||||
await updateDeviceRuntime({
|
||||
deviceId,
|
||||
...runtimePatch,
|
||||
...blePayload,
|
||||
status: '1',
|
||||
bluetoothConnected: '1',
|
||||
signalLevel,
|
||||
})
|
||||
if (!hasBleData) {
|
||||
setSyncText('蓝牙已连接,等待设备上报数据…')
|
||||
} else {
|
||||
setSyncText('刚刚更新 · 数据实时同步中')
|
||||
}
|
||||
await context.onSynced?.()
|
||||
} catch (apiErr) {
|
||||
if (hasBleData) {
|
||||
setSyncText('蓝牙已连接 · 本地数据已更新,云端同步失败')
|
||||
} else {
|
||||
setSyncText(
|
||||
`蓝牙已连接 · 云端同步失败:${getErrorMessage(apiErr, '请检查网络')}`,
|
||||
)
|
||||
}
|
||||
}
|
||||
await context.onSynced?.()
|
||||
return true
|
||||
} catch (err) {
|
||||
setSyncText(getBluetoothErrorMessage(err))
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import {
|
||||
findDeviceInBleScan,
|
||||
isBluetoothApiSupported,
|
||||
rssiToSignalLevel,
|
||||
scanBluetoothDevices,
|
||||
} from '@/utils/bluetooth'
|
||||
import { sameId } from '@/utils/device-id'
|
||||
@@ -79,26 +78,28 @@ export async function refreshDevicePresence(
|
||||
})
|
||||
|
||||
void Promise.allSettled(
|
||||
nextDevices
|
||||
.filter((device) => device.deviceId && targets.some((item) => sameId(item.deviceId, device.deviceId)))
|
||||
.map(async (device) => {
|
||||
const found = findDeviceInBleScan(
|
||||
{ mac: device.mac, name: device.name },
|
||||
scanned,
|
||||
{ strictName: true },
|
||||
)
|
||||
const present = !!found
|
||||
try {
|
||||
await updateDeviceRuntime({
|
||||
deviceId: device.deviceId!,
|
||||
status: present ? '1' : '2',
|
||||
bluetoothConnected: present ? '1' : '0',
|
||||
signalLevel: present ? rssiToSignalLevel(found?.RSSI) : '0',
|
||||
})
|
||||
} catch (err) {
|
||||
logPresence('updateRuntime failed', err)
|
||||
}
|
||||
}),
|
||||
targets.map(async (device) => {
|
||||
const found = findDeviceInBleScan(
|
||||
{ mac: device.mac, name: device.name },
|
||||
scanned,
|
||||
{ strictName: true },
|
||||
)
|
||||
const present = !!found
|
||||
const nextStatus = present ? '1' : '2'
|
||||
const nextBluetooth = present ? '1' : '0'
|
||||
if (device.status === nextStatus && device.bluetoothConnected === nextBluetooth) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
await updateDeviceRuntime({
|
||||
deviceId: device.deviceId!,
|
||||
status: nextStatus,
|
||||
bluetoothConnected: nextBluetooth,
|
||||
})
|
||||
} catch (err) {
|
||||
logPresence('updateRuntime failed', err)
|
||||
}
|
||||
}),
|
||||
)
|
||||
|
||||
return nextDevices
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { onShow } from '@dcloudio/uni-app'
|
||||
import { computed, ref } from 'vue'
|
||||
import { refreshUnreadMessageCount } from '@/hooks/use-message-inbox'
|
||||
import { fetchHomeList, resolveValidHomeId } from '@/api/home'
|
||||
import { parseId, sameId } from '@/utils/device-id'
|
||||
import { createLocation } from '@/api/location'
|
||||
@@ -109,6 +110,7 @@ export function useDevice() {
|
||||
|
||||
onShow(() => {
|
||||
void loadDevices()
|
||||
void refreshUnreadMessageCount()
|
||||
})
|
||||
|
||||
function showOperationSuccess() {
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
<template>
|
||||
<view class="auth-form-page">
|
||||
<app-navbar title="忘记密码" />
|
||||
<app-navbar :title="pageTitle" />
|
||||
<view class="auth-form-page__body">
|
||||
<text class="auth-form-page__heading">忘记密码</text>
|
||||
<text class="auth-form-page__heading">{{ pageTitle }}</text>
|
||||
|
||||
<base-input v-model="phone" icon="phone" type="number" placeholder="请输入手机号" :maxlength="11" />
|
||||
<base-input v-model="code" icon="shield" type="number" placeholder="请输入验证码" :maxlength="6">
|
||||
@@ -21,7 +21,7 @@
|
||||
<script setup lang="ts">
|
||||
import { useForgotPassword } from './use-forgot-password'
|
||||
|
||||
const { phone, code, counting, seconds, onSendCode, nextStep } = useForgotPassword()
|
||||
const { phone, code, counting, seconds, pageTitle, onSendCode, nextStep } = useForgotPassword()
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { ref } from 'vue'
|
||||
import { onLoad, onShow } from '@dcloudio/uni-app'
|
||||
import { computed, ref } from 'vue'
|
||||
import { fetchProfile } from '@/api/profile'
|
||||
import { useSmsCode } from '@/hooks/use-sms-code'
|
||||
import { getErrorMessage } from '@/utils/api-error'
|
||||
import { getStoredToken } from '@/utils/auth-token'
|
||||
import { isValidPhone, isValidSmsCode } from '@/utils/validate'
|
||||
import { SMS_CODE_SCENE } from '@/types/api'
|
||||
import { verifyForgetPasswordCode } from './forgot-password.api'
|
||||
@@ -9,9 +12,29 @@ export function useForgotPassword() {
|
||||
const phone = ref('')
|
||||
const code = ref('')
|
||||
const loading = ref(false)
|
||||
const fromPrivacy = ref(false)
|
||||
|
||||
const { counting, seconds, sendCode } = useSmsCode(SMS_CODE_SCENE.reset)
|
||||
|
||||
const pageTitle = computed(() => (fromPrivacy.value ? '修改登录密码' : '忘记密码'))
|
||||
|
||||
onLoad((query) => {
|
||||
fromPrivacy.value = query?.from === 'privacy'
|
||||
})
|
||||
|
||||
async function loadBoundPhone() {
|
||||
if (!getStoredToken()) return
|
||||
try {
|
||||
const profile = await fetchProfile()
|
||||
const bound = profile?.phonenumber || profile?.userName || ''
|
||||
if (bound) {
|
||||
phone.value = bound
|
||||
}
|
||||
} catch {
|
||||
// 未登录或加载失败时保持手动输入
|
||||
}
|
||||
}
|
||||
|
||||
function onSendCode() {
|
||||
sendCode(phone.value)
|
||||
}
|
||||
@@ -34,7 +57,7 @@ export function useForgotPassword() {
|
||||
return
|
||||
}
|
||||
uni.navigateTo({
|
||||
url: `/pages/change-password/index?resetToken=${encodeURIComponent(res.resetToken)}`,
|
||||
url: `/pages/change-password/index?resetToken=${encodeURIComponent(res.resetToken)}&from=${fromPrivacy.value ? 'privacy' : 'login'}`,
|
||||
})
|
||||
} catch (err) {
|
||||
uni.showToast({ title: getErrorMessage(err, '验证失败,请重试'), icon: 'none' })
|
||||
@@ -43,5 +66,9 @@ export function useForgotPassword() {
|
||||
}
|
||||
}
|
||||
|
||||
return { phone, code, counting, seconds, onSendCode, nextStep }
|
||||
onShow(() => {
|
||||
void loadBoundPhone()
|
||||
})
|
||||
|
||||
return { phone, code, counting, seconds, pageTitle, onSendCode, nextStep }
|
||||
}
|
||||
|
||||
180
src/pages/mine/edit/components/region-picker/index.vue
Normal file
180
src/pages/mine/edit/components/region-picker/index.vue
Normal file
@@ -0,0 +1,180 @@
|
||||
<template>
|
||||
<view v-if="visible" class="region-picker">
|
||||
<view class="region-picker__mask" @tap="onCancel" />
|
||||
<view class="region-picker__panel" @tap.stop>
|
||||
<view class="region-picker__toolbar">
|
||||
<text class="region-picker__action" @tap="onCancel">取消</text>
|
||||
<text class="region-picker__title">选择所在地</text>
|
||||
<text class="region-picker__action region-picker__action--primary" @tap="onConfirm">
|
||||
确定
|
||||
</text>
|
||||
</view>
|
||||
|
||||
<picker-view
|
||||
class="region-picker__view"
|
||||
:value="pickerIndexes"
|
||||
indicator-style="height: 88rpx;"
|
||||
@change="onPickerChange"
|
||||
>
|
||||
<picker-view-column>
|
||||
<view
|
||||
v-for="item in provinceList"
|
||||
:key="`p-${item}`"
|
||||
class="region-picker__item"
|
||||
>
|
||||
{{ item }}
|
||||
</view>
|
||||
</picker-view-column>
|
||||
<picker-view-column>
|
||||
<view
|
||||
v-for="item in cityList"
|
||||
:key="`c-${item}`"
|
||||
class="region-picker__item"
|
||||
>
|
||||
{{ item }}
|
||||
</view>
|
||||
</picker-view-column>
|
||||
<picker-view-column>
|
||||
<view
|
||||
v-for="item in districtList"
|
||||
:key="`d-${item}`"
|
||||
class="region-picker__item"
|
||||
>
|
||||
{{ item }}
|
||||
</view>
|
||||
</picker-view-column>
|
||||
</picker-view>
|
||||
</view>
|
||||
</view>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import {
|
||||
findRegionIndexes,
|
||||
getCityList,
|
||||
getDistrictList,
|
||||
getProvinceList,
|
||||
getRegionByIndexes,
|
||||
} from './region-data'
|
||||
|
||||
const props = defineProps<{
|
||||
visible: boolean
|
||||
province: string
|
||||
city: string
|
||||
district: string
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:visible': [value: boolean]
|
||||
confirm: [value: { province: string; city: string; district: string }]
|
||||
}>()
|
||||
|
||||
const pickerIndexes = ref<[number, number, number]>([0, 0, 0])
|
||||
|
||||
const provinceList = computed(() => getProvinceList())
|
||||
const cityList = computed(() => getCityList(pickerIndexes.value[0]))
|
||||
const districtList = computed(() => getDistrictList(pickerIndexes.value[0], pickerIndexes.value[1]))
|
||||
|
||||
watch(
|
||||
() => props.visible,
|
||||
(show) => {
|
||||
if (!show) return
|
||||
pickerIndexes.value = findRegionIndexes(props.province, props.city, props.district)
|
||||
},
|
||||
)
|
||||
|
||||
function onPickerChange(e: { detail: { value: number[] } }) {
|
||||
const [provinceIndex, cityIndex, districtIndex] = e.detail.value as [number, number, number]
|
||||
const [prevProvinceIndex, prevCityIndex] = pickerIndexes.value
|
||||
|
||||
if (provinceIndex !== prevProvinceIndex) {
|
||||
pickerIndexes.value = [provinceIndex, 0, 0]
|
||||
return
|
||||
}
|
||||
if (cityIndex !== prevCityIndex) {
|
||||
pickerIndexes.value = [provinceIndex, cityIndex, 0]
|
||||
return
|
||||
}
|
||||
pickerIndexes.value = [provinceIndex, cityIndex, districtIndex]
|
||||
}
|
||||
|
||||
function onCancel() {
|
||||
emit('update:visible', false)
|
||||
}
|
||||
|
||||
function onConfirm() {
|
||||
emit('confirm', getRegionByIndexes(pickerIndexes.value))
|
||||
emit('update:visible', false)
|
||||
}
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.region-picker {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 600;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.region-picker__mask {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background: rgba(0, 0, 0, 0.55);
|
||||
}
|
||||
|
||||
.region-picker__panel {
|
||||
position: relative;
|
||||
background: #fff;
|
||||
border-radius: 24rpx 24rpx 0 0;
|
||||
overflow: hidden;
|
||||
z-index: 1;
|
||||
padding-bottom: env(safe-area-inset-bottom);
|
||||
}
|
||||
|
||||
.region-picker__toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
height: 96rpx;
|
||||
padding: 0 32rpx;
|
||||
border-bottom: 1rpx solid #f0f0f0;
|
||||
}
|
||||
|
||||
.region-picker__action {
|
||||
min-width: 96rpx;
|
||||
font-size: 30rpx;
|
||||
color: $color-text-secondary;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.region-picker__action--primary {
|
||||
color: $color-primary;
|
||||
font-weight: 500;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.region-picker__title {
|
||||
font-size: 32rpx;
|
||||
font-weight: 600;
|
||||
color: $color-text;
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
.region-picker__view {
|
||||
width: 100%;
|
||||
height: 480rpx;
|
||||
}
|
||||
|
||||
.region-picker__item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 88rpx;
|
||||
font-size: 30rpx;
|
||||
color: $color-text;
|
||||
line-height: 1.2;
|
||||
}
|
||||
</style>
|
||||
61
src/pages/mine/edit/components/region-picker/region-data.ts
Normal file
61
src/pages/mine/edit/components/region-picker/region-data.ts
Normal file
@@ -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 }
|
||||
}
|
||||
@@ -84,26 +84,24 @@
|
||||
|
||||
<view class="edit-profile-page__divider" />
|
||||
|
||||
<picker mode="region" :value="regionValue" @change="onRegionChange">
|
||||
<view class="edit-profile-page__item">
|
||||
<text class="edit-profile-page__label">所在地</text>
|
||||
<view class="edit-profile-page__right">
|
||||
<text
|
||||
class="edit-profile-page__value"
|
||||
:class="{
|
||||
'edit-profile-page__value--placeholder': locationText === '未设置',
|
||||
}"
|
||||
>
|
||||
{{ locationText }}
|
||||
</text>
|
||||
<image
|
||||
class="edit-profile-page__arrow"
|
||||
:src="staticAssets.iconChevronLeft"
|
||||
mode="aspectFit"
|
||||
/>
|
||||
</view>
|
||||
<view class="edit-profile-page__item" @tap="onOpenRegionPicker">
|
||||
<text class="edit-profile-page__label">所在地</text>
|
||||
<view class="edit-profile-page__right">
|
||||
<text
|
||||
class="edit-profile-page__value"
|
||||
:class="{
|
||||
'edit-profile-page__value--placeholder': locationText === '未设置',
|
||||
}"
|
||||
>
|
||||
{{ locationText }}
|
||||
</text>
|
||||
<image
|
||||
class="edit-profile-page__arrow"
|
||||
:src="staticAssets.iconChevronLeft"
|
||||
mode="aspectFit"
|
||||
/>
|
||||
</view>
|
||||
</picker>
|
||||
</view>
|
||||
|
||||
<view class="edit-profile-page__divider" />
|
||||
|
||||
@@ -144,6 +142,14 @@
|
||||
:value="form.nickName"
|
||||
@confirm="onConfirmNickname"
|
||||
/>
|
||||
|
||||
<region-picker
|
||||
v-model:visible="regionPickerVisible"
|
||||
:province="form.province"
|
||||
:city="form.city"
|
||||
:district="form.district"
|
||||
@confirm="onConfirmRegion"
|
||||
/>
|
||||
</view>
|
||||
</template>
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -49,18 +49,13 @@ export function useEditProfile() {
|
||||
const form = ref<ProfileFormState>(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,
|
||||
}
|
||||
|
||||
@@ -27,35 +27,6 @@
|
||||
</view>
|
||||
</view>
|
||||
|
||||
<view class="mine-page__stats">
|
||||
<view
|
||||
v-for="item in stats"
|
||||
:key="item.label"
|
||||
class="mine-page__stat-item"
|
||||
>
|
||||
<text class="mine-page__stat-value">{{ item.value }}</text>
|
||||
<text class="mine-page__stat-label">{{ item.label }}</text>
|
||||
</view>
|
||||
</view>
|
||||
|
||||
<view class="mine-page__quick">
|
||||
<view
|
||||
v-for="action in quickActions"
|
||||
:key="action.id"
|
||||
class="mine-page__quick-item"
|
||||
@tap="onQuickAction(action)"
|
||||
>
|
||||
<view class="mine-page__quick-icon">
|
||||
<image
|
||||
class="mine-page__quick-icon-img"
|
||||
:src="action.icon"
|
||||
mode="aspectFit"
|
||||
/>
|
||||
</view>
|
||||
<text class="mine-page__quick-label">{{ action.label }}</text>
|
||||
</view>
|
||||
</view>
|
||||
|
||||
<view class="mine-page__menu">
|
||||
<template v-for="(item, index) in menuList" :key="item.id">
|
||||
<view
|
||||
@@ -93,11 +64,8 @@ const {
|
||||
nickName,
|
||||
phone,
|
||||
avatarUrl,
|
||||
stats,
|
||||
quickActions,
|
||||
menuList,
|
||||
onEditNickname,
|
||||
onQuickAction,
|
||||
onMenuTap,
|
||||
} = useMine()
|
||||
</script>
|
||||
|
||||
@@ -1,57 +1,55 @@
|
||||
.mine-page {
|
||||
min-height: 100vh;
|
||||
background: #f5f5f5;
|
||||
background: #fff;
|
||||
padding-bottom: calc(120rpx + env(safe-area-inset-bottom));
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.mine-page__content {
|
||||
padding: 0 24rpx 24rpx;
|
||||
padding: 0 32rpx 24rpx;
|
||||
}
|
||||
|
||||
.mine-page__profile {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 24rpx;
|
||||
padding: 16rpx 8rpx 32rpx;
|
||||
padding: 16rpx 0 40rpx;
|
||||
}
|
||||
|
||||
.mine-page__avatar-wrap {
|
||||
width: 128rpx;
|
||||
height: 128rpx;
|
||||
border: 2rpx dashed #d9d9d9;
|
||||
border-radius: 20rpx;
|
||||
padding: 8rpx;
|
||||
box-sizing: border-box;
|
||||
width: 120rpx;
|
||||
height: 120rpx;
|
||||
border-radius: 50%;
|
||||
flex-shrink: 0;
|
||||
background: #fff;
|
||||
overflow: hidden;
|
||||
background: #f0f0f0;
|
||||
}
|
||||
|
||||
.mine-page__avatar {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border-radius: 12rpx;
|
||||
border-radius: 50%;
|
||||
background: #f0f0f0;
|
||||
}
|
||||
|
||||
.mine-page__avatar-placeholder {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border-radius: 12rpx;
|
||||
border-radius: 50%;
|
||||
background: #ececec;
|
||||
}
|
||||
|
||||
.mine-page__profile-meta {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
padding-top: 8rpx;
|
||||
padding-top: 4rpx;
|
||||
}
|
||||
|
||||
.mine-page__name-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10rpx;
|
||||
margin-bottom: 12rpx;
|
||||
margin-bottom: 10rpx;
|
||||
}
|
||||
|
||||
.mine-page__nickname {
|
||||
@@ -81,82 +79,16 @@
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.mine-page__stats {
|
||||
display: flex;
|
||||
background: #fff;
|
||||
border-radius: 20rpx;
|
||||
padding: 36rpx 0 32rpx;
|
||||
margin-bottom: 20rpx;
|
||||
}
|
||||
|
||||
.mine-page__stat-item {
|
||||
flex: 1;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.mine-page__stat-value {
|
||||
display: block;
|
||||
font-size: 44rpx;
|
||||
font-weight: 600;
|
||||
color: $color-text;
|
||||
line-height: 1.1;
|
||||
margin-bottom: 12rpx;
|
||||
}
|
||||
|
||||
.mine-page__stat-label {
|
||||
display: block;
|
||||
font-size: 24rpx;
|
||||
color: #999;
|
||||
line-height: 1.3;
|
||||
}
|
||||
|
||||
.mine-page__quick {
|
||||
display: flex;
|
||||
background: #fff;
|
||||
border-radius: 20rpx;
|
||||
padding: 32rpx 8rpx 28rpx;
|
||||
margin-bottom: 20rpx;
|
||||
}
|
||||
|
||||
.mine-page__quick-item {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 16rpx;
|
||||
}
|
||||
|
||||
.mine-page__quick-icon {
|
||||
width: 48rpx;
|
||||
height: 48rpx;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.mine-page__quick-icon-img {
|
||||
width: 48rpx;
|
||||
height: 48rpx;
|
||||
}
|
||||
|
||||
.mine-page__quick-label {
|
||||
font-size: 24rpx;
|
||||
color: $color-text;
|
||||
line-height: 1.3;
|
||||
}
|
||||
|
||||
.mine-page__menu {
|
||||
background: #fff;
|
||||
border-radius: 20rpx;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.mine-page__menu-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
min-height: 108rpx;
|
||||
padding: 0 28rpx 0 32rpx;
|
||||
min-height: 112rpx;
|
||||
padding: 0 8rpx;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
@@ -188,5 +120,4 @@
|
||||
.mine-page__menu-divider {
|
||||
height: 1rpx;
|
||||
background: #f0f0f0;
|
||||
margin-left: 32rpx;
|
||||
}
|
||||
|
||||
@@ -48,6 +48,7 @@
|
||||
<view v-else-if="messages.length && !hasMore" class="notify-page__footer-tip">
|
||||
没有更多了
|
||||
</view>
|
||||
|
||||
</view>
|
||||
</scroll-view>
|
||||
</view>
|
||||
|
||||
@@ -77,7 +77,14 @@
|
||||
}
|
||||
|
||||
.notify-page__empty,
|
||||
.notify-page__loading,
|
||||
.notify-page__loading {
|
||||
margin: 32rpx;
|
||||
padding: 24rpx;
|
||||
border-radius: 16rpx;
|
||||
background: #f7f8fa;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.notify-page__footer-tip {
|
||||
padding: 80rpx 32rpx;
|
||||
text-align: center;
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
import type { AppMessageVo } from '@/types/message'
|
||||
import { buildMessageFromPush, normalizeMessageId } from '@/utils/message-push'
|
||||
|
||||
export function normalizeMessageId(message: AppMessageVo): string {
|
||||
const raw = message.messageId
|
||||
if (raw === undefined || raw === null || raw === '') return ''
|
||||
return String(raw)
|
||||
}
|
||||
export { buildMessageFromPush, normalizeMessageId }
|
||||
|
||||
export function isUnreadMessage(message: AppMessageVo): boolean {
|
||||
const flag = message.readFlag
|
||||
return flag === 0 || flag === '0' || flag === false
|
||||
return flag === 0 || flag === '0'
|
||||
}
|
||||
|
||||
export function formatNotifyTime(message: AppMessageVo): string {
|
||||
@@ -16,7 +13,9 @@ export function formatNotifyTime(message: AppMessageVo): string {
|
||||
if (!raw) return ''
|
||||
const text = String(raw).trim()
|
||||
if (/^\d{2}:\d{2}$/.test(text)) return text
|
||||
const date = new Date(text)
|
||||
|
||||
const date = /^\d{13,}$/.test(text) ? new Date(Number(text)) : new Date(text)
|
||||
if (Number.isNaN(date.getTime())) return text
|
||||
return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
|
||||
}
|
||||
|
||||
|
||||
@@ -1,11 +1,25 @@
|
||||
import { onShow, onUnload } from '@dcloudio/uni-app'
|
||||
import { computed, ref } from 'vue'
|
||||
import { fetchMessagePage, markAllMessagesRead, markMessageRead } from '@/api/message'
|
||||
import {
|
||||
fetchMessagePage,
|
||||
markAllMessagesRead,
|
||||
markMessageRead,
|
||||
} from '@/api/message'
|
||||
import { refreshUnreadMessageCount } from '@/hooks/use-message-inbox'
|
||||
import { getErrorMessage } from '@/utils/api-error'
|
||||
import { onMessagePush } from '@/utils/message-socket'
|
||||
import {
|
||||
clearPushCache,
|
||||
forgetCachedMessage,
|
||||
mergeCachedMessages,
|
||||
rememberPushPayload,
|
||||
} from '@/utils/message-push-cache'
|
||||
import type { AppMessageVo } from '@/types/message'
|
||||
import { formatNotifyTime, isUnreadMessage, normalizeMessageId } from './notify.utils'
|
||||
import {
|
||||
formatNotifyTime,
|
||||
isUnreadMessage,
|
||||
normalizeMessageId,
|
||||
} from './notify.utils'
|
||||
|
||||
const PAGE_SIZE = 20
|
||||
|
||||
@@ -36,17 +50,18 @@ export function useNotify() {
|
||||
pageNum: pageNum.value,
|
||||
pageSize: PAGE_SIZE,
|
||||
})
|
||||
total.value = nextTotal
|
||||
const mergedRows = mergeCachedMessages(rows)
|
||||
if (reset) {
|
||||
messages.value = rows
|
||||
messages.value = mergedRows
|
||||
} else {
|
||||
const map = new Map<string, AppMessageVo>()
|
||||
for (const item of [...messages.value, ...rows]) {
|
||||
for (const item of [...messages.value, ...mergedRows]) {
|
||||
const id = normalizeMessageId(item)
|
||||
if (id) map.set(id, item)
|
||||
}
|
||||
messages.value = Array.from(map.values())
|
||||
}
|
||||
total.value = Math.max(nextTotal, messages.value.length)
|
||||
const homeName = rows.find((item) => item.homeName)?.homeName
|
||||
if (homeName) sectionTitle.value = homeName
|
||||
if (rows.length > 0) {
|
||||
@@ -76,10 +91,11 @@ export function useNotify() {
|
||||
if (isUnreadMessage(message)) {
|
||||
try {
|
||||
await markMessageRead(messageId)
|
||||
forgetCachedMessage(messageId)
|
||||
messages.value = messages.value.map((item) =>
|
||||
normalizeMessageId(item) === messageId ? { ...item, readFlag: '1' } : item,
|
||||
)
|
||||
await refreshUnreadMessageCount()
|
||||
await refreshUnreadMessageCount(true)
|
||||
} catch (err) {
|
||||
uni.showToast({ title: getErrorMessage(err, '标记已读失败'), icon: 'none' })
|
||||
}
|
||||
@@ -96,19 +112,33 @@ export function useNotify() {
|
||||
async function onMarkAllRead() {
|
||||
try {
|
||||
await markAllMessagesRead()
|
||||
clearPushCache()
|
||||
messages.value = messages.value.map((item) => ({ ...item, readFlag: '1' }))
|
||||
await refreshUnreadMessageCount()
|
||||
await refreshUnreadMessageCount(true)
|
||||
uni.showToast({ title: '已全部标为已读', icon: 'none' })
|
||||
} catch (err) {
|
||||
uni.showToast({ title: getErrorMessage(err, '操作失败'), icon: 'none' })
|
||||
}
|
||||
}
|
||||
|
||||
function prependPushMessage(payload: Parameters<typeof rememberPushPayload>[0]) {
|
||||
const incoming = rememberPushPayload(payload)
|
||||
if (!incoming) return
|
||||
|
||||
const incomingId = normalizeMessageId(incoming)
|
||||
const exists = messages.value.some((item) => normalizeMessageId(item) === incomingId)
|
||||
if (exists) return
|
||||
|
||||
messages.value = mergeCachedMessages(messages.value)
|
||||
total.value = messages.value.length
|
||||
}
|
||||
|
||||
onShow(() => {
|
||||
void onRefresh()
|
||||
unsubscribePush = onMessagePush(() => {
|
||||
void onRefresh()
|
||||
unsubscribePush?.()
|
||||
unsubscribePush = onMessagePush((payload) => {
|
||||
prependPushMessage(payload)
|
||||
})
|
||||
void onRefresh()
|
||||
})
|
||||
|
||||
onUnload(() => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { onShow } from '@dcloudio/uni-app'
|
||||
import { computed, ref } from 'vue'
|
||||
import { logout } from '@/api/auth'
|
||||
import { cancelAccount, logout } from '@/api/auth'
|
||||
import { fetchProfile } from '@/api/profile'
|
||||
import { getErrorMessage } from '@/utils/api-error'
|
||||
import { teardownMessageInbox } from '@/hooks/use-message-inbox'
|
||||
@@ -58,7 +58,7 @@ export function usePrivacy() {
|
||||
|
||||
function onItemTap(itemId: string) {
|
||||
if (itemId === 'password') {
|
||||
uni.navigateTo({ url: '/pages/mine/set-password/verify/index' })
|
||||
uni.navigateTo({ url: '/pages/forgot-password/index?from=privacy' })
|
||||
return
|
||||
}
|
||||
if (itemId === 'phone') {
|
||||
@@ -72,7 +72,17 @@ export function usePrivacy() {
|
||||
confirmColor: '#f04438',
|
||||
success: (res) => {
|
||||
if (!res.confirm) return
|
||||
uni.showToast({ title: '注销功能待对接', icon: 'none' })
|
||||
void (async () => {
|
||||
try {
|
||||
await cancelAccount()
|
||||
teardownMessageInbox()
|
||||
clearStoredToken()
|
||||
uni.showToast({ title: '账号已注销', icon: 'success' })
|
||||
uni.reLaunch({ url: '/pages/login/index' })
|
||||
} catch (err) {
|
||||
uni.showToast({ title: getErrorMessage(err, '注销失败'), icon: 'none' })
|
||||
}
|
||||
})()
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,85 +1,18 @@
|
||||
import { onShow } from '@dcloudio/uni-app'
|
||||
import { computed, ref } from 'vue'
|
||||
import { fetchProfile } from '@/api/profile'
|
||||
import { useSmsCode } from '@/hooks/use-sms-code'
|
||||
import { SMS_CODE_SCENE } from '@/types/api'
|
||||
import { getErrorMessage } from '@/utils/api-error'
|
||||
import { isValidSmsCode } from '@/utils/validate'
|
||||
import { verifySetPasswordCode } from '../set-password.api'
|
||||
|
||||
function maskPhone(phone: string): string {
|
||||
const digits = phone.replace(/\D/g, '')
|
||||
if (digits.length < 7) return phone
|
||||
return digits.replace(/(\d{3})\d{4}(\d+)/, '$1****$2')
|
||||
}
|
||||
import { onLoad } from '@dcloudio/uni-app'
|
||||
import { ref } from 'vue'
|
||||
|
||||
/** 兼容旧入口,统一跳转到忘记密码流程 */
|
||||
export function useSetPasswordPhone() {
|
||||
const boundPhone = ref('')
|
||||
const code = ref('')
|
||||
const loading = ref(false)
|
||||
|
||||
const { counting, seconds, sendCode } = useSmsCode(SMS_CODE_SCENE.reset)
|
||||
|
||||
const maskedPhone = computed(() => maskPhone(boundPhone.value))
|
||||
|
||||
async function loadBoundPhone() {
|
||||
try {
|
||||
const profile = await fetchProfile()
|
||||
boundPhone.value = profile?.phonenumber || profile?.userName || ''
|
||||
if (!boundPhone.value) {
|
||||
uni.showToast({ title: '未绑定手机号', icon: 'none' })
|
||||
}
|
||||
} catch (err) {
|
||||
uni.showToast({ title: getErrorMessage(err, '加载账号信息失败'), icon: 'none' })
|
||||
}
|
||||
}
|
||||
|
||||
function onSendCode() {
|
||||
if (!boundPhone.value) {
|
||||
uni.showToast({ title: '未绑定手机号', icon: 'none' })
|
||||
return
|
||||
}
|
||||
sendCode(boundPhone.value)
|
||||
}
|
||||
|
||||
async function nextStep() {
|
||||
if (!boundPhone.value) {
|
||||
uni.showToast({ title: '未绑定手机号', icon: 'none' })
|
||||
return
|
||||
}
|
||||
if (!isValidSmsCode(code.value)) {
|
||||
uni.showToast({ title: '请输入验证码', icon: 'none' })
|
||||
return
|
||||
}
|
||||
if (loading.value) return
|
||||
|
||||
loading.value = true
|
||||
try {
|
||||
const res = await verifySetPasswordCode({ phone: boundPhone.value, code: code.value })
|
||||
if (!res.resetToken) {
|
||||
uni.showToast({ title: '验证失败,未获取重置令牌', icon: 'none' })
|
||||
return
|
||||
}
|
||||
uni.navigateTo({
|
||||
url: `/pages/mine/set-password/index?resetToken=${encodeURIComponent(res.resetToken)}`,
|
||||
})
|
||||
} catch (err) {
|
||||
uni.showToast({ title: getErrorMessage(err, '验证失败,请重试'), icon: 'none' })
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onShow(() => {
|
||||
void loadBoundPhone()
|
||||
onLoad(() => {
|
||||
uni.redirectTo({ url: '/pages/forgot-password/index?from=privacy' })
|
||||
})
|
||||
|
||||
return {
|
||||
code,
|
||||
maskedPhone,
|
||||
counting,
|
||||
seconds,
|
||||
onSendCode,
|
||||
nextStep,
|
||||
code: ref(''),
|
||||
maskedPhone: ref(''),
|
||||
counting: ref(false),
|
||||
seconds: ref(0),
|
||||
onSendCode: () => {},
|
||||
nextStep: () => {},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,63 +1,26 @@
|
||||
import { onLoad } from '@dcloudio/uni-app'
|
||||
import { ref } from 'vue'
|
||||
import { getErrorMessage } from '@/utils/api-error'
|
||||
import { isValidStrongPassword } from '@/utils/validate'
|
||||
import { resetPasswordByToken } from './set-password.api'
|
||||
|
||||
/** 兼容旧入口,统一跳转到忘记密码流程 */
|
||||
export function useSetPassword() {
|
||||
const password = ref('')
|
||||
const confirmPassword = ref('')
|
||||
const resetToken = ref('')
|
||||
const loading = ref(false)
|
||||
|
||||
onLoad((query) => {
|
||||
const raw = (query?.resetToken as string) || ''
|
||||
resetToken.value = raw ? decodeURIComponent(raw) : ''
|
||||
if (!resetToken.value) {
|
||||
uni.showToast({ title: '请先完成身份验证', icon: 'none' })
|
||||
setTimeout(() => uni.navigateBack(), 1500)
|
||||
const resetToken = raw ? decodeURIComponent(raw) : ''
|
||||
if (resetToken) {
|
||||
uni.redirectTo({
|
||||
url: `/pages/change-password/index?resetToken=${encodeURIComponent(resetToken)}&from=privacy`,
|
||||
})
|
||||
return
|
||||
}
|
||||
uni.redirectTo({ url: '/pages/forgot-password/index?from=privacy' })
|
||||
})
|
||||
|
||||
function onForgotPassword() {
|
||||
uni.navigateTo({ url: '/pages/forgot-password/index' })
|
||||
return {
|
||||
password: ref(''),
|
||||
confirmPassword: ref(''),
|
||||
onForgotPassword: () => {
|
||||
uni.navigateTo({ url: '/pages/forgot-password/index?from=privacy' })
|
||||
},
|
||||
submit: () => {},
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
if (!resetToken.value) {
|
||||
uni.showToast({ title: '重置令牌无效', icon: 'none' })
|
||||
return
|
||||
}
|
||||
if (!isValidStrongPassword(password.value)) {
|
||||
uni.showToast({
|
||||
title: '密码需8-20位,且包含字母、数字、符号中至少2种',
|
||||
icon: 'none',
|
||||
})
|
||||
return
|
||||
}
|
||||
if (password.value !== confirmPassword.value) {
|
||||
uni.showToast({ title: '两次密码不一致', icon: 'none' })
|
||||
return
|
||||
}
|
||||
if (loading.value) return
|
||||
|
||||
loading.value = true
|
||||
try {
|
||||
await resetPasswordByToken({
|
||||
resetToken: resetToken.value,
|
||||
newPassword: password.value,
|
||||
confirmPassword: confirmPassword.value,
|
||||
})
|
||||
uni.showToast({ title: '密码修改成功', icon: 'success' })
|
||||
setTimeout(() => {
|
||||
uni.navigateBack({ delta: 3 })
|
||||
}, 1200)
|
||||
} catch (err) {
|
||||
uni.showToast({ title: getErrorMessage(err, '修改失败,请重试'), icon: 'none' })
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
return { password, confirmPassword, onForgotPassword, submit }
|
||||
}
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
import { onLoad } from '@dcloudio/uni-app'
|
||||
|
||||
/** 兼容旧入口,统一跳转到忘记密码流程 */
|
||||
export function useSetPasswordVerify() {
|
||||
onLoad(() => {
|
||||
uni.redirectTo({ url: '/pages/forgot-password/index?from=privacy' })
|
||||
})
|
||||
|
||||
function onPhoneVerify() {
|
||||
uni.navigateTo({ url: '/pages/mine/set-password/phone/index' })
|
||||
uni.redirectTo({ url: '/pages/forgot-password/index?from=privacy' })
|
||||
}
|
||||
|
||||
return { onPhoneVerify }
|
||||
|
||||
@@ -85,9 +85,6 @@
|
||||
>
|
||||
<text>{{ item.content }}</text>
|
||||
</view>
|
||||
<text v-if="item.time" class="support-page__bubble-time">
|
||||
{{ item.time }}
|
||||
</text>
|
||||
</view>
|
||||
|
||||
<view v-if="item.role === 'user'" class="support-page__msg-avatar support-page__msg-avatar--user">
|
||||
@@ -205,7 +202,6 @@
|
||||
>
|
||||
<view class="support-page__image-wrap">
|
||||
<image class="support-page__image" :src="item.src" mode="aspectFill" />
|
||||
<text v-if="item.time" class="support-page__bubble-time">{{ item.time }}</text>
|
||||
</view>
|
||||
<view class="support-page__msg-avatar support-page__msg-avatar--user">我</view>
|
||||
</view>
|
||||
@@ -215,6 +211,9 @@
|
||||
</scroll-view>
|
||||
|
||||
<view class="support-page__footer">
|
||||
<text class="support-page__secure">
|
||||
本次会话已加密,客服不会向您索要密码或验证码
|
||||
</text>
|
||||
<view class="support-page__footer-shortcuts">
|
||||
<text
|
||||
v-for="shortcut in footerShortcuts"
|
||||
@@ -226,14 +225,17 @@
|
||||
</text>
|
||||
</view>
|
||||
<view class="support-page__input-row">
|
||||
<view class="support-page__mic">
|
||||
<view class="support-page__mic" @tap="toggleInputMode">
|
||||
<image
|
||||
v-if="inputMode === 'text'"
|
||||
class="support-page__mic-icon"
|
||||
:src="staticAssets.iconSupportMic"
|
||||
mode="aspectFit"
|
||||
/>
|
||||
<text v-else class="support-page__keyboard-icon">⌨</text>
|
||||
</view>
|
||||
<view class="support-page__input-wrap">
|
||||
|
||||
<view v-if="inputMode === 'text'" class="support-page__input-wrap">
|
||||
<input
|
||||
v-model="inputValue"
|
||||
class="support-page__input"
|
||||
@@ -244,24 +246,39 @@
|
||||
@confirm="onSend"
|
||||
/>
|
||||
</view>
|
||||
<view class="support-page__tag">
|
||||
<image
|
||||
class="support-page__tag-icon"
|
||||
:src="staticAssets.iconSupportTag"
|
||||
mode="aspectFit"
|
||||
/>
|
||||
</view>
|
||||
<view class="support-page__send" @tap="onSend">
|
||||
<image
|
||||
class="support-page__send-icon"
|
||||
:src="staticAssets.iconSupportSend"
|
||||
mode="aspectFit"
|
||||
/>
|
||||
<view
|
||||
v-else
|
||||
class="support-page__voice-btn"
|
||||
:class="{
|
||||
'support-page__voice-btn--holding': voiceHolding,
|
||||
'support-page__voice-btn--recognizing': voiceRecognizing,
|
||||
}"
|
||||
@touchstart.prevent="onVoiceTouchStart"
|
||||
@touchend.prevent="onVoiceTouchEnd"
|
||||
@touchcancel.prevent="onVoiceTouchCancel"
|
||||
>
|
||||
<text class="support-page__voice-btn-text">
|
||||
{{ voiceButtonText }}
|
||||
</text>
|
||||
</view>
|
||||
|
||||
<template v-if="inputMode === 'text'">
|
||||
<view class="support-page__tag">
|
||||
<image
|
||||
class="support-page__tag-icon"
|
||||
:src="staticAssets.iconSupportTag"
|
||||
mode="aspectFit"
|
||||
/>
|
||||
</view>
|
||||
<view class="support-page__send" @tap="onSend">
|
||||
<image
|
||||
class="support-page__send-icon"
|
||||
:src="staticAssets.iconSupportSend"
|
||||
mode="aspectFit"
|
||||
/>
|
||||
</view>
|
||||
</template>
|
||||
</view>
|
||||
<text class="support-page__secure">
|
||||
本次会话已加密,客服不会向您索要密码或验证码
|
||||
</text>
|
||||
</view>
|
||||
</view>
|
||||
</template>
|
||||
@@ -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(
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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<string, unkn
|
||||
type: 'image',
|
||||
role: 'user',
|
||||
src,
|
||||
time: formatMessageTime(message.createTime),
|
||||
createTime: message.createTime,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -202,7 +253,7 @@ export function mapCsMessage(message: CsMessageVo): SupportMessage | null {
|
||||
type: 'image',
|
||||
role: 'user',
|
||||
src: content,
|
||||
time: formatMessageTime(message.createTime),
|
||||
createTime: message.createTime,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -225,7 +276,7 @@ export function mapCsMessage(message: CsMessageVo): SupportMessage | null {
|
||||
type: 'text',
|
||||
role,
|
||||
content,
|
||||
time: formatMessageTime(message.createTime),
|
||||
createTime: message.createTime,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
336
src/pages/mine/support/use-support-voice.ts
Normal file
336
src/pages/mine/support/use-support-voice.ts
Normal file
@@ -0,0 +1,336 @@
|
||||
import { onBeforeUnmount, ref } from 'vue'
|
||||
|
||||
type InputMode = 'text' | 'voice'
|
||||
|
||||
interface UseSupportVoiceOptions {
|
||||
onRecognized: (text: string) => void
|
||||
}
|
||||
|
||||
interface SpeechRecognitionInstance {
|
||||
lang: string
|
||||
continuous: boolean
|
||||
interimResults: boolean
|
||||
start: () => void
|
||||
stop: () => void
|
||||
abort: () => void
|
||||
onresult: ((event: { results: Array<Array<{ transcript?: string }>> }) => 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<InputMode>('text')
|
||||
const voiceHolding = ref(false)
|
||||
const voiceRecognizing = ref(false)
|
||||
|
||||
let touchCanceled = false
|
||||
let recordStopTimer: ReturnType<typeof setTimeout> | 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<typeof mpRecoManager>
|
||||
}
|
||||
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<boolean> {
|
||||
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,
|
||||
}
|
||||
}
|
||||
@@ -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() {
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
|
||||
BIN
src/static/通知 (1).png
Normal file
BIN
src/static/通知 (1).png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 6.0 KiB |
58
src/utils/message-push-cache.ts
Normal file
58
src/utils/message-push-cache.ts
Normal file
@@ -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<string, AppMessageVo>()
|
||||
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<string, AppMessageVo>()
|
||||
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
|
||||
}
|
||||
114
src/utils/message-push.ts
Normal file
114
src/utils/message-push.ts
Normal file
@@ -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<string, unknown> | null {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) return null
|
||||
return value as Record<string, unknown>
|
||||
}
|
||||
|
||||
function pickString(obj: Record<string, unknown>, 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<string, unknown>, 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<string, unknown>,
|
||||
): 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<string, unknown>
|
||||
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
|
||||
}
|
||||
@@ -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<typeof setInterval> | null = null
|
||||
let reconnectTimer: ReturnType<typeof setTimeout> | 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
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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<string[]> {
|
||||
const maxWaitMs = options.maxWaitMs ?? 6000
|
||||
const idleMs = options.idleMgs ?? 400
|
||||
const idleMs = options.idleMs ?? 400
|
||||
let buffer = ''
|
||||
let settled = false
|
||||
|
||||
|
||||
Reference in New Issue
Block a user