import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';
import 'package:chat/chat/group_chat_view.dart';
import 'package:chat/data/UserData.dart';
import 'package:chat/data/chat_data_mgr.dart';
import 'package:chat/data/constants.dart';
import 'package:chat/data/group_data_mgr.dart';
import 'package:chat/data/translate_hk_data_mgr.dart';
import 'package:chat/generated/i18n.dart';
import 'package:chat/home/IndexPage.dart';
import 'package:chat/models/ChatMsg.dart';
import 'package:chat/models/group_info_model.dart';
import 'package:chat/proto/all.pbserver.dart';
import 'package:chat/proto/transhousekeeper.pb.dart';
import 'package:chat/utils/NetUtil.dart';
import 'package:chat/utils/blacklist_mgr.dart';
import 'package:chat/utils/friend_list_mgr.dart';
import 'package:chat/utils/group_member_model.dart';
import 'package:chat/utils/local_notification_util.dart';
import 'package:chat/utils/sound_util.dart';
import 'package:chat/utils/sql_util.dart';
import 'package:chat/utils/upload_util.dart';
import 'package:flutter/material.dart';
import 'package:oktoast/oktoast.dart';

import 'package:fixnum/fixnum.dart';
import 'MessageMgr.dart';

const MaxMsgContentSize = 1024 * 1024 * 3;

class MsgHandler {
  //当前会话ID
  static int curActiveSession;
  static bool isTranslate = false;

  static bool isAudioConnect = false;

  static BuildContext context = Constants.getCurrentContext();

  static List<MsgModel> sendCache = [];

  static Timer ringTimer;

  static int audioChatRequestFriendId = 0;

  static Function createGroupComplete;

  static updateActiveSesstion(int session, {bool isGroup = false}) {
    curActiveSession = session;
    getUnreadMsgDetail(isGroup);
    ChatDataMgr().signRead(curActiveSession, isGroup: isGroup);
  }

  static getActiveSesstion(List<int> memberList) {
    var seq = CreateSessionReq();

    var member = seq.memberIds;
    member.addAll(memberList);

    NetWork().sendMsg(ComId.Chat, 101, seq);
  }

  //根据会话获取会话成员信息
  static getSessionInfo(int sessionId) {
    var seq = QuerySessionReq();
    seq.sessionId = sessionId;
    NetWork().sendMsg(ComId.Chat, 102, seq);
  }

  //创建群
  static createGroup(List<int> members, Function complete) {
    var seq = CreateChatGroupReq.create();
    seq.members.addAll(members);

    createGroupComplete = complete;

    var curTime = DateTime.now();
    print('发送建群消息 $curTime');
    NetWork().sendMsg(ComId.Chat, 201, seq);
  }

  //创建群结果
  static handleCreateGroup(List<int> content) async {
    var res = CreateChatGroupRes.fromBuffer(content);

    if (res.errorCode == 0) {
      var curTime = DateTime.now();
      print('建群成功  $curTime');
      GroupInfoModel infoModel = GroupInfoModel.fromInfo(res.group);
      GroupInfoMgr().addGroup(infoModel);

      if (createGroupComplete != null) {
        createGroupComplete(infoModel);
        createGroupComplete = null;
      }
      MessageMgr().emit('Update Group List');
    } else {
      print('建群失败');
    }
  }

  static createCoinBagMsg(Map args) {
    MsgModel msg;

    Int64 time = Int64((DateTime.now()).millisecondsSinceEpoch);

    var friendId = args['friendId'];

    RedWallet wallet = RedWallet.create();
    wallet.amount = args['amount'];
    wallet.title = args['title'];
    wallet.orderId = args['redNo'];
    wallet.tuId = friendId;
    wallet.suId = UserData().basicInfo.userId;
    wallet.state = RedWalletState.Uncollected;
    var myId = UserData().basicInfo.userId;
    msg = MsgModel(myId, friendId, ChatType.RedWalletChatType.value,
        wallet.writeToBuffer(), time.toInt(), curActiveSession);

    return msg;
  }

  static createSendMsg(ChatType chatType, content,
      {int extra,
      int friendId,
      String localFile,
      MsgModel refMsg,
      String refShortTxt,
      List<int> altUsers,
      ChatChannelType channelType = ChatChannelType.Session}) {
    MsgModel msg;

    if (content is String) {
      content = utf8.encode(content);
    }
    Int64 time = Int64((DateTime.now()).millisecondsSinceEpoch);

    var myId = UserData().basicInfo.userId;
    if (channelType == ChatChannelType.Group) {
      msg = MsgModel(
          myId, 0, chatType.value, content, time.toInt(), curActiveSession,
          channelType: channelType.value);
    } else {
      msg = MsgModel(myId, friendId, chatType.value, content, time.toInt(),
          curActiveSession,
          channelType: channelType.value);
    }

    if (localFile != null) {
      var fileId = curActiveSession.toString() + time.toString();
      msg.localFile = localFile;
      msg.extraFile = fileId;
    }

    if (extra != null) {
      msg.extraInfo = extra;
    }

    if (refMsg != null) {
      QuoteMsg quoteMsg = QuoteMsg.create();
      quoteMsg.sendUserId = refMsg.from;
      quoteMsg.sendTime = Int64(refMsg.time);
      quoteMsg.targetId = refMsg.sessionId;
      quoteMsg.content = refShortTxt;
      quoteMsg.channelType = ChatChannelType.valueOf(refMsg.channelType);

      msg.refMsgContent = quoteMsg.writeToBuffer();
    }

    if (altUsers != null && altUsers.length > 0) {
      msg.altUsers = altUsers;
    }

    return msg;
  }

  static insertMsgToDB(MsgModel msg) {
    //缓存消息,发送成功之后清理
    if (!sendCache.contains(msg)) {
      sendCache.add(msg);
      ChatDataMgr().saveMsg(msg);
    }
  }

  //登录成功之后重新发送缓存的消息
  static flushCacheMsg() {
    for (var i = 0; i < sendCache.length; i++) {
      sendChatMsg(sendCache[i]);
    }
  }

