hookehuyr

feat(网络): 添加弱网检测和离线模式处理逻辑

在应用启动时检测网络状态,当网络较弱时提示用户使用缓存的预约码进入离线模式
1 /* 1 /*
2 * @Date: 2025-06-28 10:33:00 2 * @Date: 2025-06-28 10:33:00
3 * @LastEditors: hookehuyr hookehuyr@gmail.com 3 * @LastEditors: hookehuyr hookehuyr@gmail.com
4 - * @LastEditTime: 2026-01-13 00:28:35 4 + * @LastEditTime: 2026-01-13 13:49:42
5 * @FilePath: /xyxBooking-weapp/src/app.js 5 * @FilePath: /xyxBooking-weapp/src/app.js
6 * @Description: 应用入口文件 6 * @Description: 应用入口文件
7 */ 7 */
...@@ -14,6 +14,8 @@ import Taro from '@tarojs/taro' ...@@ -14,6 +14,8 @@ import Taro from '@tarojs/taro'
14 import { qrcodeListAPI } from '@/api/index' 14 import { qrcodeListAPI } from '@/api/index'
15 import { formatDatetime } from '@/utils/tools' 15 import { formatDatetime } from '@/utils/tools'
16 16
17 +let has_shown_network_modal = false
18 +
17 /** 19 /**
18 * 格式化支付记录,按 pay_id 分组,相同 pay_id 下的记录 sort 为 0,否则为 1 20 * 格式化支付记录,按 pay_id 分组,相同 pay_id 下的记录 sort 为 0,否则为 1
19 * @param {*} data 支付记录数组 21 * @param {*} data 支付记录数组
...@@ -99,6 +101,69 @@ const App = createApp({ ...@@ -99,6 +101,69 @@ const App = createApp({
99 return ['wifi', '4g', '5g', '3g'].includes(network_type) 101 return ['wifi', '4g', '5g', '3g'].includes(network_type)
100 } 102 }
101 103
104 + const get_network_type = async () => {
105 + try {
106 + const result = await new Promise((resolve, reject) => {
107 + Taro.getNetworkType({
108 + success: resolve,
109 + fail: reject,
110 + })
111 + })
112 + return result?.networkType || 'unknown'
113 + } catch (e) {
114 + return 'unknown'
115 + }
116 + }
117 +
118 + const has_offline_qr_cache = () => {
119 + try {
120 + const data = Taro.getStorageSync('OFFLINE_QR_DATA')
121 + return Array.isArray(data) && data.length > 0
122 + } catch (e) {
123 + return false
124 + }
125 + }
126 +
127 + const handle_bad_network_on_launch = async () => {
128 + if (has_shown_network_modal) return false
129 +
130 + const network_type = await get_network_type()
131 + const is_none_network = network_type === 'none'
132 + const is_weak_network = !is_usable_network(network_type)
133 +
134 + if (!is_weak_network) return false
135 +
136 + has_shown_network_modal = true
137 +
138 + if (has_offline_qr_cache()) {
139 + try {
140 + const modal_res = await Taro.showModal({
141 + title: '网络连接不畅',
142 + content: '当前网络信号较弱,可使用已缓存的预约码进入离线模式',
143 + confirmText: '预约码',
144 + cancelText: '知道了',
145 + })
146 + if (modal_res?.confirm) {
147 + await Taro.reLaunch({ url: '/pages/offlineBookingCode/index' })
148 + return true
149 + }
150 + } catch (e) {
151 + return is_none_network
152 + }
153 + } else {
154 + try {
155 + await Taro.showToast({ title: '网络连接不畅', icon: 'none', duration: 2000 })
156 + } catch (e) {
157 + return is_none_network
158 + }
159 + }
160 +
161 + return is_none_network
162 + }
163 +
164 + const should_stop = await handle_bad_network_on_launch()
165 + if (should_stop) return
166 +
102 /** 167 /**
103 * 尝试在网络可用时预加载二维码数据 168 * 尝试在网络可用时预加载二维码数据
104 * - 仅在有授权时调用 169 * - 仅在有授权时调用
......