业务交流通
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

wechat2.js 16KB

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