hejianhao
2026-03-01 1226d624fc1bf33fb0a3a15f8f0bd563d8d257fb
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
405
406
407
408
409
410
import Taro from '@tarojs/taro';
import { getStorage } from './tools';
import { _UID } from '../constants/api';
 
type MessageCallback = (data: any) => void;
 
class WebSocketManager {
  private static instance: WebSocketManager;
  private socketTask: Taro.SocketTask | null = null;
  private url: string = '';
  private isConnected: boolean = false;
  private reconnectAttempts: number = 0;
  private maxReconnectAttempts: number = 5;
  private reconnectTimer: any = null;
  private heartbeatTimer: any = null;
  private heartbeatInterval: number = 30000; // 30秒心跳
  private listeners: Map<string, MessageCallback[]> = new Map();
  private globalEventsBound: boolean = false;
 
  private constructor() { }
 
  public static getInstance(): WebSocketManager {
    if (!WebSocketManager.instance) {
      WebSocketManager.instance = new WebSocketManager();
    }
    return WebSocketManager.instance;
  }
 
  /**
   * 初始化连接
   * @param url WebSocket地址
   */
  public async connect(url: string) {
    if (this.socketTask || this.isConnected) {
      console.log('WebSocket 已连接或正在连接中');
      return;
    }
 
    this.url = url;
    console.log(`正在连接 WebSocket: ${url}`);
 
    const uid = await getStorage(_UID) || '-1';
    const task = Taro.connectSocket({
      header: {
        'XP-Uid': '20260227200715' || uid.toString(),
      },
      url: this.url,
      success: () => { },
      fail: (err) => {
        console.error('WebSocket 连接失败:', err);
        this.handleReconnect();
      }
    });
    const maybeTask: any = task as any;
    if (maybeTask && typeof maybeTask.onOpen === 'function') {
      this.socketTask = maybeTask;
      this.initEventListeners();
      return;
    }
    if (maybeTask && typeof maybeTask.then === 'function') {
      maybeTask
        .then((resolvedTask) => {
          this.socketTask = resolvedTask;
          this.initEventListeners();
        })
        .catch((err) => {
          console.error('WebSocket 连接失败:', err);
          this.handleReconnect();
        });
      return;
    }
    this.socketTask = null;
    this.initEventListeners();
  }
 
  public isConnectedStatus() {
    return this.isConnected;
  }
 
  /**
   * 初始化事件监听
   */
  private initEventListeners() {
    if (this.socketTask && typeof this.socketTask.onOpen === 'function') {
      this.socketTask.onOpen(async () => {
        console.log('WebSocket 连接已打开');
        this.isConnected = true;
        this.reconnectAttempts = 0;
        this.startHeartbeat();
        const uid = await getStorage(_UID) || '-1';
        this.send({ type: 'auth', appUserId: '20260227200715', timestamp: Date.now() });
        this.notifyListeners('open', { status: 'connected' });
      });
 
      this.socketTask.onMessage((res) => {
        try {
          const data = JSON.parse(res.data as string);
          const content = JSON.parse(data.content || '{}');
          this.handleIncomingMessage(data, content);
          if (data.type) {
            this.notifyListeners(data.type, data);
          }
          this.notifyListeners('message', data);
        } catch (e) {
          console.warn('解析 WebSocket 消息失败:', res.data);
          this.notifyListeners('message', res.data);
        }
      });
 
      this.socketTask.onClose((res) => {
        console.log('WebSocket 连接已关闭', res);
        this.isConnected = false;
        this.stopHeartbeat();
        this.socketTask = null;
 
        if (res.code !== 1000) {
          this.handleReconnect();
        }
        this.notifyListeners('close', res);
      });
 
      this.socketTask.onError((err) => {
        console.error('WebSocket 错误:', err);
        this.isConnected = false;
        this.notifyListeners('error', err);
      });
      return;
    }
 
    if (this.globalEventsBound) return;
    this.globalEventsBound = true;
 
    Taro.onSocketOpen(async () => {
      console.log('WebSocket 连接已打开');
      this.isConnected = true;
      this.reconnectAttempts = 0;
      this.startHeartbeat();
      const uid = await getStorage(_UID) || '-1';
      this.send({ type: 'auth', appUserId: '20260227200715', timestamp: Date.now() });
      this.notifyListeners('open', { status: 'connected' });
    });
 
    Taro.onSocketMessage((res) => {
      try {
        const data = JSON.parse(res.data as string);
        const content = JSON.parse(data.content || '{}');
        this.handleIncomingMessage(data, content);
        if (data.type) {
          this.notifyListeners(data.type, data);
        }
        this.notifyListeners('message', data);
      } catch (e) {
        console.warn('解析 WebSocket 消息失败:', res.data);
        this.notifyListeners('message', res.data);
      }
    });
 
    Taro.onSocketClose((res) => {
      console.log('WebSocket 连接已关闭', res);
      this.isConnected = false;
      this.stopHeartbeat();
      this.socketTask = null;
 
      if (res.code !== 1000) {
        this.handleReconnect();
      }
      this.notifyListeners('close', res);
    });
 
    Taro.onSocketError((err) => {
      console.error('WebSocket 错误:', err);
      this.isConnected = false;
      this.notifyListeners('error', err);
    });
  }
 
