业务交流通
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

wechat2.js 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  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. // 是发送图片---用于阻止触发onhide
  53. isSendImg: false,
  54. // 发送图片url
  55. mangerUrl: "",
  56. },
  57. /**
  58. * 生命周期函数--监听页面加载
  59. */
  60. onLoad(options) {
  61. this.setData({
  62. mangerUrl: app.mangerUrl + "/file/getPhotos.action?path="
  63. })
  64. const eventChannel = this.getOpenerEventChannel()
  65. // 监听acceptDataFromOpenerPage事件,获取上一页面通过eventChannel传送到当前页面的数据
  66. eventChannel.on('customerid', data => {
  67. let productInfo = data.info ? data.info : null;
  68. let businessCommunicationDemandId = null;
  69. if (data.businessCommunicationDemandId) {
  70. businessCommunicationDemandId = data.businessCommunicationDemandId;
  71. }
  72. this.setData({
  73. sendMemberId: data.customerid,
  74. businessCommunicationDemandId,
  75. receivebaseInfo: {
  76. avatar: data.chatHeads,
  77. },
  78. productInfo
  79. })
  80. // 获取历史记录
  81. this.getHistory();
  82. })
  83. let customerId = app.globalData.customerId;
  84. let sendAvatar = app.globalData.businessCommunicationCustomer.chatHeads;
  85. this.setData({
  86. receiveMemberId: customerId,
  87. sendAvatar,
  88. connectemoji: $faces.getfaces(),
  89. })
  90. // 如果全局的 websocket 是连接的,需要关闭连接 调用自身的
  91. if (app.globalData.isOnSocketOpen) {
  92. wx.closeSocket();
  93. }
  94. // 获取内存中的数据
  95. this.getStorageBaseInfo()
  96. // 设置滚动区域的高度
  97. this.setScrollHeight()
  98. // 初始化websocket
  99. this.initWebSocket()
  100. // setTimeout(() => {
  101. // }, 100);
  102. },
  103. /**
  104. * 生命周期函数--监听页面初次渲染完成
  105. */
  106. onReady: function () {
  107. },
  108. // websocket初始化
  109. initWebSocket: function () {
  110. var _this = this;
  111. let { receiveMemberId, sendMemberId } = _this.data;
  112. let url = encodeURI(`ws://` + app.webSocketUrl + `/webSocket/{"userno":${receiveMemberId},"messageModule":"010"}`);
  113. //建立连接
  114. wx.connectSocket({
  115. url,//本地
  116. success: function () {
  117. console.log('websocket接口调通~还没真正的成功!')
  118. },
  119. fail: function () {
  120. console.log('websocket连接失败~')
  121. },
  122. })
  123. //连接成功
  124. wx.onSocketOpen(function () {
  125. console.log('onSocketOpen', '连接成功,真正的成功');
  126. // wx.showToast({
  127. // title: '连接成功,真正的成功',
  128. // icon: 'success',
  129. // duration: 2000
  130. // })
  131. })
  132. wx.onSocketError(res => {
  133. console.log(`打印异常`)
  134. console.log(res);
  135. })
  136. // 接收服务器的消息事件
  137. wx.onSocketMessage(function (res) {
  138. console.log(res, '消息发送页接受---------------------------------');
  139. // 接收到的消息{date,message,type} type类型为 1 是对方的消息 为 0 是自己的消息
  140. let list = [];
  141. list = _this.data.newsList;
  142. let _data = JSON.parse(res.data);
  143. if (_data.readMessageCode) {
  144. } else {
  145. _data.chatRecord = JSON.parse(_data.chatRecord);
  146. console.log(_data, '_data');
  147. let msgData = {};
  148. // type 0 自己 1 对方
  149. if (_data.chatRecord.chatRecord.sender != _this.data.receiveMemberId) {
  150. msgData.type = 1;
  151. } else {
  152. msgData.type = 0;
  153. }
  154. msgData.isRead = true;
  155. msgData.message = _data.chatRecord.chatRecord.content;
  156. msgData.messageType = _data.chatRecord.chatRecord.messageType;
  157. if (msgData.messageType == 1) {
  158. msgData.object = _data.chatRecord.chatRecord.object;
  159. }
  160. let d = {
  161. sendno: _this.data.receiveMemberId,
  162. userno: _this.data.sendMemberId,
  163. messageModule : "010",
  164. readMessageCode: _data.chatRecord.chatRecord.chatRecordCode,
  165. };
  166. wx.sendSocketMessage({
  167. data: JSON.stringify(d),
  168. success: (res) => {
  169. console.log(`发送成功`)
  170. console.log(res)
  171. },
  172. fail: (err) => {
  173. console.log('sendSocketMessage', '失败')
  174. }
  175. })
  176. msgData.date = utils.formatTime(new Date(_data.chatRecord.chatRecord.sendTime));
  177. msgData.date = msgData.date.replaceAll('/', '-');
  178. list.push(msgData);
  179. _this.setData({
  180. newsList: list
  181. })
  182. _this.setMsgRead('newsList', _this.data.newsList, 0)
  183. _this.scrollBottom()
  184. }
  185. },
  186. )
  187. // 监听连接关闭
  188. wx.onSocketClose(function () {
  189. console.log('监听 WebSocket 连接关闭事件')
  190. })
  191. },
  192. // 获取历史记录
  193. getHistory() {
  194. var { sendMemberId, businessCommunicationDemandId } = this.data;
  195. $request.get('/businessCommunicationDemand/getChatRecordById/' + sendMemberId + '.action').then(res => {
  196. if (res.status == 0) {
  197. var historyList = [...res.data.chatRecordList, ...this.data.historyList]
  198. if (historyList && historyList.length > 0) {
  199. historyList.forEach(item => {
  200. // type 0 自己 1 对方
  201. if (item.sender != sendMemberId) {
  202. item.type = 0
  203. } else {
  204. item.type = 1
  205. }
  206. item.date = utils.formatTime(new Date(item.sendTime));
  207. item.date = item.date.replaceAll('/', '-');
  208. });
  209. this.setData({
  210. historyList
  211. })
  212. }
  213. // 如果产品ID存在
  214. if (businessCommunicationDemandId) {
  215. if (historyList.length > 0) {
  216. let tempArr = [];
  217. for (let index = historyList.length - 1; index >= 0; index--) {
  218. const element = historyList[index];
  219. if (element.messageType == 1 && tempArr.length < 1) {
  220. tempArr.push(element);
  221. }
  222. }
  223. // 说明没有一条是messageType == 1 的
  224. if (tempArr.length < 1) {
  225. this.sendmsgApi("", 1);
  226. } else {
  227. if (tempArr[0].transactionId != businessCommunicationDemandId) {
  228. this.sendmsgApi("", 1);
  229. }
  230. }
  231. } else {
  232. this.sendmsgApi("", 1);
  233. }
  234. }
  235. }
  236. // 设置消息已读
  237. this.setMsgRead('historyList', this.data.historyList, 1)
  238. // 页面进入滚动到底部
  239. this.scrollBottom()
  240. }).catch(err => {
  241. console.log(err)
  242. })
  243. },
  244. // 滚动到底部
  245. scrollBottom: function () {
  246. this.setData({
  247. scrollid: "sendmessage"
  248. })
  249. },
  250. // 设置滚动区域的高度
  251. setScrollHeight: function () {
  252. const client = wx.getSystemInfoSync().windowHeight // 获取当前窗口的高度
  253. var scrollHeight = (client - 136) + 'px'
  254. this.setData({
  255. scrollHeight
  256. })
  257. },
  258. // 进入详情
  259. goDetails(e) {
  260. let value = e.currentTarget.dataset.value;
  261. wx.navigateTo({
  262. url: '/pages/index/components/listDetails/Details?businessCommunicationDemandId=' + value,
  263. })
  264. },
  265. // 获取内存中聊天列表的用户信息
  266. getStorageBaseInfo: function () {
  267. //获取存储信息
  268. wx.getStorage({
  269. key: 'receivebaseInfo',
  270. success: (res) => {
  271. this.setData({
  272. receivebaseInfo: res.data
  273. })
  274. }
  275. })
  276. },
  277. // 自定义下拉刷新
  278. refresh: function () {
  279. // // 下拉的实际操作
  280. // var pageNo = this.data.pageNo + 1
  281. // this.setData({
  282. // pageNo
  283. // })
  284. // if (this.timer) {
  285. // clearTimeout(this.timer)
  286. // }
  287. // this.timer = setTimeout(() => {
  288. // this.setData({
  289. // triggered: false
  290. // })
  291. // this.getHistory()
  292. // }, 2000)
  293. },
  294. /**
  295. * 生命周期函数--监听页面显示
  296. */
  297. onShow: function () {
  298. },
  299. /**
  300. * 生命周期函数--监听页面隐藏
  301. */
  302. onHide: function () {
  303. // 如果是发送图片就不触发
  304. if (!this.data.isSendImg) {
  305. wx.closeSocket();
  306. // 检测到全局的 websocket 是连接的 关闭
  307. if (app.globalData.isOnSocketOpen) {
  308. app.globalData.isOnSocketOpen = false;
  309. }
  310. }
  311. },
  312. /**
  313. * 生命周期函数--监听页面卸载
  314. */
  315. onUnload: function () {
  316. // 如果是发送图片就不触发
  317. if (!this.data.isSendImg) {
  318. wx.closeSocket();
  319. // 检测到全局的 websocket 是连接的 关闭
  320. if (app.globalData.isOnSocketOpen) {
  321. app.globalData.isOnSocketOpen = false;
  322. }
  323. }
  324. },
  325. /**
  326. * 页面相关事件处理函数--监听用户下拉动作
  327. */
  328. onPullDownRefresh: function () {
  329. },
  330. /**
  331. * 页面上拉触底事件的处理函数
  332. */
  333. onReachBottom: function () {
  334. },
  335. send: function () {
  336. var _this = this;
  337. if (_this.data.input) {
  338. // wx.sendSocketMessage({
  339. // data: _this.data.input,
  340. // success: (res) => {
  341. // console.log(`发送成功`)
  342. // console.log(res)
  343. // // let { sendMemberId, receiveMemberId, businessCommunicationDemandId } = _this.data;
  344. // // let params = {
  345. // // sender: receiveMemberId, // 发件人Id
  346. // // addressee: sendMemberId, // 收件人Id
  347. // // transactionId: businessCommunicationDemandId, // 产品ID
  348. // // content: _this.data.input
  349. // // };
  350. // },
  351. // fail: (err) => {
  352. // console.log('sendSocketMessage', '失败')
  353. // }
  354. // })
  355. // return
  356. this.sendmsgApi(_this.data.input, 0);
  357. }
  358. },
  359. sendmsgApi(content, msgType) {
  360. let { sendMemberId, receiveMemberId, businessCommunicationDemandId } = this.data;
  361. let transactionId = businessCommunicationDemandId;
  362. if (!businessCommunicationDemandId) {
  363. if (this.data.historyList.length > 0) {
  364. transactionId = this.data.historyList[this.data.historyList.length - 1].transactionId;
  365. }
  366. }
  367. if (!transactionId) {
  368. transactionId = "";
  369. }
  370. let params = {
  371. sender: receiveMemberId, // 发件人Id
  372. addressee: sendMemberId, // 收件人Id
  373. transactionId, // 产品ID
  374. content,
  375. messageType: msgType,
  376. };
  377. $request.post('/businessCommunicationDemand/addChatRecord.action', params).then(res => {
  378. // 是由需求点击的聊一聊 保存完信息后需要再发送一条
  379. if (msgType == 1) {
  380. this.sendmsgApi("你好,我对这个需求很有兴趣,可以聊聊吗?", 0);
  381. }
  382. }).catch(err => {
  383. console.log(err)
  384. })
  385. var list = [];
  386. list = this.data.newsList;
  387. var temp = { 'message': content, 'date': utils.formatTime(new Date()), type: 0 };
  388. temp.date = temp.date.replaceAll('/', '-');
  389. temp.messageType = msgType;
  390. temp.transactionId = transactionId;
  391. temp.isRead = false;
  392. if (msgType == 1) {
  393. temp.object = {};
  394. temp.object.info = this.data.productInfo;
  395. }
  396. list.push(temp);
  397. this.setData({
  398. newsList: list,
  399. input: null,
  400. inputShowed: true,
  401. })
  402. this.scrollBottom()
  403. // 表情选择隐藏
  404. this.setData({
  405. emotionVisible: false,
  406. })
  407. const client = wx.getSystemInfoSync().windowHeight // 获取当前窗口的高度
  408. },
  409. bindChange: function (res) {
  410. this.setData({
  411. input: res.detail.value,
  412. })
  413. },
  414. back: function () {
  415. wx.closeSocket();
  416. console.log('连接断开');
  417. },
  418. emotionChange() {
  419. this.setData({
  420. emotionVisible: !this.data.emotionVisible
  421. })
  422. },
  423. addemotion: function (e) {
  424. let { connectemoji, input } = this.data
  425. if (input) {
  426. input = input + connectemoji[e.currentTarget.dataset.index];
  427. } else {
  428. input = connectemoji[e.currentTarget.dataset.index]
  429. }
  430. this.setData({
  431. input,
  432. emotionVisible: false,
  433. inputShowed: true,
  434. })
  435. },
  436. closeEmotionVisible() {
  437. this.setData({
  438. emotionVisible: false,
  439. })
  440. },
  441. // 发送图片
  442. upImg() {
  443. this.setData({
  444. isSendImg: true
  445. })
  446. wx.chooseImage({
  447. count: 1,
  448. success: (res) => {
  449. wx.uploadFile({
  450. filePath: res.tempFilePaths[0],
  451. name: "file",
  452. url: app.mangerUrl + "/file/uploading.action?fileType=TinymceImg",
  453. success: (res2) => {
  454. let data = JSON.parse(res2.data);
  455. this.sendmsgApi(data.data, 2);
  456. }
  457. })
  458. // /file/uploading.action?fileType=TinymceImg
  459. },
  460. complete: (res) => {
  461. // 调用结束后要关闭isSendImg
  462. this.setData({
  463. isSendImg: false
  464. })
  465. }
  466. })
  467. },
  468. // 设置已读未读
  469. setMsgRead(key, data, type) {
  470. data.forEach(el => {
  471. if (el.type == type) {
  472. el.isRead = true;
  473. }
  474. })
  475. if (key == 'historyList') {
  476. this.setData({
  477. historyList: data
  478. })
  479. } else {
  480. this.setData({
  481. newsList: data
  482. })
  483. }
  484. },
  485. // 图片预览
  486. viewImg(e) {
  487. let url = e.currentTarget.dataset.url;
  488. url += "?time=" + Date.now();
  489. wx.previewImage({
  490. current: url, // 当前显示图片的http链接
  491. urls: [url] // 需要预览的图片http链接列表
  492. })
  493. },
  494. })