业务交流通
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 17KB

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