  static sendChatMsg(MsgModel msg) {
    var seq = ChatSendReq.create();
    seq.targetId = msg.sessionId;
    seq.sendTime = Int64(msg.time);
    seq.cType = ChatType.valueOf(msg.msgType);
    seq.channelType = ChatChannelType.valueOf(msg.channelType);

    if (msg.extraFile != null) {
      seq.enclosureUrl = msg.extraFile;
    }

    if (msg.extraInfo != null) {
      seq.contentSzie = msg.extraInfo;
    }

    if (msg.refMsgContent != null && msg.refMsgContent.length > 0) {
      seq.quoteMsg = msg.refMsgContent;
    }

    if (msg.altUsers != null && msg.altUsers.length > 0) {
      print('设置@信息 ${msg.altUsers.toString()}');
      seq.altUserIds.addAll(msg.altUsers);
    }
    seq.contentBuff = msg.msgContent;

    if (msg.msgContent.length > MaxMsgContentSize) {
      showToast(I18n.of(context).server_error_tips);
      print('消息包大小超过3M');
    }

    //本地文件为空或者等发送成功之后才可以发送
    if (msg.localFile == null || msg.state >= MsgState.Uploaded) {
      Future.delayed(Duration(seconds: 60), () {
        if (msg.state != MsgState.SendingSuccess) {
          msg.state = MsgState.SendingFailed;
          ChatDataMgr().updateMsgState(
              msg.sessionId, msg.time, msg.channelType, msg.state);
        }
      });

      NetWork().sendMsg(ComId.Chat, 1, seq);
      msg.state = MsgState.Sending;
    }
  }

  //获取会话未读消息
  static getUnreadMsgDetail(bool isGroup) {
    print('获取未读消息 群$isGroup');
//    showToast('获取未读消息 群$isGroup');
    var seq = RequestTargetUnreadReq.create();

    seq.targetId = curActiveSession;
    if (curActiveSession == 10000) {

      seq.channelType = ChatChannelType.CSD;
    } else {
      seq.channelType =
          isGroup ? ChatChannelType.Group : ChatChannelType.Session;
    }

    NetWork().sendMsg(ComId.Chat, 5, seq);
  }

