package com.efounder.chat.activity;

import android.app.NotificationManager;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowInsets;
import android.widget.AbsListView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.efounder.chat.R;
import com.efounder.chat.adapter.ChatVoicePlayClickListener;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.event.AtUserInfoEvent;
import com.efounder.chat.event.NotifyChatUIRefreshEvent;
import com.efounder.chat.fragment.ChatSenderFragment;
import com.efounder.chat.handler.ChatMessageListener;
import com.efounder.chat.http.GetHttpUtil;
import com.efounder.chat.interf.IChatTopFloatView;
import com.efounder.chat.manager.ChatInterfaceSkipManager;
import com.efounder.chat.manager.ChatListManager;
import com.efounder.chat.manager.ChatMessageSendManager;
import com.efounder.chat.model.AnimationEvent;
import com.efounder.chat.model.ChatMenuModel;
import com.efounder.chat.model.ChatTopFloatModel;
import com.efounder.chat.model.Group;
import com.efounder.chat.model.GroupBanSpeakEvent;
import com.efounder.chat.model.GroupRootBean;
import com.efounder.chat.model.UpdateBadgeViewEvent;
import com.efounder.chat.model.UserEvent;
import com.efounder.chat.model.VoicePlayingEvent;
import com.efounder.chat.service.MessageService;
import com.efounder.chat.service.SystemInfoService;
import com.efounder.chat.struct.StructFactory;
import com.efounder.chat.utils.ChatConfigUtil;
import com.efounder.chat.utils.GroupAvatarHelper;
import com.efounder.chat.utils.GroupAvatarUtil;
import com.efounder.chat.utils.GroupNameUtil;
import com.efounder.chat.utils.ImageUtil;
import com.efounder.chat.utils.TextFormatMessageUtil;
import com.efounder.chat.utils.VoiceRecognitionSoundFileCacheUtil;
import com.efounder.chat.view.ChatTopFloatView;
import com.efounder.chat.widget.ChatListView;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.utils.Constants;
import com.efounder.message.manager.JFMessageListener;
import com.efounder.message.manager.JFMessageManager;
import com.efounder.message.struct.IMStruct002;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.pansoft.chat.animation.AnimationFactory;
import com.efounder.pansoft.chat.animation.ChatStyleFactory;
import com.efounder.pansoft.chat.input.ChatInputView;
import com.efounder.pansoft.chat.input.JFChatAdapter;
import com.efounder.pansoft.chat.input.SecretInputView;
import com.efounder.pansoft.chat.listener.OnMenuClickListener;
import com.efounder.pansoft.chat.listener.VoiceDictateSendListener;
import com.efounder.pansoft.chat.record.voice.VoiceView;
import com.efounder.router.constant.RouterConstant;
import com.efounder.util.AbFragmentManager;
import com.efounder.util.AppContext;
import com.efounder.util.EnvSupportManager;
import com.efounder.util.ToastUtil;
import com.efounder.utils.EasyPermissionUtils;
import com.efounder.utils.ResStringUtil;
import com.groupimageview.NineGridImageView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.utilcode.util.KeyboardUtils;
import com.utilcode.util.ReflectUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

import static com.efounder.frame.utils.NetStateBroadcastReceiver.isNetActive;

/**
 * 聊天对话Activity
 * 2018/04/12
 *
 * @author YQS
 */
