Selaa lähdekoodia

bug: fix chat

张延森 5 vuotta sitten
vanhempi
commit
5f492f2da0
5 muutettua tiedostoa jossa 159 lisäystä ja 215 poistoa
  1. 2
    2
      src/app.js
  2. 138
    174
      src/pages/im/index.js
  3. 2
    2
      src/pages/im/msgItem/index.js
  4. 5
    4
      src/store/index.js
  5. 12
    33
      src/utils/im.js

+ 2
- 2
src/app.js Näytä tiedosto

@@ -26,10 +26,10 @@ import {
26 26
 } from '@constants/user'
27 27
 import ready from '@utils/ready'
28 28
 import login from '@utils/login'
29
-import configStore from './store'
29
+import store  from './store'
30 30
 import socket from '@utils/im'
31 31
 
32
-const store = configStore()
32
+// const store = configStore()
33 33
 
34 34
 class App extends Component {
35 35
   config = {

+ 138
- 174
src/pages/im/index.js Näytä tiedosto

@@ -18,8 +18,9 @@ import { dispatchCardInfo } from '@actions/card'
18 18
 // import { dispatchUserPhone } from '@actions/user'
19 19
 import getUserPhone from '@utils/getUserPhone'
20 20
 
21
-import socket from '@utils/im'
21
+import socket, { MESSAGETYPE } from '@utils/im'
22 22
 import ready from '@utils/ready'
23
+import store from '../../store'
23 24
 
24 25
 @connect(state => (
25 26
   { ...state.card, ...state.user, ...state.login }),
@@ -33,8 +34,7 @@ export default class Chat extends Component {
33 34
   state = {
34 35
     msgList: [],
35 36
     inputText: '',
36
-    imageFile: '',
37
-    messageType: 'text',
37
+    messageType: MESSAGETYPE.TEXT,
38 38
     // chatInputHeight: 120,
39 39
     marginTop: 0,
40 40
     visExtra: false,
@@ -52,10 +52,9 @@ export default class Chat extends Component {
52 52
     prompts: ['现在在售的户型有哪些?', '现在项目均价多少钱一平?', '项目周边的配套有哪些?', '未来周边规划的配套有哪些?'],
53 53
     recordId: null,
54 54
 
55
-    sendPersonId: null,
56
-    sendPersonName: null,
57
-    receivePersonId: null,
58
-    receivePersonName: null
55
+    noChatting: false,  // 异常
56
+    chatting: null, // 当前聊天对象
57
+    me: null, // 自己
59 58
   }
60 59
 
61 60
   originList = []
@@ -76,43 +75,62 @@ export default class Chat extends Component {
76 75
   componentDidMount() {
77 76
     ready.queue(() => {
78 77
       const { sendId, sendName, receiverId, receiverName } = this.$router.params
79
-      const { scene } = Taro.getStorageSync('router')
80
-
81
-
82
-      /**
83
-       * 当 scene ==1014 时,是从服务消息直接进入聊天页面,
84
-       * 则id为 sendId,反之是为receiverId
85
-       */
86
-      const fromTempleteMsg = scene == 1014
87
-      let sendPersonId = fromTempleteMsg ? receiverId : sendId
88
-      let sendPersonName = fromTempleteMsg ? receiverName : sendName
89
-      let receivePersonId = fromTempleteMsg ? sendPersonId : receiverId
90
-      let receivePersonName = fromTempleteMsg ? sendName : receiverName
91
-
92
-      // debugger
93
-      // if (!receivePersonId) {
94
-      //   Taro.showToast({ title: 'receivePersonId不存在' })
95
-      //   this.redirectTo()
96
-      //   return
97
-      // }
98
-
99
-      // if (receivePersonId === personId) {
100
-      //   Taro.showToast({ title: '你不能自己跟自己聊天~' })
101
-      //   this.redirectTo()
102
-      //   return
103
-      // }
104
-
105
-      Taro.setNavigationBarTitle({
106
-        title: decodeURIComponent(receivePersonName) || '聊天'
107
-      })
78
+      const me = this.props.userInfo.person
79
+      const { personId: mineId } = me
80
+            
81
+      // 系统异常
82
+      if (!sendId || !receiverId) {
83
+        Taro.showToast({
84
+          title: '无聊天对象, 请退出重试',
85
+          icon: 'none',
86
+          duration: 5000
87
+        })
88
+
89
+        this.setState({ noChatting: true })
90
+        return;
91
+      }
92
+
93
+      // 自己跟自己聊
94
+      if (sendId === mineId && receiverId === mineId) {
95
+        Taro.showToast({
96
+          title: '暂不支持自我聊天',
97
+          icon: 'none',
98
+          duration: 5000
99
+        })
100
+
101
+        this.setState({ noChatting: true })
102
+        return;
103
+      }
104
+
105
+      // 非当前人员页面
106
+      if (sendId != mineId && receiverId != mineId) {
107
+        Taro.showToast({
108
+          title: '数据获取错误, 请退出重试',
109
+          icon: 'none',
110
+          duration: 5000
111
+        })
112
+
113
+        this.setState({ noChatting: true })
114
+        return;
115
+      }
108 116
 
109
-      this.setState({ sendPersonId, sendPersonName, receivePersonId, receivePersonName }, () => {
117
+      const chatting = {
118
+        personId: sendId === mineId ? receiverId : sendId,
119
+        nickname: sendId === mineId ? decodeURIComponent(receiverName) : decodeURIComponent(sendName),
120
+        avatarurl: null,
121
+        personType: null,
122
+      }
123
+
124
+      // 设置页面 title
125
+      Taro.setNavigationBarTitle({ title: chatting.nickname || '聊天' })
126
+
127
+      this.setState({ chatting, me }, () => {
110 128
         this.loadList(res => {
111 129
           this.toBottom()
112 130
 
113 131
           const { records } = res
114 132
           const newMsg = records[0]
115
-          const isCardMsg = newMsg && newMsg.messageType === 'card'
133
+          const isCardMsg = newMsg && newMsg.messageType === MESSAGETYPE.CARD
116 134
 
117 135
           // 如果最新一条消息不是卡片类型 则自动发送卡片信息
118 136
           if (!isCardMsg) {
@@ -123,45 +141,61 @@ export default class Chat extends Component {
123 141
         });
124 142
       });
125 143
 
126
-      socket.wss.onMessage(res => {
144
+      socket.wss.onMessage(res => {    
127 145
         const data = JSON.parse(res.data)
128
-        // debugger
129
-        this.handlerRecive(data)
146
+
147
+        console.log('receive message ==>', data)
148
+
149
+        if (data.sendPerson != chatting.personId) {
150
+          // store.dispatch({ type: INCREASE_UNREADNUM })
151
+        } else {
152
+          this.handlerRecive(data)
153
+        }
130 154
       })
131 155
     })
132 156
   }
133 157
 
134
-  sendCardMsg() {
135
-    // const { userInfo: { person: { personId, personType } } } = this.props
136
-    // const isConsultant = (personType === ROLE_CODE['CONSULTANT'])
137
-    // const { receivePerson } = this.state
138
-    // const cardId = isConsultant ? personId : receivePerson
139
-    const { userInfo: { person: { personType: sendPersonType } } } = this.props
140
-    const { receivePersonId, receivePersonName, sendPersonId } = this.state
141
-    this.props.dispatchCardInfo(receivePersonId).then(res => {
142
-      // debugger
143
-      // 本人不是置业顾问且对方是置业顾问 则对方向我发送消息
144
-      const { personType: receivePersonType } = res
145
-      const hasSend = (sendPersonType != ROLE_CODE['CONSULTANT'] && receivePersonType == ROLE_CODE['CONSULTANT'])
146
-      if (hasSend) {
147
-        let payload = {
148
-          sendPerson: receivePersonId,
149
-          receivePerson: sendPersonId,
150
-          message: `您好,我是${receivePersonName},有什么可以帮助您的吗?您可以在这里跟我实时沟通哦~`,
151
-          messageType: 'card',
152
-          createDate: new Date().valueOf(),
153
-        }
154
-        // 发送消息
155
-        socket.sendNotice(payload)
156
-      }
158
+  componentWillUnmount() {
159
+    // socket.closeSocket()
160
+    const { recordId } = this.state
161
+    recordId && updatePoint(recordId)
162
+  }
163
+
164
+  sendCardMsg = () => {
165
+    const { me, chatting } = this.state
166
+
167
+    // 本人是置业顾问, 不做卡片发送操作
168
+    if (me.personType === ROLE_CODE['CONSULTANT']) {
169
+      return;
170
+    }
171
+
172
+    // 本人不是置业, 对方必然是置业
173
+    this.props.dispatchCardInfo(chatting.personId).then(res => {
174
+      const chattingName = res.name || chatting.nickname
175
+
176
+      // 发送 卡片 消息
177
+      socket.sendNotice({
178
+        sendPerson: chatting.personId,
179
+        receivePerson: me.personId,
180
+        message: `您好,我是${chattingName},有什么可以帮助您的吗?您可以在这里跟我实时沟通哦~`,
181
+        messageType: MESSAGETYPE.CARD,
182
+        createDate: new Date().valueOf(),
183
+      }, res => {
184
+        console.log('发送成功')
185
+        this.appendData(payload)
186
+      })
187
+
188
+      this.setState({
189
+        nickname: chattingName,
190
+        avatarurl: res.picture || res.avatar,
191
+        personType: res.personType,
192
+      })
157 193
     })
158 194
   }
159 195
 
160 196
   getPhoneNumber = (e) => {
161
-    const { userInfo: { person: { phone, sendPersonId, receivePersonId } } } = this.props
162
-    // const { receivePerson } = this.state
163 197
     getUserPhone(e, (phoneNumber) => {
164
-      const selfPhone = phone || phoneNumber
198
+      const selfPhone = tel || phone || phoneNumber
165 199
       if (!selfPhone) {
166 200
         Taro.showToast({
167 201
           icon: 'none',
@@ -170,23 +204,11 @@ export default class Chat extends Component {
170 204
         return
171 205
       }
172 206
 
173
-      let payload = {
174
-        sendPerson: sendPersonId,
175
-        receivePerson: receivePersonId,
176
-        message: `我的手机号是${selfPhone},请来电联系我哦~`,
177
-        messageType: 'text',
178
-        createDate: new Date().valueOf()
179
-      }
180
-
181
-      // 发送消息
182
-      socket.sendNotice(payload, res => {
183
-        console.log('发送成功')
184
-        this.appendData(payload)
185
-      })
207
+      this.sendMessage(`我的手机号是${selfPhone},请来电联系我哦~`)
186 208
     })
187 209
   }
188 210
 
189
-  redirectTo() {
211
+  redirectTo = () => {
190 212
     const length = getCurrentPages().length
191 213
     setTimeout(() => {
192 214
       if (length > 1) {
@@ -197,42 +219,16 @@ export default class Chat extends Component {
197 219
     }, 500)
198 220
   }
199 221
 
200
-  componentWillUnmount() {
201
-    // socket.closeSocket()
202
-    const { recordId } = this.state
203
-    recordId && updatePoint(recordId)
204
-  }
205
-  // createSocket() {
206
-  //   const { userInfo: { person: { personId } } } = this.props
207
-  //   socket.createSocket({
208
-  //     id: personId,
209
-  //     success: (res) => {
210
-  //       console.log('success', res)
211
-  //     },
212
-  //     close: (res) => {
213
-  //       console.log('close', res)
214
-  //     },
215
-  //     receive: (res) => {
216
-  //       console.log('receive', res)
217
-  //       let data = JSON.parse(res.data)
218
-  //       this.handlerRecive(data)
219
-  //     },
220
-  //     fail: (res) => {
221
-  //       console.log('fail', res)
222
-  //     }
223
-  //   })
224
-  // }
225
-
226
-  handlerRecive(data) {
222
+  handlerRecive = (data) => {
227 223
     // debugger
228 224
     this.appendData(data)
229 225
   }
230 226
 
231
-  loadList(cb) {
227
+  loadList = (cb) => {
232 228
     if (this.loading) return
233 229
     this.loading = true
234
-    const { pagination, receivePersonId } = this.state
235
-    const payload = Object.assign(pagination, { chatWith: receivePersonId })
230
+    const { pagination, chatting } = this.state
231
+    const payload = Object.assign(pagination, { chatWith: chatting.personId })
236 232
 
237 233
     Taro.showLoading({ title: '正在加载' })
238 234
     queryChatHistory(payload).then(res => {
@@ -265,7 +261,7 @@ export default class Chat extends Component {
265 261
     })
266 262
   }
267 263
 
268
-  formatData(data) {
264
+  formatData = (data) => {
269 265
     let _map = {}
270 266
     let _rows = deepClone(data)
271 267
     let _time = null
@@ -308,7 +304,7 @@ export default class Chat extends Component {
308 304
     return newArr.reverse()
309 305
   }
310 306
 
311
-  dealChatData(data, type) {
307
+  dealChatData = (data, type) => {
312 308
     let list = null
313 309
     if (type == 'new') {
314 310
       list = [...(data || []), ...this.originList]
@@ -331,8 +327,7 @@ export default class Chat extends Component {
331 327
     }).exec()
332 328
   }
333 329
 
334
-  bindAlbumClick(e) {
335
-    debugger
330
+  bindAlbumClick = (e) => {
336 331
     e.stopPropagation()
337 332
     Taro.chooseImage({
338 333
       count: 1,
@@ -340,54 +335,35 @@ export default class Chat extends Component {
340 335
       sourceType: ['album', 'camera'],
341 336
       success: res => {
342 337
         uploadFiles(res.tempFilePaths).then(data => {
338
+          this.sendMessage(data[0], MESSAGETYPE.IMAGE)
339
+
343 340
           this.setState({
344 341
             marginTop: 0,
345
-            messageType: 'image',
346 342
             visExtra: false,
347
-            imageFile: data[0]
348
-          }, this.onSendMsg)
343
+          })
349 344
         })
350 345
       }
351 346
     })
352 347
   }
353 348
 
354
-  onSendMsg() {
355
-    const { inputText, imageFile, messageType, sendPersonId, receivePersonId } = this.state
349
+  sendMessage = (message, messageType = MESSAGETYPE.TEXT) => {
350
+    const { me, chatting } = this.state
356 351
 
357
-    if (!inputText && !imageFile) return
358
-
359
-    let message = ''
360
-    if (messageType === 'text') {
361
-      message = inputText
362
-    } else if (messageType === 'image') {
363
-      message = imageFile
364
-    }
365
-
366
-    let payload = {
367
-      sendPerson: sendPersonId,
368
-      receivePerson: receivePersonId,
352
+    const payload = {
353
+      sendPerson: me.personId,
354
+      receivePerson: chatting.personId,
369 355
       message,
370 356
       messageType,
371 357
       createDate: new Date().valueOf(),
372 358
     }
373 359
 
374
-    payload.chatId = payload.createDate
375
-
376
-    // 发送消息
377 360
     socket.sendNotice(payload, res => {
378 361
       console.log('发送成功')
379
-
380 362
       this.appendData(payload)
381
-      // this.setState({
382
-      //   inputText: '',
383
-      //   imageFile: '',
384
-      //   msgList: list
385
-      // }, this.toBottom)
386 363
     })
387 364
   }
388 365
 
389
-
390
-  appendData(data) {
366
+  appendData = (data) => {
391 367
     const { msgList } = this.state
392 368
 
393 369
     this.originList.unshift(data)
@@ -408,34 +384,17 @@ export default class Chat extends Component {
408 384
  
409 385
     this.setState({
410 386
       inputText: '',
411
-      imageFile: '',
412 387
       msgList: list
413 388
     }, this.toBottom)
414 389
   }
415 390
 
416
-  handleIssueClick(message, e) {
417
-    // e.stopPropagation()
418
-    const { sendPersonId, receivePersonId } = this.state
419
-    let payload = {
420
-      sendPerson: sendPersonId,
421
-      receivePerson: receivePersonId,
422
-      message,
423
-      messageType: 'text',
424
-      createDate: new Date().valueOf()
425
-    }
426
-
427
-    payload.chatId = payload.createDate
428
-    socket.sendNotice(payload, res => {
429
-      console.log('发送成功')
430
-      this.appendData(payload)
431
-    })
391
+  handleIssueClick = (message, e) => {
392
+    this.sendMessage(message)
432 393
   }
433 394
 
434
-  bindSendBtn(e) {
395
+  bindSendBtn = (e) => {
435 396
     // e.stopPropagation()
436
-    this.setState({
437
-      messageType: 'text'
438
-    }, this.onSendMsg)
397
+    this.sendMessage(this.state.inputText, MESSAGETYPE.TEXT)
439 398
     this.hideExtraArea()
440 399
     savePoint({
441 400
       event: 'essential',
@@ -447,18 +406,19 @@ export default class Chat extends Component {
447 406
     })
448 407
   }
449 408
 
450
-  bindTextInput(e) {
409
+  bindTextInput = (e) => {
410
+    console.log('--------->', e)
451 411
     this.setState({
452 412
       inputText: e.detail.value
453 413
     })
454 414
   }
455 415
 
456
-  bindInputConfirm(e) {
416
+  bindInputConfirm = (e) => {
457 417
     e.stopPropagation()
458
-    this.onSendMsg()
418
+    this.sendMessage(this.state.inputText, MESSAGETYPE.TEXT)
459 419
   }
460 420
 
461
-  showExtraArea(e) {
421
+  showExtraArea = (e) => {
462 422
     e.stopPropagation()
463 423
     this.setState({
464 424
       visExtra: true,
@@ -466,7 +426,7 @@ export default class Chat extends Component {
466 426
     })
467 427
   }
468 428
 
469
-  hideExtraArea(e) {
429
+  hideExtraArea = (e) => {
470 430
     e && e.stopPropagation()
471 431
     if (!this.state.visExtra) {
472 432
       return
@@ -478,7 +438,7 @@ export default class Chat extends Component {
478 438
     })
479 439
   }
480 440
 
481
-  onScrolltoupper() {
441
+  onScrolltoupper = () => {
482 442
     const { pagination } = this.state
483 443
     const { pageNumber, pages } = pagination
484 444
 
@@ -499,7 +459,7 @@ export default class Chat extends Component {
499 459
     })
500 460
   }
501 461
 
502
-  togglePromptVisible(flag) {
462
+  togglePromptVisible = (flag) => {
503 463
     this.setState({
504 464
       visiblePrompt: !!flag
505 465
     })
@@ -514,7 +474,11 @@ export default class Chat extends Component {
514 474
   }
515 475
 
516 476
   render() {
517
-    const { marginTop, visiblePrompt, prompts, msgList } = this.state
477
+    const { marginTop, visiblePrompt, prompts, msgList, noChatting } = this.state
478
+
479
+    // 如果有错误, 不显示内容
480
+    if (noChatting) return null;
481
+
518 482
     const extraWrap = (
519 483
       <View className="import-bottom">
520 484
         <View className="extra-item" onClick={this.bindAlbumClick}>
@@ -539,7 +503,7 @@ export default class Chat extends Component {
539 503
                 {/* <View className="prompt__title">常见问题咨询</View> */}
540 504
                 {prompts.map((text, index) => (
541 505
                   <View
542
-                    key={index+'im'}
506
+                    key={index}
543 507
                     className="prompt__item"
544 508
                     onClick={this.handleIssueClick.bind(this, text)}>
545 509
                     <Text>{text}</Text>
@@ -594,4 +558,4 @@ export default class Chat extends Component {
594 558
       </View>
595 559
     );
596 560
   }
597
-}
561
+}

+ 2
- 2
src/pages/im/msgItem/index.js Näytä tiedosto

@@ -62,7 +62,7 @@ export default class MsgItem extends Component {
62 62
       )
63 63
     }
64 64
     if (row.messageType === 'image') {
65
-      return (<Image className="item__content-img" mode="aspectFill" src={row.message} onClick={this.onPreviewImg.bind(this, row)} />)
65
+      return (<Image className="item__content-img" mode="widthFix" src={row.message} onClick={this.onPreviewImg.bind(this, row)} />)
66 66
     }
67 67
 
68 68
     return (<View className="item__content-txt">{row.message}</View>)
@@ -87,4 +87,4 @@ export default class MsgItem extends Component {
87 87
       </View>
88 88
     );
89 89
   }
90
-}
90
+}

+ 5
- 4
src/store/index.js Näytä tiedosto

@@ -21,7 +21,8 @@ const enhancer = composeEnhancers(
21 21
   // other store enhancers if any
22 22
 )
23 23
 
24
-export default function configStore () {
25
-  const store = createStore(rootReducer, enhancer)
26
-  return store
27
-}
24
+// export default function configStore () {
25
+//   const store = createStore(rootReducer, enhancer)
26
+//   return store
27
+// }
28
+export default createStore(rootReducer, enhancer)

+ 12
- 33
src/utils/im.js Näytä tiedosto

@@ -68,39 +68,8 @@ class IMManager {
68 68
         this.reconnect()
69 69
       }
70 70
     })
71
-
72
-    //接收新消息必须做点什么(判断类型,订阅DOM更新)
73
-    // this.wss.onMessage(res => {
74
-    //   // let message = {};
75
-    //   // try {
76
-    //   //   message = JSON.parse(res.data)
77
-    //   // } catch (err) {
78
-    //   //   message = res.data
79
-    //   // }
80
-    //   // this.onReceiveMessage(res)
81
-    //   // receive && receive(res)
82
-    //   // if (message.type) {
83
-    //   //   switch (message.type) {
84
-    //   //     case 'notice': //拿到了新消息
85
-    //   //       //更新消息列表
86
-    //   //       console.log('收到了一条消息', message)
87
-    //   //       //监听到消息 
88
-    //   //       //筛选本房间消息                           
89
-    //   //       //推入视图消息队列
90
-
91
-    //   //       break;
92
-    //   //     case 'join':
93
-
94
-    //   //       break;
95
-    //   //     case 'leave':
96
-
97
-    //   //       break;
98
-    //   //   }
99
-    //   // } else {
100
-    //   //   console.log(message)
101
-    //   // }
102
-    // })
103 71
   };
72
+
104 73
   //组装消息
105 74
   makeUpNotice(send_id, consult_id, room_id, type, content, duration) {
106 75
     return {
@@ -152,4 +121,14 @@ class IMManager {
152 121
   }
153 122
 }
154 123
 
155
-export default new IMManager()
124
+export default new IMManager()
125
+
126
+const MESSAGETYPE = {
127
+  IMAGE: 'image',
128
+  TEXT: 'text',
129
+  CARD: 'card',
130
+}
131
+
132
+export {
133
+  MESSAGETYPE
134
+}