  static int tempGroupId=0;
  static int mLastClickTime = 0;
  static int timeInterval = 2500;
//  static int receivedCount=0;
  static handlerReceiveMsg(PushChat chat) async {
    bool isGroup = false;
    bool isTranslateHK= false;
    if (chat.channelType == ChatChannelType.Group) {
      print('群聊消息');
      isGroup = true;
    }else  if (chat.channelType == ChatChannelType.TransHK) {
      print('聊天管家消息');
      isTranslateHK = true;
    }

    MsgModel msgModel;
    if (chat.sendUserId == 1) {
      //更新消息
      print('服务器更新消息');
      MsgModel findMsg;

      var msgList;
      if (isGroup) {
        msgList = ChatDataMgr().getGroupRecord();
      } else {
        msgList = ChatDataMgr().getRecord();
      }

      for (var i = 0; i < msgList.length; i++) {
        var msg = msgList[i];
        if (msg.time == chat.sendTime.toInt()) {
          findMsg = msg;
        }
      }
      //更新翻译
      if (findMsg != null) {
        findMsg.transTag = chat.translateState;

        if (chat.translateState == 4) {
          print('人工翻译结果更新${chat.targetId},${chat.translateState}');
          findMsg.translateContent = chat.humanTranslate;

          findMsg.enTranslateContent = chat.googleTranslate ?? Uint8List(0);

          ChatDataMgr().updateLastMsgWithTranslateMsg(chat);
          SqlUtil().updateUserTranslateContent(chat.targetId,
              chat.sendTime.toInt(), chat.humanTranslate, chat.translateState);
        } else if (chat.translateState == 3 || chat.translateState == 2) {
          print('机器翻译结果更新');

          ChatDataMgr().updateLastMsgWithTranslateMsg(chat);

          findMsg.translateContent = chat.tencentTranslate;
          findMsg.enTranslateContent = chat.googleTranslate;
          SqlUtil().updateMachineTranslateContent(
              chat.targetId,
              chat.sendTime.toInt(),
              chat.tencentTranslate,
              chat.googleTranslate,
              chat.translateState);
        }

        MessageMgr().emit('Update Translate Message', findMsg);
      }
    } else {
      if (chat.sendUserId == 0) {
        print('服务器通知消息 ${chat.sendTime.toInt()}  是否是翻译管家 $isTranslateHK');

        if (isGroup) {
          if (chat.cType == ChatType.GroupChatNoticeType) {
            //检查是否存在群信息
            var info = await GroupInfoMgr().getGroupInfo(chat.targetId);
            if (info == null) {
              print('群不存在');
              return;
            }

            var myId = UserData().basicInfo.userId;
            var notice = GroupChatNotice.fromBuffer(chat.contentBuff);

            print('群改变消息 changeType ${notice.changeType.toString()}');

            bool isShow = true;
            switch (notice.changeType) {
              case GroupChangeType.AddMember:
                GroupInfoMgr().addMembers(chat.targetId, notice.operateduId);
                break;
              case GroupChangeType.RemoveMember:
                var isMeIn = isContainMe(notice.operateduId);
                if (!isMeIn) {
                  //别人，这个自己有群信息
                  GroupInfoMgr()
                      .removeMembers(chat.targetId, notice.operateduId);
                } else {
                  //自己
                  GroupInfoMgr().removeSelf(chat.targetId);
                  print('已被移出该群,不能发消息了');
                }

                break;
              case GroupChangeType.GroupNameChange:
                print('更改群名  ${notice.changeStr}');
                GroupInfoMgr().updateGroupName(chat.targetId, notice.changeStr);
                break;
              case GroupChangeType.GroupNoticeChange:
                print('更改群公告  ${notice.changeStr}');
                GroupInfoMgr()
                    .updateGroupDescription(chat.targetId, notice.changeStr);
                break;
              case GroupChangeType.GroupMemberAliasChange:
                isShow = false;
                print('修改别名 ${notice.operatuId.id} ${notice.changeStr}');
                GroupInfoMgr().updateMemberRefName(
                    chat.targetId, notice.operatuId.id, notice.changeStr);
                //该消息不用显示和保存
                break;

              case GroupChangeType.MasterTrans:
                print(
                    '转让群主 转让人${notice.operatuId.id},被转让人${notice.operateduId[0].id}');
                GroupInfoMgr().updateGroupMaster(chat.targetId,
                    notice.operatuId.id, notice.operateduId[0].id);
                break;
              case GroupChangeType.QRCodeAddMemberNotice:
                if (notice.operatuId.id != myId) {
                  //别人在此处理,自己走回应消息
                  GroupInfoMgr().addMembers(chat.targetId, [notice.operatuId]);
                } else {}
                break;

              case GroupChangeType.GroupIsOpenMemberCheckChange:
                print('群主开启了群验证: ${notice.changeBool}');
                GroupInfoMgr()
                    .updateAskSwitch(chat.targetId, notice.changeBool);

                break;
              case GroupChangeType.GroupMemberCheckAddMemberNotice:
                print('群主确认进群: ${notice.operateduId.length}');
                GroupInfoMgr().addMembers(chat.targetId, notice.operateduId);
                break;
              case GroupChangeType.GroupMemberLeave:
                print('有人离开群: ${notice.operatuId}');
                isShow = false;
                GroupInfoMgr().removeMembers(chat.targetId, [notice.operatuId]);
                break;
              default:
            }

            //不需要展示给用户看
            if (!isShow) {
              print('该消息不用展示');
              return;
            }

            msgModel = MsgModel(0, chat.sendUserId, chat.cType.value,
                chat.contentBuff, chat.sendTime.toInt(), chat.targetId,
                channelType: ChatChannelType.Group.value);
          }
        }
        else if(isTranslateHK){
          var myId = UserData().basicInfo.userId;
          print('chat.contentBuff:${chat.contentBuff.length}');
          TransHKChatNotice notice = TransHKChatNotice.fromBuffer(chat.contentBuff);
          BaseUserInfo friendId ;
          print('chat.contentBuff AAAA');
           TranslateHKMgr().isUser = myId== notice.employer.id; ///判断自己是翻译官还是用户

          print('chat.contentBuff BBBB');
          if(myId== notice.employer.id){
            friendId  =notice.inter;
          }else{
            friendId = notice.employer;
          }


          print('friend id: ${friendId.id}    ');

          int sessionId = chat.targetId;
          if (chat.cType == ChatType.GroupChatNoticeType) {

            msgModel = MsgModel(0, friendId.id, chat.cType.value,
                chat.contentBuff, chat.sendTime.toInt(), sessionId,
                channelType: ChatChannelType.Session.value);
          }

          ///接到开始翻译管家消息-打开翻译管家聊天页面
          if(notice.noticeType==TransHKChatNoticeType.StartChat){


            Future.delayed(Duration(seconds: 1),(){
              TranslateHKMgr().orderStatus = TranslateHKMgr.ORDER_STATUS_EMPTY;
              MessageMgr().emit(MessageMgr.TRANSLATE_HK_REFRESH_ORDER );

              curActiveSession = sessionId;
              print('curActiveSession:$curActiveSession');
              MessageMgr().emit(MessageMgr.TRANSLATE_HK_START_CHAT, friendId.id);
            });

          }else if(notice.noticeType==TransHKChatNoticeType.EndChat){
            print('chat.contentBuff cccc');
            MessageMgr().emit(MessageMgr.TRANSLATE_HK_END_CHAT, friendId.id);
          }

        }else{//私聊通知消息
          if (chat.cType == ChatType.RedWalletChatType) {
            //系统红包通知消息
            RedWallet wallet = RedWallet.fromBuffer(chat.contentBuff);
            var myId = UserData().basicInfo.userId;

            var friendId;
            if (myId == wallet.suId) {
              friendId = wallet.tuId;
            } else {
              friendId = wallet.suId;
            }

            int sessionId = chat.targetId;
            msgModel = MsgModel(0, friendId, chat.cType.value, chat.contentBuff,
                chat.sendTime.toInt(), sessionId,
                channelType: ChatChannelType.Session.value);

            //更新红包信息
            ChatDataMgr()
                .updateRedWalletMsg(sessionId, wallet.orderId, wallet.state);
          } else {
            print('未知私聊通知消息');
          }
        }
      } else { //聊天消息





        int sessionId = chat.targetId;
        print('sessionId $sessionId');
        if (isGroup) {
          GroupInfoMgr()
              .getGroupInfo(sessionId)
              .then((GroupInfoModel groupInfo) {
            bool showGroup = false;
            if (groupInfo != null) {
              showGroup = groupInfo.messageFree == 0;
            }
            if (showGroup  ) {


              int nowTime = DateTime.now().millisecondsSinceEpoch;

              if (nowTime - mLastClickTime < timeInterval && tempGroupId==sessionId) { //2秒内同一群不重复弹出
                return;
              }

              tempGroupId = sessionId;
              LocalNotificationUtil.instance.show(
                  I18n.of(context).notice, I18n.of(context).new_chat_msg,
                  id: sessionId > 1000
                      ? int.parse(sessionId.toString().substring(0, 3))
                      : sessionId);
              mLastClickTime = nowTime;
            }
          });
        } else {
          LocalNotificationUtil.instance
              .show(I18n.of(context).notice, I18n.of(context).new_chat_msg);
        }

        msgModel = MsgModel(chat.sendUserId, chat.sendUserId, chat.cType.value,
            chat.contentBuff, chat.sendTime.toInt(), chat.targetId,
            channelType: chat.channelType.value);

//        if (chat.cType == ChatType.TextChatType){
//                  String content =utf8.decode(msgModel.msgContent);
//        print('当前收到消息条数$receivedCount  $content');
//        }



        if (chat.hasTencentTranslate()) {
          msgModel.translateContent = chat.tencentTranslate;
        }

        if (chat.hasGoogleTranslate()) {
          msgModel.enTranslateContent = chat.googleTranslate;
        }

        if (chat.hasContentSzie()) {
          msgModel.extraInfo = chat.contentSzie;
        }

        if (chat.targetId != curActiveSession) {
          msgModel.readState = 1; //未读标记
        }

        //视频附件
        if (chat.hasEnclosureUrl()) {
          msgModel.extraFile = chat.enclosureUrl;
        }

        if (chat.hasQuoteMsg()) {
          print('存在引用消息');
          msgModel.refMsgContent = chat.quoteMsg;
        }

        if (chat.altUserIds.length > 0) {
          print('存在@消息');
          msgModel.altUsers = chat.altUserIds;

          var myId = UserData().basicInfo.userId;
          for (var i = 0; i < msgModel.altUsers.length; i++) {
            if (msgModel.altUsers[i] == myId && curActiveSession != sessionId) {
              print('有人@了你');
              ChatDataMgr().groupUnreadProvider.setAlterMe(sessionId,msgModel.time);
              //to do
            }
          }

          print(chat.altUserIds.toString());
        }

        if (chat.cType == ChatType.TextChatType ||
            chat.cType == ChatType.ShortVoiceChatType ||
            chat.cType == ChatType.RedWalletChatType) {
          if (chat.hasTranslateState()) {
            //是否有人工翻译
            msgModel.transTag = chat.translateState;
            print('翻译标记：${chat.translateState}');
          }
        } else {
          msgModel.transTag = 0;
        }
      }

      if (msgModel == null) {
        print('消息为空,无法保存');
        return;
      }
      print('收到消息，准备保存 会话Id：${msgModel.sessionId} friendId: ${msgModel.friendId} ChatType: ${msgModel.channelType}');
      ChatDataMgr().saveMsg(msgModel);
      if (msgModel.msgType == ChatType.ShortVoiceChatType.value) {
        //如果是语音消息,自动下载
        msgModel.state = MsgState.Downloading;
        var filePath = await UploadUtil().downloadFile(msgModel);

        if (filePath != null) {
          msgModel.localFile = filePath;
          SqlUtil().updateLocalFile(msgModel.extraFile, filePath,
              isGroup: msgModel.channelType == ChatChannelType.Group.value);

          msgModel.state = MsgState.DownloadSuccess;
        } else {
          print('下载文件失败');
          msgModel.state = MsgState.DownloadFailed;
        }
      }

        if (msgModel.sessionId == 10000 ) {
          print('收到反馈小助手消息');
        }
      if (msgModel.sessionId == curActiveSession) {
      
        MessageMgr().emit('New Chat Message', msgModel.sessionId);
      }
    }
  }