@Route(path = RouterConstant.CHAT_INPUT_MESSAGE)
public class JFChatActivity extends BaseActivity implements MessageService.MessageServiceNetStateListener,
        MessageService.MessageServiceLoginListener,
        OnMenuClickListener, VoiceView.MyRecordVoiceListener, VoiceDictateSendListener {
    public static final String TAG = "JFChatActivity";
    //更新消息状态
    public static final int HANDLER_UPDATE_MSG_STATE = 1;
    //发送消息，刷新
    public static final int HANDLER_SEND_MSG_REFRESH = 2;
    //加载历史消息，刷新
    public static final int HANDLER_LOAD_MORE_REFRESH = 3;
    //断网
    public static final int HANDLER_NETWORK_UNREACHABLE = 4;
    //网络恢复
    public static final int HANDLER_NETWORK_RESUME = 5;
    //显示正在发送
    public static final int HANDLER_SEND_INPUTTING_MSG = 6;
    //取消显示正在发送
    public static final int HANDLER_CANCEL_INPUTTING_MSG = 7;
    //聊天文件路径
    public static String chatFilePath = ImageUtil.chatpath;
    //聊天输入框
    private ChatInputView mChatInputView;
    //密码输入view
    private SecretInputView secretInputView;
    // 聊天ListView
    private ChatListView chatListView;
    // 聊天ListView 的 adapter
    private JFChatAdapter chatAdapter;
    // 聊天类型：判断单聊，还是群聊，还是公众号
    private byte chatType;
    public JFChatActivity activityInstance = null;
    //聊天对象id
    private int chatUserId;
    //聊天群组
    private Group group;
    //用户
    private User user;
    //下拉加载更多（转圈圈）
    private ProgressBar loadmorePB;
    //下拉刷新组件
    private SmartRefreshLayout smartRefreshLayout;
    String toUserNick = "";
    // 设置按钮
    private ImageView iv_setting;
    private ImageView iv_setting_group;
    //左上角显示的用户名称
    private TextView toChatUserNickTextView;
    //未读消息提示的布局
    private LinearLayout llLeftSidebar;
    private TextView tvLeftSidebar;

    //上方悬浮view
    private ChatTopFloatView chatTopFloatView;
    //传来的上方悬浮view的数据
    private ChatTopFloatModel chatTopFloatModel;

    //消息管理器
    private JFMessageManager messageManager;
    //消息监听
    private JFMessageListener messageListener;
    //数据库
    private Handler messageHandler = new MessageHandler(this);

    private ChatListViewOnTouchListener chatListViewOnTouchListener;
    //消息列表
    List<IMStruct002> messageList;

    //使用targetList来作为一个缓冲的list存储messageList的数据变化，刷新ListView，防止闪退
    private List<IMStruct002> targetList = new ArrayList<>();

    private ChatListManager chatListManager = new ChatListManager();
    private ImageView iv_chat_add;
    private LinearLayout llMenu;

    //选择语音播放方式的layout
    private LinearLayout llVoicePlayTypeLayout;
    private ImageView ivVoicePlayView;
    private TextView tvVoicePlayTypeView;
    //动画布局
    private FrameLayout animFrameLayout;
    //群组人数
    private TextView tvGroupUserCount;

    private GroupRootBean bean;
    private AbFragmentManager abFragmentManager;

    //聊天权限String
    private String current_Chat_permissionType = "";
    private String current_Chat_permissionContent = "";

    //消息发送管理
    private ChatMessageSendManager chatMessageSendManager = new ChatMessageSendManager(this);
    //更多菜单界面跳转管理
    private ChatInterfaceSkipManager interfaceSkipManager;
    //是否从分享界面跳转来的
    private boolean skipByShare = false;
    //是否加载右上角菜单设置按钮
    private boolean isLoadRightTopBtn;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.qqstyle_layout_activity_chat);
        isLoadRightTopBtn = EnvSupportManager.isSupportChatSetting();
        initView();
        if (savedInstanceState != null) {
            Intent intent = new Intent();
            intent.putExtra("id", savedInstanceState.getInt("chatUserId"));
            intent.putExtra("chattype", savedInstanceState.getByte("chatType"));
            initChatObjectInfo(intent);
            initAttr();
            setUpView();
            getChatConfig();
        } else {
            initChatObjectInfo(getIntent());
            initAttr();
            setUpView();
            getChatConfig();
            //initUserChatPermission();
            initShareData(getIntent());
        }


        MessageService.addMessageServiceLoginListener(this);
        MessageService.addMessageServiceNetStateListener(this);
        //注册eventbus
        EventBus.getDefault().register(this);
        setApplyWindowInsets(findViewById(R.id.ll_input));
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putSerializable("chatUserId", chatUserId);
        outState.putSerializable("chatType", chatType);
    }


    @Override
    protected void onResume() {
        super.onResume();
        mChatInputView.setMenuClickbale(true);
        try {
            //！！！启动服务(再onResume中启动，防止这种情况：Activity处于前台，service先于Activity被回收掉)
            startService(new Intent(this, MessageService.class));
        } catch (Exception e) {
            e.printStackTrace();
        }
        //env存储正在聊天的人
        EnvironmentVariable.setProperty("currentChatUserId", String.valueOf(chatUserId));
        // 清除通知栏消息
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        int requestCode = Integer.valueOf(chatUserId + "" + chatType);
        notificationManager.cancel(requestCode);

        updateChatUser();
        requestGroupUsers();
        initUserChatPermission();

        //判断是否显示网络不可用
        if (!isNetActive() || !JFMessageManager.isChannelActived()) {
            if (chatType == StructFactory.TO_USER_TYPE_PERSONAL) {
//                toChatUserNickTextView.setText(user.getReMark() + "(网络不可用)");
                toChatUserNickTextView.setText(user.getReMark());
            } else {
                tvGroupUserCount.setVisibility(View.VISIBLE);
//                tvGroupUserCount.setText("(" + group.getUsers().size() + ")" + "(网络不可用)");
                tvGroupUserCount.setText("(" + group.getUsers().size() + ")");
                toChatUserNickTextView.setText(group.getGroupName());
            }
        }

        chatAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //清除掉保存的未读@消息提醒
        //TextFormatMessageUtil.clearMentionHintEV(chatUserId+"", chatType+"");
        JFMessageManager.getInstance().clearAtMe(chatUserId, chatType);
        //使用id+type作为保存草稿的key
        String unfinishedText = chatUserId + "" + chatType;
        //将草稿保存到EV中(没有@人才存草稿)
        if (!TextFormatMessageUtil.editTextHasAt(mChatInputView.getInputView().getText())) {
            //去掉多余空格
            String draft = mChatInputView.getInputView().getText().toString().trim();
            EnvironmentVariable.setProperty(unfinishedText, draft);
        } else {
            EnvironmentVariable.setProperty(unfinishedText, "");
        }

        chatListManager.clearunReadCount(chatUserId, chatType);
        EventBus.getDefault().post(new UpdateBadgeViewEvent(chatUserId + "", chatType));
        //停止语音播放
        if (ChatVoicePlayClickListener.currentPlayListener != null && ChatVoicePlayClickListener.isPlaying) {
            ChatVoicePlayClickListener.currentPlayListener.stopPlayVoice();
            //隐藏播放方式的view
            llVoicePlayTypeLayout.setVisibility(View.GONE);
        }
        //这个地方清空一下回调的map
        ChatVoicePlayClickListener.clearCallBacks();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mChatInputView.setMenuClickbale(false);
        //发送取消正在输入的消息
        if (chatType == StructFactory.TO_USER_TYPE_PERSONAL && EnvSupportManager.isSupportShowInputting()) {
            IMStruct002 imStruct002 = StructFactory.getInstance().createWhetherBeInputtingImStruct(chatUserId, false);
            sendMessage(imStruct002);
        }
    }

    @Override
    protected void onDestroy() {
        Log.i(TAG, "onDestroy");
        super.onDestroy();
        if (messageListener != null) {
            messageManager.removeMessageListener(TAG, messageListener);
        }
        MessageService.removeMessageServiceLoginListener(this);
        MessageService.removeMessageServiceNetStateListener(this);
        //如果可以，请在chatListManager中释放资源
        chatListManager.release(activityInstance);
        chatMessageSendManager.release();
        ChatStyleFactory.clear();
        activityInstance = null;
        chatAdapter.removeDownLoadListener();
        //释放波形图缓存
        VoiceRecognitionSoundFileCacheUtil.clearMessageList();
        chatListView.setOnTouchListener(null);
        chatListViewOnTouchListener = null;
        EventBus.getDefault().unregister(this);
        //释放一些其他资源
        mChatInputView.release();

        //取消getChatConfig的网络任务
        ChatConfigUtil.getInstance().cancleRequest(JFChatActivity.this);
    }


    //初始化聊天对象的信息
    public void initChatObjectInfo(Intent intent) {
        chatUserId = intent.getIntExtra("id", 1);
        chatType = intent.getByteExtra("chattype", StructFactory.TO_USER_TYPE_GROUP);
        Log.i(TAG, "--chatUserId:" + chatUserId + "");
        Log.i(TAG, "--chattype:" + chatType + "");

        chatTopFloatModel = (ChatTopFloatModel) intent.getSerializableExtra("chatTopFloatModel");

        abFragmentManager = new AbFragmentManager(this);
        chatMessageSendManager.setChatType(chatType);
        chatMessageSendManager.setCurrentChatUserId(chatUserId);
        chatMessageSendManager.setPreSendMessageCallback(preSendMessageCallback);

    }

    /*titleBar添加快捷按钮*/
    private void getChatConfig() {
        if (chatType == StructFactory.TO_USER_TYPE_PERSONAL) {
            llMenu.removeAllViews();
        } else {
            ChatConfigUtil.getInstance().getChatConfig(JFChatActivity.this, llMenu, group);
        }
    }

    /**
     * 初始化一些属性
     */
    private void initAttr() {
        messageManager = JFMessageManager.getInstance();
        if (messageListener != null) {
            messageManager.removeMessageListener(TAG, messageListener);
        }
        messageListener = new ChatMessageListener(this, chatUserId, messageHandler);
        messageManager.addMessageListener(TAG, messageListener);
        interfaceSkipManager = new ChatInterfaceSkipManager(this);
    }

    /**
     * initView
     */
    protected void initView() {
        mChatInputView = (ChatInputView) findViewById(R.id.chat_input);
        secretInputView = (SecretInputView) findViewById(R.id.secret_inut);
        //必须设置
        mChatInputView.setMyRecordVoiceListener(this);
        //设置按钮回调
        mChatInputView.setMenuClickListener(this);
        //设置语音识别回调
        mChatInputView.setVoiceDictateSendListener(this);
        //提及@功能
        if (EnvSupportManager.isSupportMentionSomeone()) {
            mChatInputView.setOnMentionInputListener(new ChatInputView.OnMentionInputListener() {
                @Override
                public void onMentionCharacterInput() {
                    //跳转到@界面
                    if (chatType == StructFactory.TO_USER_TYPE_GROUP) {
                        Intent intent = new Intent(JFChatActivity.this, SelectGroupUserActivity.class);
                        intent.putExtra("title", ResStringUtil.getString(R.string.wechatview_select_group_user));
                        intent.putExtra("id", chatUserId);
                        intent.putExtra("isShowSelf", false);
                        startActivityForResult(intent, 0);
                    }
                }
            });
        }

        chatListView = (ChatListView) findViewById(R.id.list);
        chatListViewOnTouchListener = new ChatListViewOnTouchListener();
        chatListView.setOnTouchListener(chatListViewOnTouchListener);

        chatListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                //当滑动到的item position 小于等于 未读标记的position 取消显示 左侧未读通知
                if (firstVisibleItem <= finalSmoothPosition) {
                    if (llLeftSidebar != null) {
                        llLeftSidebar.setVisibility(View.GONE);
                    }
                }
            }
        });
        loadmorePB = (ProgressBar) findViewById(R.id.pb_load_more);
        toChatUserNickTextView = ((TextView) findViewById(R.id.name));
        animFrameLayout = (FrameLayout) findViewById(R.id.framelayout_anim);
        llVoicePlayTypeLayout = (LinearLayout) findViewById(R.id.ll_voice_play_style);
        ivVoicePlayView = (ImageView) findViewById(R.id.iv_voice_playtype);
        tvVoicePlayTypeView = (TextView) findViewById(R.id.tv_voice_type);
        smartRefreshLayout = (SmartRefreshLayout) findViewById(R.id.refreshLayout);
        iv_setting = (ImageView) this.findViewById(R.id.iv_setting);
        iv_setting_group = (ImageView) this.findViewById(R.id.iv_setting_group);
        iv_chat_add = (ImageView) this.findViewById(R.id.iv_chat_add);
        llMenu = (LinearLayout) findViewById(R.id.ll_chat_menu);
        tvGroupUserCount = (TextView) findViewById(R.id.group_count);
        llLeftSidebar = (LinearLayout) findViewById(R.id.ll_left_sidebar);
        llLeftSidebar.setVisibility(View.GONE);
        tvLeftSidebar = (TextView) findViewById(R.id.tv_left_sidebar);
        chatTopFloatView = (ChatTopFloatView) findViewById(R.id.chat_top_float_view);
    }

    private void setUpView() {
        activityInstance = this;
        //设置草稿文字
        mChatInputView.setEnableWatcher(false);
        mChatInputView.getInputView().setText(EnvironmentVariable.getProperty(chatUserId + "" + chatType));
        mChatInputView.setEnableWatcher(true);
//        mChatInputView.getInputView().setFocusable(true);
//        mChatInputView.getInputView().setFocusableInTouchMode(true);
//        mChatInputView.getInputView().requestFocus();
        //设置语音播放方式的view
        if (voicePlayType.equals("0")) {
            tvVoicePlayTypeView.setText(R.string.wrchatview_earpiece);
            ivVoicePlayView.setImageDrawable(getResources().getDrawable(R.drawable.qqstyle_voice_play_type_tingtong));
        } else {
            tvVoicePlayTypeView.setText(R.string.wrchatview_handfree);
            ivVoicePlayView.setImageDrawable(getResources().getDrawable(R.drawable.qqstyle_voice_play_type_mainti));
        }
        //必须写这个
        updateChatUser();
        iv_setting.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(JFChatActivity.this,
                        ChatSingleSettingActivity.class);
                intent.putExtra("id", chatUserId);
                intent.putExtra("chattype", chatType);
                startActivity(intent);
            }

        });

        // iv_chat_add.setOnClickListener(this); Toast.makeText(this, "群聊快捷按钮", Toast.LENGTH_LONG).show();
        iv_setting_group.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(JFChatActivity.this,
                        ChatGroupSettingActivity.class);
                intent.putExtra("id", chatUserId);
                intent.putExtra("chattype", chatType);
                startActivity(intent);
            }

        });
        smartRefreshLayout.setEnableAutoLoadMore(false);//开启自动加载功能（非必须）
        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                tryLoadHistoryMessage();
            }
        });
        setupChatListView();
        setUpTopFloatView();
    }

    /**
     * 设置上方悬浮view
     */
    private void setUpTopFloatView() {
        if (chatTopFloatModel != null) {
            try {
                ReflectUtils reflectUtils = ReflectUtils.reflect(chatTopFloatModel.getClazzName());
                IChatTopFloatView iChatTopFloatView = reflectUtils.newInstance(this).get();
                iChatTopFloatView.setParentView(chatTopFloatView);
                iChatTopFloatView.setData(chatTopFloatModel);
//                View childView = iChatTopFloatView.getCustomContentView();
//                iChatTopFloatView.setData(chatTopFloatModel);
//                chatTopFloatView.addView(childView);
//                iChatTopFloatView.setParentMargin(chatTopFloatModel.getLeftMargin(), chatTopFloatModel.getTopMargin(),
//                        chatTopFloatModel.getRightMargin(), chatTopFloatModel.getBottomMargin());
                iChatTopFloatView.show();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void setupChatListView() {
        //获取消息未读数量
        final int unReadCount = JFMessageManager.getInstance().getUnReadCount(chatUserId, chatType);

        messageList = JFMessageManager.getInstance().getMessageList(chatUserId, chatType);
        // TODO 获取历史消息
        if (messageList.size() == 0) {
            List<IMStruct002> historyImStruct002s = chatListManager.getHistoryMessage(chatType, user,
                    messageManager, group, null, 20, null);
        }

        for (int i = messageList.size() - 1; i >= 0; i--) {
            if (messageList.get(i).getFromUserId() != Integer.valueOf(EnvironmentVariable
                    .getProperty(Constants.CHAT_USER_ID))
                    && messageList.get(i).getState() != IMStruct002.MESSAGE_STATE_READ
                    && messageList.get(i).getToUserType() != StructFactory.TO_USER_TYPE_GROUP
                    && messageList.get(i).getReadState() != IMStruct002.MESSAGE_STATE_READ
            ) {
                JFMessageManager.getInstance().sendReadMessage(messageList.get(i));
            }
//            else {
//                if (messageList.get(i).getToUserType() == StructFactory.TO_USER_TYPE_GROUP) {
//
//                }
//            }
        }
        targetList.clear();
        targetList.addAll(messageList);
        chatAdapter = new JFChatAdapter(this, chatListView, targetList);
        chatListView.setAdapter(chatAdapter);
        chatListView.setSelection(chatListView.getCount() - 1);
        //获取第一个显示的item position
        chatListView.post(new Runnable() {
            @Override
            public void run() {
                int visibleCount = chatListView.getLastVisiblePosition() - chatListView.getFirstVisiblePosition() + 1;
                //判断是否需要显示左侧未读数量
//                if (visibleCount > 0 && unReadCount > visibleCount && unReadCount <= targetList.size()) {
                if (visibleCount > 0 && unReadCount > visibleCount) {
                    showLeftSideBar(unReadCount, visibleCount);
                }
            }
        });
        if (!"".equals(mChatInputView.getInputView().getText().toString())) {
            KeyboardUtils.showSoftInput(mChatInputView.getInputView());
        }
    }

    /**
     * 展示左边未读消息提示
     *
     * @param unReadCount  未读数量
     * @param visibleCount 当前界面显示的item数量
     */
    private int finalSmoothPosition;

    private void showLeftSideBar(int unReadCount, int visibleCount) {
        int leftCount = targetList.size() - visibleCount;
        //要滑动到的position
        int smoothPosition = 0;
        //如果未显示的消息 大于未读数量 表示并不是所有的消息都未读
        if (leftCount > unReadCount) {
            smoothPosition = targetList.size() - unReadCount - 1;
            if (smoothPosition < 0) {
                smoothPosition = 0;
            }
            finalSmoothPosition = smoothPosition;

        } else {
            finalSmoothPosition = 0;
        }
        llLeftSidebar.setVisibility(View.VISIBLE);
        tvLeftSidebar.setText(getResources().getString(R.string.jfchat_unread_text, (unReadCount - visibleCount) + ""));
        llLeftSidebar.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                llLeftSidebar.setVisibility(View.GONE);
                chatListView.smoothScrollToPosition(finalSmoothPosition);
            }
        });

    }

    //初始化用户权限
    private void initUserChatPermission() {
        if (chatType == StructFactory.TO_USER_TYPE_PERSONAL) {// 单聊
            /*****************增加聊天权限控制************************/
            String chat_permission = EnvironmentVariable.getProperty("chatpermission", "");
            if (!chat_permission.equals("")) {
                JSONObject chat_permissionJson = null;
                try {
                    chat_permissionJson = new JSONObject(chat_permission);
                    JSONArray chat_permissionJsonArray = chat_permissionJson.getJSONArray("chatPermission");
                    //JsonObject chat_permissionJson = new JsonParser().parse(chat_permission).getAsJsonObject();
                    //JsonArray chat_permissionJsonArray = chat_permissionJson.getAsJsonArray("chatPermission");
                    for (int i = 0; i < chat_permissionJsonArray.length(); i++) {
                        JSONObject jsonObject = (JSONObject) chat_permissionJsonArray.get(i);
                        String userID = jsonObject.getString("userID");
                        if (userID.equals(chatUserId + "")) {
                            current_Chat_permissionType = jsonObject.getString("type");
                            current_Chat_permissionContent = jsonObject.getString("content");
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (current_Chat_permissionType.equals("0")) {
                    mChatInputView.setVisibility(View.GONE);
                }
                mChatInputView.setChatUserInfo(chatUserId, chatType, current_Chat_permissionContent);
            } else {
                mChatInputView.setChatUserInfo(chatUserId, chatType, current_Chat_permissionContent);
            }
            /*****************增加聊天权限控制************************/

        } else {
            mChatInputView.setChatUserInfo(chatUserId, chatType, current_Chat_permissionContent);
        }
    }

    //刷新用户信息
    private void updateChatUser() {
        if (chatType == StructFactory.TO_USER_TYPE_PERSONAL) {
            group = null;
            user = WeChatDBManager.getInstance().getOneUserById(chatUserId, UserEvent.EVENT_CHAT_ACTIVITY);

            toUserNick = user.getReMark();
            toChatUserNickTextView.setText(toUserNick);
            tvGroupUserCount.setVisibility(View.GONE);
            iv_setting.setVisibility(View.VISIBLE);
            iv_chat_add.setVisibility(View.GONE);
            iv_setting_group.setVisibility(View.GONE);

        } else if (chatType == StructFactory.TO_USER_TYPE_OFFICIAL_ACCOUNT) {
            user = new User();
            toChatUserNickTextView.setText(getIntent().getStringExtra("nickName"));
            tvGroupUserCount.setVisibility(View.GONE);

        } else if (chatType == StructFactory.TO_USER_TYPE_GROUP) {
            user = null;
            group = WeChatDBManager.getInstance().getGroupWithUsers(chatUserId);
            tvGroupUserCount.setVisibility(View.VISIBLE);
            tvGroupUserCount.setText("(" + group.getUsers().size() + ")");
            toChatUserNickTextView.setText(group.getGroupName());
            iv_setting_group.setVisibility(View.VISIBLE);
            iv_setting.setVisibility(View.GONE);
            refreshBanSpeak(group);

        }
        if (!isLoadRightTopBtn) {
            iv_setting.setVisibility(View.GONE);
            iv_setting_group.setVisibility(View.GONE);
        }
    }

    private void requestGroupUsers() {
        if (group != null && chatType == StructFactory.TO_USER_TYPE_GROUP) {
            // 从服务器获取群组联系人
            if (!isNetActive()) {
                return;
            }
            //如果map中没有此id，说明本地登陆没有请求过群组成员被数据
            if (SystemInfoService.CHATMAP.containsKey(chatUserId)) {
                return;
            }
            try {
                GetHttpUtil.getGroupUsers(JFChatActivity.this, group.getGroupId(),
                        new GetHttpUtil.ReqCallBack<List<User>>() {
                            @Override
                            public void onReqSuccess(List<User> result) {
                                onGetGroupUserSuccess(result, group.getGroupId());
                            }

                            @Override
                            public void onReqFailed(String errorMsg) {

                            }
                        });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 返回
     *
     * @param view
     */
    @Override
    public void back(View view) {
        onBackPressed();
    }

    @Override
    public void onBackPressed() {
        if (skipByShare || isTaskRoot()) {
            try {
                String className = getResources().getString(R.string.from_group_backto_first);
                Class clazz = Class.forName(className);
                Intent myIntent = new Intent(this, clazz);
                startActivity(myIntent);
                finish();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }

        } else {
            super.onBackPressed();
        }

    }

    public void sendMessage(IMStruct002 struct002) {
        try {
            if (struct002 != null) {
                struct002.setToUserId(chatUserId);
                struct002.setFromUserId(Integer.parseInt(EnvironmentVariable.getProperty(Constants.CHAT_USER_ID)));
                struct002.setToUserType(chatType);
                boolean b = messageManager.sendMessage(struct002);
                messageHandler.sendEmptyMessage(HANDLER_SEND_MSG_REFRESH);
//                chatAdapter.notifyDataSetChanged();
//                chatListView.setSelection(chatListView.getCount() - 1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        initChatObjectInfo(intent);
        initAttr();
        setUpView();
        getChatConfig();
        initShareData(intent);
        //initUserChatPermission();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mChatInputView.getMenuState() == View.VISIBLE) {
                mChatInputView.onBackPressed();
                return true;
            } else {
                onBackPressed();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    //为了解决弹出PopupWindow后外部的事件不会分发,既外部的界面不可以点击
    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        if (mChatInputView != null && mChatInputView.getVoiceRecognitionPopWindowIsShown()) {
            return false;
        }
        return super.dispatchTouchEvent(event);
    }

    /**
     * 初始化分享的数据
     */

    private void initShareData(Intent intent) {
        if (intent.hasExtra("share")) {
            skipByShare = true;
            if (intent.hasExtra("shareImages")) {
                ArrayList<String> shareImageList = intent.getStringArrayListExtra("shareImages");
                if (shareImageList != null) {
                    chatMessageSendManager.sendPicture(shareImageList, false);
                }
            }

        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshUser(UserEvent event) {
        if (event.getEventType() == UserEvent.EVENT_CHAT_ACTIVITY) {
            updateChatUser();
        }
    }


    //处理语音播放显示选择播放方式的弹框
    private String voicePlayType = EnvironmentVariable.getProperty("voicePlayType", "0");

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onVoicePlaying(VoicePlayingEvent event) {
        //语音正在播放时的事件
        if (event.isPlaying()) {
            llVoicePlayTypeLayout.setVisibility(View.VISIBLE);
            llVoicePlayTypeLayout.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if ("0".equals(voicePlayType)) {
                        voicePlayType = "1";
                        tvVoicePlayTypeView.setText(R.string.wrchatview_handfree);
                        ivVoicePlayView.setImageDrawable(getResources().getDrawable(R.drawable.qqstyle_voice_play_type_mainti));
                    } else {
                        voicePlayType = "0";
                        tvVoicePlayTypeView.setText(R.string.wrchatview_earpiece);
                        ivVoicePlayView.setImageDrawable(getResources().getDrawable(R.drawable.qqstyle_voice_play_type_tingtong));

                    }
                    EnvironmentVariable.setProperty("voicePlayType", voicePlayType);
                    ChatVoicePlayClickListener.setPlayType(Integer.valueOf(voicePlayType));
                }
            });
        } else {
            llVoicePlayTypeLayout.setVisibility(View.GONE);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    //播放帧动画的时间
    public void startAnim(AnimationEvent event) {
        final AnimationDrawable drawable = event.getAnimationDrawable();
        if (drawable == null || animFrameLayout.getVisibility() == View.VISIBLE) {
            //如果animFrameLayout 显示，说明正在播放动画，不操作
            return;
        }
        animFrameLayout.setVisibility(View.VISIBLE);
        //animFrameLayout.setBackground(drawable);
        mChatInputView.hideKeyBoardAndMenuContainer();
        final ImageView imageView = animFrameLayout.findViewById(R.id.ivAnimView);
        imageView.setBackground(drawable);
        drawable.start();
        imageView.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (drawable.isRunning()) {
                    drawable.stop();
                }
                animFrameLayout.setVisibility(View.GONE);
                imageView.setBackground(null);
            }
        }, event.getDurationTime());


    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    //点击加密消息事件
    public void secretMessageOnclick(final IMStruct002 imStruct002) {
        showSecretInputView(imStruct002);
    }

    private void showSecretInputView(IMStruct002 imStruct002) {
        mChatInputView.hideKeyBoardAndMenuContainer();
        //点击密图密信 item
        secretInputView.setImstruct(imStruct002);
        secretInputView.setSecrectInputViewListener(new SecretInputView.SecrectInputViewListener() {
            @Override
            public void secretInputViewClose() {
                mChatInputView.setVisibility(View.VISIBLE);
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    //群组禁言系统消息
    public void groupBanSpeak(final GroupBanSpeakEvent event) {
        if (chatType == StructFactory.TO_USER_TYPE_GROUP) {
            if (chatUserId == event.getGroupId()) {
                if (event.getType() == GroupBanSpeakEvent.TYPE_GROUP) {
                    if (event.isBanSpeak()) {
                        //禁言
                        group.setBanSpeak(true);
                    } else {
                        //取消禁言
                        group.setBanSpeak(false);
                    }
                }
                refreshBanSpeak(group);
            }
        }

    }

    //刷新群组禁言
    private void refreshBanSpeak(Group group) {
        if (group != null) {
            if (group.isBanSpeak()) {
                int userType = GroupNameUtil.getOwnerRoleInGroup(group.getGroupId());
                if (userType == User.GROUPCREATOR || userType == User.GROUPMANAGER) {
                    return;
                }
                mChatInputView.setBanSpeak(true, false);
            } else {
                //判断我是否在群里被禁言
                boolean ownerIsBan = GroupNameUtil.judgeOwnerIsBanSpeakInGroup(group.getGroupId());
                if (ownerIsBan) {
                    mChatInputView.setBanSpeak(true, true);
                } else {
                    mChatInputView.setBanSpeak(false, false);
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    //撤回消息刷新界面消息事件
    public void refreshListData(NotifyChatUIRefreshEvent event) {
        if (event.getNotifyType() == NotifyChatUIRefreshEvent.TYPE_DEFAULT) {

            if (event.getParamMap().containsKey("fromUserId")) {
                int fromUserId = (int) event.getParamMap().get("fromUserId");
                byte type = (byte) event.getParamMap().get("chatType");
                if (fromUserId == chatUserId && chatType == type) {
                    //是当前聊天人的消息才会刷新界面
                    chatAdapter.notifyDataSetChanged();
                }
            } else {
                chatAdapter.notifyDataSetChanged();
            }
        } else if (event.getNotifyType() == NotifyChatUIRefreshEvent.TYPE_EXIT
                && event.getChatType() == chatType && event.getChatUserId() == chatUserId) {
            onBackPressed();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    //@消息
    public void addAtUser(AtUserInfoEvent event) {
        User atUser = event.getUser();
        mChatInputView.getmChatInputEditText()
                .insertOneAt("@" + atUser.getNickName(), atUser.getId());
    }

    public void onGetGroupUserSuccess(final List<User> groupUsers, int groupId) {
        Log.i(TAG, "--请求群组联系人成功--");
        SystemInfoService.CHATMAP.put(chatUserId, true);
        Disposable disposable = Observable.create(new ObservableOnSubscribe<Group>() {

            @Override
            public void subscribe(ObservableEmitter<Group> emitter) throws Exception {
                Log.e(TAG, "Observable thread is : " + Thread.currentThread().getName());
                group = WeChatDBManager.getInstance().getGroupWithUsers(chatUserId);
                emitter.onNext(group);
                emitter.onComplete();
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Group>() {
            @Override
            public void accept(final Group group) throws Exception {
                Log.e(TAG, "After observeOn(io)，Current thread is " + Thread.currentThread().getName());

                if (group.getUsers().size() < groupUsers.size()) {
                    group.setUsers(groupUsers);
                }
                refreshBanSpeak(group);
                tvGroupUserCount.setVisibility(View.VISIBLE);
                tvGroupUserCount.setText("(" + group.getUsers().size() + ")");
                toChatUserNickTextView.setText(group.getGroupName());
                final String avatar = group.getAvatar();
                //如果群头像是网络图片就不自动生成了
                if (GroupAvatarUtil.isServerAvatar(avatar)) {
                    return;
                }
                File file = new File(group.getAvatar());

                if (avatar.equals("") || !file.exists()) {
                    List<String> avatars = new ArrayList<>();
                    for (User user : groupUsers) {
                        if (user.getId() == group.getCreateId()) {
                            avatars.add(0, user.getAvatar());
                        } else {
                            avatars.add(user.getAvatar());
                        }
                    }
                    final GroupAvatarHelper helper = new GroupAvatarHelper(JFChatActivity.this);
                    helper.getAvatar(group, avatars, new GroupAvatarHelper.LoadImageListener() {
                        @Override
                        public void loadImageComplete(NineGridImageView view) {
                            if (view == null) {
                                return;
                            }
                            String path = helper.getAvatarPath(view);
                            group.setAvatar(path);
                            WeChatDBManager.getInstance().insertOrUpdateGroup(group);
                        }
                    });
                }
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {

            }
        });


    }

    @Override
    public void netStateChange(int net_state) {
        Log.i(TAG, "netStateChange--监听网络状态--" + net_state);
        if (net_state == 0) {
            //断网
            this.messageHandler.sendEmptyMessage(HANDLER_NETWORK_UNREACHABLE);
        } else {
            //网络已恢复
            this.messageHandler.sendEmptyMessage(HANDLER_NETWORK_RESUME);
        }
    }

  /*  //处理网络监听状态handle
    Handler netStateChangeHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    if (chatType == StructFactory.TO_USER_TYPE_PERSONAL)
//                        toChatUserNickTextView.setText(user.getReMark() + "(网络不可用)");
                        toChatUserNickTextView.setText(user.getReMark());
                    else {
                        tvGroupUserCount.setVisibility(View.VISIBLE);
//                        tvGroupUserCount.setText("(" + group.getUsers().size() + ")" + "(网络不可用)");
                        tvGroupUserCount.setText("(" + group.getUsers().size() + ")");
                        toChatUserNickTextView.setText(group.getGroupName());
                    }
                    break;
                case 1:
                    if (chatType == StructFactory.TO_USER_TYPE_PERSONAL)
                        toChatUserNickTextView.setText(user.getReMark());
                    else {
                        tvGroupUserCount.setVisibility(View.VISIBLE);
                        tvGroupUserCount.setText("(" + group.getUsers().size() + ")");
                        toChatUserNickTextView.setText(group.getGroupName());
                    }

                    break;
                default:
                    break;
            }
            super.handleMessage(msg);
        }
    };*/

    //监听tcp是否可用事件
    @Override
    public void onLoginSuccess() {
        this.messageHandler.sendEmptyMessage(HANDLER_NETWORK_RESUME);
    }

    @Override
    public void onLoginFail(String errorMsg) {

    }

    /**
     * 语音听写发送回调
     *
     * @param content   发送的文本
     * @param voicePath 语音的路径
     */
    @Override
    public void onViceDictateSendListener(String content, String voicePath) {
        chatMessageSendManager.sendVoiceRecognitionMessage(content, voicePath);
    }


    private class ChatListViewOnTouchListener implements View.OnTouchListener {

        private long chatListViewTouchMoveTime;
        private int chatListViewDownY;
        private int chatListViewDownYSlop;

        public ChatListViewOnTouchListener() {
            chatListViewDownYSlop = (int) (5 * getResources().getDisplayMetrics().density);
        }

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:

                    chatListViewDownY = (int) event.getY();
                    mChatInputView.hideKeyBoardAndMenuContainer();
                    break;
//                case MotionEvent.ACTION_UP:
//                    v.performClick();
//                    break;
//                case MotionEvent.ACTION_MOVE:
//                    //触发下拉事件，每0.5秒执行一次
//                    if (event.getY() - chatListViewDownY > chatListViewDownYSlop && System.currentTimeMillis() - chatListViewTouchMoveTime > 500) {
//                        Log.e("==", "=====每0.5秒执行一次：" + event.getAction());
//                        tryLoadHistoryMessage();
//                        chatListViewTouchMoveTime = System.currentTimeMillis();
//                    }
//                    break;

                default:
                    break;
            }
            return false;
        }
    }

    private void tryLoadHistoryMessage() {
        View topView = chatListView.getChildAt(0);
        if (chatListView.getFirstVisiblePosition() == 0 && topView != null && topView.getTop() == 0
                && loadmorePB.getVisibility() != View.VISIBLE) {
            Log.e("==", "加载更多--onScroll==firstVisibleItem：" + topView.getTop());
            //1.先显示ProgressBar
            //  loadmorePB.setVisibility(View.VISIBLE);
            Disposable disposable = Observable.create(new ObservableOnSubscribe<List<IMStruct002>>() {
                @Override
                public void subscribe(ObservableEmitter<List<IMStruct002>> emitter) throws Exception {
                    List<IMStruct002> historyImStruct002s = chatListManager.getHistoryMessage(chatType, user,
                            messageManager, group, messageList.get(0).getMessageID(), 20, null);
                    chatListManager.solveUnRead(messageList, historyImStruct002s);
                    emitter.onNext(historyImStruct002s);
                    emitter.onComplete();
                }
            }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<List<IMStruct002>>() {
                        @Override
                        public void accept(List<IMStruct002> imStruct002s) throws Exception {
                            Message message = messageHandler.obtainMessage();
                            message.what = HANDLER_LOAD_MORE_REFRESH;
                            message.arg1 = imStruct002s.size();
                            messageHandler.sendMessage(message);
//                            chatAdapter.notifyDataSetChanged();
//                            int historyMessageCount = imStruct002s.size();
//                            chatListView.setSelection(historyMessageCount - 1);
//                            //3.隐藏显示ProgressBar
//                            loadmorePB.setVisibility(View.GONE);
//                            smartRefreshLayout.finishRefresh();
                        }
                    }, new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) throws Exception {
                            Log.e(TAG, "accept: " + throwable.getMessage());
                            loadmorePB.setVisibility(View.GONE);
                            smartRefreshLayout.finishRefresh(100);
                            ToastUtil.showToast(AppContext.getInstance(), R.string.wrchatview_get_history_fail);
                        }
                    });


        } else {
            loadmorePB.setVisibility(View.GONE);
            smartRefreshLayout.finishRefresh(100);
        }
    }

    //todo 各种回调 ，点击按钮 录音，拍照

    //预发送回调
    ChatSenderFragment.PreSendMessageCallback preSendMessageCallback = new ChatSenderFragment.PreSendMessageCallback() {
        @Override
        public void preSendMessage(IMStruct002 struct002) {
            if (struct002 != null) {
                struct002.setToUserId(chatUserId);
                struct002.setFromUserId(Integer.parseInt(EnvironmentVariable.getProperty(Constants.CHAT_USER_ID)));
                struct002.setToUserType(chatType);
                struct002.putExtra("progress", 0);
                struct002.putExtra("startUploadTime", System.currentTimeMillis());
                messageManager.preSendMessage(struct002);
                messageHandler.sendEmptyMessage(HANDLER_SEND_MSG_REFRESH);
//                chatAdapter.notifyDataSetChanged();
//                chatListView.setSelection(chatListView.getCount() - 1);
            }
        }

        @Override
        public void updateProgress(IMStruct002 struct002, double percent) {
            if (percent == -1.0d) {
                JFMessageManager.getInstance().updateMessage(struct002);
            }
            chatAdapter.notifyDataSetChanged();
        }

        @Override
        public void sendPreMessage(final IMStruct002 struct002) {
            if (struct002 != null) {
                messageManager.sendPreMessage(struct002);
                Log.i(TAG, "发送 ------ sendPreMessage:" + struct002.toString());
            }
        }
    };


    @Override
    public void recordFinish(int time, File file) {
        //录音完成
        chatMessageSendManager.sendVoiceMesage(time, file);

    }

    @Override
    public boolean onSendTextMessage(CharSequence input) {
        if (input.length() == 0) {
            return false;
        }
        IMStruct002 struct002 = TextFormatMessageUtil.getSendTextImStruct(input, chatType);
        sendMessage(struct002);
        return true;
    }

    @Override
    public boolean onSendStruct002Message(IMStruct002 imStruct002) {
        sendMessage(imStruct002);
        return true;
    }

    @Override
    public void onSendFiles(List<String> mSelectedPics, boolean isRawPic) {
        //发送按钮发送图片
        chatMessageSendManager.sendPicture(mSelectedPics, isRawPic);
    }

    @Override
    public boolean switchToMicrophoneMode() {
        if (EasyPermissionUtils.checkAudioPermission()) {
            return true;
        } else {
            EasyPermissionUtils.requestAudioPermission(this);
            return false;
        }
    }

    @Override
    public boolean switchToGalleryMode() {
        return true;
    }

    @Override
    public boolean switchToCameraMode() {
        if (EasyPermissionUtils.checkCameraPermission()) {
            return true;
        } else {
            EasyPermissionUtils.requestCameraPermission(this);
            return false;
        }
    }

    @Override
    public boolean switchToEmojiMode() {
        return true;
    }

    @Override
    public void onSendShakeAnim(String name) {
        //抖动动画
        IMStruct002 imStruct002 = StructFactory.getInstance().createShakeImstruct002(name);
        if (imStruct002 != null) {
            //播放动画
            AnimationFactory.startAnimFromIMStruct(JFChatActivity.this, imStruct002);
            sendMessage(imStruct002);
        }
    }

    @Override
    public void clickMoreMenuItem(ChatMenuModel model) {
        //更多中的菜单被点击
        interfaceSkipManager.setChatType(chatType);
        interfaceSkipManager.setCurrentChatUserId(chatUserId);
        interfaceSkipManager.onChatMenuClick(model);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == ChatInputView.REQUEST_CODE_CAMERA) {
            // 相机拍摄的照片
            File cameraFile = mChatInputView.getTakePictureFile();
            chatMessageSendManager.sendPicture(cameraFile);
        } else if (resultCode == RESULT_FIRST_USER && requestCode == 0) {
            User selectUser = (User) data.getSerializableExtra("selectUser");
            String selectUserName = selectUser.getNickName();
            int selectId = selectUser.getId();
            mChatInputView.getmChatInputEditText()
                    .insertSpecialStr("@" + selectUserName, true, 1, null, selectId);
//            mChatInputView.mChatInputEditText.getSpDatas()
        } else {
            chatMessageSendManager.onActivityResult(requestCode, resultCode, data);
        }
    }


    private static class MessageHandler extends Handler {
        private WeakReference<JFChatActivity> weakReference;
        // private long endTime;

        public MessageHandler(JFChatActivity activity) {
            weakReference = new WeakReference<JFChatActivity>(activity);
        }

        @Override
        public synchronized void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (weakReference == null) {
                return;
            }
            JFChatActivity activity = weakReference.get();
            if (activity == null) {
                return;
            }
            switch (msg.what) {
                case HANDLER_UPDATE_MSG_STATE:
                    if (activity != null && activity.chatAdapter != null) {
                        // activity.chatListView.setVisibility(View.GONE);
                        // activity.chatListView.requestLayout();
                        refreshChatList(activity);
                        //activity.chatListView.setVisibility(View.VISIBLE);
                        if (activity.chatListView.getLastVisiblePosition() == activity.chatListView.getCount() - 2) {
                            activity.chatListView.setSelection(activity.chatListView.getCount() - 1);
                        } else {
                            Log.i(TAG, "不滚动到最后一条-------");
                        }
                    }
                    break;
                case HANDLER_SEND_MSG_REFRESH:
                    refreshChatList(activity);
                    activity.chatListView.setSelection(activity.chatListView.getCount() - 1);
                    break;
                case HANDLER_LOAD_MORE_REFRESH:
                    refreshChatList(activity);
                    activity.chatListView.setSelection(msg.arg1 - 1);
                    //3.隐藏显示ProgressBar
                    activity.loadmorePB.setVisibility(View.GONE);
                    activity.smartRefreshLayout.finishRefresh();
                    break;
                case HANDLER_NETWORK_UNREACHABLE:
                    //网络已中断
                    if (activity.chatType == StructFactory.TO_USER_TYPE_PERSONAL) {
//                        toChatUserNickTextView.setText(user.getReMark() + "(网络不可用)");
                        activity.toChatUserNickTextView.setText(activity.user.getReMark());
                    } else {
                        activity.tvGroupUserCount.setVisibility(View.VISIBLE);
//                        tvGroupUserCount.setText("(" + group.getUsers().size() + ")" + "(网络不可用)");
                        activity.tvGroupUserCount.setText("(" + activity.group.getUsers().size() + ")");
                        activity.toChatUserNickTextView.setText(activity.group.getGroupName());
                    }
                    break;
                case HANDLER_NETWORK_RESUME:
                    //网络已恢复
                    if (activity.chatType == StructFactory.TO_USER_TYPE_PERSONAL) {
                        activity.toChatUserNickTextView.setText(activity.user.getReMark());
                    } else {
                        activity.tvGroupUserCount.setVisibility(View.VISIBLE);
                        activity.tvGroupUserCount.setText("(" + activity.group.getUsers().size() + ")");
                        activity.toChatUserNickTextView.setText(activity.group.getGroupName());
                    }
                    break;
                case HANDLER_SEND_INPUTTING_MSG:
                    //正在输入 chatmessagelistener 会发送这个
                    boolean isInputting = (boolean) msg.obj;
                    String titleText = null;
                    //先移除取消的消息
                    this.removeMessages(HANDLER_CANCEL_INPUTTING_MSG);
                    if (isInputting) {
                        activity.toChatUserNickTextView.setText(R.string.wechatview_other_be_inputting);
                        // endTime = System.currentTimeMillis() + 6 * 1000;
                        this.sendEmptyMessageDelayed(HANDLER_CANCEL_INPUTTING_MSG, 6 * 1000);
                    } else {
                        if (activity.chatType == StructFactory.TO_USER_TYPE_PERSONAL) {
                            activity.toChatUserNickTextView.setText(activity.user.getReMark());
                        }
                    }
                    break;
                case HANDLER_CANCEL_INPUTTING_MSG:
                    //6中发送的取消正在输入
                    // if (System.currentTimeMillis() >= endTime && activity.chatType == StructFactory.TO_USER_TYPE_PERSONAL) {
                    if (activity.chatType == StructFactory.TO_USER_TYPE_PERSONAL) {
                        activity.toChatUserNickTextView.setText(activity.user.getReMark());
                    }
                    break;
                default:
                    break;
            }
        }
    }

    private static void refreshChatList(JFChatActivity activity) {
        activity.targetList.clear();
        activity.targetList.addAll(activity.messageList);
        activity.chatAdapter.notifyDataSetChanged();
    }
}
