chat.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. // pages/list/list.js
  2. import * as chatInput from "../../modules/chat-input/chat-input";
  3. import IMOperator from "./im-operator";
  4. import UI from "./ui";
  5. import MsgManager from "./msg-manager";
  6. /**
  7. * 聊天页面
  8. */
  9. Page({
  10. /**
  11. * 页面的初始数据
  12. */
  13. data: {
  14. textMessage: '',
  15. chatItems: [],
  16. latestPlayVoicePath: '',
  17. isAndroid: true,
  18. chatStatue: 'open',
  19. limit_page:1,
  20. charItem_message:[]
  21. },
  22. /**
  23. * 生命周期函数--监听页面加载
  24. */
  25. onLoad(options) {
  26. this.ArrMsg = [];
  27. // to_id
  28. // nickname
  29. // headUrl
  30. // wx.startPullDownRefresh
  31. //请空未读消息条数
  32. console.log(options);
  33. console.log(options,'chat');
  34. const friend = options;
  35. this.SocketSend({ to_id: friend.to_id, form_id: getApp().UserId(), type: 'get_history', page: this.data.limit_page});
  36. getApp().Imsocket().onSocketMessageCallback = this.onSocketMessageCallback;
  37. // const friend = JSON.parse(options.friend);//获取传递进来的信息
  38. this.setData({
  39. friendId: friend.to_id,
  40. myheadurl: friend.myheadurl,
  41. headUrl: friend.headUrl
  42. })
  43. // console.log(friend);
  44. // return false;
  45. this.initData();
  46. //设置bar内容
  47. wx.setNavigationBarTitle({
  48. title: friend.nickName || ''
  49. });
  50. this.imOperator = new IMOperator(this, friend);
  51. this.UI = new UI(this);
  52. this.msgManager = new MsgManager(this);
  53. // this.imOperator.onSimulateReceiveMsg((msg) => {
  54. // console.log(msg);
  55. // this.msgManager.showMsg({msg})
  56. // });
  57. // this.UI.updateChatStatus('正在聊天中:' + friend.nickname);
  58. },
  59. onShow: function (e) {
  60. //获取历史消息getget
  61. // this.onLoad();
  62. },
  63. initData() {
  64. let that = this;
  65. let systemInfo = wx.getSystemInfoSync();
  66. chatInput.init(this, {
  67. systemInfo: systemInfo,
  68. minVoiceTime: 1,
  69. maxVoiceTime: 60,
  70. startTimeDown: 56,
  71. format: 'mp3',//aac/mp3
  72. sendButtonBgColor: 'mediumseagreen',
  73. sendButtonTextColor: 'white',
  74. extraArr: [{
  75. picName: 'choose_picture',
  76. description: '照片'
  77. }
  78. // , {
  79. // picName: 'take_photos',
  80. // description: '拍摄'
  81. // }, {
  82. // picName: 'close_chat',
  83. // description: '自定义功能'
  84. // }
  85. ],
  86. // tabbarHeigth: 48
  87. });
  88. that.setData({
  89. pageHeight: systemInfo.windowHeight,
  90. isAndroid: systemInfo.system.indexOf("Android") !== -1,
  91. });
  92. wx.setNavigationBarTitle({
  93. title: '好友'
  94. });
  95. that.textButton();
  96. that.extraButton();
  97. that.voiceButton();
  98. },
  99. textButton() {
  100. let _that = this;
  101. chatInput.setTextMessageListener((e) => {
  102. console.log(e,'发送的消息');
  103. let content = e.detail.value;
  104. this.msgManager.sendMsg({type: IMOperator.TextType, content});
  105. });
  106. },
  107. voiceButton() {
  108. console.log(1);
  109. // chatInput.recordVoiceListener((res, duration) => {
  110. // let tempFilePath = res.tempFilePath;
  111. // this.msgManager.sendMsg({type: IMOperator.VoiceType, content: tempFilePath, duration});
  112. // });
  113. // chatInput.setVoiceRecordStatusListener((status) => {
  114. // this.msgManager.stopAllVoice();
  115. // })
  116. },
  117. //模拟上传文件,注意这里的cbOk回调函数传入的参数应该是上传文件成功时返回的文件url,这里因为模拟,我直接用的savedFilePath
  118. simulateUploadFile({savedFilePath, duration, itemIndex, success, fail}) {
  119. setTimeout(() => {
  120. let urlFromServerWhenUploadSuccess = savedFilePath;
  121. success && success(urlFromServerWhenUploadSuccess);
  122. }, 1000);
  123. },
  124. extraButton() {
  125. let that = this;
  126. chatInput.clickExtraListener((e) => {
  127. console.log('图片上传111111111111');
  128. let chooseIndex = parseInt(e.currentTarget.dataset.index);
  129. if (chooseIndex === 2) {
  130. that.myFun();
  131. return;
  132. }
  133. wx.chooseImage({
  134. count: 5, // 默认9
  135. sizeType: ['compressed'],
  136. sourceType: chooseIndex === 0 ? ['album'] : ['camera'],
  137. success: (res) => {
  138. let ImgRes = res;
  139. //发送上传图片
  140. //上传图片
  141. wx.uploadFile({
  142. url: getApp().globalData.url + 'imsocket/images/chatimg',
  143. filePath: res.tempFilePaths[0],
  144. name: 'photo',
  145. formData: {
  146. key: wx.getStorageSync('access_key'),
  147. token: wx.getStorageSync('access_token')
  148. },
  149. success: function (res) {
  150. var data = JSON.parse(res.data);
  151. console.log(data,'图片上传成功');
  152. if (data.code == 201) {
  153. let con = data.data;
  154. //显示图片
  155. console.log(con,1);
  156. console.log(ImgRes.tempFilePaths[0], 1222222);
  157. that.msgManager.sendMsg({ type: IMOperator.ImageType, content: con })
  158. } else if (data.code == 301) {
  159. wx.showModal({
  160. title: '提示',
  161. content: data.msg,
  162. showCancel: false,
  163. })
  164. }
  165. }, fail: function (d) {
  166. }
  167. })
  168. // that.msgManager.sendMsg({ type: IMOperator.ImageType, content: res.tempFilePaths[0] })
  169. }
  170. });
  171. });
  172. },
  173. /**
  174. * 自定义事件
  175. */
  176. myFun() {
  177. wx.showModal({
  178. title: '小贴士',
  179. content: '演示更新会话状态',
  180. confirmText: '确认',
  181. showCancel: true,
  182. success: (res) => {
  183. if (res.confirm) {
  184. this.msgManager.sendMsg({type: IMOperator.CustomType})
  185. }
  186. }
  187. })
  188. },
  189. resetInputStatus() {
  190. chatInput.closeExtraView();
  191. },
  192. sendMsg({content, itemIndex, success}) {
  193. //发送消息
  194. this.imOperator.onSimulateSendMsg({
  195. content,
  196. success: (msg) => {
  197. this.UI.updateViewWhenSendSuccess(msg, itemIndex);
  198. success && success(msg);
  199. },
  200. fail: () => {
  201. this.UI.updateViewWhenSendFailed(itemIndex);
  202. }
  203. })
  204. },
  205. /**
  206. * 重发消息
  207. * @param e
  208. */
  209. resendMsgEvent(e) {
  210. const itemIndex = parseInt(e.currentTarget.dataset.resendIndex);
  211. const item = this.data.chatItems[itemIndex];
  212. this.UI.updateDataWhenStartSending(item, false, false);
  213. this.msgManager.resend({...item, itemIndex});
  214. },
  215. onSocketMessageCallback:function(e){
  216. let data = JSON.parse(e);
  217. console.log(data,11222);
  218. let _that = this;
  219. if(data.type){
  220. switch (data.type) {
  221. case 'get_history':
  222. console.log(data, '分页消息');
  223. console.log(getApp().UserId(),'UserId');
  224. for (var index in data.data) {
  225. switch(data.data[index].type){
  226. case 1:
  227. data.data[index].type = 'text';
  228. break;
  229. case 2:
  230. data.data[index].type = 'image';
  231. break
  232. }
  233. data.data[index].timestamp = data.data[index].create_at;
  234. // data.data[index].time = data.data[index].create_at;
  235. data.data[index].showTime = true;
  236. //自己
  237. console.log(getApp().UserToken());
  238. if (data.data[index].form_id == getApp().UserToken()) {
  239. data.data[index].isMy = true;
  240. data.data[index].userId = data.data[index].form_id;
  241. data.data[index].headUrl = _that.data.myheadurl
  242. } else {
  243. //别人
  244. data.data[index].isMy = false;
  245. data.data[index].headUrl = _that.data.headUrl
  246. }
  247. _that.ArrMsg.push(data.data[index]);
  248. }
  249. // data.data.push(_that.data.chatItems)
  250. // let content = data.data;
  251. // _that.msgManager.showMsg({ type: IMOperator.TextType, content});
  252. // console.log(CharItemMessage);
  253. _that.scrollTopValLength = data.data.length
  254. if (_that.data.limit_page == 1){
  255. _that.scrollTopValLength = data.data.length * 999
  256. }else{
  257. _that.scrollTopValLength = data.data.length * 100
  258. }
  259. _that.setData({
  260. chatItems: _that.sortarr(_that.ArrMsg),
  261. scrollTopVal: _that.scrollTopValLength
  262. })
  263. break;
  264. case 'alone':
  265. let content = data.data.content;
  266. let msg = _that.imOperator.createNormalChatItem({
  267. type: 'text',
  268. content: content,
  269. isMy: false
  270. })
  271. _that.msgManager = new MsgManager(_that);
  272. _that.msgManager.showMsg({ msg});
  273. break;
  274. }
  275. }
  276. // let msg = data.data
  277. // this.msgManager.showMsg({ msg})
  278. // console.log(e,'接受到历史消息');
  279. },
  280. onUnload:function(e){
  281. let url = 'imsocket/imchatmessage/clearunreadmsg';
  282. let datas = {
  283. to_id: this.data.friendId, form_id: getApp().UserId()
  284. };
  285. //清除未读信息
  286. getApp().postRequest(url, datas, function (res) {
  287. console.log(res,11111);
  288. })
  289. console.log('销毁页面');
  290. },
  291. SocketSend:function(msg){
  292. // { to_id: friend.to_id, form_id: getApp().UserId(), type: 'get_history' }
  293. // msg.type = 'get_history';
  294. getApp().Imsocket().sendSocketMessage({
  295. msg: JSON.stringify(msg),
  296. success: function (res) {
  297. console.log(res, '获取历史消息成功');
  298. }, fail: function (res) {
  299. console.log('获取历史消息失败')
  300. }
  301. })
  302. },
  303. sortarr: function (arr) {//冒泡排序
  304. for (let i = 0; i < arr.length - 1; i++) {
  305. for (let j = 0; j < arr.length - 1 - i; j++) {
  306. if (arr[j].create_at > arr[j + 1].create_at) {
  307. var temp = arr[j];
  308. arr[j] = arr[j + 1];
  309. arr[j + 1] = temp;
  310. }
  311. }
  312. }
  313. return arr;
  314. },
  315. upper:function(e){
  316. console.log(e);
  317. let _that = this;
  318. this.setData({
  319. limit_page: this.data.limit_page * 1 + 1
  320. })
  321. this.SocketSend({ to_id: _that.data.friendId, form_id: getApp().UserId(), type: 'get_history', page: _that.data.limit_page})
  322. },
  323. emojis:function(){
  324. getApp().Tips('该功能正在开发中。');
  325. }
  326. });