import 'package:chat/data/UserData.dart';
import 'package:chat/models/ChatMsg.dart';
import 'package:chat/models/group_info_server_model.dart';
import 'package:chat/models/last_message_model.dart';
import 'package:chat/proto/all.pbserver.dart';
import 'package:chat/utils/MessageMgr.dart';
import 'package:chat/utils/group_member_model.dart';
import 'package:chat/utils/sql_util.dart';

class GroupInfoModel {
  int sessionId; //群ID
  List<GroupMemberModel> members; //群成员
  int hosterId; // 群主id
  int topTag; //是否置顶
  String describe; //群公告
  int decribeTime; //群公告时间
  String name; //群名称
  LastMessageModel lastMsg;
  String image; //群图片
  String myName; //我在群中的别名
  int isSave; //是否保存到通讯录
  int askSwitch; //是否开启验证
  int messageFree; //群信息提醒
  int isShowName; //在聊天消息中是否显示名称
  bool isInGroup; //自己是否还在该群中

  GroupInfoModel(this.sessionId,
      {this.hosterId,
      this.topTag = 0,
      this.describe = '',
      this.decribeTime = 0,
      this.name = '',
      this.image = '',
      this.myName = '',
      this.askSwitch = 0,
      this.messageFree = 0,
      this.isShowName = 1,
      this.isSave = 0,
      this.isInGroup = true})
      : this.members = [];

  GroupInfoModel.fromJson(Map<String, dynamic> jsonStr) {
    print('群信息 $jsonStr');
    this.sessionId = jsonStr['sessionId'];
    this.hosterId = jsonStr['hosterId'];
    this.topTag = jsonStr['topTag'] ?? 0;
    this.describe = jsonStr['describe'];
    this.decribeTime = jsonStr['decribeTime'];
    this.name = jsonStr['name'];
    this.image = jsonStr['image'];
    this.myName = jsonStr['my_name'];
    this.askSwitch = jsonStr['ask_switch'] ?? 0;
    this.isSave = jsonStr['is_save'] ?? 0;
    this.messageFree = jsonStr['messageFree'] ?? 0;
    this.isShowName = jsonStr['show_name'] ?? 1;
    this.isInGroup = true;
  }

  GroupInfoModel.fromInfo(GroupInfo groupInfo) {
    this.sessionId = groupInfo.id;

    var myId = UserData().basicInfo.userId;
    if (members == null) {
      members = [];
    }

    for (var i = 0; i < groupInfo.members.length; i++) {
      var member = groupInfo.members[i];
      GroupMemberModel model = GroupMemberModel.fromPb(member);
      members.add(model);

      if (model.identity == GroupMemberIdentity.identityMaster.value) {
        hosterId = model.memberId;
      }
      if (member.info.id == myId) {
        myName = member.name;
        messageFree = member.messageFree ? 1 : 0;
      }
    }

    describe = groupInfo.notice;
    askSwitch = groupInfo.isOpenMemberCheck ? 1 : 0;
    isShowName = members.length > 20 ? 1 : 0;//群人数大于20个自动打开
    topTag = 0;
    isSave = 0;
    this.isInGroup = true;
    this.name = groupInfo.groupName;
  }

  GroupInfoModel.fromServerGroupInfo(GroupInfoServerModel groupInfo) {
    this.sessionId = groupInfo.id;

    var myId = UserData().basicInfo.userId;
    if (members == null) {
      members = [];
    }

    for (var i = 0; i < groupInfo.members.length; i++) {
      var member = groupInfo.members[i];
      GroupMemberModel model = GroupMemberModel.fromServerMember(member);
      members.add(model);

      if (model.identity == GroupMemberIdentity.identityMaster.value) {
        hosterId = model.memberId;
      }
      if (member.info.id == myId) {
        myName = member.name;
        messageFree = member.messageFree ? 1 : 0;
      }
    }

    describe = groupInfo.notice;
    askSwitch = groupInfo.isOpenMemberCheck ? 1 : 0;
    isShowName = members.length > 20 ? 1 : 0;//群人数大于20个自动打开
    isSave = 0;
    topTag = 0;
    this.isInGroup = true;
    this.name = groupInfo.groupName;
  }

