chat-room.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. // pages/chat-room/chat-room.js
  2. const app = getApp();
  3. const disp = require("../../utils/broadcast.js");
  4. const WebIM = require("../../utils/WebIM.js")["default"];
  5. const util = require('../../utils/util.js');
  6. Page({
  7. /**
  8. * 页面的初始数据
  9. */
  10. data: {
  11. imgPath: app.globalData.imgPath,
  12. cursor: null,
  13. limit: 10,
  14. list: [],
  15. search_btn: true,
  16. search_chats: false,
  17. show_mask: false,
  18. yourname: "",
  19. unReadSpotNum: 0,
  20. unReadNoticeNum: 0,
  21. messageNum: 0,
  22. unReadTotalNotNum: 0,
  23. arr: [],
  24. show_clear: false,
  25. groupName: {}
  26. },
  27. /**
  28. * 生命周期函数--监听页面加载
  29. */
  30. onLoad: function (options) {
  31. // let that = this;
  32. // this.getRoster();
  33. this.listGroups();
  34. // this.getChatList();
  35. },
  36. /**
  37. * 生命周期函数--监听页面初次渲染完成
  38. */
  39. onReady: function () {
  40. },
  41. /**
  42. * 生命周期函数--监听页面显示
  43. */
  44. onShow: function () {
  45. },
  46. /**
  47. * 生命周期函数--监听页面隐藏
  48. */
  49. onHide: function () {
  50. },
  51. /**
  52. * 生命周期函数--监听页面卸载
  53. */
  54. onUnload: function () {
  55. },
  56. /**
  57. * 页面相关事件处理函数--监听用户下拉动作
  58. */
  59. onPullDownRefresh: function () {
  60. },
  61. /**
  62. * 页面上拉触底事件的处理函数
  63. */
  64. onReachBottom: function () {
  65. },
  66. /**
  67. * 用户点击右上角分享
  68. */
  69. onShareAppMessage: function () {
  70. },
  71. /**
  72. * 跳转到群组列表
  73. */
  74. into_groups: function () {
  75. wx.navigateTo({
  76. url: "../chat-group/chat-group?myName=" + this.data.myName
  77. });
  78. },
  79. /**
  80. * 查询联系人
  81. */
  82. getRoster: function () {
  83. let that = this;
  84. let rosters = {
  85. success(roster) {
  86. console.info(roster)
  87. var member = [];
  88. for (let i = 0; i < roster.length; i++) {
  89. if (roster[i].subscription == "both") {
  90. member.push(roster[i]);
  91. }
  92. }
  93. wx.setStorage({
  94. key: "member",
  95. data: member
  96. });
  97. that.setData({ member: member });
  98. that.listGroups();
  99. //if(!systemReady){
  100. disp.fire("em.main.ready");
  101. //systemReady = true;
  102. //}
  103. // that.setData({
  104. // arr: that.getChatList(),
  105. // unReadSpotNum: getApp().globalData.unReadMessageNum > 99 ? '99+' : getApp().globalData.unReadMessageNum,
  106. // });
  107. },
  108. error(err) {
  109. console.log(err);
  110. }
  111. };
  112. WebIM.conn.getRoster(rosters);
  113. },
  114. /**
  115. * 查询群组
  116. */
  117. listGroups: function () {
  118. var that = this;
  119. return WebIM.conn.getGroup({
  120. limit: 100,
  121. success: function (res) {
  122. console.info(res)
  123. let groupName = {}
  124. let listGroup = res.data || []
  125. listGroup.forEach((item) => {
  126. groupName[item.groupid] = item.groupname
  127. });
  128. that.setData({
  129. groupName
  130. })
  131. wx.setStorage({
  132. key: "listGroup",
  133. data: res.data
  134. });
  135. that.getChatList();
  136. },
  137. error: function (err) {
  138. console.log(err)
  139. }
  140. });
  141. },
  142. /**
  143. * 查询聊天记录(包含陌生人版本)
  144. */
  145. getChatList: function () {
  146. let myName = wx.getStorageSync("myUsername");
  147. let that = this
  148. wx.getStorageInfo({
  149. success: function (res) {
  150. console.info(res);
  151. let storageKeys = res.keys;
  152. console.log('res.keys +++ ', res.keys);
  153. let newChatMsgKeys = [];
  154. let historyChatMsgKeys = [];
  155. let len = myName.length;
  156. storageKeys.forEach((item) => {
  157. console.info(item);
  158. // 未读
  159. if (item.slice(-len) == myName && item.indexOf('rendered_') == -1) {
  160. newChatMsgKeys.push(item);
  161. }
  162. // 已读
  163. else if (item.slice(-len) == myName && item.indexOf('rendered_') > -1) {
  164. historyChatMsgKeys.push(item);
  165. }
  166. });
  167. cul.call(that, newChatMsgKeys, historyChatMsgKeys);
  168. }
  169. });
  170. function cul(newChatMsgKeys, historyChatMsgKeys) {
  171. let array = []
  172. let lastChatMsg;
  173. for (let i = 0; i < historyChatMsgKeys.length; i++) {
  174. // 判断新消息是否包含历史聊天(截断'rendered_')
  175. let index = newChatMsgKeys.indexOf(historyChatMsgKeys[i].slice(9));
  176. if (index > -1) {
  177. let newChatMsgs = wx.getStorageSync(newChatMsgKeys[index]) || [];
  178. if (newChatMsgKeys.includes()) { }
  179. if (newChatMsgs.length) {
  180. lastChatMsg = newChatMsgs[newChatMsgs.length - 1];
  181. lastChatMsg.unReadCount = newChatMsgs.length;
  182. if (lastChatMsg.unReadCount > 99) {
  183. lastChatMsg.unReadCount = "99+";
  184. }
  185. lastChatMsg.time = that.chatTime(lastChatMsg.time);
  186. lastChatMsg.dateTimeNum = new Date(lastChatMsg.time.replace(/-/g, '/')).getTime();
  187. newChatMsgKeys.splice(index, 1);
  188. } else {
  189. let historyChatMsgs = wx.getStorageSync(historyChatMsgKeys[i]);
  190. if (historyChatMsgs.length) {
  191. lastChatMsg = historyChatMsgs[historyChatMsgs.length - 1];
  192. lastChatMsg.time = that.chatTime(lastChatMsg.time);
  193. lastChatMsg.dateTimeNum = new Date(lastChatMsg.time.replace(/-/g, '/')).getTime();
  194. }
  195. }
  196. } else {
  197. let historyChatMsgs = wx.getStorageSync(historyChatMsgKeys[i]);
  198. if (historyChatMsgs.length) {
  199. lastChatMsg = historyChatMsgs[historyChatMsgs.length - 1];
  200. lastChatMsg.time = that.chatTime(lastChatMsg.time);
  201. lastChatMsg.dateTimeNum = new Date(lastChatMsg.time.replace(/-/g, '/')).getTime();
  202. }
  203. }
  204. if (lastChatMsg.chatType == 'groupchat' || lastChatMsg.chatType == 'chatRoom') {
  205. lastChatMsg.groupName = that.data.groupName[lastChatMsg.info.to];
  206. }
  207. lastChatMsg && lastChatMsg.username != myName && array.push(lastChatMsg);
  208. }
  209. for (let i = 0; i < newChatMsgKeys.length; i++) {
  210. let newChatMsgs = wx.getStorageSync(newChatMsgKeys[i]) || [];
  211. if (newChatMsgs.length) {
  212. lastChatMsg = newChatMsgs[newChatMsgs.length - 1];
  213. lastChatMsg.unReadCount = newChatMsgs.length;
  214. if (lastChatMsg.unReadCount > 99) {
  215. lastChatMsg.unReadCount = "99+";
  216. }
  217. lastChatMsg.time = that.chatTime(lastChatMsg.time);
  218. lastChatMsg.dateTimeNum = new Date(lastChatMsg.time.replace(/-/g, '/')).getTime();
  219. if (lastChatMsg.chatType == 'groupchat' || lastChatMsg.chatType == 'chatRoom') {
  220. lastChatMsg.groupName = that.data.groupName[lastChatMsg.info.to];
  221. }
  222. lastChatMsg.username != myName && array.push(lastChatMsg)
  223. }
  224. }
  225. array.sort((a, b) => {
  226. return b.dateTimeNum - a.dateTimeNum
  227. });
  228. console.info(array)
  229. this.setData({
  230. arr: array
  231. })
  232. }
  233. },
  234. onShow: function () {
  235. this.getChatList()
  236. this.setData({
  237. //arr: this.getChatList(),
  238. unReadSpotNum: getApp().globalData.unReadMessageNum > 99 ? '99+' : getApp().globalData.unReadMessageNum,
  239. messageNum: getApp().globalData.saveFriendList.length,
  240. unReadNoticeNum: getApp().globalData.saveGroupInvitedList.length,
  241. unReadTotalNotNum: getApp().globalData.saveFriendList.length + getApp().globalData.saveGroupInvitedList.length
  242. });
  243. if (getApp().globalData.isIPX) {
  244. this.setData({
  245. isIPX: true
  246. })
  247. }
  248. },
  249. openSearch: function () {
  250. this.setData({
  251. search_btn: false,
  252. search_chats: true,
  253. gotop: true
  254. });
  255. },
  256. onSearch: function (val) {
  257. var myName = wx.getStorageSync("myUsername");
  258. const that = this
  259. let searchValue = val.detail.value
  260. let chartList = this.data.arr;
  261. let serchList = [];
  262. console.log('arr', that.data.arr)
  263. chartList.forEach((item, index) => {
  264. if (String(item.username).indexOf(searchValue) != -1 || (item.groupName && item.groupName.indexOf(searchValue) != -1)) {
  265. serchList.push(item)
  266. }
  267. })
  268. this.setData({
  269. arr: serchList,
  270. })
  271. },
  272. cancel: function () {
  273. this.getChatList()
  274. this.setData({
  275. search_btn: true,
  276. search_chats: false,
  277. //arr: this.getChatList(),
  278. unReadSpotNum: getApp().globalData.unReadMessageNum > 99 ? '99+' : getApp().globalData.unReadMessageNum,
  279. gotop: false
  280. });
  281. },
  282. clearInput: function () {
  283. this.setData({
  284. input_code: '',
  285. show_clear: false
  286. })
  287. },
  288. onInput: function (e) {
  289. let inputValue = e.detail.value
  290. if (inputValue) {
  291. this.setData({
  292. show_clear: true
  293. })
  294. } else {
  295. this.setData({
  296. show_clear: false
  297. })
  298. }
  299. },
  300. tab_contacts: function () {
  301. wx.redirectTo({
  302. url: "../main/main?myName=" + wx.getStorageSync("myUsername")
  303. });
  304. },
  305. close_mask: function () {
  306. this.setData({
  307. search_btn: true,
  308. search_chats: false,
  309. show_mask: false
  310. });
  311. },
  312. tab_setting: function () {
  313. wx.redirectTo({
  314. url: "../setting/setting"
  315. });
  316. },
  317. tab_notification: function () {
  318. wx.redirectTo({
  319. url: "../notification/notification"
  320. });
  321. },
  322. /**
  323. * 进入聊天界面
  324. */
  325. into_chatRoom: function (event) {
  326. let detail = event.currentTarget.dataset.item;
  327. console.info('detail:', detail);
  328. //群聊的chatType居然是singlechat?脏数据? 等sdk重写后整理一下字段
  329. if (detail.chatType == 'groupchat' || detail.chatType == 'chatRoom' || detail.groupName) {
  330. this.into_groupChatRoom(detail);
  331. } else {
  332. this.into_singleChatRoom(detail);
  333. }
  334. },
  335. /**
  336. * 进入单聊
  337. */
  338. into_singleChatRoom: function (detail) {
  339. var my = wx.getStorageSync("myUsername");
  340. let title = '';
  341. if (detail.info.from == my) {
  342. title = detail.info.toInfo.nickname;
  343. } else {
  344. title = detail.info.fromInfo.nickname;
  345. }
  346. var nameList = {
  347. myName: my,
  348. your: detail.username,
  349. navigationTitle: title
  350. };
  351. wx.navigateTo({
  352. url: "../chat-detail/chat-detail?username=" + JSON.stringify(nameList)
  353. });
  354. },
  355. /**
  356. * 进入群聊
  357. * 群聊 和 聊天室 (两个概念)
  358. */
  359. into_groupChatRoom: function (detail) {
  360. var my = wx.getStorageSync("myUsername");
  361. var nameList = {
  362. myName: my,
  363. your: detail.groupName,
  364. groupId: detail.info.to
  365. };
  366. wx.navigateTo({
  367. url: "../chat-group-detail/chat-group-detail?username=" + JSON.stringify(nameList)
  368. });
  369. },
  370. /**
  371. * 删除聊天
  372. */
  373. del_chat: function (event) {
  374. let detail = event.currentTarget.dataset.item;
  375. let nameList;
  376. let that = this;
  377. if (detail.chatType == 'groupchat' || detail.chatType == 'chatRoom') {
  378. nameList = {
  379. your: detail.info.to
  380. };
  381. } else {
  382. nameList = {
  383. your: detail.username
  384. };
  385. }
  386. var myName = wx.getStorageSync("myUsername");
  387. var currentPage = getCurrentPages();
  388. wx.showModal({
  389. title: "删除该聊天记录",
  390. confirmText: "删除",
  391. success: function (res) {
  392. if (res.confirm) {
  393. wx.removeStorageSync(nameList.your + myName);
  394. wx.removeStorageSync("rendered_" + nameList.your + myName);
  395. if (currentPage[0]) {
  396. currentPage[0].onShow();
  397. }
  398. that.getChatList()
  399. disp.fire("em.chat.session.remove");
  400. }
  401. },
  402. fail: function (err) {
  403. }
  404. });
  405. },
  406. /**
  407. * 进入聊天界面(废弃)
  408. */
  409. chatDetail: function (e) {
  410. let id = e.currentTarget.dataset.id;
  411. let name = e.currentTarget.dataset.name;
  412. wx.navigateTo({
  413. url: '../chat-detail/chat-detail?id=' + id + "&name=" + name,
  414. })
  415. },
  416. /**
  417. * 自定义格式化聊天时间
  418. * @param {*} chatTime
  419. */
  420. chatTime: function (chatTime) {
  421. let dateArr = chatTime.split(' ')[0].split('-');
  422. let timeArr = chatTime.split(' ')[1].split(':');
  423. let nowArr = util.formatDate(null).split(' ')[0].split('-');
  424. let month = dateArr[1] < 10 ? '0' + dateArr[1] : dateArr[1];
  425. let day = dateArr[2] < 10 ? '0' + dateArr[2] : dateArr[2];
  426. console.info('dateArr', dateArr);
  427. console.info('nowArr', nowArr);
  428. if (nowArr[0] == dateArr[0] && nowArr[1] == month && nowArr[2] == day) {
  429. return `${timeArr[0]}:${timeArr[1]}`;
  430. } else {
  431. return `${dateArr[0]}/${dateArr[1]}/${dateArr[2]}`;
  432. }
  433. },
  434. /**
  435. * 查询环信用户属性
  436. */
  437. getUserShowName: function (lastChatMsg) {
  438. util.post({
  439. url: '/api/easemob/getUpUserAttribute/' + lastChatMsg.username,
  440. success: (res) => {
  441. wx.hideLoading();
  442. console.info(res);
  443. return res.data.data.data.nickname;
  444. }
  445. });
  446. },
  447. /**
  448. * 扫一扫加入群聊
  449. */
  450. scanJoinGroup: function () {
  451. wx.scanCode({
  452. onlyFromCamera: true,
  453. success: (res) => {
  454. console.info('scanCode', res);
  455. if (res.result) {
  456. util.post({
  457. url: '/api/easemob/addGroupUser',
  458. data: {
  459. chatgroupid: res.result,
  460. usernames: [wx.getStorageSync('myUsername')]
  461. },
  462. success: (res) => {
  463. wx.hideLoading();
  464. console.info('addGroupUser', res);
  465. if (res.data.code != 200) {
  466. util.toast(res.data.msg);
  467. } else {
  468. util.toast(res.data.msg);
  469. }
  470. }
  471. });
  472. }
  473. },
  474. fail: (err) => {
  475. console.info('scanCode', err);
  476. }
  477. });
  478. }
  479. })