chat.jsx 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. import Taro, { Component } from '@tarojs/taro'
  2. import { View, ScrollView } from '@tarojs/components'
  3. import ListMore from '@/c/pageDataList/listMore'
  4. import { strTrim, arrToObj } from '@utils'
  5. import './chat.scss'
  6. class Index extends Component {
  7. constructor (props) {
  8. super(props)
  9. const {id: curId} = this.$router.params
  10. this.state = {
  11. page_size: 10,
  12. page: 1,
  13. isListEnd: false,
  14. isListLoading: false,
  15. isListEmpty: false,
  16. dataList: [],
  17. curId,
  18. curObj: {},
  19. commentVal: '',
  20. msgSocketList: [],
  21. uObj: {},
  22. chatUserObj: {},
  23. viewId: '',
  24. socketTimer: null
  25. }
  26. }
  27. config = {
  28. navigationBarTitleText: '在线沟通',
  29. }
  30. componentWillUnmount () {
  31. this.closeSocket()
  32. let pages = getCurrentPages()
  33. let prevPage = pages[ pages.length - 2 ]
  34. if (prevPage.$component.getNotifycount) prevPage.$component.getNotifycount()
  35. }
  36. closeSocket () {
  37. Taro.closeSocket()
  38. const { socketTimer } = this.state
  39. clearInterval(socketTimer)
  40. }
  41. componentDidMount () {
  42. const that = this
  43. let uObj = Taro.getStorageSync('APP_userInfo')
  44. const { to_user_id } = this.$router.params
  45. this.setState({
  46. uObj
  47. }, () => {
  48. let uArr = [uObj.user_id, to_user_id]
  49. Taro.api.base.apiuserinfolist({
  50. user_ids: uArr.join(',')
  51. }).then(res => {
  52. let chatUserObj = {}
  53. const list = res.list || []
  54. list.forEach(item => {
  55. chatUserObj[item.id] = item
  56. })
  57. that.setState({
  58. chatUserObj
  59. })
  60. })
  61. Taro.$AHU(this)
  62. this.getDataList()
  63. this.initSocket()
  64. })
  65. }
  66. getDataList () {
  67. const { to_user_id } = this.$router.params
  68. let { page_size, page, dataList, isListEmpty } = this.state
  69. Taro.api.room.apiuserchatlist({
  70. page,
  71. page_size,
  72. to_user_id,
  73. }).then(res => {
  74. let curData = res.list || []
  75. curData = curData.reverse()
  76. let isListEnd = false
  77. if (curData.length > 0) {
  78. if (page === 1) {
  79. dataList = curData
  80. } else {
  81. dataList = [].concat(curData, dataList)
  82. }
  83. if (curData.length === page_size && res.total !== curData.length) {
  84. isListEnd = false
  85. } else {
  86. isListEnd = true
  87. }
  88. }
  89. if (curData.length === 0 && page === 1) {
  90. isListEmpty = true
  91. dataList = []
  92. } else {
  93. isListEmpty = false
  94. }
  95. const that = this
  96. this.setState({
  97. dataList,
  98. isListEnd,
  99. isListEmpty,
  100. isListLoading: false
  101. }, () => {
  102. if (page > 1) {
  103. setTimeout(() => {
  104. that.setState({
  105. viewId: `history11`
  106. })
  107. }, 100)
  108. }
  109. })
  110. })
  111. }
  112. onScrollToUpper (e) {
  113. let { isListEnd, isListLoading, page } = this.state
  114. if (!isListEnd && !isListLoading) {
  115. page++
  116. this.setState({
  117. page,
  118. isListLoading: true
  119. }, () => {
  120. this.getDataList()
  121. })
  122. }
  123. }
  124. initSocket () {
  125. const { uObj } = this.state
  126. const that = this
  127. Taro.connectSocket({
  128. url: 'ws://192.168.101.147:8089/acc',
  129. success: function () {
  130. console.log('connect success')
  131. }
  132. }).then(task => {
  133. task.onOpen(function () {
  134. // console.log('onOpen')
  135. // const { to_user_id } = that.$router.params
  136. let token = Taro.getStorageSync('APP_token')
  137. task.send({ data: '{"seq":"' + that.sendId() + '","cmd":"login","data":{"userId":"' + uObj.user_id + '","appId":101,"serviceToken":"' + token + '"}}' })
  138. const socketTimer = setInterval(() => {
  139. task.send({data: '{"seq":"' + that.sendId() + '","cmd":"heartbeat","data":{}}'});
  140. }, 30000)
  141. that.setState({
  142. socketTimer
  143. })
  144. })
  145. task.onMessage(function (msg) {
  146. // console.log('onMessage: ', msg)
  147. let { msgSocketList } = that.state
  148. const data = JSON.parse(msg.data)
  149. // console.log(data)
  150. if (data.cmd === 'msg' || data.cmd === 'login') {
  151. const res = data.response || {}
  152. if (res.code === 200) {
  153. if (data.cmd === 'login') {
  154. msgSocketList.push({msg: '登录成功~'})
  155. } else {
  156. msgSocketList.push(res.data)
  157. }
  158. that.setState({
  159. msgSocketList
  160. }, () => {
  161. setTimeout(() => {
  162. that.setState({
  163. viewId: `item${msgSocketList.length - 1}`
  164. })
  165. }, 100)
  166. })
  167. }
  168. }
  169. if (data.cmd === 'heartbeat') {
  170. const res = data.response || {}
  171. if (res.code !== 200) {
  172. msgSocketList.push({msg: res.codeMsg + '|暂无法接收消息,请退出当前页面重新登录~'})
  173. that.setState({
  174. msgSocketList
  175. }, () => {
  176. setTimeout(() => {
  177. that.setState({
  178. viewId: `item${msgSocketList.length - 1}`
  179. }, () => {
  180. that.closeSocket()
  181. })
  182. }, 100)
  183. })
  184. }
  185. }
  186. // task.close()
  187. })
  188. task.onError(function () {
  189. console.log('onError')
  190. })
  191. task.onClose(function (e) {
  192. console.log('onClose: ', e)
  193. })
  194. })
  195. }
  196. sendId () {
  197. let timeStamp = +new Date()
  198. let randId = parseInt(Math.random() * 1000000)
  199. return `${timeStamp}-${randId}`
  200. }
  201. componentDidShow () { }
  202. componentDidHide () { }
  203. renderList () {
  204. const { chatUserObj, uObj, viewId } = this.state
  205. const { dataList, isListEnd, isListLoading, isListEmpty } = this.state
  206. const itemList = dataList.map((item, index) => {
  207. return (
  208. <View className="sl-item" key={index} id={`history${index}`}>
  209. <View className={item.user_id === uObj.user_id ? 'sl-wrap' : 'sl-wrap t2'}>
  210. <View className="sl-img">
  211. <Image className="img" src={chatUserObj[item.user_id].avatar}></Image>
  212. </View>
  213. <View className="sl-right">
  214. <View className="sign"></View>
  215. <View className="sl-text">{item.content}</View>
  216. <View className="sl-time">{item.create_at}</View>
  217. </View>
  218. </View>
  219. </View>
  220. )
  221. })
  222. return (
  223. <ScrollView
  224. className='l-scroll-view'
  225. scrollY
  226. scrollWithAnimation
  227. upperThreshold="10"
  228. scrollIntoView={viewId}
  229. onScrollToUpper={this.onScrollToUpper.bind(this)}
  230. >
  231. <ListMore isListEnd={isListEnd} isListLoading={isListLoading} isListEmpty={isListEmpty} text="暂无历史消息" />
  232. <View className="scoped-list">
  233. {itemList}
  234. </View>
  235. {/* {
  236. dataList.length > 0
  237. &&
  238. <AtDivider content="以上为历史消息" fontColor='#ccc' lineColor='#ccc' />
  239. } */}
  240. {this.renderMsgList()}
  241. <View id="msgId"></View>
  242. </ScrollView>
  243. )
  244. }
  245. renderMsgList () {
  246. const { msgSocketList } = this.state
  247. const { chatUserObj, uObj } = this.state
  248. const curItems = msgSocketList.map((item, index) => {
  249. return (
  250. <View className="sl-item" key={index} id={`item${index}`}>
  251. {
  252. item.from
  253. ?
  254. <View className={item.from === uObj.user_id ? 'sl-wrap' : 'sl-wrap t2'}>
  255. <View className="sl-img">
  256. <Image className="img" src={chatUserObj[item.from].avatar}></Image>
  257. </View>
  258. <View className="sl-right">
  259. <View className="sign"></View>
  260. <View className="sl-text">{item.msg}</View>
  261. </View>
  262. </View>
  263. :
  264. <View className="scoped-msg-tips">{item.msg}</View>
  265. }
  266. </View>
  267. )
  268. })
  269. return (
  270. <View className="scoped-list">
  271. {curItems}
  272. </View>
  273. )
  274. }
  275. sendHandle () {
  276. const that = this
  277. const { uObj } = this.state
  278. const { commentVal } = this.state
  279. let { msgSocketList } = this.state
  280. const { to_user_id } = this.$router.params
  281. let apiStr = 'apiusersendmessage'
  282. if (commentVal) {
  283. Taro.api.room[apiStr]({
  284. message: commentVal,
  285. type: 'text',
  286. to_user: to_user_id,
  287. }).then(res => {
  288. msgSocketList.push({
  289. from: uObj.user_id,
  290. msg: commentVal
  291. })
  292. this.setState({
  293. msgSocketList,
  294. commentVal: '',
  295. }, () => {
  296. setTimeout(() => {
  297. that.setState({
  298. viewId: `item${msgSocketList.length - 1}`
  299. })
  300. }, 100)
  301. })
  302. })
  303. } else {
  304. Taro.$msg('请输入')
  305. }
  306. }
  307. changeInput (e) {
  308. const val = strTrim(e.target.value)
  309. this.setState({
  310. commentVal: val
  311. })
  312. }
  313. renderFooter () {
  314. const { commentVal } = this.state
  315. return (
  316. <View className="l-floor-footer">
  317. <View className="scoped-footer">
  318. <View className="sf-input">
  319. <Input className="input" placeholder={`请输入`} value={commentVal} onInput={this.changeInput.bind(this)} />
  320. <View className="btn" onClick={this.sendHandle.bind(this)}>发送</View>
  321. </View>
  322. </View>
  323. </View>
  324. )
  325. }
  326. render () {
  327. return (
  328. <View className="l-box has-footer">
  329. {this.renderList()}
  330. {this.renderFooter()}
  331. </View>
  332. )
  333. }
  334. }
  335. export default Index