  static isContainMe(List<BaseUserInfo> members) {
    var myId = UserData().basicInfo.userId;
    for (var i = 0; i < members.length; i++) {
      if (myId == members[i].id) {
        print('我在其中');
        return true;
      }
    }

    return false;
  }

  static getGroupNoticeMsg(
      GroupChatNotice notice, GroupInfoModel groupInfoModel) {
    var showStr = '';

    if (groupInfoModel == null) {
      print('群不存在');
      return '';
    }

    var myId = UserData().basicInfo.userId;
    var optId = notice.operatuId;
    List<BaseUserInfo> optedIds = notice.operateduId;

    switch (notice.changeType) {
      case GroupChangeType.AddMember:

        if (optId.id == myId) {
          var otherNames = '';
          for (var i = 0; i < optedIds.length; i++) {
            //获取用户名
            var nickName = _getUserName(optedIds[i].id, groupInfoModel.members);
            if (otherNames.length == 0) {
              otherNames = nickName;
            } else {
              otherNames = '$otherNames、$nickName';
            }
          }
          showStr = I18n.of(context).you_invite.replaceFirst('/s1', otherNames);
        } else {
          bool isMySelf = false;
          var otherNames = '';
          for (var i = 0; i < optedIds.length; i++) {
            //获取用户名
            isMySelf = myId == optedIds[i].id;
            var nickName = _getUserName(optedIds[i].id, groupInfoModel.members);
            if (otherNames.length == 0) {
              otherNames = nickName;
            } else {
              otherNames = '$otherNames、$nickName';
            }
          }
          var optName = _getUserName(optId.id, groupInfoModel.members);
          if (isMySelf) {
            showStr = I18n.of(context).invite_you.replaceFirst('/s1', optName);
          } else {
            showStr = I18n.of(context)
                .invite_someone
                .replaceFirst('/s1', optName)
                .replaceFirst('/s2', otherNames);
          }
        }
        break;
      case GroupChangeType.RemoveMember:
        var optName = _getUserName(optId.id, groupInfoModel.members);
        if (optId.id == myId) {
          optName = I18n.of(context).you;
        }

        var otherNames = '';

        for (var i = 0; i < optedIds.length; i++) {
          if (optedIds[i].id == myId) {
            otherNames = I18n.of(context).you;
          } else {
            //获取用户名
            var nickName = _getUserName(optedIds[i].id, groupInfoModel.members);
            if (otherNames.length == 0) {
              otherNames = nickName;
            } else {
              otherNames = '$otherNames,$nickName';
            }
          }
        }
        showStr = I18n.of(context)
            .delete_group
            .replaceFirst('/s1', optName)
            .replaceFirst('/s2', otherNames);
        break;
      case GroupChangeType.MasterTrans:
        var optedName = _getUserName(optedIds.first.id, groupInfoModel.members);

        if (optedIds.first.id == myId) {
          showStr = I18n.of(context).you_group_owner;
        } else {
          showStr = I18n.of(context)
              .someone_group_owner
              .replaceFirst('/s1', optedName);
        }
        break;

      case GroupChangeType.GroupNameChange:
        var groupName = notice.changeStr;

        var optName = _getUserName(notice.operatuId.id, groupInfoModel.members);
        if (notice.operatuId.id == myId) {
          showStr = '你 更改群名为 $groupName';
        } else {
          showStr = '$optName 更改群名为 $groupName';
        }
        // I18n.of(context).change_group_owner1.replaceFirst('/s1', groupName);
        break;
      case GroupChangeType.GroupNoticeChange:
        print('optId.id ${optId.id}');
        showStr = I18n.of(context).update_group_announce;
        break;
      case GroupChangeType.QRCodeAddMemberNotice:
        var optName = _getUserName(optId.id, groupInfoModel.members);
        print('optId.id ${optId.id}');
        showStr = optId.id == UserData().basicInfo.userId
            ? I18n.of(context).you_qr
            : I18n.of(context).others_qr.replaceFirst('/s1', optName);
        break;

      case GroupChangeType.GroupMemberCheckNotice:
        var optedName = _getUserName(optId.id, groupInfoModel.members);
        print('groupInfoModel.hosterId:${groupInfoModel.hosterId}');
        if (myId == groupInfoModel.hosterId) {
          showStr = I18n.of(context)
              .invite_confirm
              .replaceFirst('/s1', optedName)
              .replaceFirst('/s2', optedIds.length.toString());
        } else {
          //获取用户名
          var otherNames = '';
          for (var i = 0; i < optedIds.length; i++) {
            //获取用户名
            var nickName = optedIds[i].niceName;
            if (otherNames.length == 0) {
              otherNames = nickName;
            } else {
              otherNames = '$otherNames、$nickName';
            }
          }
          showStr = I18n.of(context)
              .want_invite_confirm
              .replaceFirst('/s1', optedName)
              .replaceFirst('/s2', otherNames);
        }

        break;

      case GroupChangeType.GroupMemberCheckAddMemberNotice:
//        var optedName = _getUserName(optId.id, groupInfoModel.members);
        bool isMy = false;
        var otherNames = '';
        for (var i = 0; i < optedIds.length; i++) {
          if (optedIds[i].id == myId) {
            isMy = true;
          }
          //获取用户名
          var nickName = optedIds[i].niceName;
          if (otherNames.length == 0) {
            otherNames = nickName;
          } else {
            otherNames = '$otherNames、$nickName';
          }
        }
        if (myId == groupInfoModel.hosterId) {
          showStr = I18n.of(context)
              .join_group_confirm
              .replaceFirst('/s1', otherNames);
        } else {
          if (isMy) {
            showStr = I18n.of(context)
                .you_invite_gourp
                .replaceFirst('/s1', optId.niceName);
          } else {
            showStr = I18n.of(context)
                .someone_join_group
                .replaceFirst('/s1', otherNames);
          }
        }

        break;

      case GroupChangeType.GroupIsOpenMemberCheckChange:
        showStr = notice.changeBool
            ? I18n.of(context).group_setting_tips1
            : I18n.of(context).group_setting_tips2;

        break;

      default:
    }

    return showStr;
  }

