import 'package:chat/models/ChatMsg.dart'; import 'package:chat/models/last_message_model.dart'; import 'package:chat/proto/all.pbserver.dart'; import 'package:chat/utils/MessageMgr.dart'; import 'package:flutter/material.dart'; class LastMsgProvider with ChangeNotifier { List lastMsgList = []; addMsg(MsgModel msgModel) { var lastMsg = getLastRecordBy(msgModel.sessionId); //服务器消息优先级高 if (lastMsg == null) { lastMsg = LastMessageModel.fromChatMsg(msgModel); lastMsgList.insert(0, lastMsg); if (msgModel.channelType == ChatChannelType.Group.value) { MessageMgr().emit('Update Group List'); } else { MessageMgr().emit('Update LastMsg',lastMsg.sessionId); } } } sortLastMsg() { lastMsgList.sort((b, a) => a.updateAt.compareTo(b.updateAt)); } updateLastMsg(MsgModel msgModel) { var lastMsg = getLastRecordBy(msgModel.sessionId); if (lastMsg != null) { //更新 lastMsg.updateWithMessage(msgModel); lastMsgList.sort((b, a) => a.updateAt.compareTo(b.updateAt)); } else { lastMsg = LastMessageModel.fromChatMsg(msgModel); lastMsgList.insert(0, lastMsg); } if (msgModel.channelType == ChatChannelType.Group.value) { MessageMgr().emit('Update Group List'); } else { MessageMgr().emit('Update LastMsg',lastMsg.sessionId); } } updateWithTranslateMsg(PushChat chat) { //更新 if (chat.cType == ChatType.TextChatType) { print('更新最新数据的翻译结果'); var lastMsg = getLastRecordBy(chat.targetId); if (lastMsg != null && chat.hasTencentTranslate()) { lastMsg.msgContent = chat.tencentTranslate; } if (chat.channelType == ChatChannelType.Group) { MessageMgr().emit('Update Group List'); } else { MessageMgr().emit('Update LastMsg',lastMsg.sessionId); } } } addUnreadMsg(UserUnreadMsgNotice unread) { var lastMsg = getLastRecordBy(unread.targetId); if (lastMsg == null) { lastMsg = LastMessageModel.fromUnreadMsg(unread); lastMsgList.insert(0, lastMsg); //可能是新增的用户 } else { lastMsg.updateWithUnreadMsg(unread); lastMsgList.sort((b, a) => a.updateAt.compareTo(b.updateAt)); } if (unread.channelType == ChatChannelType.Group) { MessageMgr().emit('Update Group List'); } else { MessageMgr().emit('Update LastMsg',lastMsg.sessionId); } } deleteMsg(LastMessageModel msgModel) { lastMsgList.remove(msgModel); if (msgModel.channelType == ChatChannelType.Group.value) { MessageMgr().emit('Update Group List'); } else { MessageMgr().emit('Update LastMsg',msgModel.sessionId); } } LastMessageModel getLastRecordBy(int sessionId) { for (var i = 0; i < lastMsgList.length; i++) { var lastMsg = lastMsgList[i]; if (lastMsg.sessionId == sessionId) { return lastMsg; } } return null; } clear() { lastMsgList.clear(); } }