package com.hyphenate.chatdemo;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;

import com.hyphenate.EMCallBack;
import com.hyphenate.EMChatRoomChangeListener;
import com.hyphenate.EMContactListener;
import com.hyphenate.EMGroupChangeListener;
import com.hyphenate.EMMessageListener;
import com.hyphenate.EMValueCallBack;
import com.hyphenate.chat.EMChatRoom;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMCombineMessageBody;
import com.hyphenate.chat.EMContact;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMCursorResult;
import com.hyphenate.chat.EMCustomConversationFilter;
import com.hyphenate.chat.EMCustomMessageBody;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.chat.EMGroupMemberInfo;
import com.hyphenate.chat.EMImageMessageBody;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMMessageBody;
import com.hyphenate.chat.EMMucSharedFile;
import com.hyphenate.chat.EMPushManager;
import com.hyphenate.chat.EMRTCTokenInfo;
import com.hyphenate.chat.EMSilentModeParam;
import com.hyphenate.chat.EMSilentModeResult;
import com.hyphenate.chat.EMSilentModeTime;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.chat.EMVideoMessageBody;
import com.hyphenate.chat.adapter.EMASilentModeItem;
import com.hyphenate.chatdemo.databinding.ActivityEmBinding;
import com.hyphenate.exceptions.HyphenateException;
import com.hyphenate.util.EMFileHelper;
import com.hyphenate.util.EMLog;

import org.json.JSONObject;

