import Taro, { Component } from '@tarojs/taro' import { View, ScrollView } from '@tarojs/components' import ListMore from '@/c/pageDataList/listMore' import { strTrim, arrToObj } from '@utils' const HLKEY = '654mca0l38b489d9' const CJ = require('crypto-js') import './chat.scss' class Index extends Component { constructor (props) { super(props) const {id: curId} = this.$router.params this.state = { page_size: 10, page: 1, isListEnd: false, isListLoading: false, isListEmpty: false, dataList: [], curId, curObj: {}, commentVal: '', msgSocketList: [], uObj: {}, chatUserObj: {}, viewId: '', socketTimer: null, } } config = { navigationBarTitleText: '在线沟通', } componentWillUnmount () { this.closeSocket() let pages = getCurrentPages() let prevPage = pages[ pages.length - 2 ] if (prevPage.$component.getNotifycount) prevPage.$component.getNotifycount() // if (prevPage.$component.getNewData) prevPage.$component.getNewData() } closeSocket () { Taro.closeSocket() const { socketTimer } = this.state clearInterval(socketTimer) } componentDidMount () { const that = this let uObj = Taro.getStorageSync('APP_userInfo') const { to_user_id } = this.$router.params this.setState({ uObj }, () => { let uArr = [uObj.user_id, to_user_id] Taro.api.base.apiuserinfolist({ user_ids: uArr.join(',') }).then(res => { let chatUserObj = {} const list = res.list || [] list.forEach(item => { if (item.id !== uObj.user_id) { Taro.setNavigationBarTitle({ title: item.nickname }) } chatUserObj[item.id] = item }) that.setState({ chatUserObj }) }) Taro.$AHU(this) this.getDataList() this.initSocket() }) } getDataList () { const { to_user_id } = this.$router.params let { page_size, page, dataList, isListEmpty } = this.state Taro.api.room.apiuserchatlist({ page, page_size, to_user_id, }).then(res => { let curData = res.list || [] curData = curData.reverse() let isListEnd = false if (curData.length > 0) { if (page === 1) { dataList = curData } else { dataList = [].concat(curData, dataList) } if (curData.length === page_size && res.total !== curData.length) { isListEnd = false } else { isListEnd = true } } if (curData.length === 0 && page === 1) { isListEmpty = true dataList = [] } else { isListEmpty = false } const that = this this.setState({ dataList, isListEnd, isListEmpty, isListLoading: false }, () => { if (page > 1) { setTimeout(() => { that.setState({ viewId: `history11` }) }, 500) } }) }) } onScrollToUpper (e) { let { isListEnd, isListLoading, page } = this.state if (!isListEnd && !isListLoading) { page++ this.setState({ page, isListLoading: true }, () => { this.getDataList() }) } } initSocket () { const { uObj } = this.state const that = this Taro.connectSocket({ url: 'wss://chat.honglouplus.com/acc', success: function () { console.log('connect success') } }).then(task => { task.onOpen(function () { // console.log('onOpen') let token = Taro.getStorageSync('APP_token') task.send({ data: '{"seq":"' + that.sendId() + '","cmd":"login","data":{"userId":"' + uObj.user_id + '","appId":101,"serviceToken":"' + token + '"}}' }) const socketTimer = setInterval(() => { task.send({data: '{"seq":"' + that.sendId() + '","cmd":"heartbeat","data":{}}'}); }, 30000) that.setState({ socketTimer }) }) task.onMessage(function (msg) { // console.log('onMessage: ', msg) let { msgSocketList } = that.state const data = JSON.parse(msg.data) // console.log(data) if (data.cmd === 'msg' || data.cmd === 'login') { const res = data.response || {} if (res.code === 200) { if (data.cmd === 'login') { msgSocketList.push({msg: '登录成功~'}) } else { const { to_user_id } = that.$router.params if (to_user_id === res.data.from) { msgSocketList.push(res.data) } else { msgSocketList.push({msg: '有其他人给你发消息啦,返回消息列表查看'}) } } that.setState({ msgSocketList }, () => { const { qId } = that.$router.params if (qId) that.sendHandle('house') const { eTitle, eId } = that.$router.params if (eId) that.sendHandle('text', `我刚刚浏览了楼盘:${eTitle},想咨询你一下`) setTimeout(() => { that.setState({ viewId: `item${msgSocketList.length - 1}` }) }, 500) }) } } if (data.cmd === 'heartbeat') { const res = data.response || {} if (res.code !== 200) { msgSocketList.push({msg: res.codeMsg + '|暂无法接收消息,请退出当前页面重新登录~'}) that.setState({ msgSocketList }, () => { setTimeout(() => { that.setState({ viewId: `item${msgSocketList.length - 1}` }, () => { that.closeSocket() }) }, 100) }) } } // task.close() }) task.onError(function () { console.log('onError') }) task.onClose(function (e) { console.log('onClose: ', e) }) }) } sendId () { let timeStamp = +new Date() let randId = parseInt(Math.random() * 1000000) return `${timeStamp}-${randId}` } componentDidShow () { } componentDidHide () { } avatarHandle (item) { const { uObj } = this.state if (uObj.is_sale === '1') { Taro.navigateTo({ url: `/pagesRoom/follow/user?uId=${item.user_id}` }) } } renderList () { const { chatUserObj, uObj, viewId } = this.state const { dataList, isListEnd, isListLoading, isListEmpty } = this.state const itemList = dataList.map((item, index) => { let tObj = {} if (item.type === 'house') tObj = JSON.parse(item.content) return ( { item.user_id === uObj.user_id ? : } { item.type === 'house' ? 你好,我想咨询一下 #{tObj.name}# : '' } { item.type === 'image' ? : '' } { item.type === 'text' ? {item.content} : '' } {item.create_at} ) }) return ( {itemList} {/* { dataList.length > 0 && } */} {this.renderMsgList()} ) } previewImageHandle (current, urls) { Taro.previewImage({ current, urls }) } renderMsgList () { const { msgSocketList } = this.state const { chatUserObj, uObj } = this.state const curItems = msgSocketList.map((item, index) => { let tObj = {} if (item.type === 'house') tObj = JSON.parse(item.msg) return ( { item.from ? { item.type === 'house' ? 你好,我想咨询一下 #{tObj.name}# : '' } { item.type === 'image' ? : '' } { item.type === 'text' ? {item.msg} : '' } : {item.msg} } ) }) return ( {curItems} ) } copyHandle (msg) { Taro.setClipboardData({ data: msg, success: function (res) { Taro.getClipboardData({ success: function (res) { console.log(res.data) } }) } }) } sendHandle (type, curMsg) { const that = this const { uObj } = this.state const { commentVal } = this.state let { msgSocketList } = this.state const { to_user_id } = this.$router.params let apiStr = 'apiusersendmessage' let msg = commentVal if (type === 'house') { const { qTitle, qId } = that.$router.params msg = JSON.stringify({ name: qTitle, id: qId, }) } if (curMsg && type === 'image') msg = curMsg if (typeof(curMsg) === 'string' && type === 'text') msg = curMsg if (msg) { Taro.api.room[apiStr]({ message: msg, type, to_user: to_user_id, }).then(res => { msgSocketList.push({ from: uObj.user_id, type, msg }) this.setState({ msgSocketList, commentVal: '', }, () => { setTimeout(() => { that.setState({ viewId: `item${msgSocketList.length - 1}` }) }, 100) }) }) } else { Taro.$msg('请输入') } } changeInput (e) { const val = strTrim(e.target.value) this.setState({ commentVal: val }) } uploadImgHandle () { let token = Taro.getStorageSync('APP_token') const that = this Taro.chooseImage({ count: 1, // 默认9 sizeType: ['original', 'compressed'], sourceType: ['album', 'camera'], success: function (res) { const tempFilePaths = res.tempFilePaths Taro.uploadFile({ url: `https://api.honglouplus.com/api/upload/cloud`, filePath: tempFilePaths[0], name: 'upload', formData: { 'token': token }, success (res){ const msg = res.data || '' const key = CJ.enc.Utf8.parse(HLKEY) const bytes = CJ.AES.decrypt(msg, key, { mode: CJ.mode.ECB, padding: CJ.pad.Pkcs7 }) const originalText = bytes.toString(CJ.enc.Utf8) const cData = JSON.parse(originalText) const curImg = cData.data.url || '' that.sendHandle('image', curImg) } }) } }) } renderFooter () { const { commentVal } = this.state const bgImg = require('./img/img_uploads.png') return ( 发送 ) } render () { return ( {this.renderList()} {this.renderFooter()} ) } } export default Index