业务交流通
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

wechat2.js 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. var utils = require("../../../utils/util.js")
  2. const app = getApp()
  3. const $request = require('../../../utils/request.js');
  4. const $faces = require('../../../utils/faces.js');
  5. Page({
  6. /**
  7. * 页面的初始数据
  8. */
  9. data: {
  10. receivebaseInfo: {
  11. avatar: "http://wx.qlogo.cn/mmopen/ajNVdqHZLLAIliaZvz5B1ibTzTehYzXdfBZ9hXTL7yuhuCUQGyzbuHeYS2yr8rO5PkbUBbHuWb5h9SibpRQkj3GTw/0",
  12. },
  13. sendAvatar: 'http://wx.qlogo.cn/mmopen/ajNVdqHZLLAIliaZvz5B1ibTzTehYzXdfBZ9hXTL7yuhuCUQGyzbuHeYS2yr8rO5PkbUBbHuWb5h9SibpRQkj3GTw/0',
  14. newsList: [
  15. // {
  16. // date: "2020.10.19",
  17. // message: '哈喽,好久不见',
  18. // type: 0
  19. // },
  20. // {
  21. // date: "2020.10.20",
  22. // message: '是呀,好久不见',
  23. // type: 1
  24. // },
  25. ],//消息列表
  26. historyList: [],
  27. input: null,
  28. openid: null,
  29. // 表情
  30. connectemoji: [],
  31. emoji_list: ['emoji1i1', 'emoji2i2', 'emoji3i3', 'emoji4i4', 'emoji5i5'],
  32. emotionVisible: false,
  33. inputShowed: false,
  34. scrollTop: 0,
  35. inputBottom: '0px',
  36. // 当前登录用户的ID
  37. receiveMemberId: null,
  38. // 对方的聊天ID
  39. sendMemberId: null,
  40. scrollid: 'scrollid',
  41. scrollHeight: '300px',
  42. // 下拉刷新
  43. triggered: true,
  44. // 历史记录当前页
  45. pageNo: 1,
  46. // 当前产品ID
  47. businessCommunicationDemandId: null,
  48. // 当前产品详情
  49. productInfo: null,
  50. // 发送框是否获取焦点
  51. inputShowed: false,
  52. },
  53. /**
  54. * 生命周期函数--监听页面加载
  55. */
  56. onLoad(options) {
  57. const eventChannel = this.getOpenerEventChannel()
  58. // 监听acceptDataFromOpenerPage事件,获取上一页面通过eventChannel传送到当前页面的数据
  59. eventChannel.on('customerid', data => {
  60. let productInfo = data.info ? data.info : null;
  61. let businessCommunicationDemandId = null;
  62. if (data.businessCommunicationDemandId) {
  63. businessCommunicationDemandId = data.businessCommunicationDemandId;
  64. }
  65. this.setData({
  66. sendMemberId: data.customerid,
  67. businessCommunicationDemandId,
  68. receivebaseInfo: {
  69. avatar: data.chatHeads,
  70. },
  71. productInfo
  72. })
  73. // 获取历史记录
  74. this.getHistory();
  75. })
  76. let customerId = app.globalData.customerId;
  77. let sendAvatar = app.globalData.businessCommunicationCustomer.chatHeads;
  78. this.setData({
  79. receiveMemberId: customerId,
  80. sendAvatar,
  81. connectemoji: $faces.getfaces(),
  82. })
  83. // 获取内存中的数据
  84. this.getStorageBaseInfo()
  85. // 设置滚动区域的高度
  86. this.setScrollHeight()
  87. // 初始化websocket
  88. this.initWebSocket()
  89. // setTimeout(() => {
  90. // }, 100);
  91. },
  92. /**
  93. * 生命周期函数--监听页面初次渲染完成
  94. */
  95. onReady: function () {
  96. },
  97. // websocket初始化
  98. initWebSocket: function () {
  99. var _this = this;
  100. let { receiveMemberId, sendMemberId } = _this.data;
  101. // console.log()
  102. //建立连接
  103. wx.connectSocket({
  104. url: `ws://192.168.18.138/webSocket/{"userno":${receiveMemberId},"messageModule":"010"}`,//本地
  105. success: function () {
  106. console.log('websocket连接成功~')
  107. },
  108. fail: function () {
  109. console.log('websocket连接失败~')
  110. },
  111. })
  112. //连接成功
  113. wx.onSocketOpen(function () {
  114. console.log('onSocketOpen', '连接成功,真正的成功');
  115. })
  116. // 接收服务器的消息事件
  117. wx.onSocketMessage(function (res) {
  118. // 接收到的消息{date,message,type} type类型为 1 是对方的消息 为 0 是自己的消息
  119. let list = [];
  120. list = _this.data.newsList;
  121. let _data = JSON.parse(res.data);
  122. _data.chatRecord = JSON.parse(_data.chatRecord);
  123. let msgData = {};
  124. if (_data.chatRecord.sender != _this.data.receiveMemberId) {
  125. msgData.type = 1;
  126. } else {
  127. msgData.type = 0;
  128. }
  129. msgData.message = _data.chatRecord.content;
  130. list.push(msgData);
  131. _this.setData({
  132. newsList: list
  133. })
  134. _this.scrollBottom()
  135. },
  136. )
  137. // 监听连接关闭
  138. wx.onSocketClose(function () {
  139. console.log('监听 WebSocket 连接关闭事件')
  140. })
  141. },
  142. // 获取历史记录
  143. getHistory() {
  144. var { sendMemberId, businessCommunicationDemandId } = this.data;
  145. $request.get('/businessCommunicationDemand/getChatRecordById/' + sendMemberId + '.action').then(res => {
  146. if (res.status == 0) {
  147. var historyList = [...res.data.chatRecordList, ...this.data.historyList]
  148. if (historyList && historyList.length > 0) {
  149. historyList.forEach(item => {
  150. if (item.sender != sendMemberId) {
  151. item.type = 0
  152. } else {
  153. item.type = 1
  154. }
  155. item.date = utils.formatTime(new Date(item.sendTime));
  156. item.date = item.date.replaceAll('/', '-');
  157. });
  158. this.setData({
  159. historyList
  160. })
  161. console.log(this.data.historyList, '历史记录数据')
  162. }
  163. // 如果产品ID存在
  164. console.log(businessCommunicationDemandId, '产品ID是否存在')
  165. if (businessCommunicationDemandId) {
  166. if (historyList.length > 0) {
  167. let tempArr = [];
  168. for (let index = historyList.length - 1; index >= 0; index--) {
  169. const element = historyList[index];
  170. if (element.messageType == 1) {
  171. tempArr.push(element);
  172. if (element.transactionId == businessCommunicationDemandId) {
  173. break;
  174. } else {
  175. this.sendmsgApi("", 1);
  176. console.log(`走这里1`)
  177. }
  178. }
  179. }
  180. // 说明没有一条是messageType == 1 的
  181. if(tempArr.length < 1){
  182. this.sendmsgApi("", 1);
  183. console.log(`走这里3`)
  184. }
  185. } else {
  186. this.sendmsgApi("", 1);
  187. console.log(`走这里2`)
  188. }
  189. }
  190. }
  191. // 页面进入滚动到底部
  192. this.scrollBottom()
  193. }).catch(err => {
  194. console.log(err)
  195. })
  196. },
  197. // 滚动到底部
  198. scrollBottom: function () {
  199. var { newsList } = this.data
  200. var scrollid = `scrollid${newsList.length - 1}`;
  201. if (newsList.length == 0) {
  202. scrollid = "scrollid0"
  203. }
  204. this.setData({
  205. scrollid
  206. })
  207. },
  208. // 设置滚动区域的高度
  209. setScrollHeight: function () {
  210. const client = wx.getSystemInfoSync().windowHeight // 获取当前窗口的高度
  211. var scrollHeight = (client - 136) + 'px'
  212. this.setData({
  213. scrollHeight
  214. })
  215. },
  216. // 进入详情
  217. goDetails(e) {
  218. let value = e.currentTarget.dataset.value;
  219. wx.reLaunch({
  220. url: '/pages/index/components/listDetails/Details?businessCommunicationDemandId=' + value,
  221. })
  222. },
  223. // 获取内存中聊天列表的用户信息
  224. getStorageBaseInfo: function () {
  225. //获取存储信息
  226. wx.getStorage({
  227. key: 'receivebaseInfo',
  228. success: (res) => {
  229. this.setData({
  230. receivebaseInfo: res.data
  231. })
  232. }
  233. })
  234. },
  235. // 自定义下拉刷新
  236. refresh: function () {
  237. // // 下拉的实际操作
  238. // var pageNo = this.data.pageNo + 1
  239. // this.setData({
  240. // pageNo
  241. // })
  242. // if (this.timer) {
  243. // clearTimeout(this.timer)
  244. // }
  245. // this.timer = setTimeout(() => {
  246. // this.setData({
  247. // triggered: false
  248. // })
  249. // this.getHistory()
  250. // }, 2000)
  251. },
  252. /**
  253. * 生命周期函数--监听页面显示
  254. */
  255. onShow: function () {
  256. },
  257. /**
  258. * 生命周期函数--监听页面隐藏
  259. */
  260. onHide: function () {
  261. // wx.closeSocket();
  262. },
  263. /**
  264. * 生命周期函数--监听页面卸载
  265. */
  266. onUnload: function () {
  267. // wx.closeSocket();
  268. },
  269. /**
  270. * 页面相关事件处理函数--监听用户下拉动作
  271. */
  272. onPullDownRefresh: function () {
  273. },
  274. /**
  275. * 页面上拉触底事件的处理函数
  276. */
  277. onReachBottom: function () {
  278. },
  279. /**
  280. * 用户点击右上角分享
  281. */
  282. onShareAppMessage: function () {
  283. },
  284. send: function () {
  285. var _this = this;
  286. if (_this.data.input) {
  287. this.sendmsgApi(_this.data.input, 0);
  288. }
  289. },
  290. sendmsgApi(content, msgType) {
  291. let { sendMemberId, receiveMemberId, businessCommunicationDemandId } = this.data;
  292. let transactionId = businessCommunicationDemandId;
  293. if (!businessCommunicationDemandId) {
  294. if(this.data.historyList.length > 0){
  295. transactionId = this.data.historyList[this.data.historyList.length - 1].transactionId;
  296. }
  297. }
  298. if(!transactionId){
  299. transactionId = "";
  300. }
  301. let params = {
  302. sender: receiveMemberId, // 发件人Id
  303. addressee: sendMemberId, // 收件人Id
  304. transactionId, // 产品ID
  305. content,
  306. messageType: msgType,
  307. };
  308. $request.post('/businessCommunicationDemand/addChatRecord.action', params).then(res => {
  309. console.log(`------------聊一聊保存记录-----------------`)
  310. console.log(res);
  311. // 是由需求点击的聊一聊 保存完信息后需要再发送一条
  312. if (msgType == 1) {
  313. this.sendmsgApi("你好,我对这个需求很有兴趣,可以聊聊吗?", 0);
  314. }
  315. console.log(`------------聊一聊保存记录-----------------`)
  316. }).catch(err => {
  317. console.log(err)
  318. })
  319. var list = [];
  320. list = this.data.newsList;
  321. var temp = { 'message': content, 'date': utils.formatTime(new Date()), type: 0 };
  322. temp.date = temp.date.replaceAll('/', '-');
  323. temp.messageType = msgType;
  324. temp.transactionId = transactionId;
  325. if (msgType == 1) {
  326. temp.info = this.data.productInfo;
  327. }
  328. list.push(temp);
  329. this.setData({
  330. newsList: list,
  331. input: null
  332. })
  333. console.log(this.data.newsList, 'this.data.newsList')
  334. this.scrollBottom()
  335. // 表情选择隐藏
  336. this.setData({
  337. emotionVisible: false,
  338. })
  339. const client = wx.getSystemInfoSync().windowHeight // 获取当前窗口的高度
  340. console.log(client, '当前消息高度')
  341. },
  342. bindChange: function (res) {
  343. this.setData({
  344. input: res.detail.value,
  345. })
  346. },
  347. back: function () {
  348. wx.closeSocket();
  349. console.log('连接断开');
  350. },
  351. emotionChange() {
  352. console.log(`测试打开表情`)
  353. this.setData({
  354. emotionVisible: !this.data.emotionVisible
  355. })
  356. },
  357. addemotion: function (e) {
  358. console.log(e.currentTarget.dataset.index, "点了设默默")
  359. let { connectemoji, input } = this.data
  360. if (input) {
  361. input = input + connectemoji[e.currentTarget.dataset.index];
  362. } else {
  363. input = connectemoji[e.currentTarget.dataset.index]
  364. }
  365. console.log(input, '输入框额值')
  366. this.setData({
  367. input,
  368. emotionVisible: false,
  369. inputShowed: true,
  370. })
  371. },
  372. closeEmotionVisible() {
  373. this.setData({
  374. emotionVisible: false,
  375. })
  376. },
  377. // 发送图片
  378. upImg() {
  379. wx.chooseImage({
  380. count: 1,
  381. success: (res) => {
  382. console.log(res);
  383. console.log(res.tempFilePaths[0], '拿到的URL');
  384. wx.uploadFile({
  385. filePath: res.tempFilePaths[0],
  386. name: "file",
  387. url: "/file/uploading.action?fileType=TinymceImg",
  388. success: (res2) => {
  389. console.log(`上传之后的res2`,res2)
  390. }
  391. })
  392. // /file/uploading.action?fileType=TinymceImg
  393. }
  394. })
  395. },
  396. // 公共聚焦方法,方法比较笨,但是过度效果平滑流畅
  397. bottom: function () {
  398. var that = this;
  399. // 获取元素的高度
  400. let query = wx.createSelectorQuery();
  401. query.select('.news').boundingClientRect(rect => {
  402. //获取到元素
  403. let scrollTop = rect.height;
  404. this.setData({
  405. scrollTop
  406. })
  407. }).exec();
  408. console.log(this.data.scrollTop, 'hahah')
  409. wx.pageScrollTo({
  410. // scrollTop: this.data.scrollTop + 30,
  411. scrollTop: 10000,
  412. // duration: 0
  413. })
  414. },
  415. })