  static _getUserName(int uId, List<GroupMemberModel> members) {
    for (var uItem in members) {
      if (uItem.memberId == uId) {
        print('用户$uId 的名字 是 ${uItem.refName}');
        return uItem.refName;
      }
    }
    return '';
  }

  static void handlerUnreadMsg(msg) {
    var msgContent = PushUserUnreadMsgNotice.fromBuffer(msg);
    var noticeList = msgContent.notices;

    ChatDataMgr().updateRecordWithUnreadMsg(noticeList);
  }

  static handlerServerMsg(int comId, int msgId, List<int> content) {
    switch (comId) {
      case ComId.Chat:
        if (msgId == 2) {
          //发送消息成功回应
          var msgContent = ChatSendRes.fromBuffer(content);
          if (msgContent.errorCode == 0 ||
              msgContent.errorCode == 17 ||
              msgContent.errorCode == 16) {
            print('发送聊天消息成功');

            ChatDataMgr().updateMsgState(
                msgContent.targetId,
                msgContent.sendTime.toInt(),
                msgContent.channelType.value,
                MsgState.SendingSuccess);

            //去除缓存
            for (var i = 0; i < sendCache.length; i++) {
              MsgModel msg = sendCache[i];
              if (msgContent.targetId == msg.sessionId &&
                  msgContent.sendTime.toInt() == msg.time) {
                msg.state = MsgState.SendingSuccess;
                sendCache.remove(msg);
                break;
              }
            }
          } else {
            if (msgContent.errorCode == 3001) {
              print('用户没有登录,重新登录');
              NetWork().reLogin();
            } else {
              ChatDataMgr().updateMsgState(
                  msgContent.targetId,
                  msgContent.sendTime.toInt(),
                  msgContent.channelType.value,
                  MsgState.SendingFailed);

              for (var i = 0; i < sendCache.length; i++) {
                MsgModel msg = sendCache[i];
                if (msgContent.targetId == msg.sessionId &&
                    msgContent.sendTime.toInt() == msg.time) {
                  msg.state = MsgState.SendingFailed;
                  break;
                }
              }
            }
          }
        } else if (msgId == 3) {
          print('收到聊天消息');
          var msgContent = PushChat.fromBuffer(content);
          print('收到聊天消息BBBBB');
          ackServerMsg(msgContent.sendTime);
          handlerReceiveMsg(msgContent);
        } else if (msgId == 4) {
          print('处理未读消息汇总');
          handlerUnreadMsg(content);
        } else if (msgId == 9) {
          print('切换人工翻译状态通知');
          receiveTranslateState(content);
        } else if (msgId == 11) {
          //
          var msgContent = RequestRealtimeCallRes.fromBuffer(content);
          if (msgContent.errorCode == 0) {
            print('发送连麦消息成功');
            // showToast('发送连麦消息成功');
          } else {
            print('发送连麦消息失败');
            MessageMgr().emit('AudioChat Failed');
          }
        } else if (msgId == 12) {
          var msgContent = PushRealtimeCall.fromBuffer(content);

          var friendId = msgContent.sUserId;
          print('收到连麦消息 $friendId');

          //只能一次接收一个人的连麦
          if (!isAudioConnect) {
            LocalNotificationUtil.instance
                .show(I18n.of(context).notice, I18n.of(context).new_video_msg);
            playAudioRing();
            MessageMgr().emit('Receive AudioChat Request', friendId);
          }
        } else if (msgId == 14) {
          var msgContent = PushRealtimeCallRespond.fromBuffer(content);

          var friendId = msgContent.tUserId;
          print('收到连麦消息 $friendId');
          bool isAnswer = msgContent.isAnswer;
          stopAudioRing();

          if (!isAnswer) {
            audioChatRequestFriendId = 0;
          }

          MessageMgr().emit(
              'AudioChat State', {'fdId': friendId, 'isAnswer': isAnswer});
        } else if (msgId == 18) {
          var res = PushGiftGiving.fromBuffer(content);
          print('收到礼物：${res.sendUserId} , ${res.giftId} ,${res.giftAmount}');
          MessageMgr().emit("Receive Gift", res);
        } else if (msgId == 103) {
          print('收到会话成员信息');
        } else if (msgId == 202) {
          handleCreateGroup(content);
        } else if (msgId == 204) {
          handlerQuitGroup(content);
        } else if (msgId == 206) {
          handelerQueryGroupInfoRes(content);
        } else if (msgId == 208) {
          handlerAddGroupMemberRes(content);
        } else if (msgId == 210) {
          handlerRemoveGroupMemberRes(content);
        } else if (msgId == 212) {
          handlerUpdateGroupNoticeRes(content);
        } else if (msgId == 214) {
          handlerUpdateGroupNameRes(content);
        } else if (msgId == 216) {
          handlerUpdateMemberRefName(content);
        } else if (msgId == 218) {
          handlerGetGroupListRes(content);
        } else if (msgId == 220) {
          handlerSetGroupSwitch(content);
        } else if (msgId == 222) {
          handlerJoinGroupRes(content);
        } else if (msgId == 224) {
          handlerUpdateGroupHoster(content);
        } else if (msgId == 226) {
          handlerAgreeMember(content);
        } else if (msgId == 228) {
          handlerUpdateMemberMsgFree(content);
        }else if (msgId == 230) {
          handlerGroupIsShowMenberNiceName(content);
        }
        break;


      case ComId.TranslateOrder:

        if(msgId==2){
          handlerCreateTranslateOrder(content);
        }else if(msgId ==4){
          handlerReceiveOrder(content);
        }else if(msgId ==6){
          handlerCancelTranslateOrder(content);
        }else if(msgId==20){
          handlerDeliveryInterpreterOrderPush(content);
        }else if(msgId==21){
          handlerCancellationTransHKOrderPush(content);
        }else if(msgId==8){
          handlerEndTransHKOrderRes(content);
        }
        break;

      case ComId.PushMsg:
        String msg = PushNetRelay.fromBuffer(content).msg;
        print('接受的推送消息：msg $msg');
        Map map = json.decode(msg);
        String type = map['type'];

        switch (type) {
          case 'notice':

            ///由于极光本地推送点击事件无反应，暂时不走这，由远端推
            String messageJson = map['message'];
            Map messageMap = json.decode(messageJson);

            Map ext = json.decode(messageMap['extparameters']);
            print('ext $ext}');
            LocalNotificationUtil.instance.showOtherNotification(
                ext, messageMap['title'], messageMap['content']);
            break;
          case 'friends':
            FriendListMgr().getFriendListFromServer();
            MessageMgr().emit('Add friend');
            break;
          case 'deletedata':
            print('收到清空用户聊天记录通知');
            GroupInfoMgr().deleteAllGroup();
            ChatDataMgr().deleteAllRecord();
            FriendListMgr().deleteAllFriend();

            Navigator.of(context).pushAndRemoveUntil(new MaterialPageRoute(
              builder: (context) {
                return IndexPage();
              },
            ), (route) => route == null);
            NetWork().singOut();
            UserData().reset();
            break;
          case 'blacklist':
            String messageJson = map['message'];
            Map messageMap = json.decode(messageJson);
            if (messageMap['Status'] == 0) {
              BlacklistMgr.addBlackListMe(messageMap['UserId']);
            } else {
              BlacklistMgr.removeBalckListMe(messageMap['UserId']);
            }

            break;
        }

        break;
      default:
    }
  }

