rk
17 小时以前 fa4c7baec36d58b4bdca66159ece743b5a45a9c8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
<script>
    import { mapState } from 'vuex'
    import md5 from 'js-md5';
    import { getLocationWithNotice } from '@/utils/utils'
    export default {
        data() {
            return {
                locationTimer: null,
                jpushModule: null,
                tts: null,
                ttsPlatform: '',
                ttsVoice: null,
                hasGrantedLocationPermission: false
            }
        },
        computed: {
            ...mapState(['userInfo', 'token'])
        },
        watch: {
            token(newVal) {
                if (newVal) {
                    this.bindJPushAlias()
                } else {
                    this.stopLocationPolling()
                    this.deleteJPushAlias()
                }
            }
        },
        onLaunch: function() {
            uni.$on('locationPermissionGranted', this.handleLocationPermissionGranted)
            uni.$on('loginSuccessStartLocationPolling', this.handleLoginSuccessStartLocationPolling)
            uni.$on('privacyAgreed', this.handlePrivacyAgreed)
            // 检查是否已经同意过隐私政策,如果是则直接初始化极光推送
            console.log('login_privacy_policy_agreed', uni.getStorageSync('login_privacy_policy_agreed'))
            if (uni.getStorageSync('login_privacy_policy_agreed')) {
                // 初始化极光推送
                this.initJPush()
                // 初始化语音播报
                this.initTTS()
                // 获取版本号
                this.checkAppUpdate()
            }
        },
        onShow: function() {
            console.log('App Show')
        },
        onHide: function() {
            console.log('App Hide')
        },
        onUnload() {
            uni.$off('locationPermissionGranted', this.handleLocationPermissionGranted)
            uni.$off('loginSuccessStartLocationPolling', this.handleLoginSuccessStartLocationPolling)
            uni.$off('privacyAgreed', this.handlePrivacyAgreed)
            if (this.tts) {
                try {
                    if (this.ttsPlatform === 'android') {
                        this.tts.stop()
                        this.tts.shutdown()
                    } else if (this.ttsPlatform === 'ios') {
                        this.tts.stopSpeakingAtBoundary(0)
                    }
                } catch (e) {
                    console.log('释放语音播报失败', e)
                }
            }
            this.stopLocationPolling()
        },
        methods: {
            handleLoginSuccessStartLocationPolling() {
                if (this.locationTimer) return
                if (this.hasGrantedLocationPermission) {
                    console.log('登录成功后开始位置轮询上报')
                    this.startLocationPolling()
                    return
                }
                this.checkAndStartLocationPolling()
            },
            handlePrivacyAgreed() {
                console.log('隐私政策已同意,初始化极光推送')
                this.initJPush()
            },
            handleLocationPermissionGranted() {
                this.hasGrantedLocationPermission = true
                if (!this.token || this.locationTimer) return
                console.log('定位授权成功,开始位置轮询上报')
                this.startLocationPolling()
            },
            initTTS() {
                const platform = uni.getSystemInfoSync().platform
                this.ttsPlatform = platform
 
                if (platform === 'android') {
                    try {
                        const TextToSpeech = plus.android.importClass('android.speech.tts.TextToSpeech')
                        const Locale = plus.android.importClass('java.util.Locale')
 
                        this.tts = new TextToSpeech(plus.android.runtimeMainActivity(), {
                            onInit: (status) => {
                                if (status == 0) {
                                    this.tts.setLanguage(Locale.CHINA)
                                    console.log('安卓语音初始化成功')
                                }
                            }
                        })
                    } catch (e) {
                        console.log('安卓语音初始化失败', e)
                    }
                    return
                }
 
                if (platform === 'ios') {
                    try {
                        const AVSpeechSynthesizer = plus.ios.importClass('AVSpeechSynthesizer')
                        const AVSpeechSynthesisVoice = plus.ios.importClass('AVSpeechSynthesisVoice')
                        this.tts = new AVSpeechSynthesizer()
                        this.ttsVoice = AVSpeechSynthesisVoice.voiceWithLanguage('zh-CN')
                        console.log('iOS语音初始化成功')
                    } catch (e) {
                        console.log('iOS语音初始化失败', e)
                    }
                    return
                }
 
                console.log('当前平台暂不支持语音播报')
            },
            speak(text) {
                if (!this.tts) {
                    uni.showToast({
                        title: '语音未准备好',
                        icon: 'none'
                    })
                    return
                }
 
                try {
                    if (this.ttsPlatform === 'android') {
                        this.tts.speak(text, 0, null)
                        return
                    }
 
                    if (this.ttsPlatform === 'ios') {
                        const content = String(text || '').trim()
                        if (!content) return
                        const AVSpeechUtterance = plus.ios.importClass('AVSpeechUtterance')
                        const utterance = AVSpeechUtterance.speechUtteranceWithString(content)
                        if (this.ttsVoice) {
                            utterance.setVoice(this.ttsVoice)
                        }
                        utterance.setRate(0.5)
                        utterance.setVolume(1)
                        utterance.setPitchMultiplier(1)
                        this.tts.stopSpeakingAtBoundary(0)
                        this.tts.speakUtterance(utterance)
                    }
                } catch (err) {
                    console.log('播报失败', err)
                }
            },
            initJPush() {
                console.log('开始初始化极光推送...')
                // #ifdef APP-PLUS
                let jpushModule = null
                try {
                    jpushModule = uni.requireNativePlugin('JG-JPush')
                } catch (e) {
                    console.error('加载极光推送插件失败:', e)
                    return
                }
                if (!jpushModule) {
                    console.error('极光推送插件未找到')
                    return
                }
                this.jpushModule = jpushModule
                console.log('极光推送插件加载成功,模块:', typeof jpushModule)
                console.log('模块方法:', Object.keys(jpushModule))
 
                if (typeof jpushModule.initJPushService === 'function') {
                    jpushModule.initJPushService()
                    console.log('极光推送initJPushService调用成功')
                } else {
                    console.error('jpushModule.initJPushService 不是函数,当前方法:', typeof jpushModule.initJPushService)
                    return
                }
 
                if (typeof jpushModule.setLoggerEnable === 'function') {
                    jpushModule.setLoggerEnable(true)
                }
                console.log('极光推送初始化完成,设置监听器...')
                this.setupJPushListeners()
                this.getRegistrationID()
                // #endif
            },
 
            setupJPushListeners() {
                var that = this
                if (!this.jpushModule) return
 
                // 监听连接状态
                this.jpushModule.addConnectEventListener((result) => {
                    console.log('极光连接状态:', result.connectEnable)
                })
 
                // 监听通知
                this.jpushModule.addNotificationListener((result) => {
                    console.log('收到通知:', JSON.stringify(result))
                    that.speak(result.content || '')
                    const notificationEventType = result.notificationEventType
                    // notificationOpened = 点击通知
                    if (notificationEventType === 'notificationOpened') {
                        console.log('通知被点击', result.extras)
                        const extras = result.extras ? result.extras : {}
                        if (extras.type === 'new_order' && extras.orderId) {
                            uni.navigateTo({
                                url: '/pages/order-detail/order-detail?id=' + extras.orderId
                            })
                        } else {
                            uni.switchTab({
                                url: '/pages/index/index'
                            })
                        }
                    }
                })
            },
 
            getRegistrationID() {
                if (!this.jpushModule) {
                    console.log('JPush模块未初始化,无法获取RegistrationID')
                    return
                }
                console.log('开始获取JPush RegistrationID...')
                this.jpushModule.getRegistrationID((result) => {
                    console.log('JPush getRegistrationID result:', JSON.stringify(result))
                    if (result && result.registerID) {
                        console.log('JPush RegistrationID获取成功:', result.registerID)
                        uni.setStorageSync('jpush_registration_id', result.registerID)
                    } else {
                        console.log('JPush RegistrationID获取失败,尝试重新获取')
                        setTimeout(() => {
                            this.getRegistrationID()
                        }, 2000)
                    }
                })
            },
 
            bindJPushAlias() {
                if (!this.token) return
                if (!this.jpushModule) {
                    console.log('JPush未初始化,延迟设置别名')
                    setTimeout(() => {
                        this.bindJPushAlias()
                    }, 1000)
                    return
                }
                // 优先从store获取,如果为空则从本地存储获取
                let telephone = this.$store.state.userInfo?.telephone || ''
                if (!telephone) {
                    telephone = uni.getStorageSync('userInfo')?.telephone || ''
                }
                if (!telephone) {
                    console.log('用户手机号为空,延迟获取...')
                    setTimeout(() => {
                        this.bindJPushAlias()
                    }, 2000)
                    return
                }
                const alias = md5(telephone)
                console.log('设置极光别名:', alias)
                this.jpushModule.setAlias({
                    alias: alias,
                    sequence: Date.now()
                }, (result) => {
                    console.log('设置别名结果:', JSON.stringify(result))
                    if (result && (result.code === 0 || result.errCode === 0)) {
                        console.log('设置极光别名成功')
                    } else {
                        console.log('设置极光别名失败')
                    }
                })
            },
 
            deleteJPushAlias() {
                if (!this.jpushModule) return
                this.jpushModule.deleteAlias({
                    sequence: Date.now()
                }, (result) => {
                    console.log('删除极光别名:', JSON.stringify(result))
                })
            },
 
            checkAndStartLocationPolling() {
                if (!this.token) return
                getLocationWithNotice({
                    type: 'gcj02',
                    success: (res) => {
                        console.log('获取定位权限成功,开始定时更新位置')
                        this.startLocationPolling()
                    },
                    fail: (err) => {
                        // console.log('获取定位权限失败:', err.errMsg)
                        // uni.showToast({
                        //     title: '需要定位权限才能更新位置',
                        //     icon: 'none'
                        // })
                    }
                }).catch(() => {})
            },
 
            startLocationPolling() {
                this.stopLocationPolling()
                this.updateLocation()
                this.locationTimer = setInterval(() => {
                    this.updateLocation()
                }, 60000)
            },
 
            stopLocationPolling() {
                if (this.locationTimer) {
                    clearInterval(this.locationTimer)
                    this.locationTimer = null
                }
            },
 
            updateLocation() {
                if (!this.token) return
                var that = this;
                getLocationWithNotice({
                    type: 'gcj02',
                    success: (res) => {
                        console.log('定时更新位置:', res.latitude, res.longitude)
                        that.$store.commit('setLocation', { latitude: res.latitude, longitude: res.longitude })
                        that.$u.api.updateLocation({
                            latitude: res.latitude,
                            longitude: res.longitude
                        }).then(res => {
                            if (res.code === 200) {
                                console.log('更新位置成功')
                            } else {
                                console.log('更新位置失败')
                            }
                        }).catch(err => {
                            console.log('更新位置请求失败:', err)
                        })
                    },
                    fail: (err) => {
                        console.log('获取位置失败:', err.errMsg)
                    }
                }).catch(() => {})
            },
 
            checkAppUpdate() {
                plus.runtime.getProperty(plus.runtime.appid, (inf) => {
                    const currentVersion = inf.versionCode
                    this.$u.api.getApiVersion({ type: 0 }).then(res => {
                        if (res.code === 200 && res.data) {
                            const latestVersion = res.data.versionNum
                            if (latestVersion > currentVersion) {
                                if (res.data.isForce === 1) {
                                    this.showForceUpdateDialog(res.data.fileUrl, res.data.versionNum)
                                } else {
                                    this.showOptionalUpdateDialog(res.data.fileUrl, res.data.versionNum)
                                }
                            }
                        }
                    })
                })
            },
 
            showForceUpdateDialog(fileUrl, version) {
                uni.showModal({
                    title: '版本更新',
                    content: `检测到新版本${version},请更新后继续使用`,
                    showCancel: false,
                    confirmText: '立即更新',
                    success: () => {
                        plus.runtime.openURL(fileUrl)
                    }
                })
            },
 
            showOptionalUpdateDialog(fileUrl, version) {
                uni.showModal({
                    title: '版本更新',
                    content: `检测到新版本${version},是否更新?`,
                    confirmText: '更新',
                    cancelText: '稍后',
                    success: (res) => {
                        if (res.confirm) {
                            plus.runtime.openURL(fileUrl)
                        }
                    }
                })
            }
        }
    }
</script>
 
<style>
    page {
        background-color: #f6f8fc;
    }
    uni-mp-share {
        display: none !important;
    }
</style>