package com.bc_chat.im.fragment;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.*;
import android.content.res.Resources;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.view.*;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import com.bc_chat.im.R;
import com.bc_chat.im.adapter.MessageListAdapter;
import com.bc_chat.im.view.SwipeRefreshRecyclerLayout;
import com.zhaohaoting.framework.utils.ToastUtils;
import io.rong.common.RLog;
import io.rong.eventbus.EventBus;
import io.rong.imkit.*;
import io.rong.imkit.actions.IClickActions;
import io.rong.imkit.actions.OnMoreActionStateListener;
import io.rong.imkit.fragment.IHistoryDataResultCallback;
import io.rong.imkit.fragment.UriFragment;
import io.rong.imkit.manager.*;
import io.rong.imkit.mention.DraftHelper;
import io.rong.imkit.mention.RongMentionManager;
import io.rong.imkit.model.ConversationInfo;
import io.rong.imkit.model.Event;
import io.rong.imkit.model.GroupUserInfo;
import io.rong.imkit.model.UIMessage;
import io.rong.imkit.plugin.DefaultLocationPlugin;
import io.rong.imkit.plugin.IPluginModule;
import io.rong.imkit.plugin.location.*;
import io.rong.imkit.userInfoCache.RongUserInfoManager;
import io.rong.imkit.utilities.PermissionCheckUtil;
import io.rong.imkit.utilities.PromptPopupDialog;
import io.rong.imkit.utils.SystemUtils;
import io.rong.imkit.widget.CSEvaluateDialog;
import io.rong.imkit.widget.SingleChoiceDialog;
import io.rong.imkit.widget.provider.EvaluatePlugin;
import io.rong.imkit.widget.provider.MessageItemLongClickAction;
import io.rong.imlib.*;
import io.rong.imlib.common.DeviceUtils;
import io.rong.imlib.destruct.DestructionTaskManager;
import io.rong.imlib.destruct.MessageBufferPool;
import io.rong.imlib.location.RealTimeLocationConstant;
import io.rong.imlib.location.message.RealTimeLocationStartMessage;
import io.rong.imlib.model.*;
import io.rong.message.*;
import io.rong.push.RongPushClient;

import java.lang.reflect.Method;
import java.util.*;

/**
 * author：Created by zhaohaoting on 2019/3/13
 * email：526309416@qq.com
 * desc：
 */
public class MyConversationFragment extends UriFragment implements IExtensionClickListener, IUserInfoProvider, CSEvaluateDialog.EvaluateClickListener {
    public static final String TAG = "ConversationFragment";
    protected PublicServiceProfile mPublicServiceProfile;
    private RongExtension mRongExtension;
    private boolean mEnableMention;
    private float mLastTouchY;
    private boolean mUpDirection;
    private float mOffsetLimit;
    private boolean finishing = false;
    private CSCustomServiceInfo mCustomUserInfo;
    private ConversationInfo mCurrentConversationInfo;
    private String mDraft;
    private static final int REQUEST_CODE_ASK_PERMISSIONS = 100;
    private static final int REQUEST_CODE_LOCATION_SHARE = 101;
    private static final int REQUEST_CS_LEAVEL_MESSAGE = 102;
    public static final int SCROLL_MODE_NORMAL = 1;
    public static final int SCROLL_MODE_TOP = 2;
    public static final int SCROLL_MODE_BOTTOM = 3;
    private static final int DEFAULT_HISTORY_MESSAGE_COUNT = 10;
    private static final int DEFAULT_REMOTE_MESSAGE_COUNT = 10;
    private static final int TIP_DEFAULT_MESSAGE_COUNT = 1;
    private static final int SHOW_UNREAD_MESSAGE_COUNT = 10;
    private static final String UN_READ_COUNT = "unReadCount";
    private static final String LIST_STATE = "listState";
    private static final String NEW_MESSAGE_COUNT = "newMessageCount";
    private int historyMessageCount = DEFAULT_HISTORY_MESSAGE_COUNT;
    private int remoteMessageCount = DEFAULT_REMOTE_MESSAGE_COUNT;
    private String mTargetId;
    private Conversation.ConversationType mConversationType;
    private long indexMessageTime;
    private boolean mReadRec;
    private boolean mSyncReadStatus;
    private int mNewMessageCount;
    private int mUnReadCount;
    private SwipeRefreshRecyclerLayout recyclerLayout;
    private LinearLayout mUnreadMsgLayout;
    private TextView mUnreadMsgCountTv;
    private ImageButton mNewMessageBtn;
    private TextView mNewMessageTextView;
    private MessageListAdapter mListAdapter;
    private View mMsgListView;
    private LinearLayout mNotificationContainer;
    private boolean mHasMoreLocalMessagesUp = true;
    private boolean mHasMoreLocalMessagesDown = true;
    private int mLastMentionMsgId;
    private long mSyncReadStatusMsgTime;
    private boolean mCSNeedToQuit = false;
    private List<String> mLocationShareParticipants;
    private CustomServiceConfig mCustomServiceConfig;
    private CSEvaluateDialog mEvaluateDialg;
    private RongKitReceiver mKitReceiver;
    private MessageItemLongClickAction clickAction;
    private OnMoreActionStateListener moreActionStateListener;
    private Bundle mSavedInstanceState;
    private Parcelable mListViewState;
    private final int CS_HUMAN_MODE_CUSTOMER_EXPIRE = 0;
    private final int CS_HUMAN_MODE_SEAT_EXPIRE = 1;
    private Message firstUnreadMessage;
    private int lastItemPosition = -1;
    private int lastListHeight = 0;
    private int lastItemHeight = 0;
    private int lastItemBottomOffset = 0;
    private boolean isShowTipMessageCountInBackground = true;

    public void setHistoryMessageCount(int historyMessageCount) {
        this.historyMessageCount = historyMessageCount;
    }

    public void setRemoteMessageCount(int remoteMessageCount) {
        this.remoteMessageCount = remoteMessageCount;
    }

    private RecyclerView.OnScrollListener mOnScrollListener = new RecyclerView.OnScrollListener() {

        @Override
        public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
        }