  //设置群验证开关
  static setGroupSwitch(int groupId, bool isCheck) {
    print('设置群验证开关 $isCheck');
    var seq = SettingGroupReq.create();
    seq.groupId = groupId;
    seq.isOpenMemberCheck = isCheck;

    NetWork().sendMsg(ComId.Chat, 219, seq);
  }

  //设置群验证开关结果
  static handlerSetGroupSwitch(List<int> msgContent) {
    print('设置群验证开关结果');
    var res = SettingGroupRes.fromBuffer(msgContent);

    if (res.errorCode == 0) {
      print('设置群验证开关结果成功');
    } else {
      print('设置群验证开关结果失败${res.errorCode}');
    }
  }

  //退出群
  static quitGroup(int groupId) {
    print('退出群');
    var seq = QuitChatGroupReq.create();
    seq.groupId = groupId;

    NetWork().sendMsg(ComId.Chat, 203, seq);
  }

  static handlerQuitGroup(List<int> msgContent) {
    print('退出群结果');
    var res = QuitChatGroupRes.fromBuffer(msgContent);

    if (res.errorCode == 0) {
      print('退出群结果成功 ${res.groupId}');
    } else {
      print('退出群结果失败${res.errorCode}');
    }
  }

  //添加群成员
  static addGroupMember(int groupId, List<int> uIdList) {
    print('##发送207  添加群成员------');
    var seq = AddGroupMemberReq.create();
    seq.groupId = groupId;
    seq.userIds.addAll(uIdList);

    NetWork().sendMsg(ComId.Chat, 207, seq);
  }

  //添加群成员结果
  static handlerAddGroupMemberRes(List<int> msgContent) {
    var res = AddGroupMemberRes.fromBuffer(msgContent);
    print('##发送返回 添加群成员 res.errorCode:${res.errorCode}');
    if (res.errorCode == 0) {
      MessageMgr().emit('Update Group Info');
      print('添加群成员成功');
    } else {
      switch (res.errorCode) {
        case 3007:
          showToast(I18n.of(context).members_max);
          break;
        default:
      }
      print('添加群成员失败');
    }
  }

  //扫码加入群
  static joinGroup(int groupId) {
    print('添加群成员');
    var seq = GroupQRcodeAddMemberReq.create();
    seq.groupId = groupId;

    NetWork().sendMsg(ComId.Chat, 221, seq);
  }

  //扫码加入群结果
  static handlerJoinGroupRes(List<int> msgContent) async {
    print('扫码加入群结果');
    var res = GroupQRcodeAddMemberRes.fromBuffer(msgContent);
    if (res.errorCode == 0) {
      print('扫码加入群结果成功');
      var groupInfoModel = GroupInfoModel.fromInfo(res.group);
      GroupInfoMgr().addGroup(groupInfoModel);

      Navigator.pushReplacement(context,
          MaterialPageRoute<void>(builder: (BuildContext context) {
        return GroupChatPage(
            key: Key('GroupChat'), groupInfoModel: groupInfoModel);
      }));
    } else {
      switch (res.errorCode) {
        case 3007:
          showToast(I18n.of(context).members_max);
          break;
        default:
      }
      print('扫码加入群结果失败${res.errorCode}');
    }
  }

  //移出群成员
  static removeGroupMember(int groupId, List<int> uIdList) {
    print('添加群成员');
    var seq = RemoveGroupMemberReq.create();
    seq.groupId = groupId;
    seq.userIds.addAll(uIdList);

    NetWork().sendMsg(ComId.Chat, 209, seq);
  }

  //移出群成员结果
  static handlerRemoveGroupMemberRes(List<int> msgContent) {
    print('移出群成员结果');
    var res = RemoveGroupMemberRes.fromBuffer(msgContent);
    if (res.errorCode == 0) {
      MessageMgr().emit('Update Group Info');
      print('移出群成员结果成功');
    } else {
      print('移出群成员结果失败${res.errorCode}');
    }
  }

  //修改群公告
  static updateGroupNotice(int groupId, String notice) {
    print('修改群公告');
    var seq = ModifyGroupNoticeReq.create();
    seq.groupId = groupId;
    seq.notice = notice;

    NetWork().sendMsg(ComId.Chat, 211, seq);
  }

  //修改群公告结果
  static handlerUpdateGroupNoticeRes(List<int> msgContent) {
    print('修改群公告结果');
    var res = ModifyGroupNoticeRes.fromBuffer(msgContent);
    if (res.errorCode == 0) {
      print('修改群公告结果成功');
    } else {
      print('修改群公告结果失败${res.errorCode}');
    }
  }

  //修改群名称请求
  static updateGroupName(int groupId, String name) {
    print('修改群名称请求');
    var seq = ModifyGroupNameReq.create();
    seq.groupId = groupId;
    seq.name = name;

    NetWork().sendMsg(ComId.Chat, 213, seq);
  }

  //修改群名称请求结果
  static handlerUpdateGroupNameRes(List<int> msgContent) {
    print('修改群名称请求结果');
    var res = ModifyGroupNameRes.fromBuffer(msgContent);
    if (res.errorCode == 0) {
      print('修改群名称请求成功');
    } else {
      showToast(I18n.of(context).fail);
      print('修改群名称请求失败${res.errorCode}');
    }
  }

