/**
  * 回话是否已经被设定为屏蔽
  *
  * @param unreadEntity
  */
 private void addIsForbidden(UnreadEntity unreadEntity) {
   if (unreadEntity.getSessionType() == DBConstant.SESSION_TYPE_GROUP) {
     GroupEntity groupEntity = IMGroupManager.instance().findGroup(unreadEntity.getPeerId());
     if (groupEntity != null && groupEntity.getStatus() == DBConstant.GROUP_STATUS_SHIELD) {
       unreadEntity.setForbidden(true);
     }
   }
 }
 // 屏蔽群,相关的通知全部删除
 public void onEventMainThread(GroupEvent event) {
   GroupEntity gEntity = event.getGroupEntity();
   if (event.getEvent() == GroupEvent.Event.SHIELD_GROUP_OK) {
     if (gEntity == null) {
       return;
     }
     cancelSessionNotifications(gEntity.getSessionKey());
   }
 }
 public List<GroupEntity> getNormalGroupList() {
   List<GroupEntity> normalGroupList = new ArrayList<>();
   for (Entry<Integer, GroupEntity> entry : groupMap.entrySet()) {
     GroupEntity group = entry.getValue();
     if (group == null) {
       continue;
     }
     if (group.getGroupType() == DBConstant.GROUP_TYPE_NORMAL) {
       normalGroupList.add(group);
     }
   }
   return normalGroupList;
 }
  /** 1. 加载本地信息 2. 请求正规群信息 , 与本地进行对比 3. version groupId 请求 */
  public void onLocalLoginOk() {
    logger.i("group#loadFromDb");

    if (!EventBus.getDefault().isRegistered(inst)) {
      EventBus.getDefault().registerSticky(inst);
    }

    // 加载本地group
    List<GroupEntity> localGroupInfoList = dbInterface.loadAllGroup();
    for (GroupEntity groupInfo : localGroupInfoList) {
      groupMap.put(groupInfo.getPeerId(), groupInfo);
    }

    triggerEvent(new GroupEvent(GroupEvent.Event.GROUP_INFO_OK));
  }
  public void onReqCreateTempGroup(IMGroup.IMGroupCreateRsp groupCreateRsp) {
    logger.d("group#onReqCreateTempGroup");

    int resultCode = groupCreateRsp.getResultCode();
    if (0 != resultCode) {
      logger.e("group#createGroup failed");
      triggerEvent(new GroupEvent(GroupEvent.Event.CREATE_GROUP_FAIL));
      return;
    }
    GroupEntity groupEntity = ProtoBuf2JavaBean.getGroupEntity(groupCreateRsp);
    // 更新DB 更新map
    groupMap.put(groupEntity.getPeerId(), groupEntity);

    IMSessionManager.instance().updateSession(groupEntity);
    dbInterface.insertOrUpdateGroup(groupEntity);
    triggerEvent(new GroupEvent(GroupEvent.Event.CREATE_GROUP_OK, groupEntity)); // 接收到之后修改UI
  }
  public List<UserEntity> getGroupMembers(int groupId) {
    logger.d("group#getGroupMembers groupId:%s", groupId);

    GroupEntity group = findGroup(groupId);
    if (group == null) {
      logger.e("group#no such group id:%s", groupId);
      return null;
    }
    Set<Integer> userList = group.getlistGroupMemberIds();
    ArrayList<UserEntity> memberList = new ArrayList<UserEntity>();
    for (Integer id : userList) {
      UserEntity contact = IMContactManager.instance().findContact(id);
      if (contact == null) {
        logger.e("group#no such contact id:%s", id);
        continue;
      }
      memberList.add(contact);
    }
    return memberList;
  }
  /** 收到群成员发生变更消息 服务端主动发出 DB */
  public void receiveGroupChangeMemberNotify(IMGroup.IMGroupChangeMemberNotify notify) {
    int groupId = notify.getGroupId();
    int changeType = ProtoBuf2JavaBean.getGroupChangeType(notify.getChangeType());
    List<Integer> changeList = notify.getChgUserIdListList();

    List<Integer> curMemberList = notify.getCurUserIdListList();
    if (groupMap.containsKey(groupId)) {
      GroupEntity entity = groupMap.get(groupId);
      entity.setlistGroupMemberIds(curMemberList);
      dbInterface.insertOrUpdateGroup(entity);
      groupMap.put(groupId, entity);

      GroupEvent groupEvent = new GroupEvent(GroupEvent.Event.CHANGE_GROUP_MEMBER_SUCCESS);
      groupEvent.setChangeList(changeList);
      groupEvent.setChangeType(changeType);
      groupEvent.setGroupEntity(entity);
      triggerEvent(groupEvent);
    } else {
      // todo 没有就暂时不管了,只要聊过天都会显示在回话里面
    }
  }
  public void onReqChangeGroupMember(IMGroup.IMGroupChangeMemberRsp groupChangeMemberRsp) {
    int resultCode = groupChangeMemberRsp.getResultCode();
    if (0 != resultCode) {
      triggerEvent(new GroupEvent(GroupEvent.Event.CHANGE_GROUP_MEMBER_FAIL));
      return;
    }

    int groupId = groupChangeMemberRsp.getGroupId();
    List<Integer> changeUserIdList = groupChangeMemberRsp.getChgUserIdListList();
    IMBaseDefine.GroupModifyType groupModifyType = groupChangeMemberRsp.getChangeType();

    GroupEntity groupEntityRet = groupMap.get(groupId);
    groupEntityRet.setlistGroupMemberIds(groupChangeMemberRsp.getCurUserIdListList());
    groupMap.put(groupId, groupEntityRet);
    dbInterface.insertOrUpdateGroup(groupEntityRet);

    GroupEvent groupEvent = new GroupEvent(GroupEvent.Event.CHANGE_GROUP_MEMBER_SUCCESS);
    groupEvent.setChangeList(changeUserIdList);
    groupEvent.setChangeType(ProtoBuf2JavaBean.getGroupChangeType(groupModifyType));
    groupEvent.setGroupEntity(groupEntityRet);
    triggerEvent(groupEvent);
  }
  public void onRepGroupDetailInfo(IMGroup.IMGroupInfoListRsp groupInfoListRsp) {
    logger.i("group#onRepGroupDetailInfo");
    int groupSize = groupInfoListRsp.getGroupInfoListCount();
    int userId = groupInfoListRsp.getUserId();
    int loginId = imLoginManager.getLoginId();
    logger.i("group#onRepGroupDetailInfo cnt:%d", groupSize);
    if (groupSize <= 0 || userId != loginId) {
      logger.i("group#onRepGroupDetailInfo size empty or userid[%d]≠ loginId[%d]", userId, loginId);
      return;
    }
    ArrayList<GroupEntity> needDb = new ArrayList<>();
    for (IMBaseDefine.GroupInfo groupInfo : groupInfoListRsp.getGroupInfoListList()) {
      // 群组的详细信息
      // 保存在DB中
      // GroupManager 中的变量
      GroupEntity groupEntity = ProtoBuf2JavaBean.getGroupEntity(groupInfo);
      groupMap.put(groupEntity.getPeerId(), groupEntity);
      needDb.add(groupEntity);
    }

    dbInterface.batchInsertOrUpdateGroup(needDb);
    triggerEvent(new GroupEvent(GroupEvent.Event.GROUP_INFO_UPDATED));
  }
  private void showNotification(final UnreadEntity unreadEntity) {
    // todo eric need to set the exact size of the big icon
    // 服务端有些特定的支持 尺寸是不是要调整一下 todo 100*100  下面的就可以不要了
    ImageSize targetSize = new ImageSize(80, 80);
    int peerId = unreadEntity.getPeerId();
    int sessionType = unreadEntity.getSessionType();
    String avatarUrl = "";
    String title = "";
    String content = unreadEntity.getLatestMsgData();
    String unit = ctx.getString(R.string.msg_cnt_unit);
    int totalUnread = unreadEntity.getUnReadCnt();

    if (unreadEntity.getSessionType() == DBConstant.SESSION_TYPE_SINGLE) {
      UserEntity contact = IMContactManager.instance().findContact(peerId);
      if (contact != null) {
        title = contact.getMainName();
        avatarUrl = contact.getAvatar();
      } else {
        title = "User_" + peerId;
        avatarUrl = "";
      }

    } else {
      GroupEntity group = IMGroupManager.instance().findGroup(peerId);
      if (group != null) {
        title = group.getMainName();
        avatarUrl = group.getAvatar();
      } else {
        title = "Group_" + peerId;
        avatarUrl = "";
      }
    }
    // 获取头像
    avatarUrl = IMUIHelper.getRealAvatarUrl(avatarUrl);
    final String ticker = String.format("[%d%s]%s: %s", totalUnread, unit, title, content);
    final int notificationId = getSessionNotificationId(unreadEntity.getSessionKey());
    final Intent intent = new Intent(ctx, MessageActivity.class);
    intent.putExtra(IntentConstant.KEY_SESSION_KEY, unreadEntity.getSessionKey());

    logger.d("notification#notification avatarUrl:%s", avatarUrl);
    final String finalTitle = title;
    ImageLoader.getInstance()
        .loadImage(
            avatarUrl,
            targetSize,
            null,
            new SimpleImageLoadingListener() {

              @Override
              public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                logger.d("notification#icon onLoadComplete");
                // holder.image.setImageBitmap(loadedImage);
                showInNotificationBar(finalTitle, ticker, loadedImage, notificationId, intent);
              }

              @Override
              public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                logger.d("notification#icon onLoadFailed");
                // 服务器支持的格式有哪些
                // todo eric default avatar is too small, need big size(128 * 128)
                Bitmap defaultBitmap =
                    BitmapFactory.decodeResource(
                        ctx.getResources(),
                        IMUIHelper.getDefaultAvatarResId(unreadEntity.getSessionType()));
                showInNotificationBar(finalTitle, ticker, defaultBitmap, notificationId, intent);
              }
            });
  }