  /**
   * 发送消息
   * @param data 消息内容
   */
  public send(data: any) {
    if (!this.isConnected) {
      console.warn('WebSocket 未连接,消息未发送:', data);
      return;
    }
 
    const message = typeof data === 'string' ? data : JSON.stringify(data);
    if (this.socketTask) {
      this.socketTask.send({
        data: message,
        fail: (err) => {
          console.error('发送消息失败:', err);
        }
      });
    } else {
      Taro.sendSocketMessage({
        data: message,
        fail: (err) => {
          console.error('发送消息失败:', err);
        }
      });
    }
  }
 
  /**
   * 关闭连接
   */
  public close() {
    this.stopHeartbeat();
    if (this.reconnectTimer) {
      clearTimeout(this.reconnectTimer);
      this.reconnectTimer = null;
    }
 
    if (this.socketTask) {
      this.socketTask.close({
        code: 1000,
        reason: '用户主动关闭连接'
      });
      this.socketTask = null;
    }
    this.isConnected = false;
  }
 
  /**
   * 处理重连
   */
  private handleReconnect() {
    if (this.reconnectAttempts >= this.maxReconnectAttempts) {
      console.error('达到最大重连次数,停止重连。');
      return;
    }
 
    if (this.reconnectTimer) return;
 
    const delay = Math.min(1000 * Math.pow(2, this.reconnectAttempts), 30000); // 指数退避
    console.log(`正在尝试重连,延迟 ${delay}ms... (第 ${this.reconnectAttempts + 1}/${this.maxReconnectAttempts} 次尝试)`);
 
    this.reconnectTimer = setTimeout(() => {
      this.reconnectAttempts++;
      this.reconnectTimer = null;
      this.connect(this.url);
    }, delay);
  }
 
  /**
   * 开启心跳
   */
  private startHeartbeat() {
    this.stopHeartbeat();
    this.heartbeatTimer = setInterval(() => {
      if (this.isConnected) {
        this.send({ type: 'ping', timestamp: Date.now() });
      }
    }, this.heartbeatInterval);
  }
 
  /**
   * 停止心跳
   */
  private stopHeartbeat() {
    if (this.heartbeatTimer) {
      clearInterval(this.heartbeatTimer);
      this.heartbeatTimer = null;
    }
  }
 
  /**
   * 注册事件监听
   * @param event 事件名称
   * @param callback 回调函数
   */
  public on(event: string, callback: MessageCallback) {
    if (!this.listeners.has(event)) {
      this.listeners.set(event, []);
    }
    this.listeners.get(event)?.push(callback);
  }
 
  /**
   * 移除事件监听
   * @param event 事件名称
   * @param callback 回调函数
   */
  public off(event: string, callback: MessageCallback) {
    const callbacks = this.listeners.get(event);
    if (callbacks) {
      const index = callbacks.indexOf(callback);
      if (index !== -1) {
        callbacks.splice(index, 1);
      }
    }
  }
 