import java.io.FileDescriptor;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class EMActivity extends AppCompatActivity implements View.OnClickListener {
    private ActivityEmBinding mBinding;
    private static final String TAG = "EMActivity";
    private static final int ATTACHMENT_SCAN_COUNT = 200;
    private String conversationId = "250481334091777";
    //线上环境 easemob#easeim
//    private String chatRoomID = "248661699264519";
    //测试环境 easemob-demo#chatdemoui
    private String chatRoomID = "264325998641153";
    private String groupId = "305355575853057";

    private String messageId;
    private String username = "xu";
    private String to="pu";
    private EMChatRoomChangeListener chatRoomChangeListener;
    private EMGroupChangeListener groupChangeListener;
    private EMContactListener contactListener;
    private String fileId="";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = ActivityEmBinding.inflate(getLayoutInflater());
        setContentView(mBinding.getRoot());
        initListener();
        initData();
    }

    private void initListener() {
        mBinding.btnSyncNoDisturb.setOnClickListener(this);
        mBinding.btnConversatonRemindType.setOnClickListener(this);
        mBinding.btnAddBlackList.setOnClickListener(this);
        mBinding.btnRemoveBlackList.setOnClickListener(this);
        mBinding.btnQueryBlackList.setOnClickListener(this);
        mBinding.btnAddContact.setOnClickListener(this);
        mBinding.btnRemoveContact.setOnClickListener(this);
        mBinding.btnAcceptInvitation.setOnClickListener(this);
        mBinding.btnRefuseInvitation.setOnClickListener(this);
        mBinding.btnQueryContacts.setOnClickListener(this);
        mBinding.btnQueryContactsFromServer.setOnClickListener(this);
        mBinding.btnVerifyContactsRemarkRetry.setOnClickListener(this);
        mBinding.btnQueryMsgCountWithDuration.setOnClickListener(this);
        mBinding.btnJoinChatroom.setOnClickListener(this);
        mBinding.btnLeaveChatroom.setOnClickListener(this);
        mBinding.btnGetUnreadMsgCount.setOnClickListener(this);
        mBinding.btnSetMsgParams.setOnClickListener(this);
        mBinding.btnSetFilterConversations.setOnClickListener(this);
        mBinding.btnSecondActivity.setOnClickListener(this);
        mBinding.btnQueryAllMsgs.setOnClickListener(this);
        mBinding.btnUploadGroupFile.setOnClickListener(this);
        mBinding.btnMakeCrash.setOnClickListener(this);
        mBinding.btnGroupFile.setOnClickListener(this);
        mBinding.btnDownloadGroupFile.setOnClickListener(this);
        mBinding.btnCustomMsg.setOnClickListener(this);
        mBinding.btnLoadMoreMsg.setOnClickListener(this);
        mBinding.btnChatroomCreatetime.setOnClickListener(this);
        mBinding.btnChatroomInWhitelist.setOnClickListener(this);
        mBinding.btnChatroomMuteExpireTime.setOnClickListener(this);
        mBinding.btnSendMessage.setOnClickListener(this);
        mBinding.btnModifyMessage.setOnClickListener(this);
        mBinding.btnNodisturbStartTime.setOnClickListener(this);
        mBinding.btnLoadMessageWithKeyword.setOnClickListener(this);
        mBinding.btnLoadMessageByIds.setOnClickListener(this);
        mBinding.btnGetRtcToken.setOnClickListener(this);
        mBinding.btnMapUid.setOnClickListener(this);
        mBinding.btnOpenFile.setOnClickListener(this);
        mBinding.btnDownloadImageOriginal.setOnClickListener(this);
        mBinding.btnDownloadImageBig.setOnClickListener(this);
        mBinding.btnDownloadImageThumbnail.setOnClickListener(this);
        mBinding.btnDownloadVideoFile.setOnClickListener(this);
        mBinding.btnDownloadVideoThumbnail.setOnClickListener(this);
        mBinding.btnDownloadParseCombineMessage.setOnClickListener(this);
        mBinding.btnGetGroupFromServer.setOnClickListener(this);
        mBinding.btnGetJoinedGroups.setOnClickListener(this);
        mBinding.btnFetchGroupMembersInfo.setOnClickListener(this);
        mBinding.btnGetContactUserInfo.setOnClickListener(this);
        mBinding.btnGetUserProfiles.setOnClickListener(this);
        mBinding.btnGetSenderInfo.setOnClickListener(this);
        mBinding.btnUpdateSelfNamecard.setOnClickListener(this);
        mBinding.btnGetCachedNamecard.setOnClickListener(this);
        mBinding.btnTestGetUserProfiles.setOnClickListener(this);
        chatRoomChangeListener = new EMChatRoomChangeListener() {
            @Override
            public void onChatRoomDestroyed(String roomId, String roomName) {
                EMLog.e(TAG, "onChatRoomDestroyed roomId:" + roomId + " roomName:" + roomName);
            }

            @Override
            public void onMemberJoined(String roomId, String participant, String ext) {
                EMLog.e(TAG, "onMemberJoined roomId:" + roomId + " participant:" + participant + " ext:" + ext);
            }

            @Override
            public void onMemberExited(String roomId, String roomName, String participant) {
                EMLog.e(TAG, "onMemberExited roomId:" + roomId + " roomName:" + roomName + " participant:" + participant);
            }

            @Override
            public void onRemovedFromChatRoom(int reason, String roomId, String roomName, String participant) {
                EMLog.e(TAG, "onRemovedFromChatRoom reason:" + reason + " roomId:" + roomId + " roomName:" + roomName + " participant:" + participant);
            }

            @Override
            public void onMuteListRemoved(String chatRoomId, List<String> mutes) {
                EMLog.e(TAG, "onMuteListRemoved chatRoomId:" + chatRoomId + " mutes:" + mutes);
            }

            @Override
            public void onWhiteListAdded(String chatRoomId, List<String> whitelist) {

            }

            @Override
            public void onWhiteListRemoved(String chatRoomId, List<String> whitelist) {

            }

            @Override
            public void onAllMemberMuteStateChanged(String chatRoomId, boolean isMuted) {

            }

            @Override
            public void onAdminAdded(String chatRoomId, String admin) {

            }

            @Override
            public void onAdminRemoved(String chatRoomId, String admin) {

            }

            @Override
            public void onOwnerChanged(String chatRoomId, String newOwner, String oldOwner) {

            }

            @Override
            public void onAnnouncementChanged(String chatRoomId, String announcement) {

            }
        };
        EMClient.getInstance().chatroomManager().addChatRoomChangeListener(chatRoomChangeListener);
        
        groupChangeListener = new EMGroupChangeListener() {
            @Override
            public void onInvitationReceived(String groupId, String groupName, String inviter, String reason) {

            }

            @Override
            public void onRequestToJoinReceived(String groupId, String groupName, String applicant, String reason) {

            }

            @Override
            public void onRequestToJoinAccepted(String groupId, String groupName, String accepter) {

            }

            @Override
            public void onInvitationAccepted(String groupId, String invitee, String reason) {

            }

            @Override
            public void onInvitationDeclined(String groupId, String invitee, String reason) {

            }

            @Override
            public void onUserRemoved(String groupId, String groupName) {

            }

            @Override
            public void onGroupDestroyed(String groupId, String groupName) {

            }

            @Override
            public void onAutoAcceptInvitationFromGroup(String groupId, String inviter, String inviteMessage) {

            }

            @Override
            public void onMuteListAdded(String groupId, List<String> mutes, long muteExpire) {

            }

            @Override
            public void onMuteListRemoved(String groupId, List<String> mutes) {

            }

            @Override
            public void onWhiteListAdded(String groupId, List<String> whitelist) {

            }

            @Override
            public void onWhiteListRemoved(String groupId, List<String> whitelist) {

            }

            @Override
            public void onAllMemberMuteStateChanged(String groupId, boolean isMuted) {

            }

            @Override
            public void onAdminAdded(String groupId, String administrator) {

            }

            @Override
            public void onAdminRemoved(String groupId, String administrator) {

            }

            @Override
            public void onOwnerChanged(String groupId, String newOwner, String oldOwner) {

            }

            @Override
            public void onAnnouncementChanged(String groupId, String announcement) {

            }

            @Override
            public void onSharedFileAdded(String groupId, EMMucSharedFile sharedFile) {

            }

            @Override
            public void onSharedFileDeleted(String groupId, String fileId) {

            }

//            @Override
//            public void onUserGroupNamecardUpdated(String groupId, String userId, String groupNamecard) {
//                EMLog.e(TAG, "onUserGroupNamecardUpdated groupId:" + groupId + " userId:" + userId + " groupNamecard:" + groupNamecard);
//            }
        };
        EMClient.getInstance().groupManager().addGroupChangeListener(groupChangeListener);
        mBinding.btnInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                username = s.toString();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        EMClient.getInstance().chatManager().addMessageListener(new EMMessageListener() {
            @Override
            public void onMessageReceived(List<EMMessage> messages) {
                EMLog.e("xcp", "onMessageReceived");
                for (EMMessage message : messages) {
                    EMMessageBody body = message.getBody();
                    if(body instanceof EMCustomMessageBody){
                        EMLog.e("xcp", "onMessageReceived EMCustomMessageBody");
                        EMCustomMessageBody customMessageBody = (EMCustomMessageBody) body;
                        String event = customMessageBody.event();
                        EMLog.e("xcp", "event:" + event);
                    }else if(body instanceof EMTextMessageBody){
                        EMTextMessageBody messageBody = (EMTextMessageBody) (body);
                        String msg = messageBody.getMessage();
                        EMLog.e(TAG, "onMessageReceived onSuccess message:" + msg);
                    }else if(body instanceof EMImageMessageBody) {
//                        logImageAttachmentState("message_received", "receive", message, (EMImageMessageBody) body);
                    }else if(body instanceof EMVideoMessageBody) {
                        logVideoAttachmentState("message_received", "receive", message, (EMVideoMessageBody) body);
                    }
                }
            }

            @Override
            public void onMessageContentChanged(EMMessage messageModified, String operatorId, long operationTime) {
                Map<String, Object> newExt = messageModified.ext();
                for (Map.Entry<String, Object> entry : newExt.entrySet()) {
                    EMLog.e(TAG, "onMessageContentChanged onSuccess key:" + entry.getKey() + " value:" + entry.getValue());
                }
                EMMessageBody body = messageModified.getBody();
                if(body instanceof EMTextMessageBody){
                    EMTextMessageBody messageBody = (EMTextMessageBody) (body);
                    String message = messageBody.getMessage();
                    EMLog.e(TAG, "onMessageContentChanged onSuccess message:" + message);
                }

            }
        });

//        EMClient.getInstance().userInfoManager().addUserInfoManagerListener(new EMUserInfoManagerListener() {
//            @Override
//            public void onSelfUserInfoUpdate(EMUserInfo userInfo) {
//                EMLog.e(TAG,"onSelfUserInfoUpdate userInfo:" + userInfo);
//            }
//
//            @Override
//            public void onUserInfoUpdate(List<EMUserInfo> userInfoList) {
//                EMLog.e(TAG,"onUserInfoUpdate userInfoList:" + userInfoList);
//            }
//        });

        contactListener = new EMContactListener() {
            @Override
            public void onContactAdded(String username) {
                EMLog.i(TAG, "contactListener onContactAdded username:" + username);
            }

            @Override
            public void onContactDeleted(String username) {
                EMLog.i(TAG, "contactListener onContactDeleted username:" + username);
            }

            @Override
            public void onContactInvited(String username, String reason) {
                EMLog.i(TAG, "contactListener onContactInvited username:" + username + " reason:" + reason);
            }

            @Override
            public void onFriendRequestAccepted(String username) {
                EMLog.i(TAG, "contactListener onFriendRequestAccepted username:" + username);
            }

            @Override
            public void onFriendRequestDeclined(String username) {
                EMLog.i(TAG, "contactListener onFriendRequestDeclined username:" + username);
            }
//            @Override
//            public void onContactSyncStart() {
//                EMLog.i(TAG, "contactListener onContactSyncStart");
//            }
//            @Override
//            public void onContactSyncFinishWithError(int errorCode, String errorMsg) {
//                EMLog.e(TAG, "contactListener onContactSyncFinishWithError errorCode:" + errorCode + " errorMsg:" + errorMsg);
//            }
//
//            @Override
//            public void onContactInfoUpdate(EMContact contact) {
//            }
        };
        EMClient.getInstance().contactManager().setContactListener(contactListener);
    }


    private void initData() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_sync_no_disturb:
                syncNoDisturb();
                break;
            case R.id.btn_conversaton_remind_type:
                conversationRemindType();
                break;
            case R.id.btn_nodisturb_start_time:
                noDisturbStartTime();
                break;
            case R.id.btn_add_black_list:
                addBlacklist();
                break;
            case R.id.btn_remove_black_list:
                removeBlacklist();
                break;
            case R.id.btn_query_black_list:
                queryBlacklistLocal();
                break;
            case R.id.btn_add_contact:
                addContact();
                break;
            case R.id.btn_remove_contact:
                removeContact();
                break;
            case R.id.btn_accept_invitation:
                acceptInvitation();
                break;
            case R.id.btn_refuse_invitation:
                refuseInvitation();
                break;
            case R.id.btn_query_contacts:
                queryContacts();
                break;
            case R.id.btn_query_contacts_from_server:
                queryServerContacts();
                break;
            case R.id.btn_verify_contacts_remark_retry:
                verifyContactsRemarkRetry();
                break;
            case R.id.btn_query_msg_count_with_duration:
                queryMsgCountWithDuration();
                break;
            case R.id.btn_join_chatroom:
                joinChatRoom();
                break;
            case R.id.btn_leave_chatroom:
                leaveChatRoom();
                break;
            case R.id.btn_get_unread_msg_count:
                getUnreadMessageCount();
                break;
            case R.id.btn_set_msg_params:
                setMsgParams();
                break;
            case R.id.btn_set_filter_conversations:
                filterConversations();
                break;
            case R.id.btn_second_activity:
                toSecondActivity();
                break;
            case R.id.btn_query_all_msgs:
                queryMsgsCount();
                break;
            case R.id.btn_upload_group_file:
                uploadGroupFile();
                break;
            case R.id.btn_group_file:
                scanGroupFile();
                break;
            case R.id.btn_download_group_file:
                downloadGroupFile();
                break;
            case R.id.btn_make_crash:
                makeCrash();
                break;
            case R.id.btn_custom_msg:
                sendCustomMsg();
                break;
            case R.id.btn_load_more_msg:
                loadMoreMsg();
                break;
            case R.id.btn_chatroom_createtime:
                chatroomCreateTime();
                break;
            case R.id.btn_chatroom_in_whitelist:
                chatroomInWhitelist();
                break;
            case R.id.btn_chatroom_mute_expire_time:
                chatroomMuteExpireTime();
                break;
            case R.id.btn_send_message:
                sendMessage();
                break;
            case R.id.btn_modify_message:
                modifyMessage();
                break;
            case R.id.btn_load_message_with_keyword:
                loadMsgWithKeyword();
                break;
            case R.id.btn_load_message_by_ids:
                loadMsgByIds();
                break;
            case R.id.btn_get_rtc_token:
                getRTCToken();
                break;
            case R.id.btn_map_uid:
                mapUid();
                break;
            case R.id.btn_open_file:
                openFile();
                break;