  updateWithInfo(GroupInfoModel groupInfo) {
    members = groupInfo.members;
    describe = groupInfo.describe;
    name = groupInfo.name;
    askSwitch = groupInfo.askSwitch;
    messageFree = groupInfo.messageFree;
    myName = groupInfo.myName;
    hosterId = groupInfo.hosterId;
    image = groupInfo.image;
    isShowName = groupInfo.isShowName;
    isSave = groupInfo.isSave;
  }

  //是否可以修改群名称
  canAlterGroupName() {
    //70人以上的群只有群主或者管理员才能修改群名
    if (members.length >= 70) {
      int myId = UserData().basicInfo.userId;
      var myInfo = getMember(myId);
      if (myInfo != null &&
          (myInfo.identity == GroupMemberIdentity.identityMaster.value ||
              myInfo.identity == GroupMemberIdentity.identityManager.value)) {
        return true;
      } else {
        return false;
      }
    } else {
      //普通群都可以修改群名
      return true;
    }
  }

  //更新最新的消息
  updateLastMsg(MsgModel msgModel) {
    if (msgModel == null) {
      print('消息未空，无法初始化最新消息');
      return;
    }
    if (lastMsg != null) {
      //更新
      lastMsg.updateWithMessage(msgModel);
    } else {
      lastMsg = LastMessageModel.fromChatMsg(msgModel);
    }
    MessageMgr().emit('Update Group List');
    print('msgModel.sessionId ${msgModel.sessionId}');
    MessageMgr().emit('Update LastMsg', msgModel.sessionId);
  }

  //更新最新的消息
  updateLastMsgWithUnread(UserUnreadMsgNotice unread) {
    if (lastMsg == null) {
      lastMsg = LastMessageModel.fromUnreadMsg(unread);
    } else {
      lastMsg.updateWithUnreadMsg(unread);
    }

    MessageMgr().emit('Update Group List');
    MessageMgr().emit('Update LastMsg', unread.targetId);
  }

  updateLastMsgWithTransMsg(PushChat chat) {
    //更新
    if (chat.cType == ChatType.TextChatType) {
      print('更新最新数据的翻译结果');

      if (lastMsg != null && chat.hasTencentTranslate()) {
        lastMsg.msgContent = chat.tencentTranslate;
      }
      MessageMgr().emit('Update Group List');
      MessageMgr().emit('Update LastMsg', chat.targetId);
    }
  }

  //获取还在群中的成员
  List<GroupMemberModel> getMembersInGroup() {
    List<GroupMemberModel> inMembers = [];

    for (var i = 0; i < members.length; i++) {
      if (members[i].inGroup == 1) {
        inMembers.add(members[i]);
      }
    }

    return inMembers;
  }

  getHoster() {
    for (var i = 0; i < members.length; i++) {
      if (members[i].identity == GroupMemberIdentity.identityMaster.value) {
        return members[i];
      }
    }
    return null;
  }

  getGroupName(Map refMap) {
    if (name != null && name != '') {
      return name;
    } else {
      var members = getMembersInGroup();
      String res = '';
      int nums = members.length > 4 ? 4 : members.length;
      for (int i = 0; i < nums; i++) {
        if (i != 0) {
          res += '、';
        }
        if (refMap[members[i].memberId] != null) {
          String name = (refMap[members[i].memberId] as String);
          res += name.length>8?name.substring(0,8)+'..':name;
        } else {
          String name = members[i].refName;
          res += name.length>8?name.substring(0,8)+'..':name;
        }
      }
      return res;
    }
  }

  //置顶
  updateTopTag(bool isTop) {
    topTag = isTop ? 1 : 0;
    SqlUtil.groupInfoTableModel.updateTopTag(sessionId, topTag);
  }

  //修改群校验开关
  updateAskSwitch(bool isOpen) {
    askSwitch = isOpen ? 1 : 0;
    SqlUtil.groupInfoTableModel.updateAskSwitch(sessionId, askSwitch);
  }

