浏览代码

bug: fix chat

张延森 5 年前
父节点
当前提交
5f492f2da0
共有 5 个文件被更改,包括 159 次插入215 次删除
  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 查看文件

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

+ 138
- 174
src/pages/im/index.js 查看文件

18
 // import { dispatchUserPhone } from '@actions/user'
18
 // import { dispatchUserPhone } from '@actions/user'
19
 import getUserPhone from '@utils/getUserPhone'
19
 import getUserPhone from '@utils/getUserPhone'
20
 
20
 
21
-import socket from '@utils/im'
21
+import socket, { MESSAGETYPE } from '@utils/im'
22
 import ready from '@utils/ready'
22
 import ready from '@utils/ready'
23
+import store from '../../store'
23
 
24
 
24
 @connect(state => (
25
 @connect(state => (
25
   { ...state.card, ...state.user, ...state.login }),
26
   { ...state.card, ...state.user, ...state.login }),
33
   state = {
34
   state = {
34
     msgList: [],
35
     msgList: [],
35
     inputText: '',
36
     inputText: '',
36
-    imageFile: '',
37
-    messageType: 'text',
37
+    messageType: MESSAGETYPE.TEXT,
38
     // chatInputHeight: 120,
38
     // chatInputHeight: 120,
39
     marginTop: 0,
39
     marginTop: 0,
40
     visExtra: false,
40
     visExtra: false,
52
     prompts: ['现在在售的户型有哪些?', '现在项目均价多少钱一平?', '项目周边的配套有哪些?', '未来周边规划的配套有哪些?'],
52
     prompts: ['现在在售的户型有哪些?', '现在项目均价多少钱一平?', '项目周边的配套有哪些?', '未来周边规划的配套有哪些?'],
53
     recordId: null,
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
   originList = []
60
   originList = []
76
   componentDidMount() {
75
   componentDidMount() {
77
     ready.queue(() => {
76
     ready.queue(() => {
78
       const { sendId, sendName, receiverId, receiverName } = this.$router.params
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
         this.loadList(res => {
128
         this.loadList(res => {
111
           this.toBottom()
129
           this.toBottom()
112
 
130
 
113
           const { records } = res
131
           const { records } = res
114
           const newMsg = records[0]
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
           if (!isCardMsg) {
136
           if (!isCardMsg) {
123
         });
141
         });
124
       });
142
       });
125
 
143
 
126
-      socket.wss.onMessage(res => {
144
+      socket.wss.onMessage(res => {    
127
         const data = JSON.parse(res.data)
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
   getPhoneNumber = (e) => {
196
   getPhoneNumber = (e) => {
161
-    const { userInfo: { person: { phone, sendPersonId, receivePersonId } } } = this.props
162
-    // const { receivePerson } = this.state
163
     getUserPhone(e, (phoneNumber) => {
197
     getUserPhone(e, (phoneNumber) => {
164
-      const selfPhone = phone || phoneNumber
198
+      const selfPhone = tel || phone || phoneNumber
165
       if (!selfPhone) {
199
       if (!selfPhone) {
166
         Taro.showToast({
200
         Taro.showToast({
167
           icon: 'none',
201
           icon: 'none',
170
         return
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
     const length = getCurrentPages().length
212
     const length = getCurrentPages().length
191
     setTimeout(() => {
213
     setTimeout(() => {
192
       if (length > 1) {
214
       if (length > 1) {
197
     }, 500)
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
     // debugger
223
     // debugger
228
     this.appendData(data)
224
     this.appendData(data)
229
   }
225
   }
230
 
226
 
231
-  loadList(cb) {
227
+  loadList = (cb) => {
232
     if (this.loading) return
228
     if (this.loading) return
233
     this.loading = true
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
     Taro.showLoading({ title: '正在加载' })
233
     Taro.showLoading({ title: '正在加载' })
238
     queryChatHistory(payload).then(res => {
234
     queryChatHistory(payload).then(res => {
265
     })
261
     })
266
   }
262
   }
267
 
263
 
268
-  formatData(data) {
264
+  formatData = (data) => {
269
     let _map = {}
265
     let _map = {}
270
     let _rows = deepClone(data)
266
     let _rows = deepClone(data)
271
     let _time = null
267
     let _time = null
308
     return newArr.reverse()
304
     return newArr.reverse()
309
   }
305
   }
310
 
306
 
311
-  dealChatData(data, type) {
307
+  dealChatData = (data, type) => {
312
     let list = null
308
     let list = null
313
     if (type == 'new') {
309
     if (type == 'new') {
314
       list = [...(data || []), ...this.originList]
310
       list = [...(data || []), ...this.originList]
331
     }).exec()
327
     }).exec()
332
   }
328
   }
333
 
329
 
334
-  bindAlbumClick(e) {
335
-    debugger
330
+  bindAlbumClick = (e) => {
336
     e.stopPropagation()
331
     e.stopPropagation()
337
     Taro.chooseImage({
332
     Taro.chooseImage({
338
       count: 1,
333
       count: 1,
340
       sourceType: ['album', 'camera'],
335
       sourceType: ['album', 'camera'],
341
       success: res => {
336
       success: res => {
342
         uploadFiles(res.tempFilePaths).then(data => {
337
         uploadFiles(res.tempFilePaths).then(data => {
338
+          this.sendMessage(data[0], MESSAGETYPE.IMAGE)
339
+
343
           this.setState({
340
           this.setState({
344
             marginTop: 0,
341
             marginTop: 0,
345
-            messageType: 'image',
346
             visExtra: false,
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
       message,
355
       message,
370
       messageType,
356
       messageType,
371
       createDate: new Date().valueOf(),
357
       createDate: new Date().valueOf(),
372
     }
358
     }
373
 
359
 
374
-    payload.chatId = payload.createDate
375
-
376
-    // 发送消息
377
     socket.sendNotice(payload, res => {
360
     socket.sendNotice(payload, res => {
378
       console.log('发送成功')
361
       console.log('发送成功')
379
-
380
       this.appendData(payload)
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
     const { msgList } = this.state
367
     const { msgList } = this.state
392
 
368
 
393
     this.originList.unshift(data)
369
     this.originList.unshift(data)
408
  
384
  
409
     this.setState({
385
     this.setState({
410
       inputText: '',
386
       inputText: '',
411
-      imageFile: '',
412
       msgList: list
387
       msgList: list
413
     }, this.toBottom)
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
     // e.stopPropagation()
396
     // e.stopPropagation()
436
-    this.setState({
437
-      messageType: 'text'
438
-    }, this.onSendMsg)
397
+    this.sendMessage(this.state.inputText, MESSAGETYPE.TEXT)
439
     this.hideExtraArea()
398
     this.hideExtraArea()
440
     savePoint({
399
     savePoint({
441
       event: 'essential',
400
       event: 'essential',
447
     })
406
     })
448
   }
407
   }
449
 
408
 
450
-  bindTextInput(e) {
409
+  bindTextInput = (e) => {
410
+    console.log('--------->', e)
451
     this.setState({
411
     this.setState({
452
       inputText: e.detail.value
412
       inputText: e.detail.value
453
     })
413
     })
454
   }
414
   }
455
 
415
 
456
-  bindInputConfirm(e) {
416
+  bindInputConfirm = (e) => {
457
     e.stopPropagation()
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
     e.stopPropagation()
422
     e.stopPropagation()
463
     this.setState({
423
     this.setState({
464
       visExtra: true,
424
       visExtra: true,
466
     })
426
     })
467
   }
427
   }
468
 
428
 
469
-  hideExtraArea(e) {
429
+  hideExtraArea = (e) => {
470
     e && e.stopPropagation()
430
     e && e.stopPropagation()
471
     if (!this.state.visExtra) {
431
     if (!this.state.visExtra) {
472
       return
432
       return
478
     })
438
     })
479
   }
439
   }
480
 
440
 
481
-  onScrolltoupper() {
441
+  onScrolltoupper = () => {
482
     const { pagination } = this.state
442
     const { pagination } = this.state
483
     const { pageNumber, pages } = pagination
443
     const { pageNumber, pages } = pagination
484
 
444
 
499
     })
459
     })
500
   }
460
   }
501
 
461
 
502
-  togglePromptVisible(flag) {
462
+  togglePromptVisible = (flag) => {
503
     this.setState({
463
     this.setState({
504
       visiblePrompt: !!flag
464
       visiblePrompt: !!flag
505
     })
465
     })
514
   }
474
   }
515
 
475
 
516
   render() {
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
     const extraWrap = (
482
     const extraWrap = (
519
       <View className="import-bottom">
483
       <View className="import-bottom">
520
         <View className="extra-item" onClick={this.bindAlbumClick}>
484
         <View className="extra-item" onClick={this.bindAlbumClick}>
539
                 {/* <View className="prompt__title">常见问题咨询</View> */}
503
                 {/* <View className="prompt__title">常见问题咨询</View> */}
540
                 {prompts.map((text, index) => (
504
                 {prompts.map((text, index) => (
541
                   <View
505
                   <View
542
-                    key={index+'im'}
506
+                    key={index}
543
                     className="prompt__item"
507
                     className="prompt__item"
544
                     onClick={this.handleIssueClick.bind(this, text)}>
508
                     onClick={this.handleIssueClick.bind(this, text)}>
545
                     <Text>{text}</Text>
509
                     <Text>{text}</Text>
594
       </View>
558
       </View>
595
     );
559
     );
596
   }
560
   }
597
-}
561
+}

+ 2
- 2
src/pages/im/msgItem/index.js 查看文件

62
       )
62
       )
63
     }
63
     }
64
     if (row.messageType === 'image') {
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
     return (<View className="item__content-txt">{row.message}</View>)
68
     return (<View className="item__content-txt">{row.message}</View>)
87
       </View>
87
       </View>
88
     );
88
     );
89
   }
89
   }
90
-}
90
+}

+ 5
- 4
src/store/index.js 查看文件

21
   // other store enhancers if any
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 查看文件

68
         this.reconnect()
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
   makeUpNotice(send_id, consult_id, room_id, type, content, duration) {
74
   makeUpNotice(send_id, consult_id, room_id, type, content, duration) {
106
     return {
75
     return {
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
+}