//            case R.id.btn_download_image_original:
//                downloadImageOriginalAttachment();
//                break;
//            case R.id.btn_download_image_big:
//                downloadImageBigAttachment();
//                break;
//            case R.id.btn_download_image_thumbnail:
//                downloadImageThumbnailAttachment();
//                break;
//            case R.id.btn_download_video_file:
//                downloadVideoFileAttachment();
//                break;
//            case R.id.btn_download_video_thumbnail:
//                downloadVideoThumbnailAttachment();
//                break;
            case R.id.btn_download_parse_combine_message:
                downloadAndParseCombineMessage();
                break;
            case R.id.btn_get_group_from_server:
                getGroupFromServer();
                break;
            case R.id.btn_get_joined_groups:
                getJoinedGroupsFromServer();
                break;
            case R.id.btn_fetch_group_members_info:
                fetchGroupMembersInfo();
                break;
            case R.id.btn_get_contact_user_info:
                getLocalContactUserInfo();
                break;
//            case R.id.btn_get_user_profiles:
//                getUserProfiles();
//                break;
//            case R.id.btn_get_sender_info:
//                getSenderInfo();
//                break;
//            case R.id.btn_update_self_namecard:
//                updateSelfNamecard();
//                break;
//            case R.id.btn_get_cached_namecard:
//                getCachedNamecard();
//                break;
//            case R.id.btn_test_get_user_profiles:
//                testGetUserProfiles();
//                break;
        }
    }

    private void openFile() {


    }

//    private void downloadImageOriginalAttachment() {
//        downloadLatestImageAttachment(EMChatManager.AttachmentDownloadType.ORIGINAL, "image_original");
//    }
//
//    private void downloadImageBigAttachment() {
//        downloadLatestImageAttachment(EMChatManager.AttachmentDownloadType.BIG, "image_big");
//    }
//
//    private void downloadImageThumbnailAttachment() {
//        downloadLatestImageAttachment(EMChatManager.AttachmentDownloadType.THUMBNAIL, "image_thumbnail");
//    }
//
//    private void downloadVideoFileAttachment() {
//        downloadLatestVideoAttachment(EMChatManager.AttachmentDownloadType.ORIGINAL, "video_file");
//    }
//
//    private void downloadVideoThumbnailAttachment() {
//        downloadLatestVideoAttachment(EMChatManager.AttachmentDownloadType.THUMBNAIL, "video_thumbnail");
//    }

    private void downloadAndParseCombineMessage() {
        final EMMessage message = findLatestAttachmentMessage(EMMessage.Type.COMBINE);
        if (message == null) {
            EMLog.e(TAG, "downloadAndParseCombineMessage no combine message found, conversation:" + to);
            return;
        }
        if (message.getBody() instanceof EMCombineMessageBody) {
            logCombineMessageState("before", message, (EMCombineMessageBody) message.getBody());
        } else {
            EMLog.e(TAG, "downloadAndParseCombineMessage body is not combine, msgId:" + message.getMsgId()
                    + " body:" + message.getBody());
        }
        EMClient.getInstance().chatManager().downloadAndParseCombineMessage(message, new EMValueCallBack<List<EMMessage>>() {
            @Override
            public void onSuccess(List<EMMessage> value) {
                EMMessage refreshedMessage = getLatestMessage(message);
                if (refreshedMessage.getBody() instanceof EMCombineMessageBody) {
                    logCombineMessageState("after_success", refreshedMessage, (EMCombineMessageBody) refreshedMessage.getBody());
                }
                if (value == null || value.isEmpty()) {
                    EMLog.i(TAG, "downloadAndParseCombineMessage onSuccess no inner messages, msgId:" + message.getMsgId());
                    return;
                }
                for (int index = 0; index < value.size(); index++) {
                    logAttachmentMessageState("combine_parsed", "inner_" + index, value.get(index));
                }

            }

            @Override
            public void onError(int error, String errorMsg) {
                EMMessage refreshedMessage = getLatestMessage(message);
                if (refreshedMessage.getBody() instanceof EMCombineMessageBody) {
                    logCombineMessageState("after_error", refreshedMessage, (EMCombineMessageBody) refreshedMessage.getBody());
                }
                EMLog.e(TAG, "downloadAndParseCombineMessage onError msgId:" + message.getMsgId()
                        + " error:" + error
                        + " errorMsg:" + errorMsg);
            }
        });
    }