        @Override
        public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
            if (mUnreadMsgLayout != null && mUnreadMsgLayout.getVisibility() == View.VISIBLE && firstUnreadMessage != null) {
                int firstPosition = mListAdapter.findPosition((long) firstUnreadMessage.getMessageId());
                if (layoutManager.findFirstVisibleItemPosition() <= firstPosition) {
                    TranslateAnimation animation = new TranslateAnimation(0.0F, 700.0F, 0.0F, 0.0F);
                    animation.setDuration(700L);
                    animation.setFillAfter(true);
                    mUnreadMsgLayout.startAnimation(animation);
                    mUnreadMsgLayout.setClickable(false);
                    recyclerLayout.removeCurrentOnScrollListener();
                }
            }
        }
    };
    private ViewTreeObserver.OnGlobalLayoutListener listViewLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
        public void onGlobalLayout() {
            if (recyclerLayout != null) {
                int height = recyclerLayout.getHeight();
                if (lastListHeight != height) {
                    if (lastItemPosition != -1) {
                        layoutManager.scrollToPositionWithOffset(lastItemPosition, height - lastItemHeight + lastItemBottomOffset);
                    }

                    lastListHeight = height;
                }
            }
        }
    };
    private boolean robotType = true;
    private long csEnterTime;
    private boolean csEvaluate = true;
    ICustomServiceListener customServiceListener = new ICustomServiceListener() {
        public void onSuccess(CustomServiceConfig config) {
            mCustomServiceConfig = config;
            if (config.isBlack) {
                onCustomServiceWarning(getString(io.rong.imkit.R.string.rc_blacklist_prompt), false, robotType);
            }

            if (config.robotSessionNoEva) {
                csEvaluate = false;
                mListAdapter.setEvaluateForRobot(true);
            }

            if (mRongExtension != null) {
                if (config.evaEntryPoint.equals(CustomServiceConfig.CSEvaEntryPoint.EVA_EXTENSION) && mCustomServiceConfig != null) {
                    mRongExtension.addPlugin(new EvaluatePlugin(mCustomServiceConfig.isReportResolveStatus));
                }

                if (config.isDisableLocation) {
                    List<IPluginModule> defaultPlugins = mRongExtension.getPluginModules();
                    IPluginModule location = null;

                    for (int ix = 0; ix < defaultPlugins.size(); ++ix) {
                        if (defaultPlugins.get(ix) instanceof DefaultLocationPlugin) {
                            location = (IPluginModule) defaultPlugins.get(ix);
                        }
                    }

                    if (location != null) {
                        mRongExtension.removePlugin(location);
                    }
                }
            }

            if (config.quitSuspendType.equals(CustomServiceConfig.CSQuitSuspendType.NONE)) {
                try {
                    mCSNeedToQuit = RongContext.getInstance().getResources().getBoolean(io.rong.imkit.R.bool.rc_stop_custom_service_when_quit);
                } catch (Resources.NotFoundException var5) {
                    RLog.e("ConversationFragment", "customServiceListener onSuccess", var5);
                }
            } else {
                mCSNeedToQuit = config.quitSuspendType.equals(CustomServiceConfig.CSQuitSuspendType.SUSPEND);
            }

            for (int i = 0; i < mListAdapter.getCount(); ++i) {
                UIMessage uiMessage = (UIMessage) mListAdapter.getItem(i);
                if (uiMessage.getContent() instanceof CSPullLeaveMessage) {
                    uiMessage.setCsConfig(config);
                }
            }

            mListAdapter.notifyDataSetChanged();
            if (!TextUtils.isEmpty(config.announceMsg)) {
                onShowAnnounceView(config.announceMsg, config.announceClickUrl);
            }

        }

        public void onError(int code, String msg) {
            onCustomServiceWarning(msg, false, robotType);
        }

        public void onModeChanged(CustomServiceMode mode) {
            if (mRongExtension != null && isActivityExist()) {
                mRongExtension.setExtensionBarMode(mode);
                if (!mode.equals(CustomServiceMode.CUSTOM_SERVICE_MODE_HUMAN) && !mode.equals(CustomServiceMode.CUSTOM_SERVICE_MODE_HUMAN_FIRST)) {
                    if (mode.equals(CustomServiceMode.CUSTOM_SERVICE_MODE_NO_SERVICE)) {
                        csEvaluate = false;
                    }
                } else {
                    if (mCustomServiceConfig != null && mCustomServiceConfig.userTipTime > 0 && !TextUtils.isEmpty(mCustomServiceConfig.userTipWord)) {
                        startTimer(0, mCustomServiceConfig.userTipTime * 60 * 1000);
                    }

                    if (mCustomServiceConfig != null && mCustomServiceConfig.adminTipTime > 0 && !TextUtils.isEmpty(mCustomServiceConfig.adminTipWord)) {
                        startTimer(1, mCustomServiceConfig.adminTipTime * 60 * 1000);
                    }

                    robotType = false;
                    csEvaluate = true;
                }

            }
        }

        public void onQuit(String msg) {
            RLog.i("ConversationFragment", "CustomService onQuit.");
            if (getActivity() != null) {
                if (mCustomServiceConfig != null && mCustomServiceConfig.evaEntryPoint.equals(CustomServiceConfig.CSEvaEntryPoint.EVA_END) && !robotType) {
                    csQuitEvaluate(msg);
                } else {
                    csQuit(msg);
                }

            }
        }

        public void onPullEvaluation(String dialogId) {
            if (mEvaluateDialg == null) {
                onCustomServiceEvaluation(true, dialogId, robotType, csEvaluate);
            }

        }

        public void onSelectGroup(List<CSGroupItem> groups) {
            onSelectCustomerServiceGroup(groups);
        }
    };
    private int conversationUnreadCount;
    private boolean isClickUnread = false;
    private LinearLayoutManager layoutManager;

    public MyConversationFragment() {
    }

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.mSavedInstanceState = savedInstanceState;
        if (savedInstanceState != null) {
            this.mNewMessageCount = savedInstanceState.getInt("newMessageCount");
            this.mListViewState = savedInstanceState.getParcelable("listState");
        }

        RLog.i("ConversationFragment", "onCreate");
        InternalModuleManager.getInstance().onLoaded();

        try {
            this.mEnableMention = this.getActivity().getResources().getBoolean(io.rong.imkit.R.bool.rc_enable_mentioned_message);
        } catch (Resources.NotFoundException var6) {
            RLog.e("ConversationFragment", "rc_enable_mentioned_message not found in rc_config.xml");
        }

        try {
            this.mReadRec = this.getResources().getBoolean(io.rong.imkit.R.bool.rc_read_receipt);
            this.mSyncReadStatus = this.getResources().getBoolean(io.rong.imkit.R.bool.rc_enable_sync_read_status);
        } catch (Resources.NotFoundException var5) {
            RLog.e("ConversationFragment", "onCreate rc_read_receipt not found in rc_config.xml", var5);
        }

        this.mKitReceiver = new RongKitReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.intent.action.PHONE_STATE");
        filter.addAction("android.intent.action.NEW_OUTGOING_CALL");

        try {
            this.getActivity().registerReceiver(this.mKitReceiver, filter);
        } catch (Exception var4) {
            RLog.e("ConversationFragment", "onCreate", var4);
        }

    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.my_fr_conversation, container, false);
        this.mRongExtension = (RongExtension) view.findViewById(R.id.rc_extension);
        this.mRongExtension.setFragment(this);
        this.mOffsetLimit = 70.0F * this.getActivity().getResources().getDisplayMetrics().density;
        this.mMsgListView = this.findViewById(view, R.id.rc_layout_msg_list);
        this.recyclerLayout = (SwipeRefreshRecyclerLayout) this.findViewById(this.mMsgListView, R.id.recycler_layout);
        layoutManager = new LinearLayoutManager(getActivity());
        this.recyclerLayout.setLayoutManager(layoutManager);
        this.recyclerLayout.requestDisallowInterceptTouchEvent(true);
        this.recyclerLayout.setRefreshMode(SwipeRefreshRecyclerLayout.Mode.BOTH);
        this.mListAdapter = this.onResolveAdapter(this.getActivity());
        this.recyclerLayout.setAdapter(this.mListAdapter);
        this.recyclerLayout.setOnRefreshListener(new SwipeRefreshRecyclerLayout.OnRefreshListener() {
            public void onRefreshFromStart() {
                if (mHasMoreLocalMessagesUp) {
                    getHistoryMessage(mConversationType, mTargetId, historyMessageCount, SwipeRefreshRecyclerLayout.Mode.START, SCROLL_MODE_NORMAL, -1);
                } else {
                    getRemoteHistoryMessages(mConversationType, mTargetId, remoteMessageCount);
                }
            }

            public void onRefreshFromEnd() {
                if (mHasMoreLocalMessagesDown && indexMessageTime > 0L) {
                    getHistoryMessage(mConversationType, mTargetId, historyMessageCount, SwipeRefreshRecyclerLayout.Mode.END, SCROLL_MODE_NORMAL, -1);
                } else {
                    onRefreshComplete(0, false);
                }
            }
        });
        this.recyclerLayout.setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == 2 && mListAdapter.getCount() - mListAdapter.getHeaderViewsCount() - mListAdapter.getFooterViewsCount() == 0) {
                    if (mHasMoreLocalMessagesUp) {
                        getHistoryMessage(mConversationType, mTargetId, historyMessageCount, SwipeRefreshRecyclerLayout.Mode.START, SCROLL_MODE_NORMAL, -1);
                    } else if (recyclerLayout.getRefreshState() != SwipeRefreshRecyclerLayout.State.REFRESHING) {
                        getRemoteHistoryMessages(mConversationType, mTargetId, remoteMessageCount);
                    }

                    return true;
                } else {
                    if (event.getAction() == 1 && mRongExtension != null && mRongExtension.isExtensionExpanded()) {
                        mRongExtension.collapseExtension();
                    }

                    return false;
                }
            }
        });
        if (RongContext.getInstance().getNewMessageState()) {
            this.mNewMessageTextView = (TextView) this.findViewById(view, R.id.rc_new_message_number);
            this.mNewMessageBtn = (ImageButton) this.findViewById(view, R.id.rc_new_message_count);
            this.mNewMessageBtn.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    layoutManager.scrollToPositionWithOffset(mListAdapter.getCount() - 1, 0);
                    mNewMessageBtn.setVisibility(View.GONE);
                    mNewMessageTextView.setVisibility(View.GONE);
                    mNewMessageCount = 0;
                }
            });
        }

        if (RongContext.getInstance().getUnreadMessageState()) {
            this.mUnreadMsgLayout = (LinearLayout) this.findViewById(this.mMsgListView, R.id.rc_unread_message_layout);
            this.mUnreadMsgCountTv = (TextView) this.findViewById(this.mMsgListView, R.id.rc_unread_message_count);
        }

        this.recyclerLayout.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int scrollState) {
                super.onScrollStateChanged(recyclerView, scrollState);
                if (scrollState == RecyclerView.SCROLL_STATE_DRAGGING) {
                    if (mRongExtension != null) {
                        mRongExtension.collapseExtension();
                    }
                } else if (scrollState == RecyclerView.SCROLL_STATE_IDLE) {
                    int last = layoutManager.findLastVisibleItemPosition();
                    if (mNewMessageBtn != null && last == mListAdapter.getCount() - 1) {
                        mNewMessageCount = 0;
                        mNewMessageBtn.setVisibility(View.GONE);
                        mNewMessageTextView.setVisibility(View.GONE);
                    }
                }

            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (recyclerLayout != null) {
                    if (recyclerLayout.getHeight() == lastListHeight) {
                        int childCount = layoutManager.getChildCount();
                        if (childCount != 0) {
                            View lastView = layoutManager.getChildAt(layoutManager.getChildCount()-1);
                            if (lastView != null) {
                                lastItemBottomOffset = lastView.getBottom() - lastListHeight;
                                lastItemHeight = lastView.getHeight();
                                lastItemPosition = layoutManager.findLastVisibleItemPosition();
                            }
                        }
                    }
                }
            }
        });
        this.mListAdapter.setOnItemHandlerListener(new MessageListAdapter.OnItemHandlerListener() {
            public boolean onWarningViewClick(final int position, final Message data, View v) {
                RongIMClient.getInstance().deleteMessages(new int[]{data.getMessageId()}, new RongIMClient.ResultCallback<Boolean>() {
                    public void onSuccess(Boolean aBoolean) {
                        if (aBoolean) {
                            mListAdapter.remove(position);
                            data.setMessageId(0);
                            onResendItemClick(data);
                        }

                    }

                    public void onError(RongIMClient.ErrorCode e) {
                    }
                });
                return true;
            }

            public void onReadReceiptStateClick(Message message) {
                onReadReceiptStateClick(message);
            }
        });
        this.showNewMessage();
        view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            public void onGlobalLayout() {
                Rect r = new Rect();
                view.getWindowVisibleDisplayFrame(r);
                int screenHeight = view.getRootView().getHeight();
                int keypadHeight = screenHeight - r.bottom;
                if ((double) keypadHeight > (double) screenHeight * 0.15D) {
                    view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                    if (mNewMessageCount > 0 && mNewMessageBtn != null) {
                        mNewMessageCount = 0;
                        mNewMessageBtn.setVisibility(View.GONE);
                        mNewMessageTextView.setVisibility(View.GONE);
                    }
                }

            }
        });
        this.recyclerLayout.getViewTreeObserver().addOnGlobalLayoutListener(this.listViewLayoutListener);
        return view;
    }

    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (this.showMoreClickItem()) {
            this.clickAction = (new MessageItemLongClickAction.Builder()).title(this.getResources().getString(io.rong.imkit.R.string.rc_dialog_item_message_more)).actionListener(new MessageItemLongClickAction.MessageItemLongClickListener() {
                public boolean onMessageItemLongClick(Context context, UIMessage message) {
                    setMoreActionState(message);
                    return true;
                }
            }).build();
            RongMessageItemLongClickActionManager.getInstance().addMessageItemLongClickAction(this.clickAction);
        }

    }

    public void onSaveInstanceState(Bundle outState) {
        outState.putInt("unReadCount", this.mUnReadCount);
        outState.putInt("newMessageCount", this.mNewMessageCount);
        outState.putParcelable("listState", this.layoutManager.onSaveInstanceState());
        super.onSaveInstanceState(outState);
    }

    public void onResume() {
        if (!this.getActivity().isFinishing() && this.mRongExtension != null) {
            RLog.d("ConversationFragment", "onResume when back from other activity.");
            this.mRongExtension.resetEditTextLayoutDrawnStatus();
            SharedPreferences sp = this.getActivity().getSharedPreferences("RongKitConfig", 0);
            long sendReadReceiptTime = sp.getLong(this.getSavedReadReceiptTimeName(), 0L);
            if (sendReadReceiptTime > 0L) {
                RongIMClient.getInstance().sendReadReceiptMessage(this.mConversationType, this.mTargetId, sendReadReceiptTime, (IRongCallback.ISendMessageCallback) null);
            }
        }

        if (this.getResources().getBoolean(io.rong.imkit.R.bool.rc_wipe_out_notification_message)) {
            RongPushClient.clearAllNotifications(this.getActivity());
        }

        super.onResume();
    }

    public final void getUserInfo(String userId, UserInfoCallback callback) {
        UserInfo userInfo = RongUserInfoManager.getInstance().getUserInfo(userId);
        if (userInfo != null) {
            callback.onGotUserInfo(userInfo);
        }

    }

    public void setMoreActionStateListener(OnMoreActionStateListener moreActionStateListener) {
        this.moreActionStateListener = moreActionStateListener;
    }

    public void setMoreActionState(UIMessage message) {
        for (int i = 0; i < this.mListAdapter.getCount(); ++i) {
            ((UIMessage) this.mListAdapter.getItem(i)).setChecked(false);
        }

        this.mListAdapter.setMessageCheckedChanged(new MessageListAdapter.OnMessageCheckedChanged() {
            public void onCheckedEnable(boolean enable) {
                if (mRongExtension != null) {
                    mRongExtension.setMoreActionEnable(enable);
                }

            }
        });
        this.mListAdapter.setSelectedCountDidExceed(new MessageListAdapter.OnSelectedCountDidExceed() {
            public void onSelectedCountDidExceed() {
                messageSelectedCountDidExceed();
            }
        });
        this.mListAdapter.setSelectedCountDidExceed(new MessageListAdapter.OnSelectedCountDidExceed() {
            public void onSelectedCountDidExceed() {
                messageSelectedCountDidExceed();
            }
        });
        this.mRongExtension.showMoreActionLayout(this.getMoreClickActions());
        this.mListAdapter.setShowCheckbox(true);
        message.setChecked(true);
        this.mListAdapter.notifyDataSetChanged();
        if (this.moreActionStateListener != null) {
            this.moreActionStateListener.onShownMoreActionLayout();
        }

    }

    public void resetMoreActionState() {
        this.mRongExtension.hideMoreActionLayout();
        this.mListAdapter.setShowCheckbox(false);
        this.mListAdapter.notifyDataSetChanged();
        if (this.moreActionStateListener != null) {
            this.moreActionStateListener.onHiddenMoreActionLayout();
        }

    }

    public List<IClickActions> getMoreClickActions() {
        List<IClickActions> actions = new ArrayList();
        DeleteClickActions deleteClickActions = new DeleteClickActions();
        actions.add(deleteClickActions);
        return actions;
    }

    public List<Message> getCheckedMessages() {
        return this.mListAdapter != null ? this.mListAdapter.getCheckedMessage() : null;
    }

    public void setMaxMessageSelectedCount(int maxMessageSelectedCount) {
        if (this.mListAdapter != null) {
            this.mListAdapter.setMaxMessageSelectedCount(maxMessageSelectedCount);
        }

    }

    protected void messageSelectedCountDidExceed() {
        ToastUtils.show(getString(R.string.rc_exceeded_max_limit));
    }

    public boolean showMoreClickItem() {
        return false;
    }

    public boolean showAboveIsHistoryMessage() {
        return true;
    }

    public MessageListAdapter onResolveAdapter(Context context) {
        return new MessageListAdapter(context);
    }

    protected void initFragment(Uri uri) {
        this.indexMessageTime = this.getActivity().getIntent().getLongExtra("indexMessageTime", 0L);
        RLog.d("ConversationFragment", "initFragment : " + uri + ",this=" + this + ", time = " + this.indexMessageTime);
        if (uri != null) {
            String typeStr = uri.getLastPathSegment().toUpperCase(Locale.US);
            this.mConversationType = Conversation.ConversationType.valueOf(typeStr);
            this.mTargetId = uri.getQueryParameter("targetId");
            this.mRongExtension.setConversation(this.mConversationType, this.mTargetId);
            RongIMClient.getInstance().getTextMessageDraft(this.mConversationType, this.mTargetId, new RongIMClient.ResultCallback<String>() {
                public void onSuccess(String s) {
                    DraftHelper draftHelper = new DraftHelper(s);
                    mDraft = draftHelper.decode();
                    if (mRongExtension != null) {
                        if (!TextUtils.isEmpty(mDraft)) {
                            EditText editText = mRongExtension.getInputEditText();
                            editText.setText(mDraft);
                            draftHelper.restoreMentionInfo();
                            editText.setSelection(editText.length());
                            editText.requestFocus();
                        }

                        mRongExtension.setExtensionClickListener(MyConversationFragment.this);
                    }

                }

                public void onError(RongIMClient.ErrorCode e) {
                    if (mRongExtension != null) {
                        mRongExtension.setExtensionClickListener(MyConversationFragment.this);
                    }

                }
            });
            this.mCurrentConversationInfo = ConversationInfo.obtain(this.mConversationType, this.mTargetId);
            RongContext.getInstance().registerConversationInfo(this.mCurrentConversationInfo);
            this.mNotificationContainer = (LinearLayout) this.mMsgListView.findViewById(R.id.rc_notification_container);
            if (this.mConversationType.equals(Conversation.ConversationType.CUSTOMER_SERVICE) && this.getActivity() != null && this.getActivity().getIntent() != null && this.getActivity().getIntent().getData() != null) {
                this.mCustomUserInfo = (CSCustomServiceInfo) this.getActivity().getIntent().getParcelableExtra("customServiceInfo");
            }

            try {
                Object obj;
                Class cls;
                if (RongContext.getInstance().getResources().getBoolean(io.rong.imkit.R.bool.rc_location_2D)) {
                    cls = Class.forName("io.rong.imkit.plugin.location.LocationManager2D");
                    obj = LocationManager2D.getInstance();
                } else {
                    cls = Class.forName("io.rong.imkit.plugin.location.LocationManager");
                    obj = LocationManager.getInstance();
                }

                Method method1 = cls.getMethod("bindConversation", Context.class, Conversation.ConversationType.class, String.class);
                Method method2 = cls.getMethod("setUserInfoProvider", IUserInfoProvider.class);
                Method method3 = cls.getMethod("setParticipantChangedListener", IRealTimeLocationStateListener.class);
                method1.invoke(obj, this.getActivity(), this.mConversationType, this.mTargetId);
                method2.invoke(obj, this);
                method3.invoke(obj, new IRealTimeLocationStateListener() {
                    private View mRealTimeBar;
                    private TextView mRealTimeText;

                    public void onParticipantChanged(List<String> userIdList) {
                        if (!isDetached()) {
                            if (this.mRealTimeBar == null) {
                                this.mRealTimeBar = inflateNotificationView(io.rong.imkit.R.layout.rc_notification_realtime_location);
                                this.mRealTimeText = (TextView) this.mRealTimeBar.findViewById(R.id.real_time_location_text);
                                this.mRealTimeBar.setOnClickListener(new View.OnClickListener() {
                                    public void onClick(View v) {
                                        RealTimeLocationConstant.RealTimeLocationStatus status = RongIMClient.getInstance().getRealTimeLocationCurrentState(mConversationType, mTargetId);
                                        if (status == RealTimeLocationConstant.RealTimeLocationStatus.RC_REAL_TIME_LOCATION_STATUS_INCOMING) {
                                            PromptPopupDialog dialog = PromptPopupDialog.newInstance(getActivity(), "", getResources().getString(io.rong.imkit.R.string.rc_real_time_join_notification));
                                            dialog.setPromptButtonClickedListener(new PromptPopupDialog.OnPromptButtonClickedListener() {
                                                public void onPositiveButtonClicked() {
                                                    int result;
                                                    if (RongContext.getInstance().getResources().getBoolean(io.rong.imkit.R.bool.rc_location_2D)) {
                                                        result = LocationManager2D.getInstance().joinLocationSharing();
                                                    } else {
                                                        result = LocationManager.getInstance().joinLocationSharing();
                                                    }

                                                    if (result == 0) {
                                                        Intent intent;
                                                        if (RongContext.getInstance().getResources().getBoolean(io.rong.imkit.R.bool.rc_location_2D)) {
                                                            intent = new Intent(getActivity(), AMapRealTimeActivity2D.class);
                                                        } else {
                                                            intent = new Intent(getActivity(), AMapRealTimeActivity.class);
                                                        }

                                                        if (mLocationShareParticipants != null) {
                                                            intent.putStringArrayListExtra("participants", (ArrayList) mLocationShareParticipants);
                                                        }

                                                        startActivity(intent);
                                                    } else if (result == 1) {
                                                        ToastUtils.show(getString(R.string.rc_network_exception));
                                                    } else if (result == 2) {
                                                        ToastUtils.show(getString(R.string.rc_location_sharing_exceed_max));
                                                    }

                                                }
                                            });
                                            dialog.show();
                                        } else {
                                            Intent intent;
                                            if (RongContext.getInstance().getResources().getBoolean(io.rong.imkit.R.bool.rc_location_2D)) {
                                                intent = new Intent(getActivity(), AMapRealTimeActivity2D.class);
                                            } else {
                                                intent = new Intent(getActivity(), AMapRealTimeActivity.class);
                                            }

                                            if (mLocationShareParticipants != null) {
                                                intent.putStringArrayListExtra("participants", (ArrayList) mLocationShareParticipants);
                                            }

                                            startActivity(intent);
                                        }

                                    }
                                });
                            }

                            mLocationShareParticipants = userIdList;
                            if (userIdList != null) {
                                if (userIdList.size() == 0) {
                                    hideNotificationView(this.mRealTimeBar);
                                } else {
                                    if (userIdList.size() == 1 && userIdList.contains(RongIM.getInstance().getCurrentUserId())) {
                                        this.mRealTimeText.setText(getResources().getString(io.rong.imkit.R.string.rc_you_are_sharing_location));
                                    } else if (userIdList.size() == 1 && !userIdList.contains(RongIM.getInstance().getCurrentUserId())) {
                                        this.mRealTimeText.setText(String.format(getResources().getString(io.rong.imkit.R.string.rc_other_is_sharing_location), getNameFromCache((String) userIdList.get(0))));
                                    } else {
                                        this.mRealTimeText.setText(String.format(getResources().getString(io.rong.imkit.R.string.rc_others_are_sharing_location), userIdList.size()));
                                    }

                                    showNotificationView(this.mRealTimeBar);
                                }
                            } else {
                                hideNotificationView(this.mRealTimeBar);
                            }

                        }
                    }

                    public void onErrorException() {
                        if (!isDetached()) {
                            hideNotificationView(this.mRealTimeBar);
                            if (mLocationShareParticipants != null) {
                                mLocationShareParticipants.clear();
                                mLocationShareParticipants = null;
                            }
                        }
                    }
                });
            } catch (Exception var10) {
                RLog.e("ConversationFragment", "Exception :", var10);
            } catch (Throwable var11) {
                RLog.e("ConversationFragment", "Throwable :", var11);
            }

            if (this.mConversationType.equals(Conversation.ConversationType.CHATROOM)) {
                boolean createIfNotExist = this.isActivityExist() && this.getActivity().getIntent().getBooleanExtra("createIfNotExist", true);
                int pullCount = this.getResources().getInteger(io.rong.imkit.R.integer.rc_chatroom_first_pull_message_count);
                if (createIfNotExist) {
                    RongIMClient.getInstance().joinChatRoom(this.mTargetId, pullCount, new RongIMClient.OperationCallback() {
                        public void onSuccess() {
                            RLog.i("ConversationFragment", "joinChatRoom onSuccess : " + mTargetId);
                        }

                        public void onError(RongIMClient.ErrorCode errorCode) {
                            RLog.e("ConversationFragment", "joinChatRoom onError : " + errorCode);
                            if (isActivityExist()) {
                                if (errorCode != RongIMClient.ErrorCode.RC_NET_UNAVAILABLE && errorCode != RongIMClient.ErrorCode.RC_NET_CHANNEL_INVALID) {
                                    onWarningDialog(getString(io.rong.imkit.R.string.rc_join_chatroom_failure));
                                } else {
                                    onWarningDialog(getString(io.rong.imkit.R.string.rc_notice_network_unavailable));
                                }
                            }

                        }
                    });
                } else {
                    RongIMClient.getInstance().joinExistChatRoom(this.mTargetId, pullCount, new RongIMClient.OperationCallback() {
                        public void onSuccess() {
                            RLog.i("ConversationFragment", "joinExistChatRoom onSuccess : " + mTargetId);
                        }

                        public void onError(RongIMClient.ErrorCode errorCode) {
                            RLog.e("ConversationFragment", "joinExistChatRoom onError : " + errorCode);
                            if (isActivityExist()) {
                                if (errorCode != RongIMClient.ErrorCode.RC_NET_UNAVAILABLE && errorCode != RongIMClient.ErrorCode.RC_NET_CHANNEL_INVALID) {
                                    onWarningDialog(getString(io.rong.imkit.R.string.rc_join_chatroom_failure));
                                } else {
                                    onWarningDialog(getString(io.rong.imkit.R.string.rc_notice_network_unavailable));
                                }
                            }

                        }
                    });
                }
            } else if (this.mConversationType != Conversation.ConversationType.APP_PUBLIC_SERVICE && this.mConversationType != Conversation.ConversationType.PUBLIC_SERVICE) {
                if (this.mConversationType.equals(Conversation.ConversationType.CUSTOMER_SERVICE)) {
                    this.onStartCustomService(this.mTargetId);
                } else if (this.mEnableMention && (this.mConversationType.equals(Conversation.ConversationType.DISCUSSION) || this.mConversationType.equals(Conversation.ConversationType.GROUP))) {
                    RongMentionManager.getInstance().createInstance(this.mConversationType, this.mTargetId, this.mRongExtension.getInputEditText());
                }
            } else {
                PublicServiceCommandMessage msg = new PublicServiceCommandMessage();
                msg.setCommand(PublicServiceMenu.PublicServiceMenuItemType.Entry.getMessage());
                Message message = Message.obtain(this.mTargetId, this.mConversationType, msg);
                RongIMClient.getInstance().sendMessage(message, (String) null, (String) null, new IRongCallback.ISendMessageCallback() {
                    public void onAttached(Message message) {
                    }

                    public void onSuccess(Message message) {
                    }

                    public void onError(Message message, RongIMClient.ErrorCode errorCode) {
                    }
                });
                Conversation.PublicServiceType publicServiceType;
                if (this.mConversationType == Conversation.ConversationType.PUBLIC_SERVICE) {
                    publicServiceType = Conversation.PublicServiceType.PUBLIC_SERVICE;
                } else {
                    publicServiceType = Conversation.PublicServiceType.APP_PUBLIC_SERVICE;
                }

                this.getPublicServiceProfile(publicServiceType, this.mTargetId);
            }
        }

        RongIMClient.getInstance().getConversation(this.mConversationType, this.mTargetId, new RongIMClient.ResultCallback<Conversation>() {
            public void onSuccess(final Conversation conversation) {
                if (conversation != null && isActivityExist()) {
                    if (mSavedInstanceState != null) {
                        mUnReadCount = mSavedInstanceState.getInt("unReadCount");
                    } else {
                        mUnReadCount = conversation.getUnreadMessageCount();
                    }

                    conversationUnreadCount = mUnReadCount;
                    boolean sendReadReceiptFailed = false;
                    if (getActivity() != null && isAdded()) {
                        SharedPreferences sp = getActivity().getSharedPreferences("RongKitConfig", 0);
                        sendReadReceiptFailed = sp.getBoolean(getSavedReadReceiptStatusName(), false);
                    }

                    if (mUnReadCount > 0 || sendReadReceiptFailed) {
                        boolean isPrivate = mConversationType.equals(Conversation.ConversationType.PRIVATE) && RongContext.getInstance().isReadReceiptConversationType(Conversation.ConversationType.PRIVATE);
                        boolean isEncrypted = mConversationType.equals(Conversation.ConversationType.ENCRYPTED) && RongContext.getInstance().isReadReceiptConversationType(Conversation.ConversationType.ENCRYPTED);
                        if (mReadRec && (isPrivate || isEncrypted)) {
                            RongIMClient.getInstance().sendReadReceiptMessage(mConversationType, mTargetId, conversation.getSentTime(), new IRongCallback.ISendMessageCallback() {
                                public void onAttached(Message message) {
                                }

                                public void onSuccess(Message message) {
                                    removeSendReadReceiptStatusToSp();
                                }

                                public void onError(Message message, RongIMClient.ErrorCode errorCode) {
                                    RLog.e("ConversationFragment", "sendReadReceiptMessage errorCode = " + errorCode.getValue());
                                    saveSendReadReceiptStatusToSp(true, conversation.getSentTime());
                                }
                            });
                        }

                        if (mSyncReadStatus && (!mReadRec && mConversationType == Conversation.ConversationType.PRIVATE || mConversationType == Conversation.ConversationType.GROUP || mConversationType == Conversation.ConversationType.DISCUSSION)) {
                            RongIMClient.getInstance().syncConversationReadStatus(mConversationType, mTargetId, conversation.getSentTime(), (RongIMClient.OperationCallback) null);
                        }
                    }

                    if (conversation.getMentionedCount() > 0) {
                        getLastMentionedMessageId(mConversationType, mTargetId);
                    } else {
                        RongIMClient.getInstance().getTheFirstUnreadMessage(mConversationType, mTargetId, new RongIMClient.ResultCallback<Message>() {
                            public void onSuccess(Message message) {
                                firstUnreadMessage = message;
                                if (mUnReadCount > SHOW_UNREAD_MESSAGE_COUNT && mUnreadMsgLayout != null && firstUnreadMessage != null) {
                                    showUnreadMsgLayout();
                                }

                                refreshUnreadUI();
                                RongIM.getInstance().clearMessagesUnreadStatus(mConversationType, mTargetId, (RongIMClient.ResultCallback) null);
                            }

                            public void onError(RongIMClient.ErrorCode e) {
                                RongIM.getInstance().clearMessagesUnreadStatus(mConversationType, mTargetId, (RongIMClient.ResultCallback) null);
                            }
                        });
                    }

                    if (mUnReadCount > SHOW_UNREAD_MESSAGE_COUNT && mUnreadMsgLayout != null) {
                        if (mUnReadCount > 99) {
                            mUnreadMsgCountTv.setText(String.format("%s%s", "99+", getActivity().getResources().getString(io.rong.imkit.R.string.rc_new_messages)));
                        } else {
                            mUnreadMsgCountTv.setText(String.format("%s%s", mUnReadCount, getActivity().getResources().getString(io.rong.imkit.R.string.rc_new_messages)));
                        }

                        mUnreadMsgLayout.setOnClickListener(new View.OnClickListener() {
                            public void onClick(View v) {
                                mUnreadMsgLayout.setClickable(false);
                                recyclerLayout.removeOnScrollListener(mOnScrollListener);
                                TranslateAnimation animation = new TranslateAnimation(0.0F, 500.0F, 0.0F, 0.0F);
                                animation.setDuration(500L);
                                mUnreadMsgLayout.startAnimation(animation);
                                animation.setFillAfter(true);
                                animation.setAnimationListener(new Animation.AnimationListener() {
                                    public void onAnimationStart(Animation animation) {
                                    }

                                    public void onAnimationEnd(Animation animation) {
                                        if (firstUnreadMessage == null) {
                                            RLog.e("ConversationFragment", "firstUnreadMessage is null");
                                        } else {
                                            indexMessageTime = firstUnreadMessage.getSentTime();
                                            int position = mListAdapter.findPosition((long) firstUnreadMessage.getMessageId());
                                            if (position == 0) {
                                                layoutManager.scrollToPositionWithOffset(position, 0);
                                            } else if (position > 0) {
                                                layoutManager.scrollToPositionWithOffset(position - 1, 0);
                                            } else {
                                                isClickUnread = true;
                                                mListAdapter.clear();
                                                getHistoryMessage(mConversationType, mTargetId, historyMessageCount, SwipeRefreshRecyclerLayout.Mode.END, SCROLL_MODE_TOP, firstUnreadMessage.getMessageId());
                                            }

                                        }
                                    }

                                    public void onAnimationRepeat(Animation animation) {
                                    }
                                });
                            }
                        });
                    }
                }

            }

            public void onError(RongIMClient.ErrorCode e) {
            }
        });
        SwipeRefreshRecyclerLayout.Mode mode = this.indexMessageTime > 0L ? SwipeRefreshRecyclerLayout.Mode.END : SwipeRefreshRecyclerLayout.Mode.START;
        int scrollMode = this.indexMessageTime > 0L ? SCROLL_MODE_NORMAL : SCROLL_MODE_BOTTOM;
        this.getHistoryMessage(this.mConversationType, this.mTargetId, historyMessageCount, mode, scrollMode, -1);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

    }

    private void showUnreadMsgLayout() {
        TranslateAnimation translateAnimation = new TranslateAnimation(300.0F, 0.0F, 0.0F, 0.0F);
        AlphaAnimation alphaAnimation = new AlphaAnimation(0.0F, 1.0F);
        translateAnimation.setDuration(1000L);
        alphaAnimation.setDuration(2000L);
        AnimationSet set = new AnimationSet(true);
        set.addAnimation(translateAnimation);
        set.addAnimation(alphaAnimation);
        if (this.mUnreadMsgLayout != null) {
            this.mUnreadMsgLayout.setVisibility(View.VISIBLE);
            this.mUnreadMsgLayout.startAnimation(set);
        }

    }

    public void getPublicServiceProfile(Conversation.PublicServiceType publicServiceType, String publicServiceId) {
        RongIM.getInstance().getPublicServiceProfile(publicServiceType, this.mTargetId, new RongIMClient.ResultCallback<PublicServiceProfile>() {
            public void onSuccess(PublicServiceProfile publicServiceProfile) {
                updatePublicServiceMenu(publicServiceProfile);
            }

            public void onError(RongIMClient.ErrorCode e) {
            }
        });
    }

    protected void updatePublicServiceMenu(PublicServiceProfile publicServiceProfile) {
        List<InputMenu> inputMenuList = new ArrayList();
        PublicServiceMenu menu = publicServiceProfile.getMenu();
        List<PublicServiceMenuItem> items = menu != null ? menu.getMenuItems() : null;
        if (items != null && this.mRongExtension != null) {
            this.mPublicServiceProfile = publicServiceProfile;
            Iterator var5 = items.iterator();

            while (var5.hasNext()) {
                PublicServiceMenuItem item = (PublicServiceMenuItem) var5.next();
                InputMenu inputMenu = new InputMenu();
                inputMenu.title = item.getName();
                inputMenu.subMenuList = new ArrayList();
                Iterator var8 = item.getSubMenuItems().iterator();

                while (var8.hasNext()) {
                    PublicServiceMenuItem i = (PublicServiceMenuItem) var8.next();
                    inputMenu.subMenuList.add(i.getName());
                }

                inputMenuList.add(inputMenu);
            }

            this.mRongExtension.setInputMenu(inputMenuList, true);
        }

    }

    public void hideNotificationView(View notificationView) {
        if (notificationView != null) {
            View view = this.mNotificationContainer.findViewById(notificationView.getId());
            if (view != null) {
                this.mNotificationContainer.removeView(view);
                if (this.mNotificationContainer.getChildCount() == 0) {
                    this.mNotificationContainer.setVisibility(View.GONE);
                }
            }

        }
    }

    public void showNotificationView(View notificationView) {
        if (notificationView != null) {
            View view = this.mNotificationContainer.findViewById(notificationView.getId());
            if (view == null) {
                this.mNotificationContainer.addView(notificationView);
                this.mNotificationContainer.setVisibility(View.VISIBLE);
            }
        }
    }

    public View inflateNotificationView(@LayoutRes int layout) {
        return LayoutInflater.from(this.getActivity()).inflate(layout, this.mNotificationContainer, false);
    }

    public void onResendItemClick(Message message) {
        if (message.getContent() instanceof ImageMessage) {
            ImageMessage imageMessage = (ImageMessage) message.getContent();
            if (imageMessage.getRemoteUri() != null && !imageMessage.getRemoteUri().toString().startsWith("file")) {
                RongIM.getInstance().sendMessage(message, (String) null, (String) null, (IRongCallback.ISendMessageCallback) null);
            } else {
                RongIM.getInstance().sendImageMessage(message, (String) null, (String) null, (RongIMClient.SendImageMessageCallback) null);
            }
        } else if (message.getContent() instanceof LocationMessage) {
            RongIM.getInstance().sendLocationMessage(message, (String) null, (String) null, (IRongCallback.ISendMessageCallback) null);
        } else if (message.getContent() instanceof MediaMessageContent) {
            MediaMessageContent mediaMessageContent = (MediaMessageContent) message.getContent();
            if (mediaMessageContent.getMediaUrl() != null) {
                RongIM.getInstance().sendMessage(message, (String) null, (String) null, (IRongCallback.ISendMediaMessageCallback) null);
            } else {
                RongIM.getInstance().sendMediaMessage(message, (String) null, (String) null, (IRongCallback.ISendMediaMessageCallback) null);
            }
        } else {
            RongIM.getInstance().sendMessage(message, (String) null, (String) null, (IRongCallback.ISendMessageCallback) null);
        }

    }

    public void onReadReceiptStateClick(Message message) {
    }

    public void onSelectCustomerServiceGroup(final List<CSGroupItem> groupList) {
        if (!this.isActivityExist()) {
            RLog.w("ConversationFragment", "onSelectCustomerServiceGroup Activity has finished");
        } else {
            List<String> singleDataList = new ArrayList();
            singleDataList.clear();

            for (int i = 0; i < groupList.size(); ++i) {
                if (((CSGroupItem) groupList.get(i)).getOnline()) {
                    singleDataList.add(((CSGroupItem) groupList.get(i)).getName());
                }
            }

            if (singleDataList.size() == 0) {
                RongIMClient.getInstance().selectCustomServiceGroup(this.mTargetId, (String) null);
            } else {
                final SingleChoiceDialog singleChoiceDialog = new SingleChoiceDialog(this.getActivity(), singleDataList);
                singleChoiceDialog.setTitle(this.getActivity().getResources().getString(io.rong.imkit.R.string.rc_cs_select_group));
                singleChoiceDialog.setOnOKButtonListener(new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        int selItem = singleChoiceDialog.getSelectItem();
                        RongIMClient.getInstance().selectCustomServiceGroup(mTargetId, ((CSGroupItem) groupList.get(selItem)).getId());
                    }
                });
                singleChoiceDialog.setOnCancelButtonListener(new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        RongIMClient.getInstance().selectCustomServiceGroup(mTargetId, (String) null);
                    }
                });
                singleChoiceDialog.show();
            }
        }
    }

    private void csQuit(String msg) {
        if (this.getHandler() != null) {
            this.getHandler().removeCallbacksAndMessages((Object) null);
        }

        if (this.mEvaluateDialg == null) {
            if (this.mCustomServiceConfig != null) {
                this.onCustomServiceWarning(msg, this.mCustomServiceConfig.quitSuspendType == CustomServiceConfig.CSQuitSuspendType.NONE, this.robotType);
            }
        } else {
            this.mEvaluateDialg.destroy();
        }

        if (this.mCustomServiceConfig != null && !this.mCustomServiceConfig.quitSuspendType.equals(CustomServiceConfig.CSQuitSuspendType.NONE)) {
            RongContext.getInstance().getEventBus().post(new Event.CSTerminateEvent(this.getActivity(), msg));
        }

    }

    private void csQuitEvaluateButtonClick(String msg) {
        if (this.mEvaluateDialg != null) {
            this.mEvaluateDialg.destroy();
            this.mEvaluateDialg = null;
        }

        if (this.getHandler() != null) {
            this.getHandler().removeCallbacksAndMessages((Object) null);
        }

        if (this.mEvaluateDialg == null) {
            this.onCustomServiceWarning(msg, false, this.robotType);
        } else {
            this.mEvaluateDialg.destroy();
        }

        if (this.mCustomServiceConfig != null && !this.mCustomServiceConfig.quitSuspendType.equals(CustomServiceConfig.CSQuitSuspendType.NONE)) {
            RongContext.getInstance().getEventBus().post(new Event.CSTerminateEvent(this.getActivity(), msg));
        }

    }

    private void csQuitEvaluate(final String msg) {
        if (this.mEvaluateDialg == null) {
            this.mEvaluateDialg = new CSEvaluateDialog(this.getActivity(), this.mTargetId);
            this.mEvaluateDialg.setClickListener(new CSEvaluateDialog.EvaluateClickListener() {
                public void onEvaluateSubmit() {
                    csQuitEvaluateButtonClick(msg);
                }

                public void onEvaluateCanceled() {
                    csQuitEvaluateButtonClick(msg);
                }
            });
            this.mEvaluateDialg.setOnCancelListener(new DialogInterface.OnCancelListener() {
                public void onCancel(DialogInterface dialog) {
                    if (mEvaluateDialg != null) {
                        mEvaluateDialg = null;
                    }

                }
            });
            this.mEvaluateDialg.showStar("");
        }

    }

    public void onPause() {
        this.finishing = this.getActivity().isFinishing();
        if (this.finishing) {
            this.destroy();
        } else {
            this.stopAudioThingsDependsOnVoipMode();
        }

        this.isShowTipMessageCountInBackground = !isLastItemVisible(1);
        super.onPause();
    }

    public void onShowAnnounceView(String announceMsg, String announceUrl) {
    }

    private void destroy() {
        RongIM.getInstance().clearMessagesUnreadStatus(this.mConversationType, this.mTargetId, (RongIMClient.ResultCallback) null);
        if (this.getHandler() != null) {
            this.getHandler().removeCallbacksAndMessages((Object) null);
        }

        if (this.mConversationType.equals(Conversation.ConversationType.CHATROOM)) {
            SendImageManager.getInstance().cancelSendingImages(this.mConversationType, this.mTargetId);
            SendMediaManager.getInstance().cancelSendingMedia(this.mConversationType, this.mTargetId);
            RongIM.getInstance().quitChatRoom(this.mTargetId, (RongIMClient.OperationCallback) null);
        }

        if (this.mConversationType.equals(Conversation.ConversationType.CUSTOMER_SERVICE) && this.mCSNeedToQuit) {
            this.onStopCustomService(this.mTargetId);
        }

        if (this.mSyncReadStatus && this.mSyncReadStatusMsgTime > 0L && (this.mConversationType.equals(Conversation.ConversationType.DISCUSSION) || this.mConversationType.equals(Conversation.ConversationType.GROUP))) {
            RongIMClient.getInstance().syncConversationReadStatus(this.mConversationType, this.mTargetId, this.mSyncReadStatusMsgTime, (RongIMClient.OperationCallback) null);
        }

        EventBus.getDefault().unregister(this);
        this.stopAudioThingsDependsOnVoipMode();

        try {
            if (this.mKitReceiver != null) {
                this.getActivity().unregisterReceiver(this.mKitReceiver);
            }
        } catch (Exception var2) {
            RLog.e("ConversationFragment", "destroy", var2);
        }

        RongContext.getInstance().unregisterConversationInfo(this.mCurrentConversationInfo);
        if (RongContext.getInstance().getResources().getBoolean(io.rong.imkit.R.bool.rc_location_2D)) {
            LocationManager2D.getInstance().quitLocationSharing();
            LocationManager2D.getInstance().setParticipantChangedListener((IRealTimeLocationStateListener) null);
            LocationManager2D.getInstance().setUserInfoProvider((IUserInfoProvider) null);
            LocationManager2D.getInstance().unBindConversation();
        } else {
            LocationManager.getInstance().quitLocationSharing();
            LocationManager.getInstance().setParticipantChangedListener((IRealTimeLocationStateListener) null);
            LocationManager.getInstance().setUserInfoProvider((IUserInfoProvider) null);
            LocationManager.getInstance().unBindConversation();
        }

        this.destroyExtension();
    }

    private void stopAudioThingsDependsOnVoipMode() {
        if (!AudioPlayManager.getInstance().isInVOIPMode(this.getActivity())) {
            AudioPlayManager.getInstance().stopPlay();
        }

        AudioRecordManager.getInstance().destroyRecord();
    }

    private void destroyExtension() {
        String text = this.mRongExtension.getInputEditText().getText().toString();
        String mentionInfo = RongMentionManager.getInstance().getMentionBlockInfo();
        String saveDraft = DraftHelper.encode(text, mentionInfo);
        if (TextUtils.isEmpty(text) && !TextUtils.isEmpty(this.mDraft) || !TextUtils.isEmpty(text) && TextUtils.isEmpty(this.mDraft) || !TextUtils.isEmpty(text) && !TextUtils.isEmpty(this.mDraft) && !text.equals(this.mDraft)) {
            RongIMClient.getInstance().saveTextMessageDraft(this.mConversationType, this.mTargetId, saveDraft, (RongIMClient.ResultCallback) null);
            Event.DraftEvent draft = new Event.DraftEvent(this.mConversationType, this.mTargetId, text);
            RongContext.getInstance().getEventBus().post(draft);
        }

        this.mRongExtension.onDestroy();
        this.mRongExtension = null;
        if (this.mEnableMention && (this.mConversationType.equals(Conversation.ConversationType.DISCUSSION) || this.mConversationType.equals(Conversation.ConversationType.GROUP))) {
            RongMentionManager.getInstance().destroyInstance(this.mConversationType, this.mTargetId);
        }

    }

    public void onDestroy() {
        RongMessageItemLongClickActionManager.getInstance().removeMessageItemLongClickAction(this.clickAction);
        if (!this.finishing) {
            this.destroy();
        }

        DestructionTaskManager.getInstance().removeListeners("ConversationFragment");
        if (this.recyclerLayout != null) {
            this.recyclerLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this.listViewLayoutListener);
        }

        super.onDestroy();
    }

    public boolean isLocationSharing() {
        return RongContext.getInstance().getResources().getBoolean(io.rong.imkit.R.bool.rc_location_2D) ? LocationManager2D.getInstance().isSharing() : LocationManager.getInstance().isSharing();
    }

    public void showQuitLocationSharingDialog(final Activity activity) {
        PromptPopupDialog.newInstance(activity, this.getString(io.rong.imkit.R.string.rc_ext_warning), this.getString(io.rong.imkit.R.string.rc_real_time_exit_notification), this.getString(io.rong.imkit.R.string.rc_action_bar_ok)).setPromptButtonClickedListener(new PromptPopupDialog.OnPromptButtonClickedListener() {
            public void onPositiveButtonClicked() {
                activity.finish();
            }
        }).show();
    }

    public boolean onBackPressed() {
        if (this.mRongExtension != null && this.mRongExtension.isExtensionExpanded()) {
            this.mRongExtension.collapseExtension();
            return true;
        } else if (this.mConversationType != null && this.mCustomServiceConfig != null && this.mConversationType.equals(Conversation.ConversationType.CUSTOMER_SERVICE) && this.mCustomServiceConfig != null && this.mCustomServiceConfig.quitSuspendType.equals(CustomServiceConfig.CSQuitSuspendType.NONE)) {
            return this.onCustomServiceEvaluation(false, "", this.robotType, this.csEvaluate);
        } else if (this.mRongExtension != null && this.mRongExtension.isMoreActionShown()) {
            this.resetMoreActionState();
            return true;
        } else {
            return false;
        }
    }

    public boolean handleMessage(android.os.Message msg) {
        InformationNotificationMessage info;
        switch (msg.what) {
            case 0:
                if (this.isActivityExist() && this.mCustomServiceConfig != null) {
                    info = new InformationNotificationMessage(this.mCustomServiceConfig.userTipWord);
                    RongIM.getInstance().insertMessage(Conversation.ConversationType.CUSTOMER_SERVICE, this.mTargetId, this.mTargetId, info, System.currentTimeMillis(), (RongIMClient.ResultCallback) null);
                    return true;
                }

                return true;
            case 1:
                if (this.isActivityExist() && this.mCustomServiceConfig != null) {
                    info = new InformationNotificationMessage(this.mCustomServiceConfig.adminTipWord);
                    RongIM.getInstance().insertMessage(Conversation.ConversationType.CUSTOMER_SERVICE, this.mTargetId, this.mTargetId, info, System.currentTimeMillis(), (RongIMClient.ResultCallback) null);
                    return true;
                }

                return true;
            default:
                return false;
        }
    }

    private boolean isActivityExist() {
        return this.getActivity() != null && !this.getActivity().isFinishing();
    }

    public boolean isLastItemVisible(int lastVisibleCount) {
        boolean result = false;
        int itemCount = this.mListAdapter.getCount();
        int headerViewsCount = this.mListAdapter.getHeaderViewsCount();
        int lastItemPosition = itemCount - headerViewsCount - 1;
        int lastVisiblePosition = layoutManager.findLastVisibleItemPosition();
        if (lastVisiblePosition > lastItemPosition) {
            lastVisiblePosition = lastItemPosition;
        }

        if (lastVisiblePosition >= lastItemPosition - lastVisibleCount + 1) {
            result = true;
        }

        return result;
    }


    public void onWarningDialog(String msg) {
        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this.getActivity());
        builder.setCancelable(false);
        final AlertDialog alertDialog = builder.create();
        alertDialog.show();
        Window window = alertDialog.getWindow();
        window.setContentView(io.rong.imkit.R.layout.rc_cs_alert_warning);
        TextView tv = (TextView) window.findViewById(R.id.rc_cs_msg);
        tv.setText(msg);
        window.findViewById(R.id.rc_btn_ok).setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                alertDialog.dismiss();
                FragmentManager fm = getChildFragmentManager();
                if (fm.getBackStackEntryCount() > 0) {
                    fm.popBackStack();
                } else {
                    getActivity().finish();
                }

            }
        });
    }

    public void onCustomServiceWarning(String msg, final boolean evaluate, final boolean robotType) {
        if (!this.isActivityExist()) {
            RLog.w("ConversationFragment", "Activity has finished");
        } else {
            android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this.getActivity());
            builder.setCancelable(false);
            final AlertDialog alertDialog = builder.create();
            alertDialog.show();
            Window window = alertDialog.getWindow();
            window.setContentView(io.rong.imkit.R.layout.rc_cs_alert_warning);
            TextView tv = (TextView) window.findViewById(R.id.rc_cs_msg);
            tv.setText(msg);
            window.findViewById(R.id.rc_btn_ok).setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                    alertDialog.dismiss();
                    if (evaluate) {
                        onCustomServiceEvaluation(false, "", robotType, evaluate);
                    } else {
                        FragmentManager fm = getChildFragmentManager();
                        if (fm.getBackStackEntryCount() > 0) {
                            fm.popBackStack();
                        } else {
                            getActivity().finish();
                        }
                    }

                }
            });
        }
    }

    public boolean onCustomServiceEvaluation(boolean isPullEva, String dialogId, boolean robotType, boolean evaluate) {
        if (this.isActivityExist()) {
            if (evaluate) {
                long currentTime = System.currentTimeMillis();
                int interval = 60;

                try {
                    interval = this.getActivity().getResources().getInteger(io.rong.imkit.R.integer.rc_custom_service_evaluation_interval);
                } catch (Resources.NotFoundException var10) {
                    RLog.e("ConversationFragment", "onCustomServiceEvaluation", var10);
                }

                if (currentTime - this.csEnterTime < (long) (interval * 1000) && !isPullEva) {
                    InputMethodManager imm = (InputMethodManager) this.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm != null && imm.isActive() && this.getActivity().getCurrentFocus() != null && this.getActivity().getCurrentFocus().getWindowToken() != null) {
                        imm.hideSoftInputFromWindow(this.getActivity().getCurrentFocus().getWindowToken(), 2);
                    }

                    FragmentManager fm = this.getChildFragmentManager();
                    if (fm.getBackStackEntryCount() > 0) {
                        fm.popBackStack();
                    } else {
                        this.getActivity().finish();
                    }

                    return false;
                }

                this.mEvaluateDialg = new CSEvaluateDialog(this.getActivity(), this.mTargetId);
                this.mEvaluateDialg.setClickListener(this);
                this.mEvaluateDialg.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    public void onCancel(DialogInterface dialog) {
                        if (mEvaluateDialg != null) {
                            mEvaluateDialg = null;
                        }

                    }
                });
                if (this.mCustomServiceConfig != null && this.mCustomServiceConfig.evaluateType.equals(CustomServiceConfig.CSEvaType.EVA_UNIFIED)) {
                    this.mEvaluateDialg.showStarMessage(this.mCustomServiceConfig.isReportResolveStatus);
                } else if (robotType) {
                    this.mEvaluateDialg.showRobot(true);
                } else {
                    this.onShowStarAndTabletDialog(dialogId);
                }
            } else {
                FragmentManager fm = this.getChildFragmentManager();
                if (fm.getBackStackEntryCount() > 0) {
                    fm.popBackStack();
                } else {
                    this.getActivity().finish();
                }
            }
        }

        return true;
    }

    public void onShowStarAndTabletDialog(String dialogId) {
        this.mEvaluateDialg.showStar(dialogId);
    }

    public void onSendToggleClick(View v, String text) {
        if (!TextUtils.isEmpty(text) && !TextUtils.isEmpty(text.trim())) {
            TextMessage textMessage = TextMessage.obtain(text);
            MentionedInfo mentionedInfo = RongMentionManager.getInstance().onSendButtonClick();
            if (mentionedInfo != null) {
                textMessage.setMentionedInfo(mentionedInfo);
            }

            Message message = Message.obtain(this.mTargetId, this.mConversationType, textMessage);
            RongIM.getInstance().sendMessage(message, (String) null, (String) null, (IRongCallback.ISendMessageCallback) null);
        } else {
            RLog.e("ConversationFragment", "text content must not be null");
        }
    }

    public void onImageResult(LinkedHashMap<String, Integer> selectedMedias, boolean origin) {
        Iterator var3 = selectedMedias.entrySet().iterator();

        while (var3.hasNext()) {
            Map.Entry<String, Integer> media = (Map.Entry) var3.next();
            int mediaType = (Integer) media.getValue();
            String mediaUri = (String) media.getKey();
            switch (mediaType) {
                case 1:
                    SendImageManager.getInstance().sendImages(this.mConversationType, this.mTargetId, Collections.singletonList(Uri.parse(mediaUri)), origin);
                    if (this.mConversationType.equals(Conversation.ConversationType.PRIVATE)) {
                        RongIMClient.getInstance().sendTypingStatus(this.mConversationType, this.mTargetId, "RC:ImgMsg");
                    }
                    break;
                case 3:
                    SendMediaManager.getInstance().sendMedia(this.mConversationType, this.mTargetId, Collections.singletonList(Uri.parse(mediaUri)), origin);
                    if (this.mConversationType.equals(Conversation.ConversationType.PRIVATE)) {
                        RongIMClient.getInstance().sendTypingStatus(this.mConversationType, this.mTargetId, "RC:SightMsg");
                    }
            }
        }

    }

    public void onEditTextClick(EditText editText) {
    }

    public void onLocationResult(double lat, double lng, String poi, Uri thumb) {
        LocationMessage locationMessage = LocationMessage.obtain(lat, lng, poi, thumb);
        Message message = Message.obtain(this.mTargetId, this.mConversationType, locationMessage);
        RongIM.getInstance().sendLocationMessage(message, (String) null, (String) null, (IRongCallback.ISendMessageCallback) null);
        if (this.mConversationType.equals(Conversation.ConversationType.PRIVATE)) {
            RongIMClient.getInstance().sendTypingStatus(this.mConversationType, this.mTargetId, "RC:LBSMsg");
        }

    }

    public void onSwitchToggleClick(View v, ViewGroup inputBoard) {
        if (this.robotType) {
            RongIMClient.getInstance().switchToHumanMode(this.mTargetId);
        }

    }

    public void onVoiceInputToggleTouch(View v, MotionEvent event) {
        String[] permissions = new String[]{"android.permission.RECORD_AUDIO"};
        if (!PermissionCheckUtil.checkPermissions(this.getActivity(), permissions) && event.getAction() == 0) {
            PermissionCheckUtil.requestPermissions(this, permissions, REQUEST_CODE_ASK_PERMISSIONS);
        } else {
            if (event.getAction() == 0) {
                if (AudioPlayManager.getInstance().isPlaying()) {
                    AudioPlayManager.getInstance().stopPlay();
                }

                if (!AudioPlayManager.getInstance().isInNormalMode(this.getActivity())) {
                    ToastUtils.show(getString(R.string.rc_voip_occupying));
                    return;
                }

                AudioRecordManager.getInstance().startRecord(v.getRootView(), this.mConversationType, this.mTargetId);
                this.mLastTouchY = event.getY();
                this.mUpDirection = false;
                ((Button) v).setText(io.rong.imkit.R.string.rc_audio_input_hover);
            } else if (event.getAction() == 2) {
                if (this.mLastTouchY - event.getY() > this.mOffsetLimit && !this.mUpDirection) {
                    AudioRecordManager.getInstance().willCancelRecord();
                    this.mUpDirection = true;
                    ((Button) v).setText(io.rong.imkit.R.string.rc_audio_input);
                } else if (event.getY() - this.mLastTouchY > -this.mOffsetLimit && this.mUpDirection) {
                    AudioRecordManager.getInstance().continueRecord();
                    this.mUpDirection = false;
                    ((Button) v).setText(io.rong.imkit.R.string.rc_audio_input_hover);
                }
            } else if (event.getAction() == 1 || event.getAction() == 3) {
                AudioRecordManager.getInstance().stopRecord();
                ((Button) v).setText(io.rong.imkit.R.string.rc_audio_input);
            }

            if (this.mConversationType.equals(Conversation.ConversationType.PRIVATE)) {
                RongIMClient.getInstance().sendTypingStatus(this.mConversationType, this.mTargetId, "RC:VcMsg");
            }

        }
    }

    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_CODE_ASK_PERMISSIONS && grantResults.length > 0 && grantResults[0] != 0) {
            this.mRongExtension.showRequestPermissionFailedAlter(this.getResources().getString(io.rong.imkit.R.string.rc_permission_grant_needed));
        } else {
            this.mRongExtension.onRequestPermissionResult(requestCode, permissions, grantResults);
        }

    }

    public void onEmoticonToggleClick(View v, ViewGroup extensionBoard) {
    }

    public void onPluginToggleClick(View v, ViewGroup extensionBoard) {
    }

    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    public void onTextChanged(CharSequence s, int start, int before, int count) {
        int cursor;
        int offset;
        if (count == 0) {
            cursor = start + before;
            offset = -before;
        } else {
            cursor = start;
            offset = count;
        }

        if (!this.mConversationType.equals(Conversation.ConversationType.GROUP) && !this.mConversationType.equals(Conversation.ConversationType.DISCUSSION)) {
            if (this.mConversationType.equals(Conversation.ConversationType.PRIVATE) && offset != 0) {
                RongIMClient.getInstance().sendTypingStatus(this.mConversationType, this.mTargetId, "RC:TxtMsg");
            }
        } else {
            RongMentionManager.getInstance().onTextEdit(this.mConversationType, this.mTargetId, cursor, offset, s.toString());
        }

    }

    public void afterTextChanged(Editable s) {
    }

    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (event.getKeyCode() == 67 && event.getAction() == 0) {
            EditText editText = (EditText) v;
            int cursorPos = editText.getSelectionStart();
            RongMentionManager.getInstance().onDeleteClick(this.mConversationType, this.mTargetId, editText, cursorPos);
        }

        return false;
    }

    public void onMenuClick(int root, int sub) {
        if (this.mPublicServiceProfile != null) {
            PublicServiceMenuItem item = (PublicServiceMenuItem) this.mPublicServiceProfile.getMenu().getMenuItems().get(root);
            if (sub >= 0) {
                item = (PublicServiceMenuItem) item.getSubMenuItems().get(sub);
            }

            if (item.getType().equals(PublicServiceMenu.PublicServiceMenuItemType.View)) {
                IPublicServiceMenuClickListener menuClickListener = RongContext.getInstance().getPublicServiceMenuClickListener();
                if (menuClickListener == null || !menuClickListener.onClick(this.mConversationType, this.mTargetId, item)) {
                    String action = "io.rong.imkit.intent.action.webview";
                    Intent intent = new Intent(action);
                    intent.setPackage(this.getActivity().getPackageName());
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                    intent.putExtra("url", item.getUrl());
                    this.getActivity().startActivity(intent);
                }
            }

            PublicServiceCommandMessage msg = PublicServiceCommandMessage.obtain(item);
            RongIMClient.getInstance().sendMessage(this.mConversationType, this.mTargetId, msg, (String) null, (String) null, new IRongCallback.ISendMessageCallback() {
                public void onAttached(Message message) {
                }

                public void onSuccess(Message message) {
                }

                public void onError(Message message, RongIMClient.ErrorCode errorCode) {
                }
            });
        }

    }

    public void onPluginClicked(IPluginModule pluginModule, int position) {
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CS_LEAVEL_MESSAGE) {
            this.getActivity().finish();
        } else {
            this.mRongExtension.onActivityPluginResult(requestCode, resultCode, data);
        }

    }

    private String getNameFromCache(String targetId) {
        UserInfo info = RongContext.getInstance().getUserInfoFromCache(targetId);
        return info == null ? targetId : info.getName();
    }

    public void onEventMainThread(Event.ReadReceiptRequestEvent event) {
        RLog.d("ConversationFragment", "ReadReceiptRequestEvent");
        if ((this.mConversationType.equals(Conversation.ConversationType.GROUP) || this.mConversationType.equals(Conversation.ConversationType.DISCUSSION)) && RongContext.getInstance().isReadReceiptConversationType(event.getConversationType()) && event.getConversationType().equals(this.mConversationType) && event.getTargetId().equals(this.mTargetId)) {
            for (int i = 0; i < this.mListAdapter.getCount(); ++i) {
                if (((UIMessage) this.mListAdapter.getItem(i)).getUId().equals(event.getMessageUId())) {
                    final UIMessage uiMessage = (UIMessage) this.mListAdapter.getItem(i);
                    ReadReceiptInfo readReceiptInfo = uiMessage.getReadReceiptInfo();
                    if (readReceiptInfo == null) {
                        readReceiptInfo = new ReadReceiptInfo();
                        uiMessage.setReadReceiptInfo(readReceiptInfo);
                    }

                    if (readReceiptInfo.isReadReceiptMessage() && readReceiptInfo.hasRespond()) {
                        return;
                    }

                    readReceiptInfo.setIsReadReceiptMessage(true);
                    readReceiptInfo.setHasRespond(false);
                    List<Message> messageList = new ArrayList();
                    messageList.add(((UIMessage) this.mListAdapter.getItem(i)).getMessage());
                    RongIMClient.getInstance().sendReadReceiptResponse(event.getConversationType(), event.getTargetId(), messageList, new RongIMClient.OperationCallback() {
                        public void onSuccess() {
                            uiMessage.getReadReceiptInfo().setHasRespond(true);
                        }

                        public void onError(RongIMClient.ErrorCode errorCode) {
                            RLog.e("ConversationFragment", "sendReadReceiptResponse failed, errorCode = " + errorCode);
                        }
                    });
                    break;
                }
            }
        }

    }

    public void onEventMainThread(Event.ReadReceiptResponseEvent event) {
        RLog.d("ConversationFragment", "ReadReceiptResponseEvent");
        if ((this.mConversationType.equals(Conversation.ConversationType.GROUP) || this.mConversationType.equals(Conversation.ConversationType.DISCUSSION)) && RongContext.getInstance().isReadReceiptConversationType(event.getConversationType()) && event.getConversationType().equals(this.mConversationType) && event.getTargetId().equals(this.mTargetId)) {
            for (int i = 0; i < this.mListAdapter.getCount(); ++i) {
                if (((UIMessage) this.mListAdapter.getItem(i)).getUId().equals(event.getMessageUId())) {
                    UIMessage uiMessage = (UIMessage) this.mListAdapter.getItem(i);
                    ReadReceiptInfo readReceiptInfo = uiMessage.getReadReceiptInfo();
                    if (readReceiptInfo == null) {
                        readReceiptInfo = new ReadReceiptInfo();
                        readReceiptInfo.setIsReadReceiptMessage(true);
                        uiMessage.setReadReceiptInfo(readReceiptInfo);
                    }

                    readReceiptInfo.setRespondUserIdList(event.getResponseUserIdList());
                    int first = this.layoutManager.findFirstVisibleItemPosition();
                    int last = this.layoutManager.findLastVisibleItemPosition();
                    int position = this.getPositionInListView(i);
                    if (position >= first && position <= last) {
                        this.mListAdapter.notifyItemChanged(i);
                    }
                    break;
                }
            }
        }

    }

    public void onEventMainThread(Event.MessageDeleteEvent deleteEvent) {
        RLog.d("ConversationFragment", "MessageDeleteEvent");
        if (deleteEvent.getMessageIds() != null) {
            Iterator var2 = deleteEvent.getMessageIds().iterator();

            while (var2.hasNext()) {
                long messageId = (long) (Integer) var2.next();
                int position = this.mListAdapter.findPosition(messageId);
                if (position >= 0) {
                    this.mListAdapter.remove(position);
                }
            }

            this.mListAdapter.notifyDataSetChanged();
        }

    }

    public void onEventMainThread(Event.PublicServiceFollowableEvent event) {
        RLog.d("ConversationFragment", "PublicServiceFollowableEvent");
        if (event != null && !event.isFollow()) {
            this.getActivity().finish();
        }

    }

    public void onEventMainThread(Event.MessagesClearEvent clearEvent) {
        RLog.d("ConversationFragment", "MessagesClearEvent");
        if (clearEvent.getTargetId().equals(this.mTargetId) && clearEvent.getType().equals(this.mConversationType)) {
            this.mListAdapter.clear();
            this.mListAdapter.notifyDataSetChanged();
        }

    }

    public void onEventMainThread(Event.MessageRecallEvent event) {
        RLog.d("ConversationFragment", "MessageRecallEvent");
        if (event.isRecallSuccess()) {
            RecallNotificationMessage recallNotificationMessage = event.getRecallNotificationMessage();
            int position = this.mListAdapter.findPosition((long) event.getMessageId());
            if (position != -1) {
                UIMessage uiMessage = (UIMessage) this.mListAdapter.getItem(position);
                if (uiMessage.getMessage().getContent() instanceof VoiceMessage) {
                    AudioPlayManager.getInstance().stopPlay();
                }

                if (uiMessage.getMessage().getContent() instanceof FileMessage) {
                    RongIM.getInstance().cancelDownloadMediaMessage(uiMessage.getMessage(), (RongIMClient.OperationCallback) null);
                }

                ((UIMessage) this.mListAdapter.getItem(position)).setContent(recallNotificationMessage);
                int first = this.layoutManager.findFirstVisibleItemPosition();
                int last = this.layoutManager.findLastVisibleItemPosition();
                int listPos = this.getPositionInListView(position);
                if (listPos >= first && listPos <= last) {
                    this.mListAdapter.notifyItemChanged(position);
                }
            }
        } else {
            ToastUtils.show(getString(R.string.rc_recall_failed));
        }

    }

    public void onEventMainThread(Event.RemoteMessageRecallEvent event) {
        RLog.d("ConversationFragment", "RemoteMessageRecallEvent");
        int position = this.mListAdapter.findPosition((long) event.getMessageId());
        int first = this.layoutManager.findFirstVisibleItemPosition();
        int last = this.layoutManager.findLastVisibleItemPosition();
        if (position >= 0) {
            UIMessage uiMessage = (UIMessage) this.mListAdapter.getItem(position);
            if (uiMessage.getMessage().getContent() instanceof VoiceMessage) {
                AudioPlayManager.getInstance().stopPlay();
            }

            if (uiMessage.getMessage().getContent() instanceof FileMessage) {
                RongIM.getInstance().cancelDownloadMediaMessage(uiMessage.getMessage(), (RongIMClient.OperationCallback) null);
            }

            uiMessage.setContent(event.getRecallNotificationMessage());
            int listPos = this.getPositionInListView(position);
            if (listPos >= first && listPos <= last) {
                this.mListAdapter.notifyItemChanged(position);
            }
        }

    }

    public void onEventMainThread(Message msg) {
        RLog.d("ConversationFragment", "Event message : " + msg.getMessageId() + ", " + msg.getObjectName() + ", " + msg.getSentStatus());
        if (this.mTargetId.equals(msg.getTargetId()) && this.mConversationType.equals(msg.getConversationType()) && msg.getMessageId() > 0) {
            int position = this.mListAdapter.findPosition((long) msg.getMessageId());
            if (position >= 0) {
                if (msg.getSentStatus().equals(Message.SentStatus.FAILED)) {
                    long serverTime = msg.getSentTime() - RongIMClient.getInstance().getDeltaTime();
                    msg.setSentTime(serverTime);
                }

                ((UIMessage) this.mListAdapter.getItem(position)).setMessage(msg);
                this.mListAdapter.notifyItemChanged(position);
            } else {
                UIMessage uiMessage = UIMessage.obtain(msg);
                if (msg.getContent() instanceof CSPullLeaveMessage) {
                    uiMessage.setCsConfig(this.mCustomServiceConfig);
                }

                long sentTime = uiMessage.getSentTime();
                if (uiMessage.getMessageDirection() == Message.MessageDirection.SEND && uiMessage.getSentStatus() == Message.SentStatus.SENDING || uiMessage.getContent() instanceof RealTimeLocationStartMessage) {
                    sentTime = uiMessage.getSentTime() - RongIMClient.getInstance().getDeltaTime();
                    uiMessage.setSentTime(sentTime);
                }

                int insertPosition = this.mListAdapter.getPositionBySendTime(sentTime);
                this.mListAdapter.add(uiMessage, insertPosition);
                this.mListAdapter.notifyDataSetChanged();
            }

            MessageTag msgTag = (MessageTag) msg.getContent().getClass().getAnnotation(MessageTag.class);
            if (this.mNewMessageCount <= 0 && (msgTag != null && msgTag.flag() == 3 || this.layoutManager.findLastVisibleItemPosition() == this.layoutManager.getItemCount() - 1)) {
//                this.recyclerLayout.mRecyclerView.setTranscriptMode(2);
                this.recyclerLayout.mRecyclerView.post(new Runnable() {
                    public void run() {
                        if (getActivity() != null && recyclerLayout != null) {
                            layoutManager.scrollToPositionWithOffset(layoutManager.getItemCount() - 1, 0);
                        }
                    }
                });
//                this.mList.setTranscriptMode(0);
            }

            if (this.mConversationType.equals(Conversation.ConversationType.CUSTOMER_SERVICE) && msg.getMessageDirection() == Message.MessageDirection.SEND && !this.robotType && this.mCustomServiceConfig != null && this.mCustomServiceConfig.userTipTime > 0 && !TextUtils.isEmpty(this.mCustomServiceConfig.userTipWord)) {
                this.startTimer(0, this.mCustomServiceConfig.userTipTime * 60 * 1000);
            }
        }

    }

    public void onEventMainThread(RongIMClient.ConnectionStatusListener.ConnectionStatus status) {
        RLog.d("ConversationFragment", "ConnectionStatus, " + status.toString());
        if (this.getActivity() != null && this.isAdded()) {
            SharedPreferences sp = this.getActivity().getSharedPreferences("RongKitConfig", 0);
            boolean sendReadReceiptFailed = sp.getBoolean(this.getSavedReadReceiptStatusName(), false);
            long sendReadReceiptTime = sp.getLong(this.getSavedReadReceiptTimeName(), 0L);
            if (status.equals(RongIMClient.ConnectionStatusListener.ConnectionStatus.CONNECTED) && sendReadReceiptFailed) {
                RongIMClient.getInstance().sendReadReceiptMessage(this.mConversationType, this.mTargetId, sendReadReceiptTime, (IRongCallback.ISendMessageCallback) null);
                this.removeSendReadReceiptStatusToSp();
            }
        }

    }

    public void onEventMainThread(Event.MessageSentStatusUpdateEvent event) {
        Message message = event.getMessage();
        if (message != null && !message.getMessageDirection().equals(Message.MessageDirection.RECEIVE)) {
            RLog.d("ConversationFragment", "MessageSentStatusEvent event : " + event.getMessage().getMessageId() + ", " + event.getSentStatus());
            int position = this.mListAdapter.findPosition((long) message.getMessageId());
            if (position >= 0) {
                ((UIMessage) this.mListAdapter.getItem(position)).setSentStatus(event.getSentStatus());
                mListAdapter.notifyItemChanged(position);
            }

        } else {
            RLog.e("ConversationFragment", "MessageSentStatusUpdateEvent message is null or direction is RECEIVE");
        }
    }

    public void onEventMainThread(Event.FileMessageEvent event) {
        Message msg = event.getMessage();
        RLog.d("ConversationFragment", "FileMessageEvent message : " + msg.getMessageId() + ", " + msg.getObjectName() + ", " + msg.getSentStatus());
        if (this.mTargetId.equals(msg.getTargetId()) && this.mConversationType.equals(msg.getConversationType()) && msg.getMessageId() > 0 && msg.getContent() instanceof MediaMessageContent) {
            int position = this.mListAdapter.findPosition((long) msg.getMessageId());
            if (position >= 0) {
                UIMessage uiMessage = (UIMessage) this.mListAdapter.getItem(position);
                uiMessage.setMessage(msg);
                uiMessage.setProgress(event.getProgress());
                if (msg.getContent() instanceof FileMessage) {
                    ((FileMessage) msg.getContent()).progress = event.getProgress();
                }

                ((UIMessage) this.mListAdapter.getItem(position)).setMessage(msg);
            }
        }

    }

    public void onEventMainThread(GroupUserInfo groupUserInfo) {
        RLog.d("ConversationFragment", "GroupUserInfoEvent " + groupUserInfo.getGroupId() + " " + groupUserInfo.getUserId() + " " + groupUserInfo.getNickname());
        if (groupUserInfo.getNickname() != null && groupUserInfo.getGroupId() != null) {
            int count = this.mListAdapter.getCount();
            int first = this.layoutManager.findFirstVisibleItemPosition();
            int last = this.layoutManager.findLastVisibleItemPosition();

            for (int i = 0; i < count; ++i) {
                UIMessage uiMessage = (UIMessage) this.mListAdapter.getItem(i);
                if (uiMessage.getSenderUserId().equals(groupUserInfo.getUserId())) {
                    uiMessage.setNickName(true);
                    UserInfo userInfo = uiMessage.getUserInfo();
                    if (userInfo != null) {
                        userInfo.setName(groupUserInfo.getNickname());
                        uiMessage.setUserInfo(userInfo);
                    }

                    int pos = this.getPositionInListView(i);
                    if (pos >= first && pos <= last) {
                        mListAdapter.notifyItemChanged(i);
                    }
                }
            }

        }
    }

    private View getListViewChildAt(int adapterIndex) {
        int header = this.mListAdapter.getHeaderViewsCount();
        int first = this.layoutManager.findFirstVisibleItemPosition();
        return this.recyclerLayout.getChildAt(adapterIndex + header - first);
    }

    private int getPositionInListView(int adapterIndex) {
        int header = this.mListAdapter.getHeaderViewsCount();
        return adapterIndex + header;
    }

    private int getPositionInAdapter(int listIndex) {
        int header = this.mListAdapter.getHeaderViewsCount();
        return listIndex <= 0 ? 0 : listIndex - header;
    }

    private void showNewMessage() {
        if (this.mNewMessageCount > 0 && this.mNewMessageBtn != null) {
            this.mNewMessageBtn.setVisibility(View.VISIBLE);
            if (this.mNewMessageTextView != null) {
                this.mNewMessageTextView.setVisibility(View.VISIBLE);
                if (this.mNewMessageCount > 99) {
                    this.mNewMessageTextView.setText("99+");
                } else {
                    this.mNewMessageTextView.setText(this.mNewMessageCount + "");
                }
            }
        }

    }

    public void onEventMainThread(Event.OnMessageSendErrorEvent event) {
        this.onEventMainThread(event.getMessage());
    }

    public void onEventMainThread(Event.OnReceiveMessageEvent event) {
        Message message = event.getMessage();
        RLog.i("ConversationFragment", "OnReceiveMessageEvent, " + message.getMessageId() + ", " + message.getObjectName() + ", " + message.getReceivedStatus().toString());
        Conversation.ConversationType conversationType = message.getConversationType();
        String targetId = message.getTargetId();
        if (this.mConversationType.equals(conversationType) && this.mTargetId.equals(targetId) && this.shouldUpdateMessage(message, event.getLeft())) {
            if (event.getLeft() == 0) {
                boolean isPrivate = message.getConversationType().equals(Conversation.ConversationType.PRIVATE) && RongContext.getInstance().isReadReceiptConversationType(Conversation.ConversationType.PRIVATE);
                boolean isEncrypted = message.getConversationType().equals(Conversation.ConversationType.ENCRYPTED) && RongContext.getInstance().isReadReceiptConversationType(Conversation.ConversationType.ENCRYPTED);
                if ((isPrivate || isEncrypted) && message.getMessageDirection().equals(Message.MessageDirection.RECEIVE)) {
                    if (this.mReadRec && !TextUtils.isEmpty(message.getUId())) {
                        if (RongIMClient.getInstance().getTopForegroundActivity() != null && RongIMClient.getInstance().getTopForegroundActivity().equals(this.getActivity())) {
                            RongIMClient.getInstance().sendReadReceiptMessage(message.getConversationType(), message.getTargetId(), message.getSentTime(), new IRongCallback.ISendMessageCallback() {
                                public void onAttached(Message message) {
                                }

                                public void onSuccess(Message message) {
                                    removeSendReadReceiptStatusToSp();
                                }

                                public void onError(Message message, RongIMClient.ErrorCode errorCode) {
                                    RLog.e("ConversationFragment", "sendReadReceiptMessage errorCode = " + errorCode.getValue());
                                    saveSendReadReceiptStatusToSp(true, message.getSentTime());
                                }
                            });
                        } else {
                            this.saveSendReadReceiptStatusToSp(true, message.getSentTime());
                        }
                    }

                    if (!this.mReadRec && this.mSyncReadStatus) {
                        RongIMClient.getInstance().syncConversationReadStatus(message.getConversationType(), message.getTargetId(), message.getSentTime(), (RongIMClient.OperationCallback) null);
                    }
                }
            }

            if (this.mSyncReadStatus) {
                this.mSyncReadStatusMsgTime = message.getSentTime();
            }

            if (message.getMessageId() > 0) {
                if (!SystemUtils.isInBackground(this.getActivity())) {
                    message.getReceivedStatus().setRead();
                    RongIMClient.getInstance().setMessageReceivedStatus(message.getMessageId(), message.getReceivedStatus(), (RongIMClient.ResultCallback) null);
                    if (message.getMessageDirection().equals(Message.MessageDirection.RECEIVE)) {
                        UnReadMessageManager.getInstance().onMessageReceivedStatusChanged();
                    }
                }

                if (this.mConversationType.equals(Conversation.ConversationType.CUSTOMER_SERVICE) && !this.robotType && this.mCustomServiceConfig != null && this.mCustomServiceConfig.adminTipTime > 0 && !TextUtils.isEmpty(this.mCustomServiceConfig.adminTipWord)) {
                    this.startTimer(1, this.mCustomServiceConfig.adminTipTime * 60 * 1000);
                }
            }

            RLog.d("ConversationFragment", "mList.getCount(): " + this.mListAdapter.getCount() + " getLastVisiblePosition:" + this.layoutManager.findLastVisibleItemPosition());
            this.increaseNewMessageCountIfNeed(message);
            this.onEventMainThread(event.getMessage());
            if ((this.mConversationType == Conversation.ConversationType.PRIVATE || this.mConversationType == Conversation.ConversationType.ENCRYPTED) && message.getContent().isDestruct() && this.isVisible()) {
                DestructionTag destructionTag = (DestructionTag) message.getContent().getClass().getAnnotation(DestructionTag.class);
                if (destructionTag != null && destructionTag.destructionFlag() == 1) {
                    DestructionCmdMessage destructionCmdMessage = new DestructionCmdMessage();
                    destructionCmdMessage.getBurnMessageUIds().add(message.getUId());
                    MessageBufferPool.getInstance().putMessageInBuffer(Message.obtain(this.mTargetId, this.mConversationType, destructionCmdMessage));
                    RongIMClient.getInstance().setMessageReadTime((long) message.getMessageId(), message.getSentTime(), (RongIMClient.OperationCallback) null);
                    int messagePosition = this.mListAdapter.findPosition((long) message.getMessageId());
                    ((UIMessage) this.mListAdapter.getItem(messagePosition)).getMessage().setReadTime(message.getSentTime());
                }
            }
        }

    }

    private void removeSendReadReceiptStatusToSp() {
        if (this.getActivity() != null && this.isAdded()) {
            SharedPreferences preferences = this.getActivity().getSharedPreferences("RongKitConfig", 0);
            SharedPreferences.Editor editor = preferences.edit();
            editor.remove(this.getSavedReadReceiptStatusName());
            editor.remove(this.getSavedReadReceiptTimeName());
            editor.commit();
        }

    }

    private void saveSendReadReceiptStatusToSp(boolean status, long time) {
        if (this.getActivity() != null && this.isAdded()) {
            SharedPreferences preferences = this.getActivity().getSharedPreferences("RongKitConfig", 0);
            SharedPreferences.Editor editor = preferences.edit();
            editor.putBoolean(this.getSavedReadReceiptStatusName(), status);
            editor.putLong(this.getSavedReadReceiptTimeName(), time);
            editor.commit();
        }

    }

    private String getSavedReadReceiptStatusName() {
        String savedId = DeviceUtils.ShortMD5(new String[]{RongIM.getInstance().getCurrentUserId(), this.mTargetId, this.mConversationType.getName()});
        return "ReadReceipt" + savedId + "Status";
    }

    private String getSavedReadReceiptTimeName() {
        String savedId = DeviceUtils.ShortMD5(new String[]{RongIM.getInstance().getCurrentUserId(), this.mTargetId, this.mConversationType.getName()});
        return "ReadReceipt" + savedId + "Time";
    }

    protected void increaseNewMessageCountIfNeed(Message message) {
        if (this.mNewMessageBtn != null) {
            if (SystemUtils.isInBackground(this.getContext())) {
                if (!this.isShowTipMessageCountInBackground) {
                    return;
                }
            } else if (isLastItemVisible(1)) {
                return;
            }

            if (Message.MessageDirection.SEND != message.getMessageDirection() && message.getConversationType() != Conversation.ConversationType.CHATROOM && message.getConversationType() != Conversation.ConversationType.CUSTOMER_SERVICE && message.getConversationType() != Conversation.ConversationType.APP_PUBLIC_SERVICE && message.getConversationType() != Conversation.ConversationType.PUBLIC_SERVICE) {
                ++this.mNewMessageCount;
                this.showNewMessage();
            }
        }

    }

    public void onEventBackgroundThread(final Event.PlayAudioEvent event) {
        this.getHandler().post(new Runnable() {
            public void run() {
                handleAudioPlayEvent(event);
            }
        });
    }

    private void handleAudioPlayEvent(Event.PlayAudioEvent event) {
        RLog.i("ConversationFragment", "PlayAudioEvent");
        int first = this.layoutManager.findFirstVisibleItemPosition();
        int last = this.layoutManager.findLastVisibleItemPosition();
        int position = this.mListAdapter.findPosition((long) event.messageId);
        if (event.continuously && position >= 0) {
            while (first <= last) {
                ++position;
                ++first;
                UIMessage uiMessage = (UIMessage) this.mListAdapter.getItem(position);
                if (uiMessage != null && uiMessage.getContent() instanceof VoiceMessage && uiMessage.getMessageDirection().equals(Message.MessageDirection.RECEIVE) && !uiMessage.getReceivedStatus().isListened()) {
                    uiMessage.continuePlayAudio = true;
                    mListAdapter.notifyItemChanged(position);
                    break;
                }
            }
        }

    }

    public void onEventMainThread(Event.OnReceiveMessageProgressEvent event) {
        if (this.recyclerLayout != null) {
            int first = this.layoutManager.findFirstVisibleItemPosition();

            for (int last = this.layoutManager.findLastVisibleItemPosition(); first <= last; ++first) {
                int position = this.getPositionInAdapter(first);
                UIMessage uiMessage = (UIMessage) this.mListAdapter.getItem(position);
                if (uiMessage.getMessageId() == event.getMessage().getMessageId()) {
                    uiMessage.setProgress(event.getProgress());
                    if (this.isResumed()) {
                        this.mListAdapter.notifyItemChanged(position);
                    }
                    break;
                }
            }
        }

    }

    public void onEventMainThread(Event.ConnectEvent event) {
        RLog.i("ConversationFragment", "ConnectEvent : " + event.getConnectStatus());
        if (this.mListAdapter.getCount() == 0) {
            SwipeRefreshRecyclerLayout.Mode mode = this.indexMessageTime > 0L ? SwipeRefreshRecyclerLayout.Mode.END : SwipeRefreshRecyclerLayout.Mode.START;
            int scrollMode = this.indexMessageTime > 0L ? SCROLL_MODE_NORMAL : SCROLL_MODE_BOTTOM;
            this.getHistoryMessage(this.mConversationType, this.mTargetId, historyMessageCount, mode, scrollMode, -1);
        }

    }

    public void onEventMainThread(UserInfo userInfo) {
        RLog.i("ConversationFragment", "userInfo " + userInfo.getUserId());
        int first = this.layoutManager.findFirstVisibleItemPosition();
        int last = this.layoutManager.findLastVisibleItemPosition();

        for (int i = 0; i < this.mListAdapter.getCount(); ++i) {
            UIMessage uiMessage = (UIMessage) this.mListAdapter.getItem(i);
            if (userInfo.getUserId().equals(uiMessage.getSenderUserId()) && !uiMessage.isNickName()) {
                if (uiMessage.getConversationType().equals(Conversation.ConversationType.CUSTOMER_SERVICE) && uiMessage.getMessage() != null && uiMessage.getMessage().getContent() != null && uiMessage.getMessage().getContent().getUserInfo() != null) {
                    uiMessage.setUserInfo(uiMessage.getMessage().getContent().getUserInfo());
                } else {
                    uiMessage.setUserInfo(userInfo);
                }

                int position = this.getPositionInListView(i);
                if (position >= first && position <= last) {
                    mListAdapter.notifyItemChanged(i);
                }
            }
        }
    }

    public void onEventMainThread(PublicServiceProfile publicServiceProfile) {
        RLog.i("ConversationFragment", "publicServiceProfile");
        if (publicServiceProfile != null && this.mConversationType.equals(publicServiceProfile.getConversationType()) && this.mTargetId.equals(publicServiceProfile.getTargetId())) {
            int first = this.layoutManager.findFirstVisibleItemPosition();

            for (int last = this.layoutManager.findLastVisibleItemPosition(); first <= last; ++first) {
                int position = this.getPositionInAdapter(first);
                UIMessage message = (UIMessage) this.mListAdapter.getItem(position);
                if (message != null && (TextUtils.isEmpty(message.getTargetId()) || publicServiceProfile.getTargetId().equals(message.getTargetId()))) {
                    mListAdapter.notifyItemChanged(position);
                }
            }

            this.updatePublicServiceMenu(publicServiceProfile);
        }

    }

    public void onEventMainThread(Event.ReadReceiptEvent event) {
        RLog.i("ConversationFragment", "ReadReceiptEvent");
        if (RongContext.getInstance().isReadReceiptConversationType(event.getMessage().getConversationType()) && this.mTargetId.equals(event.getMessage().getTargetId()) && this.mConversationType.equals(event.getMessage().getConversationType()) && event.getMessage().getMessageDirection().equals(Message.MessageDirection.RECEIVE)) {
            ReadReceiptMessage content = (ReadReceiptMessage) event.getMessage().getContent();
            long ntfTime = content.getLastMessageSendTime();

            for (int i = this.mListAdapter.getCount() - 1; i >= 0; --i) {
                UIMessage uiMessage = (UIMessage) this.mListAdapter.getItem(i);
                if (uiMessage.getMessageDirection().equals(Message.MessageDirection.SEND) && uiMessage.getSentStatus() == Message.SentStatus.SENT && ntfTime >= uiMessage.getSentTime()) {
                    uiMessage.setSentStatus(Message.SentStatus.READ);
                    int first = this.layoutManager.findFirstVisibleItemPosition();
                    int last = this.layoutManager.findLastVisibleItemPosition();
                    int position = this.getPositionInListView(i);
                    if (position >= first && position <= last) {
                        mListAdapter.notifyItemChanged(i);
                    }
                }
            }
        }

    }

    public void onEventMainThread(Event.DestructionEvent event) {
        int messageCount = this.mListAdapter.getCount();
        if (event.message.getContent() instanceof VoiceMessage && AudioPlayManager.getInstance().isPlaying()) {
            VoiceMessage voiceMessage = (VoiceMessage) event.message.getContent();
            if (voiceMessage.getUri().equals(AudioPlayManager.getInstance().getPlayingUri())) {
                AudioPlayManager.getInstance().stopPlay();
            }
        }

        for (int i = messageCount - 1; i >= 0; --i) {
            UIMessage uiMessage = (UIMessage) this.mListAdapter.getItem(i);
            if (TextUtils.equals(uiMessage.getUId(), event.message.getUId())) {
                this.mListAdapter.remove(i);
                this.mListAdapter.notifyDataSetChanged();
                break;
            }
        }

    }

    public void onEventMainThread(Event.ReceiveDestructionMessageEvent event) {
        int messageId = event.message.getMessageId();
        int firstVisiblePosition = this.layoutManager.findFirstVisibleItemPosition();
        int lastVisiblePosition = this.layoutManager.findLastVisibleItemPosition();
        int messagePosition = this.mListAdapter.findPosition((long) messageId);
        if (messagePosition >= 0) {
            int messageRealPosition = messagePosition + this.mListAdapter.getHeaderViewsCount();
            ((UIMessage) this.mListAdapter.getItem(messagePosition)).getMessage().setReadTime(event.message.getReadTime());
            if (messageRealPosition >= firstVisiblePosition && messageRealPosition <= lastVisiblePosition) {
                this.mListAdapter.notifyItemChanged(messagePosition);
            }
        }

    }

    public MessageListAdapter getMessageAdapter() {
        return this.mListAdapter;
    }

    public boolean shouldUpdateMessage(Message message, int left) {
        return true;
    }

    public void getHistoryMessage(Conversation.ConversationType conversationType, String targetId, int lastMessageId, int reqCount, LoadMessageDirection direction, final IHistoryDataResultCallback<List<Message>> callback) {
        if (direction == LoadMessageDirection.UP) {
            RongIMClient.getInstance().getHistoryMessages(conversationType, targetId, lastMessageId, reqCount, new RongIMClient.ResultCallback<List<Message>>() {
                public void onSuccess(List<Message> messages) {
                    if (callback != null) {
                        callback.onResult(messages);
                    }

                }

                public void onError(RongIMClient.ErrorCode e) {
                    RLog.e("ConversationFragment", "getHistoryMessages " + e);
                    if (callback != null) {
                        callback.onResult(null);
                    }

                }
            });
        } else {
            int before = historyMessageCount;
            int after = historyMessageCount;
            if (this.mListAdapter.getCount() > 0 || this.indexMessageTime != 0L || this.isClickUnread) {
                after = historyMessageCount;
                before = 0;
            }

            RongIMClient.getInstance().getHistoryMessages(conversationType, targetId, this.indexMessageTime, before, after, new RongIMClient.ResultCallback<List<Message>>() {
                public void onSuccess(List<Message> messages) {
                    if (callback != null) {
                        callback.onResult(messages);
                    }

                    if (messages != null && messages.size() > 0 && mHasMoreLocalMessagesDown) {
                        indexMessageTime = ((Message) messages.get(0)).getSentTime();
                    } else {
                        indexMessageTime = 0L;
                    }

                }

                public void onError(RongIMClient.ErrorCode e) {
                    RLog.e("ConversationFragment", "getHistoryMessages " + e);
                    if (callback != null) {
                        callback.onResult(null);
                    }

                    indexMessageTime = 0L;
                }
            });
        }

    }

    private void getHistoryMessage(Conversation.ConversationType conversationType, String targetId, final int reqCount, SwipeRefreshRecyclerLayout.Mode mode, final int scrollMode, int messageId) {
        this.recyclerLayout.onRefreshStart(mode);
        if (conversationType.equals(Conversation.ConversationType.CHATROOM)) {
            onRefreshComplete(0, false);
            RLog.w("ConversationFragment", "Should not get local message in chatroom");
        } else {
            int fromMsgId = messageId;
            if (messageId < 0) {
                if (this.mListAdapter.getCount() == 0) {
                    fromMsgId = -1;
                } else if (((UIMessage) this.mListAdapter.getItem(0)).getMessage().getContent() instanceof HistoryDividerMessage) {
                    fromMsgId = this.firstUnreadMessage.getMessageId();
                } else {
                    fromMsgId = ((UIMessage) this.mListAdapter.getItem(0)).getMessageId();
                }
            }

            final LoadMessageDirection direction = mode == SwipeRefreshRecyclerLayout.Mode.START ? LoadMessageDirection.UP : LoadMessageDirection.DOWN;
            int finalFromMsgId = fromMsgId;
            this.getHistoryMessage(conversationType, targetId, fromMsgId, reqCount, direction, new IHistoryDataResultCallback<List<Message>>() {
                public void onResult(List<Message> messages) {
                    int msgCount = messages == null ? 0 : messages.size();
                    RLog.i("ConversationFragment", "getHistoryMessage " + msgCount);
                    if (direction == LoadMessageDirection.DOWN) {
                        onRefreshComplete(msgCount > 1 ? msgCount : 0, false);
                        mHasMoreLocalMessagesDown = msgCount > 1;
                    } else {
                        onRefreshComplete(msgCount, false);
                        mHasMoreLocalMessagesUp = msgCount == reqCount;
                    }

                    if (messages != null && messages.size() > 0) {
                        int index = 0;
                        if (direction == LoadMessageDirection.DOWN) {
                            index = mListAdapter.getCount();
                        }

                        boolean needRefresh = false;
                        DestructionCmdMessage destructionCmdMessage = new DestructionCmdMessage();
                        Iterator var6 = messages.iterator();

                        while (var6.hasNext()) {
                            Message message = (Message) var6.next();
                            if (message.getMessageDirection() == Message.MessageDirection.RECEIVE && message.getContent().isDestruct() && !TextUtils.isEmpty(message.getUId()) && message.getReadTime() <= 0L) {
                                DestructionTag destructionTag = (DestructionTag) message.getContent().getClass().getAnnotation(DestructionTag.class);
                                if (destructionTag != null && destructionTag.destructionFlag() == 1) {
                                    destructionCmdMessage.getBurnMessageUIds().add(message.getUId());
                                    long serverTime = System.currentTimeMillis() - RongIMClient.getInstance().getDeltaTime();
                                    RongIMClient.getInstance().setMessageReadTime((long) message.getMessageId(), serverTime, (RongIMClient.OperationCallback) null);
                                    message.setReadTime(serverTime);
                                }
                            }

                            boolean contains = false;

                            for (int i = 0; i < mListAdapter.getCount(); ++i) {
                                contains = ((UIMessage) mListAdapter.getItem(i)).getMessageId() == message.getMessageId();
                                if (contains) {
                                    break;
                                }
                            }

                            if (!contains) {
                                UIMessage uiMessage = UIMessage.obtain(message);
                                if (message.getContent() != null && message.getContent().getUserInfo() != null) {
                                    uiMessage.setUserInfo(message.getContent().getUserInfo());
                                }

                                if (message.getContent() instanceof CSPullLeaveMessage) {
                                    uiMessage.setCsConfig(mCustomServiceConfig);
                                }

                                mListAdapter.add(uiMessage, index);
                                needRefresh = true;
                            }
                        }

                        if (firstUnreadMessage != null) {
                            refreshUnreadUI();
                        }

                        refreshUI(messages, needRefresh, index, scrollMode, finalFromMsgId, direction);
                        if (destructionCmdMessage.getBurnMessageUIds().size() > 0) {
                            MessageBufferPool.getInstance().putMessageInBuffer(Message.obtain(mTargetId, mConversationType, destructionCmdMessage));
                        }

                        refreshUI(messages, needRefresh, index, scrollMode, finalFromMsgId, direction);
                    }

                }

                public void onError() {
                    onRefreshComplete(reqCount, false);
                }
            });
        }
    }

    private void refreshUnreadUI() {
        if (this.showAboveIsHistoryMessage()) {
            int insertPosition = 0;
            boolean historyDividerInserted = false;
            if (this.firstUnreadMessage != null) {
                Message hisMessage;
                UIMessage hisUIMessage;
                List msgList;
                if (this.conversationUnreadCount > SHOW_UNREAD_MESSAGE_COUNT) {
                    if (this.conversationUnreadCount <= SHOW_UNREAD_MESSAGE_COUNT) {
                        hisMessage = Message.obtain(this.mTargetId, this.mConversationType, HistoryDividerMessage.obtain(this.getResources().getString(io.rong.imkit.R.string.rc_new_message_divider_content)));
                        hisUIMessage = UIMessage.obtain(hisMessage);
                        insertPosition = this.mListAdapter.findPosition((long) this.firstUnreadMessage.getMessageId());
                        if (insertPosition == 0) {
                            msgList = RongIM.getInstance().getHistoryMessages(this.mConversationType, this.mTargetId, this.firstUnreadMessage.getMessageId(), 1);
                            if (msgList != null && msgList.size() == 1) {
                                hisUIMessage.setSentTime(((Message) msgList.get(0)).getSentTime());
                                this.mListAdapter.add(hisUIMessage, insertPosition);
                                historyDividerInserted = true;
                            }
                        } else if (insertPosition > 0) {
                            hisUIMessage.setSentTime(((UIMessage) this.mListAdapter.getItem(insertPosition - 1)).getSentTime());
                            this.mListAdapter.add(hisUIMessage, insertPosition);
                            historyDividerInserted = true;
                        }

                        this.conversationUnreadCount = 0;
                    } else if (this.conversationUnreadCount < this.mListAdapter.getCount() && this.isAdded()) {
                        hisMessage = Message.obtain(this.mTargetId, this.mConversationType, HistoryDividerMessage.obtain(this.getResources().getString(io.rong.imkit.R.string.rc_new_message_divider_content)));
                        hisUIMessage = UIMessage.obtain(hisMessage);
                        insertPosition = this.mListAdapter.findPosition((long) this.firstUnreadMessage.getMessageId());
                        if (insertPosition > 0) {
                            hisUIMessage.setSentTime(((UIMessage) this.mListAdapter.getItem(insertPosition - 1)).getSentTime());
                            this.mListAdapter.add(hisUIMessage, insertPosition);
                            historyDividerInserted = true;
                        }

                        this.conversationUnreadCount = 0;
                    }

                    if (this.isClickUnread) {
                        this.isClickUnread = false;
                        if (!historyDividerInserted && this.getActivity() != null && this.isAdded()) {
                            hisMessage = Message.obtain(this.mTargetId, this.mConversationType, HistoryDividerMessage.obtain(this.getActivity().getResources().getString(io.rong.imkit.R.string.rc_new_message_divider_content)));
                            hisUIMessage = UIMessage.obtain(hisMessage);
                            insertPosition = this.mListAdapter.findPosition((long) this.firstUnreadMessage.getMessageId());
                            if (insertPosition == 0) {
                                msgList = RongIM.getInstance().getHistoryMessages(this.mConversationType, this.mTargetId, this.firstUnreadMessage.getMessageId(), 1);
                                long sentTime = 0L;
                                if (msgList != null && msgList.size() == 1) {
                                    sentTime = ((Message) msgList.get(0)).getSentTime();
                                }

                                if (sentTime > 0L) {
                                    hisUIMessage.setSentTime(sentTime);
                                    this.mListAdapter.add(hisUIMessage, insertPosition);
                                }
                            } else if (insertPosition > 0) {
                                hisUIMessage.setSentTime(((UIMessage) this.mListAdapter.getItem(insertPosition - 1)).getSentTime());
                                this.mListAdapter.add(hisUIMessage, insertPosition);
                            }
                        }
                        this.conversationUnreadCount = 0;
                    }
                }
            }
        }
    }

    private void refreshUI(List<Message> messages, boolean needRefresh, int index, int scrollMode, int last, LoadMessageDirection direction) {
        if (needRefresh) {
            this.mListAdapter.notifyDataSetChanged();
            if (this.mLastMentionMsgId > 0) {
                index = this.mListAdapter.findPosition((long) this.mLastMentionMsgId);
                layoutManager.scrollToPositionWithOffset(index, 0);
                this.mLastMentionMsgId = 0;
            } else if (SCROLL_MODE_TOP == scrollMode) {
                layoutManager.scrollToPositionWithOffset(0, 0);
            } else if (scrollMode == SCROLL_MODE_BOTTOM) {
                if (last == -1 && this.mSavedInstanceState != null) {
                    this.layoutManager.onRestoreInstanceState(this.mListViewState);
                } else {
                    this.layoutManager.scrollToPositionWithOffset(mListAdapter.getItemCount() - 1, 0);
                }
            } else if (direction == LoadMessageDirection.DOWN) {
                this.layoutManager.scrollToPositionWithOffset(mListAdapter.getCount() - messages.size(), 0);
            } else {
                this.layoutManager.scrollToPositionWithOffset(messages.size(), 0);
            }
            this.sendReadReceiptResponseIfNeeded(messages);
            if (RongContext.getInstance().getUnreadMessageState() && last == -1 && this.mUnReadCount > SHOW_UNREAD_MESSAGE_COUNT) {
                this.recyclerLayout.postDelayed(() -> recyclerLayout.addOnScrollListener(mOnScrollListener), 100L);
            }
        }
    }

    public void getRemoteHistoryMessages(Conversation.ConversationType conversationType, String targetId, long dateTime, int reqCount,
                                         final IHistoryDataResultCallback<List<Message>> callback) {
        RongIMClient.getInstance().getRemoteHistoryMessages(conversationType, targetId, dateTime, reqCount, new RongIMClient.ResultCallback<List<Message>>() {
            public void onSuccess(List<Message> messages) {
                if (callback != null) {
                    callback.onResult(messages);
                }

            }

            public void onError(RongIMClient.ErrorCode e) {
                RLog.e("ConversationFragment", "getRemoteHistoryMessages " + e);
                if (callback != null) {
                    callback.onResult(null);
                }
            }
        });
    }

    private void getRemoteHistoryMessages(Conversation.ConversationType conversationType, String targetId, final int reqCount) {
        this.recyclerLayout.onRefreshStart(SwipeRefreshRecyclerLayout.Mode.START);
        if (this.mConversationType.equals(Conversation.ConversationType.CHATROOM)) {
            onRefreshComplete(0, false);
            RLog.w("ConversationFragment", "Should not get remote message in chatroom");
        } else {
            long dateTime = this.mListAdapter.getCount() == 0 ? 0L : ((UIMessage) this.mListAdapter.getItem(0)).getSentTime();
            this.getRemoteHistoryMessages(conversationType, targetId, dateTime, reqCount, new IHistoryDataResultCallback<List<Message>>() {
                public void onResult(List<Message> messages) {
                    RLog.i("ConversationFragment", "getRemoteHistoryMessages " + (messages == null ? 0 : messages.size()));
                    Message lastMessage = null;
                    if (messages != null && messages.size() > 0) {
                        if (mListAdapter.getCount() == 0) {
                            lastMessage = (Message) messages.get(0);
                        }

                        List<UIMessage> remoteListx = new ArrayList();
                        Iterator var4 = messages.iterator();

                        while (var4.hasNext()) {
                            Message message = (Message) var4.next();
                            if (message.getMessageId() > 0) {
                                UIMessage uiMessage = UIMessage.obtain(message);
                                if (message.getContent() instanceof CSPullLeaveMessage) {
                                    uiMessage.setCsConfig(mCustomServiceConfig);
                                }

                                if (message.getContent() != null && message.getContent().getUserInfo() != null) {
                                    uiMessage.setUserInfo(message.getContent().getUserInfo());
                                }

                                remoteListx.add(uiMessage);
                            }
                        }

                        List<UIMessage> remoteList = filterMessage(remoteListx);
                        if (remoteList != null && remoteList.size() > 0) {
                            var4 = remoteList.iterator();

                            while (var4.hasNext()) {
                                UIMessage uiMessagex = (UIMessage) var4.next();
                                uiMessagex.setSentStatus(Message.SentStatus.READ);
                                mListAdapter.add(uiMessagex, 0);
                            }

                            mListAdapter.notifyDataSetChanged();
                            layoutManager.scrollToPositionWithOffset(messages.size(), 0);
                            sendReadReceiptResponseIfNeeded(messages);
                            onRefreshComplete(messages.size(), false);
                            if (lastMessage != null) {
                                RongContext.getInstance().getEventBus().post(lastMessage);
                            }
                        } else {
                            onRefreshComplete(0, false);
                        }
                    } else {
                        onRefreshComplete(0, false);
                    }
                }

                public void onError() {
                    onRefreshComplete(0, false);
                }
            });
        }
    }

    public void onRefreshComplete(int count, boolean needOffset) {
        recyclerLayout.setRefreshState(SwipeRefreshRecyclerLayout.State.RESET);
        if (needOffset) {
            if (recyclerLayout.getRefreshMode() == SwipeRefreshRecyclerLayout.Mode.START) {
                layoutManager.scrollToPositionWithOffset(count + mListAdapter.getHeaderViewsCount(), 0);
            }
        }
    }

    private List<UIMessage> filterMessage(List<UIMessage> srcList) {
        Object destList;
        if (this.mListAdapter.getCount() > 0) {
            destList = new ArrayList();

            for (int i = 0; i < this.mListAdapter.getCount(); ++i) {
                Iterator var4 = srcList.iterator();

                while (var4.hasNext()) {
                    UIMessage msg = (UIMessage) var4.next();
                    if (!((List) destList).contains(msg) && msg.getMessageId() != ((UIMessage) this.mListAdapter.getItem(i)).getMessageId()) {
                        ((List) destList).add(msg);
                    }
                }
            }
        } else {
            destList = srcList;
        }

        return (List) destList;
    }

    private void getLastMentionedMessageId(Conversation.ConversationType conversationType, String targetId) {
        RongIMClient.getInstance().getUnreadMentionedMessages(conversationType, targetId, new RongIMClient.ResultCallback<List<Message>>() {
            public void onSuccess(List<Message> messages) {
                if (messages != null && messages.size() > 0) {
                    mLastMentionMsgId = ((Message) messages.get(0)).getMessageId();
                    int index = mListAdapter.findPosition((long) mLastMentionMsgId);
                    RLog.i("ConversationFragment", "getLastMentionedMessageId " + mLastMentionMsgId + " " + index);
                    if (mLastMentionMsgId > 0 && index >= 0) {
                        layoutManager.scrollToPositionWithOffset(index, 0);
                        mLastMentionMsgId = 0;
                    }
                }

                RongIM.getInstance().clearMessagesUnreadStatus(mConversationType, mTargetId, (RongIMClient.ResultCallback) null);
            }

            public void onError(RongIMClient.ErrorCode e) {
                RongIM.getInstance().clearMessagesUnreadStatus(mConversationType, mTargetId, (RongIMClient.ResultCallback) null);
            }
        });
    }

    private void sendReadReceiptResponseIfNeeded(List<Message> messages) {
        if (this.mReadRec && (this.mConversationType.equals(Conversation.ConversationType.GROUP) || this.mConversationType.equals(Conversation.ConversationType.DISCUSSION)) && RongContext.getInstance().isReadReceiptConversationType(this.mConversationType)) {
            List<Message> responseMessageList = new ArrayList();
            Iterator var3 = messages.iterator();

            while (var3.hasNext()) {
                Message message = (Message) var3.next();
                ReadReceiptInfo readReceiptInfo = message.getReadReceiptInfo();
                if (readReceiptInfo != null && readReceiptInfo.isReadReceiptMessage() && !readReceiptInfo.hasRespond()) {
                    responseMessageList.add(message);
                }
            }

            if (responseMessageList.size() > 0) {
                RongIMClient.getInstance().sendReadReceiptResponse(this.mConversationType, this.mTargetId, responseMessageList, (RongIMClient.OperationCallback) null);
            }
        }

    }

    public void onExtensionCollapsed() {
    }

    public void onExtensionExpanded(int h) {
        if (this.indexMessageTime > 0L) {
            this.mListAdapter.clear();
            if (this.firstUnreadMessage == null) {
                this.indexMessageTime = 0L;
            }

            this.conversationUnreadCount = this.mUnReadCount;
            this.getHistoryMessage(this.mConversationType, this.mTargetId, historyMessageCount, SwipeRefreshRecyclerLayout.Mode.START, SCROLL_MODE_NORMAL, -1);
        } else {
            layoutManager.scrollToPositionWithOffset(mListAdapter.getItemCount() - 1, 0);
            if (this.mNewMessageCount > 0) {
                this.mNewMessageCount = 0;
                if (this.mNewMessageBtn != null) {
                    this.mNewMessageBtn.setVisibility(View.GONE);
                    this.mNewMessageTextView.setVisibility(View.GONE);
                }
            }
        }

    }

    public void onStartCustomService(String targetId) {
        this.csEnterTime = System.currentTimeMillis();
        this.mRongExtension.setExtensionBarMode(CustomServiceMode.CUSTOM_SERVICE_MODE_NO_SERVICE);
        RongIMClient.getInstance().startCustomService(targetId, this.customServiceListener, this.mCustomUserInfo);
    }

    public void onStopCustomService(String targetId) {
        RongIMClient.getInstance().stopCustomService(targetId);
    }

    public final void onEvaluateSubmit() {
        if (this.mEvaluateDialg != null) {
            this.mEvaluateDialg.destroy();
            this.mEvaluateDialg = null;
        }

        if (this.mCustomServiceConfig != null && this.mCustomServiceConfig.quitSuspendType.equals(CustomServiceConfig.CSQuitSuspendType.NONE)) {
            this.getActivity().finish();
        }

    }

    public final void onEvaluateCanceled() {
        if (this.mEvaluateDialg != null) {
            this.mEvaluateDialg.destroy();
            this.mEvaluateDialg = null;
        }

        if (this.mCustomServiceConfig != null && this.mCustomServiceConfig.quitSuspendType.equals(CustomServiceConfig.CSQuitSuspendType.NONE)) {
            this.getActivity().finish();
        }

    }

    private void startTimer(int event, int interval) {
        this.getHandler().removeMessages(event);
        this.getHandler().sendEmptyMessageDelayed(event, (long) interval);
    }

    private void stopTimer(int event) {
        this.getHandler().removeMessages(event);
    }

    public Conversation.ConversationType getConversationType() {
        return this.mConversationType;
    }

    public String getTargetId() {
        return this.mTargetId;
    }

    public static enum LoadMessageDirection {
        DOWN,
        UP;

        private LoadMessageDirection() {
        }
    }
}