  //修改是否在聊天中展示用户名称
  updateShowNameSwitch(bool isShow) {
    isShowName = isShow ? 1 : 0;
    SqlUtil.groupInfoTableModel.updateShowNameSwitch(sessionId, isShowName);
  }

  //添加群成员
  addMember(GroupMemberModel member) {
    var oldMember = getMember(member.memberId);

    //如果该群中已有数据，更新状态
    if (oldMember != null) {
      if (oldMember.inGroup == 0) {
        oldMember.inGroup = 1;
        SqlUtil.groupMemberTableModel
            .updateMemberState(sessionId, member.memberId, 1);
      }
    } else {
      members.add(member);
      SqlUtil.groupMemberTableModel.addSingleMember(sessionId, member);
    }
    print('addMember ${member.memberId}   ${UserData().basicInfo.userId}');
    if (member.memberId == UserData().basicInfo.userId) {
      print('addMember ture');
      isInGroup = true;
    }

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

  //删除成员,更新状态即可
  removeMember(int uId) {
    var member = getMember(uId);
    if (member != null) {
      member.inGroup = 0;
      SqlUtil.groupMemberTableModel.updateMemberState(sessionId, uId, 0);
    }
  }

  //修改群名称
  updateGroupName(String groupName) {
    name = groupName;

    SqlUtil.groupInfoTableModel.updateGroupName(sessionId, groupName);

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

  //修改群公告
  updateGroupNotice(String notice) {
    describe = notice;
    SqlUtil.groupInfoTableModel.updateGroupNotice(sessionId, notice);

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

  GroupMemberModel getMember(int uId) {
    for (var i = 0; i < members.length; i++) {
      if (members[i].memberId == uId) {
        return members[i];
      }
    }

    print('找不到该成员$uId');

    return null;
  }

  //修改成员免打扰设置
  updateMemberMsgFree(int isAvoid) {
    messageFree = isAvoid;
    MessageMgr().emit('Update Group Info');
    SqlUtil.groupInfoTableModel.updateGroupMesssageFree(sessionId, isAvoid);
  }

  //修改成员别名
  updateMemberRefName(int uId, String refName) {
    print('修改成员别名 $uId  $refName');
    var member = getMember(uId);
    if (member != null) {
      member.refName = refName;
      if (uId == UserData().basicInfo.userId) {
        //自己
        myName = refName;
        SqlUtil.groupInfoTableModel.updateMyName(sessionId, refName);
      } else {
        SqlUtil.groupMemberTableModel
            .updateMemberRefName(sessionId, uId, refName);
      }

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

  //修改群主
  updateGroupHoster(int oldId, int uId) {
    //系统
    if (oldId == 0) {
      //去除旧的群主
      for (var i = 0; i < members.length; i++) {
        if (members[i].identity == GroupMemberIdentity.identityMaster.value) {
          members[i].identity = 0;
          SqlUtil.groupMemberTableModel
              .updateMemberIdentity(sessionId, members[i].memberId, 0);
          break;
        }
      }
    } else {
      var member = getMember(oldId);
      member.identity = 0;
      SqlUtil.groupMemberTableModel
          .updateMemberIdentity(sessionId, member.memberId, 0);
    }

    //修改新的群主
    var member = getMember(uId);
    if (member != null) {
      hosterId = member.memberId;
      member.identity = GroupMemberIdentity.identityMaster.value;
      SqlUtil.groupMemberTableModel
          .updateMemberIdentity(sessionId, member.memberId, member.identity);
      SqlUtil.groupInfoTableModel.updateHoster(sessionId, member.memberId);
    }
    MessageMgr().emit('Update Group Info');
  }

  //判断是否在群中
  bool isGroupMember(int userId) {
    for (var i = 0; i < members.length; i++) {
      if (members[i].memberId == userId) {
        return members[i].inGroup == 1;
      }
    }
    return false;
  }

  updateAvatar(String path) {
    image = path;
    SqlUtil.groupInfoTableModel.updateImage(sessionId, image);
  }

  cleanAvatar() {
    image = '';
  }
}