//    private void downloadLatestImageAttachment(final EMChatManager.AttachmentDownloadType type, final String actionTag) {
//        final EMMessage message = findLatestAttachmentMessage(EMMessage.Type.IMAGE);
//        if (message == null) {
//            EMLog.e(TAG, "downloadLatestImageAttachment no image message found, action:" + actionTag + " conversation:" + to);
//            return;
//        }
//        if (!(message.getBody() instanceof EMImageMessageBody)) {
//            EMLog.e(TAG, "downloadLatestImageAttachment message body is not image, msgId:" + message.getMsgId());
//            return;
//        }
//        logImageAttachmentState(actionTag, "before", message, (EMImageMessageBody) message.getBody());
//        DemoUtils.download(message, type, new EMCallBack() {
//            @Override
//            public void onProgress(int progress, String status) {
//                EMLog.i(TAG, "downloadLatestImageAttachment onProgress action:" + actionTag
//                        + " msgId:" + message.getMsgId()
//                        + " type:" + type
//                        + " progress:" + progress
//                        + " status:" + status);
//            }
//
//            @Override
//            public void onSuccess() {
//                EMMessage refreshedMessage = getLatestMessage(message);
//                if (refreshedMessage.getBody() instanceof EMImageMessageBody) {
//                    logImageAttachmentState(actionTag, "after_success", refreshedMessage, (EMImageMessageBody) refreshedMessage.getBody());
//                } else {
//                    EMLog.e(TAG, "downloadLatestImageAttachment onSuccess refreshed body invalid, msgId:" + message.getMsgId());
//                }
//            }
//
//            @Override
//            public void onError(int code, String error) {
//                EMMessage refreshedMessage = getLatestMessage(message);
//                if (refreshedMessage.getBody() instanceof EMImageMessageBody) {
//                    logImageAttachmentState(actionTag, "after_error", refreshedMessage, (EMImageMessageBody) refreshedMessage.getBody());
//                }
//                EMLog.e(TAG, "downloadLatestImageAttachment onError action:" + actionTag
//                        + " msgId:" + message.getMsgId()
//                        + " type:" + type
//                        + " code:" + code
//                        + " error:" + error);
//            }
//        });
//    }
//
//    private void downloadLatestVideoAttachment(final EMChatManager.AttachmentDownloadType type, final String actionTag) {
//        final EMMessage message = findLatestAttachmentMessage(EMMessage.Type.VIDEO);
//        if (message == null) {
//            EMLog.e(TAG, "downloadLatestVideoAttachment no video message found, action:" + actionTag + " conversation:" + to);
//            return;
//        }
//        if (!(message.getBody() instanceof EMVideoMessageBody)) {
//            EMLog.e(TAG, "downloadLatestVideoAttachment message body is not video, msgId:" + message.getMsgId());
//            return;
//        }
//        logVideoAttachmentState(actionTag, "before", message, (EMVideoMessageBody) message.getBody());
//        DemoUtils.download(message, type, new EMCallBack() {
//            @Override
//            public void onProgress(int progress, String status) {
//                EMLog.i(TAG, "downloadLatestVideoAttachment onProgress action:" + actionTag
//                        + " msgId:" + message.getMsgId()
//                        + " type:" + type
//                        + " progress:" + progress
//                        + " status:" + status);
//            }
//
//            @Override
//            public void onSuccess() {
//                EMMessage refreshedMessage = getLatestMessage(message);
//                if (refreshedMessage.getBody() instanceof EMVideoMessageBody) {
//                    logVideoAttachmentState(actionTag, "after_success", refreshedMessage, (EMVideoMessageBody) refreshedMessage.getBody());
//                } else {
//                    EMLog.e(TAG, "downloadLatestVideoAttachment onSuccess refreshed body invalid, msgId:" + message.getMsgId());
//                }
//            }
//
//            @Override
//            public void onError(int code, String error) {
//                EMMessage refreshedMessage = getLatestMessage(message);
//                if (refreshedMessage.getBody() instanceof EMVideoMessageBody) {
//                    logVideoAttachmentState(actionTag, "after_error", refreshedMessage, (EMVideoMessageBody) refreshedMessage.getBody());
//                }
//                EMLog.e(TAG, "downloadLatestVideoAttachment onError action:" + actionTag
//                        + " msgId:" + message.getMsgId()
//                        + " type:" + type
//                        + " code:" + code
//                        + " error:" + error);
//            }
//        });
//    }

    private EMMessage findLatestAttachmentMessage(EMMessage.Type messageType) {
        EMConversation conversation = EMClient.getInstance().chatManager().getConversation(to);
        if (conversation == null) {
            EMLog.e(TAG, "findLatestAttachmentMessage conversation is null, conversation:" + to + " type:" + messageType);
            return null;
        }
        List<EMMessage> messages = conversation.loadMoreMsgFromDB("", ATTACHMENT_SCAN_COUNT);

        if (messages == null || messages.isEmpty()) {
            EMLog.e(TAG, "findLatestAttachmentMessage no messages loaded, conversation:" + to + " type:" + messageType);
            return null;
        }
        //反转messages，保证从最新的消息开始查找
        Collections.reverse(messages);

        for (EMMessage candidate : messages) {
            if (candidate != null && candidate.getType() == messageType) {
                EMLog.i(TAG, "findLatestAttachmentMessage found msgId:" + candidate.getMsgId()
                        + " msgTime:" + candidate.getMsgTime()
                        + " type:" + candidate.getType());
                return candidate;
            }
        }
        EMLog.e(TAG, "findLatestAttachmentMessage target type not found, conversation:" + to
                + " type:" + messageType
                + " scannedCount:" + messages.size());
        return null;
    }

    private EMMessage getLatestMessage(EMMessage fallbackMessage) {
        if (fallbackMessage == null || TextUtils.isEmpty(fallbackMessage.getMsgId())) {
            return fallbackMessage;
        }
        EMMessage latestMessage = EMClient.getInstance().chatManager().getMessage(fallbackMessage.getMsgId());
        return latestMessage != null ? latestMessage : fallbackMessage;
    }