  //修改群个人别名请求
  static updateMemberRefName(int groupId, String refName) {
    print('修改群个人别名请求$groupId');
    var seq = GroupMemberModifyAliasReq.create();
    seq.groupId = groupId;
    seq.name = refName;

    NetWork().sendMsg(ComId.Chat, 215, seq);
  }

  //修改群个人别名请求结果
  static handlerUpdateMemberRefName(List<int> msgContent) {
    print('修改群个人别名请求结果');
    var res = GroupMemberModifyAliasRes.fromBuffer(msgContent);
    if (res.errorCode == 0) {
      print('修改群个人别名请求结果成功');
    } else {
      print('修改群个人别名请求结果失败${res.errorCode}');
    }
  }

  //群主转让其他人
  static updateGroupHoster(int groupId, int uId) {
    print('群主转让其他人');
    var seq = GroupMasterTransReq.create();
    seq.groupId = groupId;
    seq.userId = uId;

    NetWork().sendMsg(ComId.Chat, 223, seq);
  }

  //群主转让其他人结果
  static handlerUpdateGroupHoster(List<int> msgContent) {
    print('群主转让其他人结果');
    var res = GroupMasterTransRes.fromBuffer(msgContent);
    if (res.errorCode == 0) {
      MessageMgr().emit('Update Group Info');
      print('群主转让其他人结果成功');
    } else {
      print('群主转让其他人结果失败${res.errorCode}');
    }
  }

  //群主批准其他人加入群
  static agreeMember(int groupId, List<int> uId) {
    print('群主批准其他人加入群 groupId:$groupId uId: $uId}');
    var seq = GroupMasterCheckAddMemberReq.create();
    seq.groupId = groupId;
    seq.userIds.addAll(uId);

    NetWork().sendMsg(ComId.Chat, 225, seq);
  }


  //是否显示群昵称
  static setGroupIsShowMenberNiceNameReq(int groupId,  bool isShow) {
    print('设置是否显示群昵称 groupId:$groupId isShow: $isShow');
    var seq = SetGroupIsShowMenberNiceNameReq.create();
    seq.groupId = groupId;
    seq.isShowMenberNiceName=isShow;

    NetWork().sendMsg(ComId.Chat, 229, seq);
  }



  //发布翻译管家帮助订单
  static sendCreateTranslateOrder(int fromLanguage,int toLanguage,int scences,String extraDesc) {

    TranslateHKMgr().isUser=true;
    debugPrint('发布翻译管家帮助订单 fromLanguage:$fromLanguage toLanguage: $toLanguage  | ${fromLanguage|toLanguage}' );
    var seq = IssueTransHKOrderReq.create();
    seq.tLanguage = fromLanguage|toLanguage;
    seq.scenes =scences;
    seq.desc = extraDesc;
    NetWork().sendMsg(ComId.TranslateOrder, 1, seq);
  }

  //发布翻译管家帮助订单回应
  static handlerCreateTranslateOrder(List<int> msgContent) {
    debugPrint('发布翻译管家帮助订单回应');
//    LoadingManage().closeLoading();
    var res = IssueTransHKOrderRes.fromBuffer(msgContent);
    if (res.errorCode == 0) {
      TranslateHKMgr().orderId = res.orderId;
      TranslateHKMgr().waitNum = res.waitNum;
      TranslateHKMgr().orderStatus=TranslateHKMgr.ORDER_STATUS_WAITING;
      MessageMgr().emit(MessageMgr.TRANSLATE_HK_REFRESH_ORDER);
//      GroupInfoMgr().updateMemberMsgFree(res.groupId, res.messageFree);
      debugPrint('发布翻译管家帮助订单回应-订单号： ${res.orderId}  等待人数 ${res.waitNum}');
    } else {
      debugPrint('发布翻译管家帮助订单失败 ${res.errorCode}');
    }
  }

  //撤销订单消息
  static sendCancelTranslateOrder( ) {


    debugPrint('取消订单 orderid:${TranslateHKMgr().orderId}' );
    var seq = CancellationTransHKOrderReq.create();
    seq.orderId = TranslateHKMgr().orderId;

    NetWork().sendMsg(ComId.TranslateOrder, 5, seq);
  }

  //撤销订单消息回应
  static handlerCancelTranslateOrder(List<int> msgContent) {
    debugPrint('撤销订单消息回应');
    var res = CancellationTransHKOrderRes.fromBuffer(msgContent);
    if (res.errorCode == 0) {

      debugPrint('撤销订单消息回应成功： ${res.orderId}');
    } else {
      debugPrint('撤销订单消息回应成功失败${res.errorCode}');
    }
  }

  //派送订单推送
  static handlerDeliveryInterpreterOrderPush(List<int> msgContent) {
    debugPrint('派送订单推送');
    var res = DeliveryTransHKOrderPush.fromBuffer(msgContent);
     print('OrderId: ${res.orderId} createTime: ${res.createTime} tLanguage:${res.tLanguage} scenes:${res.scenes} desc${res.desc}');

    TranslateOrder order = new TranslateOrder();
    order.orderId=res.orderId;
    order.desc=res.desc;
    order.createTime=res.createTime.toInt();
    order.tLanguage=res.tLanguage.toInt();
    order.scenes=res.scenes.toInt();
    TranslateHKMgr().order = order;
    MessageMgr().emit(MessageMgr.TRANSLATE_HK_RECEIVE_ORDER, order);

  }

//派送订单已被取消
  static handlerCancellationTransHKOrderPush(List<int> msgContent) {

    var res = CancellationTransHKOrderPush.fromBuffer(msgContent);
    debugPrint('派送订单已被取消: orderId${res.orderId}');
//    print('OrderId: ${res.orderId} createTime: ${res.createTime} tLanguage:${res.tLanguage} scenes:${res.scenes} desc${res.desc}');

    TranslateHKMgr().order = null;
    MessageMgr().emit(MessageMgr.TRANSLATE_HK_CANCEL_ORDER);
    showToast('派送订单已被取消');
  }



//接收订单请求
  static sendReceiveOrder( ) {
    TranslateOrder order = TranslateHKMgr().order;
    debugPrint('接收订单消息请求 orderId:${order.orderId}' );
    var seq = ReceivingTransHKOrderReq.create();
    seq.orderId = order.orderId;

    NetWork().sendMsg(ComId.TranslateOrder,3, seq);
  }

