chat.js 10 KB

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