//    private void logImageAttachmentState(String actionTag, String stage, EMMessage message, EMImageMessageBody body) {
//        EMLog.i(TAG, "imageAttachmentState action:" + actionTag
//                + " stage:" + stage
//                + " msgId:" + message.getMsgId()
//                + " msgTime:" + message.getMsgTime()
//                + " from:" + message.getFrom()
//                + " to:" + message.getTo()
//                + " direction:" + message.direct()
//                + " chatType:" + message.getChatType()
//                + "\n original:" + buildAttachmentPathLog(body.getLocalUrl(), body.getLocalUri(), body.getRemoteUrl())
//                + "\n big:" + buildAttachmentPathLog(body.getBigImageLocalUrl(), body.getBigImageLocalUri(), body.getBigImageRemoteUrl())
//                + "\n thumbnail:" + buildAttachmentPathLog(body.thumbnailLocalPath(), body.thumbnailLocalUri(), body.getThumbnailUrl())
//                + "\n file:{name=" + body.getFileName()
//                + ", displayName=" + body.displayName()
//                + ", size=" + body.getFileSize()
//                + ", secret=" + body.getSecret()
//                + ", width=" + body.getWidth()
//                + ", height=" + body.getHeight()
//                + ", gif=" + body.isGif()
//                + "}"
//                + "\n status:{original=" + body.downloadStatus()
//                + ", big=" + body.getBigImageDownloadStatus()
//                + ", thumbnail=" + body.thumbnailDownloadStatus()
//                + ", isOriginalImage=" + body.isOriginalImage()
//                + ", sendOriginalImage=" + body.isSendOriginalImage()
//                + "}");
//    }

    private void logVideoAttachmentState(String actionTag, String stage, EMMessage message, EMVideoMessageBody body) {
        EMLog.i(TAG, "videoAttachmentState action:" + actionTag
                + " stage:" + stage
                + " msgId:" + message.getMsgId()
                + " msgTime:" + message.getMsgTime()
                + " from:" + message.getFrom()
                + " to:" + message.getTo()
                + " direction:" + message.direct()
                + " chatType:" + message.getChatType()
                + "\n file:" + buildAttachmentPathLog(body.getLocalUrl(), body.getLocalUri(), body.getRemoteUrl())
                + "\n thumbnail:" + buildAttachmentPathLog(body.getLocalThumb(), body.getLocalThumbUri(), body.getThumbnailUrl())
                + "\n file:{name=" + body.getFileName()
                + ", displayName=" + body.displayName()
                + ", length=" + body.getVideoFileLength()
                + ", secret=" + body.getSecret()
                + ", thumbnailSecret=" + body.getThumbnailSecret()
                + ", thumbnailWidth=" + body.getThumbnailWidth()
                + ", thumbnailHeight=" + body.getThumbnailHeight()
                + "}"
                + "\n status:{file=" + body.downloadStatus()
                + ", thumbnail=" + body.thumbnailDownloadStatus()
                + ", duration=" + body.getDuration()
                + "}");
    }

    private void logAttachmentMessageState(String actionTag, String stage, EMMessage message) {
        if (message == null) {
            EMLog.i(TAG, "attachmentMessageState action:" + actionTag + " stage:" + stage + " message:null");
            return;
        }
        EMMessageBody body = message.getBody();
        if (body instanceof EMImageMessageBody) {
//            logImageAttachmentState(actionTag, stage, message, (EMImageMessageBody) body);
        } else if (body instanceof EMVideoMessageBody) {
            logVideoAttachmentState(actionTag, stage, message, (EMVideoMessageBody) body);
        } else {
            EMLog.i(TAG, "attachmentMessageState action:" + actionTag
                    + " stage:" + stage
                    + " msgId:" + message.getMsgId()
                    + " type:" + message.getType()
                    + " body:" + body);
        }
    }

    private void logCombineMessageState(String stage, EMMessage message, EMCombineMessageBody body) {
        EMLog.i(TAG, "combineMessageState"
                + " stage:" + stage
                + " msgId:" + message.getMsgId()
                + " msgTime:" + message.getMsgTime()
                + "\n title:" + body.getTitle()
                + "\n summary:" + body.getSummary()
                + "\n compatibleText:" + body.getCompatibleText()
                + "\n attachment:" + buildAttachmentPathLog(body.getLocalUrl(), null, body.getRemoteUrl()));
    }

    private String buildAttachmentPathLog(String localUrl, Object localUri, String remoteUrl) {
        return "{exists=" + isLocalFileExist(localUrl)
                + ", localUrl=" + localUrl
                + ", localUri=" + localUri
                + ", localPath=" + getLocalFilePath(localUrl)
                + ", remoteUrl=" + remoteUrl
                + "}";
    }

    private boolean isLocalFileExist(String localUrl) {
        if (TextUtils.isEmpty(localUrl)) {
            return false;
        }
        try {
            return EMFileHelper.getInstance().isFileExist(localUrl);
        } catch (Exception exception) {
            EMLog.e(TAG, "isLocalFileExist exception:" + exception.getMessage() + " localUrl:" + localUrl);
            return false;
        }
    }

    private String getLocalFilePath(String localUrl) {
        if (TextUtils.isEmpty(localUrl)) {
            return "";
        }
        try {
            return EMFileHelper.getInstance().getFilePath(localUrl);
        } catch (Exception exception) {
            EMLog.e(TAG, "getLocalFilePath exception:" + exception.getMessage() + " localUrl:" + localUrl);
            return localUrl;
        }
    }

    // 通过反射获取文件描述符的实际整数值
    private static int getFdValue(FileDescriptor fd) {
        try {
            Field field = FileDescriptor.class.getDeclaredField("fd");
            field.setAccessible(true);
            return field.getInt(fd);
        } catch (Exception e) {
            return -1;
        }
    }

    private void mapUid() {

    }

    private void getRTCToken() {

        EMClient.getInstance().asyncGetRTCTokenInfoWithChannelName("test_channel_name", new EMValueCallBack<EMRTCTokenInfo>() {
            @Override
            public void onSuccess(EMRTCTokenInfo value) {
                EMLog.d(TAG, "getRTCToken onSuccess value:" + value);
            }

            @Override
            public void onError(int error, String errorMsg) {
                EMLog.e(TAG, "getRTCToken onError error:" + error + " errorMsg:" + errorMsg);
            }
        });

    }

    private void loadMsgByIds() {
        for (Map.Entry<String, List<String>> entry : loadResult.entrySet()) {

            EMClient.getInstance().chatManager().asyncLoadMessages(new ArrayList<>(), "", new EMValueCallBack<List<EMMessage>>() {
                @Override
                public void onSuccess(List<EMMessage> value) {
                    EMLog.e(TAG, "asyncLoadMessages onSuccess value:" + value);
                }

                @Override
                public void onError(int error, String errorMsg) {
                    EMLog.e(TAG, "asyncLoadMessages onError error:" + error + " errorMsg:" + errorMsg);
                }
            });
        }
    }
    private Map<String, List<String>> loadResult;
    private void loadMsgWithKeyword() {
        String keyword="时间";
        EMClient.getInstance().chatManager().asyncLoadConversationMessagesWithKeyword(keyword, -1, null, EMConversation.EMSearchDirection.UP, EMConversation.EMMessageSearchScope.CONTENT, new EMValueCallBack<Map<String, List<String>>>() {
            @Override
            public void onSuccess(Map<String, List<String>> value) {
                EMActivity.this.loadResult = value;
                EMLog.e(TAG, "asyncLoadConversationMessagesWithKeyword onSuccess value:" + value);
            }

            @Override
            public void onError(int error, String errorMsg) {
                EMLog.e(TAG,"asyncLoadConversationMessagesWithKeyword onError error:" + error + " errorMsg:" + errorMsg);
            }
        });
    }

    private void noDisturbStartTime() {
        EMSilentModeParam emSilentModeParam = new EMSilentModeParam(EMSilentModeParam.EMSilentModeParamType.REMIND_TYPE);
        EMClient.getInstance().pushManager().setSilentModeForConversation(conversationId, EMConversation.EMConversationType.Chat, emSilentModeParam, new EMValueCallBack<EMSilentModeResult>() {
            @Override
            public void onSuccess(EMSilentModeResult result) {
                EMLog.i(TAG, "noDisturbStartTime onSuccess value:" + result);
                EMSilentModeTime silentModeStartTime = result.getSilentModeStartTime();
                EMLog.i(TAG, "noDisturbStartTime silentModeStartTime:" + silentModeStartTime.getHour() + ":" + silentModeStartTime.getMinute());
            }

            @Override
            public void onError(int error, String errorMsg) {
                EMLog.i(TAG, "noDisturbStartTime onError error:" + error + " errorMsg:" + errorMsg);
                EMSilentModeResult result = new EMSilentModeResult(new EMASilentModeItem());
                EMSilentModeTime silentModeStartTime = result.getSilentModeStartTime();
                EMLog.i(TAG, "noDisturbStartTime silentModeStartTime:" + silentModeStartTime.getHour() + ":" + silentModeStartTime.getMinute());
            }
        });
    }

    private void sendMessage() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("jsonKey1", "jsonValue1");
        }catch (Exception exception){
            EMLog.e(TAG, "sendMessage json exception:" + exception.getMessage());
        }

        EMMessage message = EMMessage.createTextSendMessage("hello", to);
        message.setAttribute("key1", "value1");
        message.setAttribute("key2", true);
        message.setAttribute("key3", 123);
        message.setAttribute("key4",jsonObject);
        message.setMessageStatusCallback(new EMCallBack() {
            @Override
            public void onSuccess() {
                EMLog.e(TAG, "sendMessage onSuccess");
                EMActivity.this.messageId=message.getMsgId();
                Map<String, Object> newExt = message.ext();
                for (Map.Entry<String, Object> entry : newExt.entrySet()) {
                    EMLog.e(TAG, "sendMessage onSuccess key:" + entry.getKey() + " value:" + entry.getValue());
                }

                EMTextMessageBody messageBody = (EMTextMessageBody) (message.getBody());
                String message = messageBody.getMessage();
                EMLog.e(TAG, "modifyMessage onSuccess message:" + message);
            }

            @Override
            public void onError(int code, String error) {
                EMLog.e(TAG, "sendMessage onError code:" + code + " error:" + error);
            }
        });
        EMClient.getInstance().chatManager().sendMessage(message);
        new  Handler(getMainLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 100; i++) {
                    Map<String, Object> ext = message.ext();
//                    EMLog.d(TAG, "for 循环取值 sendMessage ext:" + ext);
                }
            }
        },2000);
    }

    private void modifyMessage(){
        EMTextMessageBody body = new EMTextMessageBody("你好");
        Map<String, Object> newExt = new HashMap<>();
        newExt.put("new key1", "new value1");
        newExt.put("new key2", 1);
        newExt.put("new key3", true);

        EMClient.getInstance().chatManager().asyncModifyMessage(messageId, body,newExt, new EMValueCallBack<EMMessage>() {
            @Override
            public void onSuccess(EMMessage value) {
                EMLog.e(TAG, "modifyMessage onSuccess");
                Map<String, Object> newExt = value.ext();
                for (Map.Entry<String, Object> entry : newExt.entrySet()) {
                    EMLog.e(TAG, "modifyMessage onSuccess key:" + entry.getKey() + " value:" + entry.getValue());
                }
                EMTextMessageBody messageBody = (EMTextMessageBody) (value.getBody());
                String message = messageBody.getMessage();
                EMLog.e(TAG, "modifyMessage onSuccess message:" + message);
            }

            @Override
            public void onError(int error, String errorMsg) {
                EMLog.e(TAG, "modifyMessage onError error:" + error + " errorMsg:" + errorMsg);
            }
        });

    }

    private void leaveChatRoom() {
        EMClient.getInstance().chatroomManager().leaveChatRoom(chatRoomID, new EMCallBack() {
            @Override
            public void onSuccess() {
                EMLog.i(TAG, "leaveChatRoom onSuccess");
            }

            @Override
            public void onError(int code, String error) {
                EMLog.i(TAG, "leaveChatRoom onError code:" + code + " error:" + error);
            }
        });
    }

    private void chatroomMuteExpireTime() {
        EMChatRoom chatRoom = EMClient.getInstance().chatroomManager().getChatRoom(chatRoomID);
        if (chatRoom != null) {
            long muteExpireTimestamp = chatRoom.getMuteExpireTimestamp();
            EMLog.e(TAG, "chatroomMuteExpireTime muteExpireTimestamp:" + muteExpireTimestamp);
        }else{
            EMLog.e(TAG, "chatroomMuteExpireTime chatRoom is null");
        }
    }

    private void chatroomCreateTime() {
        EMChatRoom chatRoom = EMClient.getInstance().chatroomManager().getChatRoom(chatRoomID);
        if (chatRoom != null) {
            long createTimeStamp = chatRoom.getCreateTimestamp();
            EMLog.e(TAG, "chatroomCreateTime createTimeStamp:" + createTimeStamp);
        }else{
            EMLog.e(TAG, "chatroomCreateTime chatRoom is null");
        }
    }

    private void chatroomInWhitelist() {
        EMChatRoom chatRoom = EMClient.getInstance().chatroomManager().getChatRoom(chatRoomID);
        if (chatRoom != null) {
            boolean inWhitelist = chatRoom.isInWhitelist();
            EMLog.e(TAG, "chatroomInWhitelist inWhitelist:" + inWhitelist);
        }else{
            EMLog.e(TAG, "chatroomInWhitelist chatRoom is null");
        }
    }

    private void loadMoreMsg() {

    }

    private void sendCustomMsg() {
        EMMessage message = EMMessage.createSendMessage(EMMessage.Type.CUSTOM);
        EMCustomMessageBody body = new EMCustomMessageBody("temp");
        message.addBody(body);
        message.setTo("pu");
        message.setAttribute("isFaceShow", false);
        message.setAttribute("progress", 80);
        message.setAttribute("result", "success");
        message.setAttribute("had_received_video_msg_id", "123456");
        message.setAttribute("result", System.currentTimeMillis());

        message.setChatType(EMMessage.ChatType.Chat);
        EMClient.getInstance().chatManager().sendMessage(message);
        EMLog.e("xcp", "sendCmd event:"+body.event());
    }

    private void downloadGroupFile() {
        EMClient.getInstance().groupManager().asyncDownloadGroupSharedFile(groupId, fileId, getFilesDir().getAbsolutePath()+"/download/我是下载后的文件", new EMCallBack() {
            @Override
            public void onSuccess() {
                EMLog.i(TAG, "downloadGroupFile onSuccess");
            }

            @Override
            public void onError(int code, String error) {
                EMLog.i(TAG, "downloadGroupFile onError code:" + code + " error:" + error);
            }
        });
    }

    private void scanGroupFile() {
        EMClient.getInstance().groupManager().asyncFetchGroupSharedFileList(groupId, 1, 10, new EMValueCallBack<List<EMMucSharedFile>>() {
            @Override
            public void onSuccess(List<EMMucSharedFile> value) {
                for (EMMucSharedFile emMucSharedFile : value) {
                    EMLog.i(TAG, "scanGroupFile onSuccess emMucSharedFile:name=" + emMucSharedFile.getFileName()+" ,fileupdateTime= "+emMucSharedFile.getFileUpdateTime()+" ,fileSize= "+emMucSharedFile.getFileSize()+" ,fileId= "+emMucSharedFile.getFileId());
                    fileId=emMucSharedFile.getFileId();
                }
            }

            @Override
            public void onError(int error, String errorMsg) {
                EMLog.i(TAG, "scanGroupFile onError error:" + error + " errorMsg:" + errorMsg);
            }
        });
    }

    private void makeCrash() {
        EMMessage textSendMessage = EMMessage.createTextSendMessage("hello",to);
        EMClient.getInstance().chatManager().sendMessage(textSendMessage);
    }

    private void uploadGroupFile() {
        EMGroup group = EMClient.getInstance().groupManager().getGroup(groupId);
        if (group == null) {
            EMLog.i(TAG, "uploadGroupFile group is null");
        }
        String filePath = getFilesDir().getAbsolutePath() + "/中文名文件2";
        boolean fileExist = EMFileHelper.getInstance().isFileExist(filePath);
        EMLog.e(TAG, "uploadGroupFile fileExist:" + fileExist);
        try {
            new Thread() {
                @Override
                public void run() {
                    super.run();
                    try {
                        EMClient.getInstance().groupManager().uploadGroupSharedFile(groupId, filePath, new EMCallBack() {
                            @Override
                            public void onSuccess() {
                                EMLog.i(TAG, "uploadGroupFile onSuccess");
                            }

                            @Override
                            public void onError(int code, String error) {
                                EMLog.i(TAG, "uploadGroupFile onError code:" + code + " error:" + error);
                            }
                        });
                    } catch (HyphenateException e) {

                        EMLog.i(TAG, "uploadGroupFile HyphenateException: errorMsg:" + e.getMessage());
                    }
                }
            }.start();
        } catch (Exception e) {
            EMLog.i(TAG, "uploadGroupFile HyphenateException: errorMsg:" + e.getMessage());
        }

    }

    private void queryMsgsCount() {
//        EMClient.getInstance().chatManager().asyncGetMessageCount(new EMValueCallBack<Integer>() {
//            @Override
//            public void onSuccess(Integer value) {
//                EMLog.e(TAG,"queryMsgsCount ="+ value);
//            }
//
//            @Override
//            public void onError(int error, String errorMsg) {
//                EMLog.i(TAG, "queryMsgsCount  error:" + error + " errorMsg:" + errorMsg);
//            }
//        });
    }

    private void toSecondActivity() {
        Intent intent = new Intent(this, SecondActivity.class);
        startActivity(intent);

//        int pageNum=1;
//        int pageSize=50;
//        EMClient.getInstance().chatroomManager().asyncFetchPublicChatRoomsFromServer(pageNum, pageSize, new EMValueCallBack<EMPageResult<EMChatRoom>>() {
//            @Override
//            public void onSuccess(EMPageResult<EMChatRoom> value) {
//
//            }
//
//            @Override
//            public void onError(int error, String errorMsg) {
//
//            }
//        });
//
//        EMClient.getInstance().chatroomManager().asyncFetchChatRoomFromServer(chatRoomID, new EMValueCallBack<EMChatRoom>() {
//            @Override
//            public void onSuccess(EMChatRoom value) {
//
//            }
//
//            @Override
//            public void onError(int error, String errorMsg) {
//
//            }
//        });
//        EMChatRoom chatRoom = EMClient.getInstance().chatroomManager().getChatRoom(chatRoomID);
    }

    private void filterConversations() {
        EMClient.getInstance().chatManager().asyncFilterConversationsFromDB(new EMCustomConversationFilter() {
            @Override
            public boolean filter(EMConversation emConversation) {
                EMLog.e(TAG, "begin-------filterConversations filter emConversation:" + emConversation);
                int allMsgCount = emConversation.getAllMsgCount();
                String id = emConversation.conversationId();
                EMConversation.EMConversationType type = emConversation.getType();
                int unreadMsgCount = emConversation.getUnreadMsgCount();
                EMLog.e(TAG, "end---------filterConversations filter allMsgCount:" + allMsgCount + " id:" + id + " type:" + type.ordinal() + " unreadMsgCount:" + unreadMsgCount);
                return true;
            }
        }, true, new EMValueCallBack<List<EMConversation>>() {
            @Override
            public void onSuccess(List<EMConversation> value) {
                EMLog.i(TAG, "filterConversations onSuccess value:" + value);
            }

            @Override
            public void onError(int error, String errorMsg) {
                EMLog.i(TAG, "filterConversations onError error:" + error + " errorMsg:" + errorMsg);
            }
        });
    }

    private void setMsgParams() {
        EMMessage message = EMMessage.createSendMessage(EMMessage.Type.CUSTOM);
        EMCustomMessageBody body = new EMCustomMessageBody("userCard");
        StringBuilder temp = new StringBuilder();
        for (int i = 0; i < 100; i++) {
            temp.append("aaaaaaaaaaaa");
        }
        for (int j = 0; j < 10; j++) {
            new Thread() {
                @Override
                public void run() {
                    for (int m = 0; m < 100; m++) {
                        Map<String, String> params = new HashMap<>();
                        for (int i = 0; i < 3000; i++) {
                            params.put("key" + i, "value" + i + temp.toString());
                        }
                        body.setParams(params);
                        EMLog.e(TAG, "setParams threadId=" + Thread.currentThread().getId());
                    }
                }
            }.start();
            new Thread() {
                @Override
                public void run() {
                    for (int i = 0; i < 400; i++) {
                        body.getParams();
                        EMLog.e(TAG, "getParams threadId=" + Thread.currentThread().getId());
                    }
                }
            }.start();
        }
        message.setBody(body);
        message.setTo("pu");
        message.setMessageStatusCallback(new EMCallBack() {
            @Override
            public void onSuccess() {
                EMLog.e(TAG, "send message onSuccess");
            }

            @Override
            public void onError(int code, String error) {
                EMLog.e(TAG, "send message onError: " + code + " - " + error);
            }
        });
//        EMClient.getInstance().chatManager().sendMessage(message);
    }

    private void getUnreadMessageCount() {
        EMConversation conversation = EMClient.getInstance().chatManager().getConversation(username);
        if (conversation != null) {
            int unreadMsgCount = conversation.getUnreadMsgCount();
            EMLog.i(TAG, "getUnreadMessageCount unreadMsgCount:" + unreadMsgCount);
            List<EMMessage> allMessages = conversation.loadMoreMsgFromDB("", 100);
            for (int i = 0; i < allMessages.size(); i++) {
                EMMessage emMessage = allMessages.get(i);
                EMLog.i(TAG, "getUnreadMessageCount emMessage:" + emMessage + "},isRead:" + emMessage.isRead());
            }
        }
    }

    private void joinChatRoom() {
        String ext = "your ext info";
        boolean leaveOtherRooms = true;
        EMClient.getInstance().chatroomManager().joinChatRoom(chatRoomID, leaveOtherRooms, ext, new EMValueCallBack<EMChatRoom>() {
            @Override
            public void onSuccess(EMChatRoom value) {
                EMLog.i(TAG, "joinChatRoom onSuccess value:" + value);
            }

            @Override
            public void onError(int error, String errorMsg) {
                EMLog.i(TAG, "joinChatRoom onError error:" + error + " errorMsg:" + errorMsg);
            }
        });
    }

    private void queryMsgCountWithDuration() {
        String conversationId = "pu";
        EMConversation conversation = EMClient.getInstance().chatManager().getConversation(conversationId);
        if (conversation != null) {
            long startTimestamp = System.currentTimeMillis() - 24 * 60 * 60 * 1000;
            int count = conversation.getAllMsgCount(startTimestamp, System.currentTimeMillis());
            EMLog.i(TAG, "queryMsgCountWithDuration count:" + count);
        }
    }

    private void queryServerContacts() {
    }

    private void verifyContactsRemarkRetry() {

    }

    private void queryContacts() {
//        EMClient.getInstance().contactManager().asyncFetchAllContactsFromLocal(new EMValueCallBack<List<EMContact>>() {
//            @Override
//            public void onSuccess(List<EMContact> value) {
//                EMLog.i(TAG, "queryContacts onSuccess value:" + value);
//            }
//
//            @Override
//            public void onError(int error, String errorMsg) {
//                EMLog.i(TAG, "queryContacts onError error:" + error + " errorMsg:" + errorMsg);
//            }
//        });
        try {
            List<String> contactsFromLocal = EMClient.getInstance().contactManager().getContactsFromLocal();
            EMLog.i(TAG, "queryContacts contactsFromLocal:" + contactsFromLocal);
        } catch (HyphenateException e) {
            throw new RuntimeException(e);
        }
    }

    private void refuseInvitation() {
        EMClient.getInstance().contactManager().asyncDeclineInvitation(username, new EMCallBack() {
            @Override
            public void onSuccess() {
                EMLog.i(TAG, "refuseInvitation onSuccess");
            }

            @Override
            public void onError(int code, String error) {
                EMLog.i(TAG, "refuseInvitation onError code:" + code + " error:" + error);
            }
        });
    }

    private void acceptInvitation() {
        EMClient.getInstance().contactManager().asyncAcceptInvitation(username, new EMCallBack() {
            @Override
            public void onSuccess() {
                EMLog.i(TAG, "acceptInvitation onSuccess");
            }

            @Override
            public void onError(int code, String error) {
                EMLog.i(TAG, "acceptInvitation onError code:" + code + " error:" + error);
            }
        });
    }

    private void removeContact() {
        EMClient.getInstance().contactManager().asyncDeleteContact(username, new EMCallBack() {
            @Override
            public void onSuccess() {
                EMLog.i(TAG, "removeContact onSuccess");
            }

            @Override
            public void onError(int code, String error) {
                EMLog.i(TAG, "removeContact onError code:" + code + " error:" + error);
            }
        });
    }

    private void addContact() {
        EMClient.getInstance().contactManager().asyncAddContact(username, "hello", new EMCallBack() {
            @Override
            public void onSuccess() {
                EMLog.i(TAG, "addContact onSuccess");
            }

            @Override
            public void onError(int code, String error) {
                EMLog.i(TAG, "addContact onError code:" + code + " error:" + error);
            }
        });
    }

    private void queryBlacklistLocal() {
        List<String> blackListUsernames = EMClient.getInstance().contactManager().getBlackListUsernames();
        EMLog.i(TAG, "queryBlacklistLocal blackListUsernames:" + blackListUsernames);
    }

    private void removeBlacklist() {
        EMClient.getInstance().contactManager().asyncRemoveUserFromBlackList(username, new EMCallBack() {
            @Override
            public void onSuccess() {
                EMLog.i(TAG, "removeBlacklist onSuccess");
            }

            @Override
            public void onError(int code, String error) {
                EMLog.i(TAG, "removeBlacklist onError code:" + code + " error:" + error);
            }
        });
    }

    private void addBlacklist() {
        EMClient.getInstance().contactManager().asyncAddUserToBlackList(username, false, new EMCallBack() {
            @Override
            public void onSuccess() {
                EMLog.i(TAG, "addBlacklist onSuccess");
                queryBlacklistLocal();
            }

            @Override
            public void onError(int code, String error) {
                EMLog.i(TAG, "addBlacklist onError code:" + code + " error:" + error);
            }
        });
    }


    private void conversationRemindType() {
        Map<String, EMConversation> allConversations = EMClient.getInstance().chatManager().getAllConversations();
        EMLog.e(TAG, "conversationRemindType allConversations:" + allConversations.size());

        String conversationId = "pu";
        EMSilentModeParam emSilentModeParam = new EMSilentModeParam(EMSilentModeParam.EMSilentModeParamType.REMIND_TYPE);
        //设置免打扰类型
        emSilentModeParam.setRemindType(EMPushManager.EMPushRemindType.NONE);
        EMClient.getInstance().pushManager().setSilentModeForConversation(conversationId, EMConversation.EMConversationType.Chat, emSilentModeParam, new EMValueCallBack<EMSilentModeResult>() {
            @Override
            public void onSuccess(EMSilentModeResult value) {
                EMLog.i(TAG, "conversationRemindType onSuccess value:" + value);
            }

            @Override
            public void onError(int error, String errorMsg) {
                EMLog.i(TAG, "conversationRemindType onError error:" + error + " errorMsg:" + errorMsg);
            }
        });

        EMConversation conversation = EMClient.getInstance().chatManager().getConversation(conversationId);
        if (conversation != null) {
            EMPushManager.EMPushRemindType emPushRemindType = conversation.pushRemindType();
            EMLog.i(TAG, "conversationRemindType emPushRemindType:" + emPushRemindType);
        }

    }

    private void syncNoDisturb() {
        EMClient.getInstance().pushManager().syncSilentModeConversationsFromServer(new EMCallBack() {
            @Override
            public void onSuccess() {
                EMLog.i(TAG, "syncNoDisturb onSuccess");
            }

            @Override
            public void onError(int code, String error) {
                EMLog.i(TAG, "syncNoDisturb onError code:" + code + " error:" + error);
            }
        });


    }

    private void getGroupFromServer() {
        EMClient.getInstance().groupManager().asyncGetGroupFromServer(groupId, new EMValueCallBack<EMGroup>() {
            @Override
            public void onSuccess(EMGroup value) {
                EMLog.i(TAG, "getGroupFromServer onSuccess groupId:" + value.getGroupId() + " groupName:" + value.getGroupName() + " memberCount:" + value.getMemberCount());
            }

            @Override
            public void onError(int error, String errorMsg) {
                EMLog.e(TAG, "getGroupFromServer onError error:" + error + " errorMsg:" + errorMsg);
            }
        });
    }

    private void getJoinedGroupsFromServer() {

    }

    private void fetchGroupMembersInfo() {
        String cursor = "";
        int pageSize = 20;
        EMClient.getInstance().groupManager().asyncFetchGroupMembersInfo(groupId, cursor, pageSize, new EMValueCallBack<EMCursorResult<EMGroupMemberInfo>>() {
            @Override
            public void onSuccess(EMCursorResult<EMGroupMemberInfo> value) {
                EMLog.i(TAG, "fetchGroupMembersInfo onSuccess count:" + value.getData().size() + " cursor:" + value.getCursor());
                for (EMGroupMemberInfo memberInfo : value.getData()) {
                    EMLog.i(TAG, "fetchGroupMembersInfo member:" + memberInfo);
                }
            }

            @Override
            public void onError(int error, String errorMsg) {
                EMLog.e(TAG, "fetchGroupMembersInfo onError error:" + error + " errorMsg:" + errorMsg);
            }
        });
    }

    private void getLocalContactUserInfo() {
        EMLog.i(TAG, "getLocalContactUserInfo start target:" + to);
        EMClient.getInstance().contactManager().asyncFetchAllContactsFromLocal(new EMValueCallBack<List<EMContact>>() {
            @Override
            public void onSuccess(List<EMContact> contacts) {
                EMLog.i(TAG, "getLocalContactUserInfo fetch contacts:" + buildContactsLog(contacts));
                EMContact targetContact = null;
                if (contacts != null) {
                    for (EMContact contact : contacts) {
                        if (contact != null && to.equals(contact.getUsername())) {
                            targetContact = contact;
                            break;
                        }
                    }
                }
                if (targetContact == null) {
                    EMLog.i(TAG, "getLocalContactUserInfo target:" + to + " not found in local contacts");
                    return;
                }
                EMLog.i(TAG, "getLocalContactUserInfo hit contact username:" + targetContact.getUsername()
                        + " remark:" + targetContact.getRemark());
                final EMContact finalTargetContact = targetContact;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
//                        EMUserInfo userInfo = finalTargetContact.getUserInfo();
//                        if (userInfo == null) {
//                            EMLog.i(TAG, "getLocalContactUserInfo target:" + to + " userInfo is null in local cache");
//                            return;
//                        }
//                        EMLog.i(TAG, "getLocalContactUserInfo target:" + to
//                                + " nickname:" + userInfo.getNickname()
//                                + " avatar:" + userInfo.getAvatarUrl()
//                                + " userInfo:" + userInfo);
                    }
                }).start();
            }

            @Override
            public void onError(int error, String errorMsg) {
                EMLog.e(TAG, "getLocalContactUserInfo onError error:" + error + " errorMsg:" + errorMsg);
            }
        });
    }

    private String buildContactsLog(List<EMContact> contacts) {
        if (contacts == null || contacts.isEmpty()) {
            return "[]";
        }
        StringBuilder builder = new StringBuilder("[");
        for (int i = 0; i < contacts.size(); i++) {
            EMContact contact = contacts.get(i);
            if (i > 0) {
                builder.append(", ");
            }
            if (contact == null) {
                builder.append("null");
            } else {
                builder.append(contact.getUsername()).append(":").append(contact.getRemark());
            }
        }
        builder.append("]");
        return builder.toString();
    }