  //接收订单消息回应
  static handlerReceiveOrder(List<int> msgContent) {
    debugPrint('接收订单消息回应');
    var res = ReceivingTransHKOrderRes.fromBuffer(msgContent);
    if (res.errorCode == 0) {

//      GroupInfoMgr().updateMemberMsgFree(res.groupId, res.messageFree);
      debugPrint('接收订单消息回应成功： ');
    } else {
      debugPrint('接收订单消息回应失败${res.errorCode}');
    }
  }




  //用户主动结束翻译管家服务
  static sendEndTransHKOrderReq() {

    debugPrint('用户主动结束翻译管家服务 ${TranslateHKMgr().orderId}' );
    var seq = EndTransHKOrderReq.create();
    seq.orderId = TranslateHKMgr().orderId;
    NetWork().sendMsg(ComId.TranslateOrder, 7, seq);
  }

  //用户主动结束翻译管家服务回应
  static handlerEndTransHKOrderRes(List<int> msgContent) {
    debugPrint('用户主动结束翻译管家服务');
    var res = EndTransHKOrderRes.fromBuffer(msgContent);
    if (res.errorCode == 0) {

//      GroupInfoMgr().updateMemberMsgFree(res.groupId, res.messageFree);
      debugPrint('用户主动结束翻译管家服务 成功： ');
    } else {
      debugPrint('用户主动结束翻译管家服务 失败${res.errorCode}');
    }
  }






  //消息免打扰请求结果
  static handlerGroupIsShowMenberNiceName(List<int> msgContent) {
    print('设置是否显示群昵称');
    var res = SetGroupIsShowMenberNiceNameRes.fromBuffer(msgContent);
    if (res.errorCode == 0) {
//      GroupInfoMgr().updateMemberMsgFree(res.groupId, res.messageFree);
      print('设置是否显示群昵称成功');
    } else {
      print('消息免打扰请求结果失败${res.errorCode}');
    }
  }



  //消息免打扰请求结果
  static handlerUpdateMemberMsgFree(List<int> msgContent) {
    print('消息免打扰请求结果');
    var res = SetGroupMasterMessageFreeRes.fromBuffer(msgContent);
    if (res.errorCode == 0) {
      GroupInfoMgr().updateMemberMsgFree(res.groupId, res.messageFree);
      print('消息免打扰请求结果成功');
    } else {
      print('消息免打扰请求结果失败${res.errorCode}');
    }
  }



  //群主批准其他人加入群结果
  static handlerAgreeMember(List<int> msgContent) {
    print('群主批准其他人加入群结果');
    var res = GroupMasterCheckAddMemberRes.fromBuffer(msgContent);
    if (res.errorCode == 0) {
      print('群主批准其他人加入群结果成功');
    } else {
      switch (res.errorCode) {
        case 3007:
          showToast('群成员已满');
          break;
        default:
      }
    }
  }

  //消息免打扰请求
  static updateMemberMsgFreeReq(int groupId, bool isAvoid) {
    print('消息免打扰请求');
    var seq = SetGroupMasterMessageFreeReq.create();
    seq.groupId = groupId;
    seq.messageFree = isAvoid;

    NetWork().sendMsg(ComId.Chat, 227, seq);
  }



  //请求群列表求结果
  static handlerGetGroupListRes(List<int> msgContent) async {
    var res = QueryUserRelationGroupRes.fromBuffer(msgContent);

    if (res.relationGroup == null) {
      print('服务器也没有群存在');
      return;
    }
    for (var i = 0; i < res.relationGroup.length; i++) {
      var group = GroupInfoModel.fromInfo(res.relationGroup[i]);
      print('群id ${group.sessionId}');
      GroupInfoMgr().addGroup(group);
    }

    MessageMgr().emit('Update Group List');
  }

  //查询聊天群信息
  static queryGroupInfo(int groupId) {
    print('查询聊天群信息');
    var seq = QueryChatGroupReq.create();
    seq.groupId = groupId;

    NetWork().sendMsg(ComId.Chat, 205, seq);
  }

  //查询聊天群信息结果
  static handelerQueryGroupInfoRes(List<int> msgContent) async {
    print('处理查询聊天群信息结果');
    var res = QueryChatGroupRes.fromBuffer(msgContent);

    if (res.errorCode == 0) {
      print('获取群信息成功');
      var groupInfo = GroupInfoModel.fromInfo(res.group);
      print('开始创建群头像');

      GroupInfoMgr().addGroup(groupInfo);
    } else {
      print('获取群信息失败');
      switch (res.errorCode) {
        case 3006:
          showToast(I18n.of(context).group_max);
          break;

        default:
          showToast(I18n.of(context).fail);
      }
    }
  }

  static playAudioRing() {
    ringTimer = Timer.periodic(Duration(milliseconds: 2200), (timer) {
      SoundUtils().play(
          'http://testcyhd.chengyouhd.com/Upload/Audio/even_wheat_sound.mp3',
          isLocal: false);
    });
  }

  static stopAudioRing() {
    ringTimer?.cancel();
  }

  static ackServerMsg(Int64 msgId) {
    var seq = AnswerPushChat.create();
    seq.msgId = msgId;

    NetWork().sendMsg(ComId.Chat, 100, seq);
  }

  ///服务端已作废
//  static swtichTranslateState(TranslateState transState) {
//    print('请求切换人工翻译状态');
//    var seq = RequestSetHTranslReq.create();
//    seq.sessionId = curActiveSession;
//    seq.hTransl = transState;
//
//    NetWork().sendMsg(ComId.Chat, 7, seq);
//  }

  static void receiveTranslateState(msg) {
    var res = PushHTranslState.fromBuffer(msg);

    if (res.sessionId == curActiveSession) {
      MessageMgr().emit("Update Translate State", res);
    }
  }

  static void sendAudioChatReq(int friendId) {
    var seq = RequestRealtimeCallReq.create();
    seq.tUserId = friendId;
    seq.cType = ChatType.RealtimeCallVoiceType;

    NetWork().sendMsg(ComId.Chat, 10, seq);
  }

  static void sendReplyAudioChatReq(int friendId, bool isReply) {
    var seq = RespondRealtimeCallReq.create();
    seq.sUserId = friendId;
    seq.isAnswer = isReply;

    NetWork().sendMsg(ComId.Chat, 13, seq);
  }

  //打赏礼物
  static sendGiftTo(int friendId, int giftId, int giftAmount, int total) {
    var seq = RequestGiftGivingReq.create();
    seq.targetUserId = friendId;
    seq.giftId = giftId;
    seq.giftAmount = giftAmount;
    seq.money = total;

    NetWork().sendMsg(ComId.Chat, 17, seq);
  }

  static clear() {
    curActiveSession = 0;
    isTranslate = false;

    isAudioConnect = false;

    sendCache.clear();
  }
}
