chat-room.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  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. var myName = wx.getStorageSync("myUsername");
  147. var array = [];
  148. const that = this
  149. wx.getStorageInfo({
  150. success: function (res) {
  151. console.info(res);
  152. let storageKeys = res.keys;
  153. console.log('res.keys +++ ', res.keys);
  154. let newChatMsgKeys = [];
  155. let historyChatMsgKeys = [];
  156. let len = myName.length;
  157. storageKeys.forEach((item) => {
  158. console.info(item);
  159. // 未读
  160. if (item.slice(-len) == myName && item.indexOf('rendered_') == -1) {
  161. newChatMsgKeys.push(item);
  162. }
  163. // 已读
  164. else if (item.slice(-len) == myName && item.indexOf('rendered_') > -1) {
  165. historyChatMsgKeys.push(item);
  166. }
  167. });
  168. cul.call(that, newChatMsgKeys, historyChatMsgKeys);
  169. }
  170. })
  171. function cul(newChatMsgKeys, historyChatMsgKeys) {
  172. let array = []
  173. let lastChatMsg;
  174. for (let i = 0; i < historyChatMsgKeys.length; i++) {
  175. // 判断新消息是否包含历史聊天(截断'rendered_')
  176. let index = newChatMsgKeys.indexOf(historyChatMsgKeys[i].slice(9));
  177. if (index > -1) {
  178. let newChatMsgs = wx.getStorageSync(newChatMsgKeys[index]) || [];
  179. if (newChatMsgKeys.includes()) { }
  180. if (newChatMsgs.length) {
  181. lastChatMsg = newChatMsgs[newChatMsgs.length - 1];
  182. lastChatMsg.unReadCount = newChatMsgs.length;
  183. if (lastChatMsg.unReadCount > 99) {
  184. lastChatMsg.unReadCount = "99+";
  185. }
  186. lastChatMsg.time = that.chatTime(lastChatMsg.time);
  187. lastChatMsg.dateTimeNum = new Date(lastChatMsg.time.replace(/-/g, '/')).getTime();
  188. newChatMsgKeys.splice(index, 1);
  189. } else {
  190. let historyChatMsgs = wx.getStorageSync(historyChatMsgKeys[i]);
  191. if (historyChatMsgs.length) {
  192. lastChatMsg = historyChatMsgs[historyChatMsgs.length - 1];
  193. lastChatMsg.time = that.chatTime(lastChatMsg.time);
  194. lastChatMsg.dateTimeNum = new Date(lastChatMsg.time.replace(/-/g, '/')).getTime();
  195. }
  196. }
  197. } else {
  198. let historyChatMsgs = wx.getStorageSync(historyChatMsgKeys[i]);
  199. if (historyChatMsgs.length) {
  200. lastChatMsg = historyChatMsgs[historyChatMsgs.length - 1];
  201. lastChatMsg.time = that.chatTime(lastChatMsg.time);
  202. lastChatMsg.dateTimeNum = new Date(lastChatMsg.time.replace(/-/g, '/')).getTime();
  203. }
  204. }
  205. if (lastChatMsg.chatType == 'groupchat' || lastChatMsg.chatType == 'chatRoom') {
  206. lastChatMsg.groupName = that.data.groupName[lastChatMsg.info.to];
  207. }
  208. lastChatMsg && lastChatMsg.username != myName && array.push(lastChatMsg);
  209. }
  210. for (let i = 0; i < newChatMsgKeys.length; i++) {
  211. let newChatMsgs = wx.getStorageSync(newChatMsgKeys[i]) || [];
  212. if (newChatMsgs.length) {
  213. lastChatMsg = newChatMsgs[newChatMsgs.length - 1];
  214. lastChatMsg.unReadCount = newChatMsgs.length;
  215. if (lastChatMsg.unReadCount > 99) {
  216. lastChatMsg.unReadCount = "99+";
  217. }
  218. lastChatMsg.time = that.chatTime(lastChatMsg.time);
  219. lastChatMsg.dateTimeNum = new Date(lastChatMsg.time.replace(/-/g, '/')).getTime();
  220. if (lastChatMsg.chatType == 'groupchat' || lastChatMsg.chatType == 'chatRoom') {
  221. lastChatMsg.groupName = that.data.groupName[lastChatMsg.info.to];
  222. }
  223. lastChatMsg.username != myName && array.push(lastChatMsg)
  224. }
  225. }
  226. array.sort((a, b) => {
  227. return b.dateTimeNum - a.dateTimeNum
  228. });
  229. console.info(array)
  230. this.setData({
  231. arr: array
  232. })
  233. }
  234. },
  235. onShow: function () {
  236. this.getChatList()
  237. this.setData({
  238. //arr: this.getChatList(),
  239. unReadSpotNum: getApp().globalData.unReadMessageNum > 99 ? '99+' : getApp().globalData.unReadMessageNum,
  240. messageNum: getApp().globalData.saveFriendList.length,
  241. unReadNoticeNum: getApp().globalData.saveGroupInvitedList.length,
  242. unReadTotalNotNum: getApp().globalData.saveFriendList.length + getApp().globalData.saveGroupInvitedList.length
  243. });
  244. if (getApp().globalData.isIPX) {
  245. this.setData({
  246. isIPX: true
  247. })
  248. }
  249. },
  250. openSearch: function () {
  251. this.setData({
  252. search_btn: false,
  253. search_chats: true,
  254. gotop: true
  255. });
  256. },
  257. onSearch: function (val) {
  258. var myName = wx.getStorageSync("myUsername");
  259. const that = this
  260. let searchValue = val.detail.value
  261. let chartList = this.data.arr;
  262. let serchList = [];
  263. console.log('arr', that.data.arr)
  264. chartList.forEach((item, index) => {
  265. if (String(item.username).indexOf(searchValue) != -1 || (item.groupName && item.groupName.indexOf(searchValue) != -1)) {
  266. serchList.push(item)
  267. }
  268. })
  269. this.setData({
  270. arr: serchList,
  271. })
  272. },
  273. cancel: function () {
  274. this.getChatList()
  275. this.setData({
  276. search_btn: true,
  277. search_chats: false,
  278. //arr: this.getChatList(),
  279. unReadSpotNum: getApp().globalData.unReadMessageNum > 99 ? '99+' : getApp().globalData.unReadMessageNum,
  280. gotop: false
  281. });
  282. },
  283. clearInput: function () {
  284. this.setData({
  285. input_code: '',
  286. show_clear: false
  287. })
  288. },
  289. onInput: function (e) {
  290. let inputValue = e.detail.value
  291. if (inputValue) {
  292. this.setData({
  293. show_clear: true
  294. })
  295. } else {
  296. this.setData({
  297. show_clear: false
  298. })
  299. }
  300. },
  301. tab_contacts: function () {
  302. wx.redirectTo({
  303. url: "../main/main?myName=" + wx.getStorageSync("myUsername")
  304. });
  305. },
  306. close_mask: function () {
  307. this.setData({
  308. search_btn: true,
  309. search_chats: false,
  310. show_mask: false
  311. });
  312. },
  313. tab_setting: function () {
  314. wx.redirectTo({
  315. url: "../setting/setting"
  316. });
  317. },
  318. tab_notification: function () {
  319. wx.redirectTo({
  320. url: "../notification/notification"
  321. });
  322. },
  323. into_chatRoom: function (event) {
  324. let detail = event.currentTarget.dataset.item;
  325. console.info('detail:', detail);
  326. //群聊的chatType居然是singlechat?脏数据? 等sdk重写后整理一下字段
  327. if (detail.chatType == 'groupchat' || detail.chatType == 'chatRoom' || detail.groupName) {
  328. this.into_groupChatRoom(detail);
  329. } else {
  330. this.into_singleChatRoom(detail);
  331. }
  332. },
  333. // 单聊
  334. into_singleChatRoom: function (detail) {
  335. var my = wx.getStorageSync("myUsername");
  336. var nameList = {
  337. myName: my,
  338. your: detail.username
  339. };
  340. wx.navigateTo({
  341. url: "../chat-detail/chat-detail?username=" + JSON.stringify(nameList)
  342. });
  343. },
  344. // 群聊 和 聊天室 (两个概念)
  345. into_groupChatRoom: function (detail) {
  346. var my = wx.getStorageSync("myUsername");
  347. var nameList = {
  348. myName: my,
  349. your: detail.groupName,
  350. groupId: detail.info.to
  351. };
  352. wx.navigateTo({
  353. url: "../chat-group-detail/chat-group-detail?username=" + JSON.stringify(nameList)
  354. });
  355. },
  356. del_chat: function (event) {
  357. let detail = event.currentTarget.dataset.item;
  358. let nameList;
  359. let that = this;
  360. if (detail.chatType == 'groupchat' || detail.chatType == 'chatRoom') {
  361. nameList = {
  362. your: detail.info.to
  363. };
  364. } else {
  365. nameList = {
  366. your: detail.username
  367. };
  368. }
  369. var myName = wx.getStorageSync("myUsername");
  370. var currentPage = getCurrentPages();
  371. wx.showModal({
  372. title: "删除该聊天记录",
  373. confirmText: "删除",
  374. success: function (res) {
  375. if (res.confirm) {
  376. wx.removeStorageSync(nameList.your + myName);
  377. wx.removeStorageSync("rendered_" + nameList.your + myName);
  378. if (currentPage[0]) {
  379. currentPage[0].onShow();
  380. }
  381. that.getChatList()
  382. disp.fire("em.chat.session.remove");
  383. }
  384. },
  385. fail: function (err) {
  386. }
  387. });
  388. },
  389. chatDetail: function (e) {
  390. let id = e.currentTarget.dataset.id;
  391. let name = e.currentTarget.dataset.name;
  392. wx.navigateTo({
  393. url: '../chat-detail/chat-detail?id=' + id + "&name=" + name,
  394. })
  395. },
  396. /**
  397. * 自定义格式化聊天时间
  398. * @param {*} chatTime
  399. */
  400. chatTime: function (chatTime) {
  401. let dateArr = chatTime.split(' ')[0].split('-');
  402. let timeArr = chatTime.split(' ')[1].split(':');
  403. let nowArr = util.formatDate(null).split(' ')[0].split('-');
  404. let month = dateArr[1] < 10 ? '0' + dateArr[1] : dateArr[1];
  405. console.info('dateArr', dateArr);
  406. console.info('nowArr', nowArr);
  407. if (nowArr[0] == dateArr[0] && nowArr[1] == month && nowArr[2] == dateArr[2]) {
  408. return `${timeArr[0]}:${timeArr[1]}`;
  409. } else {
  410. return `${dateArr[0]}/${dateArr[1]}/${dateArr[2]}`;
  411. }
  412. },
  413. /**
  414. * 扫一扫加入群聊
  415. */
  416. scanJoinGroup: function () {
  417. wx.scanCode({
  418. onlyFromCamera: true,
  419. success: (res) => {
  420. console.info('scanCode', res);
  421. if (res.result) {
  422. util.post({
  423. url: '/api/easemob/addGroupUser',
  424. data: {
  425. chatgroupid: res.result,
  426. usernames: [wx.getStorageSync('myUsername')]
  427. },
  428. success: (res) => {
  429. wx.hideLoading();
  430. console.info('addGroupUser', res);
  431. if (res.data.code != 200) {
  432. util.toast(res.data.msg);
  433. } else {
  434. util.toast(res.data.msg);
  435. }
  436. }
  437. });
  438. }
  439. },
  440. fail: (err) => {
  441. console.info('scanCode', err);
  442. }
  443. });
  444. }
  445. })