//    private void getUserProfiles() {
//        String[] userIds = new String[]{username, to};
//        EMClient.getInstance().userInfoManager().getUserInfoWithUserIds(userIds, new EMValueCallBack<Map<String, EMUserInfo>>() {
//            @Override
//            public void onSuccess(Map<String, EMUserInfo> value) {
//                EMLog.i(TAG, "getUserProfiles onSuccess count:" + value.size());
//                for (Map.Entry<String, EMUserInfo> entry : value.entrySet()) {
//                    EMUserInfo userInfo = entry.getValue();
//                    EMLog.i(TAG, "getUserProfiles userId:" + entry.getKey() + " nickname:" + userInfo.getNickname() + " avatar:" + userInfo.getAvatarUrl());
//                }
//            }
//
//            @Override
//            public void onError(int error, String errorMsg) {
//                EMLog.e(TAG, "getUserProfiles onError error:" + error + " errorMsg:" + errorMsg);
//            }
//        });
//    }
//
//    private void getSenderInfo() {
//        EMMessage message = EMClient.getInstance().chatManager().getMessage("1516416376690966928");
//        EMSenderInfo senderInfo = message.getSenderInfo();
//        EMLog.i(TAG, "getSenderInfo senderInfo:" + senderInfo);
//    }
//
//    private void updateSelfNamecard() {
//        String nameCard = "测试群名片_" + System.currentTimeMillis();
//        EMClient.getInstance().groupManager().asyncUpdateGroupNamecard(groupId, nameCard, new EMCallBack() {
//            @Override
//            public void onSuccess() {
//                EMLog.i(TAG, "updateSelfNamecard onSuccess nameCard:" + nameCard);
//            }
//
//            @Override
//            public void onError(int code, String error) {
//                EMLog.e(TAG, "updateSelfNamecard onError code:" + code + " error:" + error);
//            }
//        });
//    }
//
//    private void getCachedNamecard() {
//        String groupNamecard = EMClient.getInstance().groupManager().getGroupNamecard(groupId, username);
//        EMLog.d(TAG,"getCachedNamecard groupId:" + groupId + " username:" + username + " groupNamecard:" + groupNamecard);
//    }
//
//    private void testGetUserProfiles() {
//        String[] userIds = new String[]{username, to};
//        EMClient.getInstance().userInfoManager().getUserInfoWithUserIds(userIds, new EMValueCallBack<Map<String, EMUserInfo>>() {
//            @Override
//            public void onSuccess(Map<String, EMUserInfo> value) {
//                EMLog.i(TAG, "testGetUserProfiles onSuccess count:" + value.size());
//                for (Map.Entry<String, EMUserInfo> entry : value.entrySet()) {
//                    EMUserInfo userInfo = entry.getValue();
//                    EMLog.i(TAG, "testGetUserProfiles userId:" + entry.getKey() + " nickname:" + userInfo.getNickname() + " avatar:" + userInfo.getAvatarUrl());
//                }
//            }
//
//            @Override
//            public void onError(int error, String errorMsg) {
//                EMLog.e(TAG, "testGetUserProfiles onError error:" + error + " errorMsg:" + errorMsg);
//            }
//        });
//    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EMClient.getInstance().chatroomManager().removeChatRoomChangeListener(chatRoomChangeListener);
        EMClient.getInstance().groupManager().removeGroupChangeListener(groupChangeListener);
        EMClient.getInstance().contactManager().removeContactListener(contactListener);
    }
}