  /**
   * 通知监听器
   * @param event 事件名称
   * @param data 数据
   */
  private notifyListeners(event: string, data: any) {
    const callbacks = this.listeners.get(event);
    if (callbacks) {
      callbacks.forEach(callback => {
        try {
          callback(data);
        } catch (e) {
          console.error(`WebSocket 事件 ${event} 监听器执行出错:`, e);
        }
      });
    }
  }
 
  // 处理传入消息
  private handleIncomingMessage(data: any, content: any) {
    if (data?.type === 'ORDER_STATUS') {
      const status = content?.status;
      const orderId = content?.orderId;
      if (typeof status === 'number') {
        const mapped = this.mapOrderStatusToTripStatus(status);
        if (typeof mapped.tripStatus === 'number') {
          Taro.setStorageSync('tripStatus', mapped.tripStatus);
          Taro.setStorageSync('orderId', orderId);
        }
        this.notifyListeners('order_status', { status, ...mapped, data, content });
      }
    }
    if (data?.type === 'VEHICLE_LOCATION') {
      const longitude = content?.lon;
      const latitude = content?.lat;
      if (typeof longitude === 'number' && typeof latitude === 'number') {
        this.notifyListeners('vehicle_location', { longitude, latitude, data, content });
      }
    }
    if (data?.type === 'ORDER_ROUTE') {
      const routeType = content?.routeType;
      const direction = Number(content?.direction);
      // 2-12 新增
      const duration = Number(JSON.parse(content?.route ?? '{}')?.duration ?? '0');
      const distance = Number(JSON.parse(content?.route ?? '{}')?.distance ?? '0');
      // 2-12 新增
      const points = this.normalizeRoutePoints(content);
      if (!Number.isNaN(duration)) {
        Taro.setStorageSync('orderRouteDuration', Math.round(duration));
        Taro.setStorageSync('orderRouteDurationUnit', 's');
      }
      if (!Number.isNaN(distance)) {
        const distanceKm = Number((distance / 1000).toFixed(1));
        Taro.setStorageSync('orderRouteDistance', distanceKm);
        Taro.setStorageSync('orderRouteDistanceUnit', 'km');
      }
      if (points.length > 0) {
        const cached = Taro.getStorageSync('orderRoutePoints') || {};
        if (typeof routeType === 'number') {
          cached[String(routeType)] = points;
          Taro.setStorageSync('orderRouteLatestType', routeType);
        } else {
          cached.latest = points;
        }
        Taro.setStorageSync('orderRoutePoints', cached);
        this.notifyListeners('order_route', { routeType, direction, points, data, content });
      }
    }
  }
 
  // 归一化路线点
  private normalizeRoutePoints(content: any) {
    const route = JSON.parse(content?.route ?? '{}');
    const rawPoints = route?.polyline ?? [];
    const arrPoint=JSON.parse(rawPoints);
    if (!Array.isArray(arrPoint)) return [];
    return arrPoint.map((item: any) => {
      const latitude = item?.latitude;
      const longitude = item?.longitude;
      if (typeof latitude === 'number' && typeof longitude === 'number') {
        return { latitude, longitude };
      }
      return null;
    }).filter(Boolean);
  }
 
  // 映射订单状态到行程状态
  private mapOrderStatusToTripStatus(status: number) {
    switch (status) {
      case 0:
        return { tripStatus: 1, showCancelPopup: true };
      case 1:
        return { tripStatus: 3, showPassengerNotice: true };
      case 2:
        return { tripStatus: 3 };
      case 3:
        return { tripStatus: 4 };
      case 4:
        return { tripStatus: 5, showAnnouncementsPopup: true };
      case 5:
      case 6:
        return { tripStatus: 6 };
      case 7:
        return { tripStatus: 7 };
      case 8:
        return { tripStatus: 8 };
      case 9:
      case 10:
        return { tripStatus: 9 };
      default:
        return { tripStatus: undefined };
    }
  }
}
 
export default WebSocketManager.getInstance();