123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489 |
- var utils = require("../../../utils/util.js")
- const app = getApp()
- const $request = require('../../../utils/request.js');
- const $faces = require('../../../utils/faces.js');
- Page({
-
- /**
- * 页面的初始数据
- */
- data: {
- receivebaseInfo: {
- avatar: "http://wx.qlogo.cn/mmopen/ajNVdqHZLLAIliaZvz5B1ibTzTehYzXdfBZ9hXTL7yuhuCUQGyzbuHeYS2yr8rO5PkbUBbHuWb5h9SibpRQkj3GTw/0",
- },
- sendAvatar: 'http://wx.qlogo.cn/mmopen/ajNVdqHZLLAIliaZvz5B1ibTzTehYzXdfBZ9hXTL7yuhuCUQGyzbuHeYS2yr8rO5PkbUBbHuWb5h9SibpRQkj3GTw/0',
- newsList: [
- // {
- // date: "2020.10.19",
- // message: '哈喽,好久不见',
- // type: 0
- // },
- // {
- // date: "2020.10.20",
- // message: '是呀,好久不见',
- // type: 1
- // },
- ],//消息列表
- historyList: [],
- input: null,
- openid: null,
- // 表情
- connectemoji: [],
- emoji_list: ['emoji1i1', 'emoji2i2', 'emoji3i3', 'emoji4i4', 'emoji5i5'],
- emotionVisible: false,
- inputShowed: false,
- scrollTop: 0,
- inputBottom: '0px',
- // 当前登录用户的ID
- receiveMemberId: null,
- // 对方的聊天ID
- sendMemberId: null,
- scrollid: 'scrollid',
- scrollHeight: '300px',
- // 下拉刷新
- triggered: true,
- // 历史记录当前页
- pageNo: 1,
- // 当前产品ID
- businessCommunicationDemandId: null,
- // 当前产品详情
- productInfo: null,
- // 发送框是否获取焦点
- inputShowed: false,
- // 是发送图片---用于阻止触发onhide
- isSendImg: false,
- // 发送图片url
- mangerUrl: "",
- },
-
- /**
- * 生命周期函数--监听页面加载
- */
- onLoad(options) {
- this.setData({
- mangerUrl: app.mangerUrl + "/file/getPhotos.action?path="
- })
- const eventChannel = this.getOpenerEventChannel()
- // 监听acceptDataFromOpenerPage事件,获取上一页面通过eventChannel传送到当前页面的数据
-
- eventChannel.on('customerid', data => {
- let productInfo = data.info ? data.info : null;
- let businessCommunicationDemandId = null;
- if (data.businessCommunicationDemandId) {
- businessCommunicationDemandId = data.businessCommunicationDemandId;
- }
- this.setData({
- sendMemberId: data.customerid,
- businessCommunicationDemandId,
- receivebaseInfo: {
- avatar: data.chatHeads,
- },
- productInfo
- })
-
- // 获取历史记录
- this.getHistory();
- })
- let customerId = app.globalData.customerId;
- let sendAvatar = app.globalData.businessCommunicationCustomer.chatHeads;
- this.setData({
- receiveMemberId: customerId,
- sendAvatar,
- connectemoji: $faces.getfaces(),
- })
- // 如果全局的 websocket 是连接的,需要关闭连接 调用自身的
- if(app.globalData.isOnSocketOpen){
- wx.closeSocket();
- }
- // 获取内存中的数据
- this.getStorageBaseInfo()
- // 设置滚动区域的高度
- this.setScrollHeight()
- // 初始化websocket
- this.initWebSocket()
- // setTimeout(() => {
-
- // }, 100);
- },
- /**
- * 生命周期函数--监听页面初次渲染完成
- */
- onReady: function () {
-
- },
-
- // websocket初始化
- initWebSocket: function () {
- var _this = this;
- let { receiveMemberId, sendMemberId } = _this.data;
- // console.log()
- //建立连接
- wx.connectSocket({
- url: `ws://192.168.18.138/webSocket/{"userno":${receiveMemberId},"messageModule":"010"}`,//本地
- success: function () {
- console.log('websocket连接成功~')
- },
- fail: function () {
- console.log('websocket连接失败~')
- },
- })
-
- //连接成功
- wx.onSocketOpen(function () {
- console.log('onSocketOpen', '连接成功,真正的成功');
- })
-
- // 接收服务器的消息事件
- wx.onSocketMessage(function (res) {
- // 接收到的消息{date,message,type} type类型为 1 是对方的消息 为 0 是自己的消息
- let list = [];
- list = _this.data.newsList;
- let _data = JSON.parse(res.data);
- _data.chatRecord = JSON.parse(_data.chatRecord);
-
- let msgData = {};
- // type 0 自己 1 对方
- if (_data.chatRecord.sender != _this.data.receiveMemberId) {
- msgData.type = 1;
- } else {
- msgData.type = 0;
- }
- msgData.isRead = true;
- msgData.message = _data.chatRecord.content;
- msgData.messageType = _data.chatRecord.messageType;
- if (msgData.messageType == 1) {
- msgData.object = _data.chatRecord.object;
- }
- msgData.date = utils.formatTime(new Date(_data.chatRecord.sendTime));
- msgData.date = msgData.date.replaceAll('/', '-');
- list.push(msgData);
- _this.setData({
- newsList: list
- })
- _this.setMsgRead('newsList', _this.data.newsList, 0)
- _this.scrollBottom()
- console.log('--------------对方给你发消息拉 beg -------------')
- console.log(_data);
- console.log('--------------对方给你发消息拉 end -------------')
- },
- )
-
- // 监听连接关闭
- wx.onSocketClose(function () {
- console.log('监听 WebSocket 连接关闭事件')
- })
-
- },
-
- // 获取历史记录
- getHistory() {
- var { sendMemberId, businessCommunicationDemandId } = this.data;
- $request.get('/businessCommunicationDemand/getChatRecordById/' + sendMemberId + '.action').then(res => {
-
- if (res.status == 0) {
- var historyList = [...res.data.chatRecordList, ...this.data.historyList]
- if (historyList && historyList.length > 0) {
- historyList.forEach(item => {
- // type 0 自己 1 对方
- if (item.sender != sendMemberId) {
- item.type = 0
- } else {
- item.type = 1
- }
- item.date = utils.formatTime(new Date(item.sendTime));
- item.date = item.date.replaceAll('/', '-');
- });
- this.setData({
- historyList
- })
- console.log(this.data.historyList, '历史记录数据')
- }
- // 如果产品ID存在
- console.log(businessCommunicationDemandId, '产品ID是否存在')
- if (businessCommunicationDemandId) {
- if (historyList.length > 0) {
- let tempArr = [];
- for (let index = historyList.length - 1; index >= 0; index--) {
- const element = historyList[index];
- if (element.messageType == 1 && tempArr.length < 1) {
- tempArr.push(element);
- }
- }
- // 说明没有一条是messageType == 1 的
- if (tempArr.length < 1) {
- this.sendmsgApi("", 1);
- } else {
- if (tempArr[0].transactionId != businessCommunicationDemandId) {
- this.sendmsgApi("", 1);
- }
- }
- } else {
- this.sendmsgApi("", 1);
- }
- }
- }
- // 设置消息已读
- this.setMsgRead('historyList', this.data.historyList, 1)
- // 页面进入滚动到底部
- this.scrollBottom()
- }).catch(err => {
- console.log(err)
- })
- },
-
- // 滚动到底部
- scrollBottom: function () {
- var { newsList } = this.data
- var scrollid = `scrollid${newsList.length - 1}`;
- if (newsList.length == 0) {
- scrollid = "scrollid0"
- }
- this.setData({
- scrollid
- })
- },
-
- // 设置滚动区域的高度
- setScrollHeight: function () {
- const client = wx.getSystemInfoSync().windowHeight // 获取当前窗口的高度
- var scrollHeight = (client - 136) + 'px'
- this.setData({
- scrollHeight
- })
- },
- // 进入详情
- goDetails(e) {
- let value = e.currentTarget.dataset.value;
- wx.navigateTo({
- url: '/pages/index/components/listDetails/Details?businessCommunicationDemandId=' + value,
- })
- },
- // 获取内存中聊天列表的用户信息
- getStorageBaseInfo: function () {
- //获取存储信息
- wx.getStorage({
- key: 'receivebaseInfo',
- success: (res) => {
- this.setData({
- receivebaseInfo: res.data
- })
- }
- })
- },
-
- // 自定义下拉刷新
- refresh: function () {
- // // 下拉的实际操作
- // var pageNo = this.data.pageNo + 1
- // this.setData({
- // pageNo
- // })
- // if (this.timer) {
- // clearTimeout(this.timer)
- // }
- // this.timer = setTimeout(() => {
- // this.setData({
- // triggered: false
- // })
- // this.getHistory()
- // }, 2000)
- },
-
- /**
- * 生命周期函数--监听页面显示
- */
- onShow: function () {
- },
-
- /**
- * 生命周期函数--监听页面隐藏
- */
- onHide: function () {
- // 如果是发送图片就不触发
- if (!this.data.isSendImg) {
- wx.closeSocket();
- // 检测到全局的 websocket 是连接的 关闭
- if(app.globalData.isOnSocketOpen){
- app.globalData.isOnSocketOpen = false;
- }
- }
- },
-
- /**
- * 生命周期函数--监听页面卸载
- */
- onUnload: function () {
- // 如果是发送图片就不触发
- if (!this.data.isSendImg) {
- wx.closeSocket();
- // 检测到全局的 websocket 是连接的 关闭
- if(app.globalData.isOnSocketOpen){
- app.globalData.isOnSocketOpen = false;
- }
- }
- },
-
- /**
- * 页面相关事件处理函数--监听用户下拉动作
- */
- onPullDownRefresh: function () {
-
- },
-
- /**
- * 页面上拉触底事件的处理函数
- */
- onReachBottom: function () {
-
- },
- send: function () {
- var _this = this;
- if (_this.data.input) {
- this.sendmsgApi(_this.data.input, 0);
- }
- },
- sendmsgApi(content, msgType) {
- let { sendMemberId, receiveMemberId, businessCommunicationDemandId } = this.data;
- let transactionId = businessCommunicationDemandId;
- if (!businessCommunicationDemandId) {
- if (this.data.historyList.length > 0) {
- transactionId = this.data.historyList[this.data.historyList.length - 1].transactionId;
- }
- }
- if (!transactionId) {
- transactionId = "";
- }
- let params = {
- sender: receiveMemberId, // 发件人Id
- addressee: sendMemberId, // 收件人Id
- transactionId, // 产品ID
- content,
- messageType: msgType,
- };
- $request.post('/businessCommunicationDemand/addChatRecord.action', params).then(res => {
- // 是由需求点击的聊一聊 保存完信息后需要再发送一条
- if (msgType == 1) {
- this.sendmsgApi("你好,我对这个需求很有兴趣,可以聊聊吗?", 0);
- }
- }).catch(err => {
- console.log(err)
- })
- var list = [];
- list = this.data.newsList;
- var temp = { 'message': content, 'date': utils.formatTime(new Date()), type: 0 };
- temp.date = temp.date.replaceAll('/', '-');
- temp.messageType = msgType;
- temp.transactionId = transactionId;
- temp.isRead = false;
- if (msgType == 1) {
- temp.object = {};
- temp.object.info = this.data.productInfo;
- }
- list.push(temp);
- this.setData({
- newsList: list,
- input: null
- })
-
- console.log(this.data.newsList, 'this.data.newsList')
- this.scrollBottom()
- // 表情选择隐藏
- this.setData({
- emotionVisible: false,
- })
- const client = wx.getSystemInfoSync().windowHeight // 获取当前窗口的高度
- console.log(client, '当前消息高度')
- },
- bindChange: function (res) {
- this.setData({
- input: res.detail.value,
- })
- },
- back: function () {
- wx.closeSocket();
- console.log('连接断开');
- },
- emotionChange() {
- console.log(`测试打开表情`)
- this.setData({
- emotionVisible: !this.data.emotionVisible
- })
- },
- addemotion: function (e) {
- console.log(e.currentTarget.dataset.index, "点了设默默")
- let { connectemoji, input } = this.data
- if (input) {
- input = input + connectemoji[e.currentTarget.dataset.index];
- } else {
- input = connectemoji[e.currentTarget.dataset.index]
- }
-
- console.log(input, '输入框额值')
- this.setData({
- input,
- emotionVisible: false,
- inputShowed: true,
- })
- },
- closeEmotionVisible() {
- this.setData({
- emotionVisible: false,
- })
- },
- // 发送图片
- upImg() {
- this.setData({
- isSendImg: true
- })
- wx.chooseImage({
- count: 1,
- success: (res) => {
- wx.uploadFile({
- filePath: res.tempFilePaths[0],
- name: "file",
- url: app.mangerUrl + "/file/uploading.action?fileType=TinymceImg",
- success: (res2) => {
- let data = JSON.parse(res2.data);
- this.sendmsgApi(data.data, 2);
- }
- })
- // /file/uploading.action?fileType=TinymceImg
- },
- complete: (res) => {
- // 调用结束后要关闭isSendImg
- this.setData({
- isSendImg: false
- })
- }
- })
- },
- // 设置已读未读
- setMsgRead(key, data, type) {
- data.forEach(el => {
- if (el.type == type) {
- el.isRead = true;
- }
- })
- if (key == 'historyList') {
- this.setData({
- historyList: data
- })
- } else {
- this.setData({
- newsList: data
- })
- }
- },
- // 图片预览
- viewImg(e) {
- let url = e.currentTarget.dataset.url;
- url += "?time=" + Date.now();
- console.log(url)
- wx.previewImage({
- current: url, // 当前显示图片的http链接
- urls: [url] // 需要预览的图片http链接列表
- })
- },
- })
-
|