package com.efounder.chat.publicnumber;

import android.annotation.SuppressLint;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.AnimationDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowInsets;
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 androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;

import com.efounder.chat.R;
import com.efounder.chat.activity.ChatGroupSettingActivity;
import com.efounder.chat.activity.PublicNumerInfoActivity;
import com.efounder.chat.adapter.ChatVoicePlayClickListener;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.event.NotifyChatUIRefreshEvent;
import com.efounder.chat.fragment.ChatSenderFragment;
import com.efounder.chat.handler.ChatMessageListener;
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.Group;
import com.efounder.chat.model.GroupRootBean;
import com.efounder.chat.model.UpdateBadgeViewEvent;
import com.efounder.chat.model.VoicePlayingEvent;
import com.efounder.chat.service.MessageService;
import com.efounder.chat.struct.StructFactory;
import com.efounder.chat.utils.ImageUtil;
import com.efounder.chat.utils.TextFormatMessageUtil;
import com.efounder.chat.utils.VoiceRecognitionSoundFileCacheUtil;
import com.efounder.chat.widget.ChatListView;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.form.comp.shoppingcar.ShoppingUtils;
import com.efounder.frame.activity.EFTransformFragmentActivity;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.frame.bean.FilterBean;
import com.efounder.frame.utils.Constants;
import com.efounder.message.db.MessageDBManager;
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.util.AbFragmentManager;
import com.efounder.util.EnvSupportManager;
import com.efounder.utils.ApplyWindowInsetsUtil;
import com.efounder.utils.EasyPermissionUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

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 java.util.Map;
import java.util.concurrent.Executors;

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 android.content.Context.NOTIFICATION_SERVICE;
import static com.efounder.frame.utils.NetStateBroadcastReceiver.isNetActive;

/**
 * 应用号聊天fragment
 *
 * @author hudq
 */
@SuppressLint("ClickableViewAccessibility")
public class JFPublicChatFragment extends BaseFragment implements
        OnMenuClickListener, VoiceView.MyRecordVoiceListener,
        MessageService.MessageServiceNetStateListener,
        MessageService.MessageServiceLoginListener, VoiceDictateSendListener {
    public static final String TAG = "JFPublicChatFragment";

    /**
     * 从数据库查询过滤后消息的起始位置;
     */
    private int filterMessageStart = 0;
    /**
     * 判断数据库是否还有更多的消息;
     */
    boolean hasMoreFilterMessage = true;


    /**
     * 进入展示过滤消息的时段
     */

    private boolean isFiltering = false;

    //聊天权限String
    private String current_Chat_permissionType = "";
    private String current_Chat_permissionContent = "";
    /**
     * 每次展示过滤数据的item数量
     */
    private final int FILTER_MESSAGE_COUNT = 8;
    //聊天文件路径
    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 = StructFactory.TO_USER_TYPE_PERSONAL;
    public JFPublicChatFragment 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 JFMessageManager messageManager;
    //消息监听
    private JFMessageListener messageListener;
    private Handler messageHandler = new MessageHandler(this);
    //消息列表
    List<IMStruct002> messageList;

    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;


    //消息发送管理
    private ChatMessageSendManager chatMessageSendManager;
    //更多菜单界面跳转管理
    private ChatInterfaceSkipManager interfaceSkipManager;

    //标记是否触发滚动到最后
    private boolean isScrollLast = false;

    private RefreshChatBroadcastReceive refreshChatBroadcastReceive = new RefreshChatBroadcastReceive();


    /**
     * 用户展示过滤消息的Adapter;
     */
    private JFChatAdapter filterChatAdapter;
    private List<IMStruct002> filterMessages;
    private String sql;
    private ImageView filterImageView;


    private static class MessageHandler extends Handler {
        private WeakReference<JFPublicChatFragment> weakReference;

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

        @Override
        public synchronized void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (weakReference == null) {
                return;
            }
            JFPublicChatFragment activity = weakReference.get();
            if (activity == null) {
                return;
            }
            switch (msg.what) {
                case 1:
                    if (activity != null && activity.chatAdapter != null) {
                        // activity.chatListView.setVisibility(View.GONE);
                        activity.chatListView.requestLayout();
                        activity.chatAdapter.notifyDataSetChanged();
                        //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 2:
                    activity.chatAdapter.notifyDataSetChanged();
                    activity.chatListView.setSelection(activity.chatListView.getCount() - 1);
                    break;
                case 3:
                    Bundle bundle = msg.getData();
                    if (bundle != null && bundle.containsKey("historyMessageCount")) {
                        int historyMessageCount = bundle.getInt("historyMessageCount");
                        activity.chatAdapter.notifyDataSetChanged();
                        activity.chatListView.setSelection(historyMessageCount - 1);
                    }
                    //3.隐藏显示ProgressBar
                    activity.loadmorePB.setVisibility(View.GONE);
                    break;
                case 4:
//                    activity.toChatUserNickTextView.setText(activity.user.getReMark() + ResStringUtil.getString(R.string.wrchatview_network_unavailable));
                    //暂时去掉网络不可用的标题
                    activity.toChatUserNickTextView.setText(activity.user.getReMark());


                    break;
                case 5:
                    if (activity.getContext() == null) {
                        return;
                    }
                    activity.toChatUserNickTextView.setText(activity.getActivity().getIntent().getStringExtra
                            ("nickName"));

                    break;
                default:
                    break;
            }
        }
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
            savedInstanceState) {
        View view = inflater.inflate(R.layout.wechatview_jffragment_public_chat, container, false);
        initView(view);
        initChatObjectInfo(getActivity().getIntent());
        initAttr();
        setUpView();

        //initUserChatPermission();

        MessageService.addMessageServiceLoginListener(this);
        MessageService.addMessageServiceNetStateListener(this);

        ApplyWindowInsetsUtil.setApplyWindowInsets(view.findViewById(R.id.ll_input));
        return view;
    }



    @Override
    public void onStart() {
        super.onStart();
        Log.i("---------", "onStart-----------注册刷新聊天列表广播");
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ShoppingUtils.BROADCAST_ACTION_REFRESH_CHAT); //为BroadcastReceiver指定action，即要监听的消息名字。
        getContext().registerReceiver(refreshChatBroadcastReceive, intentFilter); //注册监听
    }

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

        // 判断是否显示网络不可用
        if (!isNetActive() || !JFMessageManager.isChannelActived()) {
//            toChatUserNickTextView.setText(user.getReMark() + ResStringUtil.getString(R.string.wrchatview_network_unavailable));
            toChatUserNickTextView.setText(user.getReMark());

        }

        resumeFilterImageView();
        chatAdapter.notifyDataSetChanged();
        if (!EnvSupportManager.supportOfficialChatInput()) {
            mChatInputView.setVisibility(View.GONE);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        //清除掉保存的未读@消息提醒
        //TextFormatMessageUtil.clearMentionHintEV(chatUserId+"", chatType+"");
        JFMessageManager.getInstance().clearAtMe(chatUserId, chatType);
        hiddenFilterImageView();
        chatListManager.clearunReadCount(chatUserId, chatType);
        // EventBus.getDefault().post(new UpdateBadgeViewEvent(chatUserId + "", chatType));
        EventBus.getDefault().post(new UpdateBadgeViewEvent(user.getId() + "", (byte) 2));
        //停止语音播放
        if (ChatVoicePlayClickListener.currentPlayListener != null && ChatVoicePlayClickListener.isPlaying) {
            ChatVoicePlayClickListener.currentPlayListener.stopPlayVoice();
            //隐藏播放方式的view
            llVoicePlayTypeLayout.setVisibility(View.GONE);
        }
        //这个地方清空一下回调的map
        ChatVoicePlayClickListener.clearCallBacks();
        //使用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);
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.i("---------", "onStop-----------取消刷新聊天列表广播");
        getContext().unregisterReceiver(refreshChatBroadcastReceive); //取消监听

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        MessageService.removeMessageServiceLoginListener(this);
        MessageService.removeMessageServiceNetStateListener(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (messageListener != null) {
            messageManager.removeMessageListener(TAG, messageListener);
        }

        //如果可以，请在chatListManager中释放资源
        chatListManager.release(activityInstance);
        chatMessageSendManager.release();
        ChatStyleFactory.clear();
        activityInstance = null;
        chatAdapter.removeDownLoadListener();
        EventBus.getDefault().unregister(this);
        //释放波形图缓存
        VoiceRecognitionSoundFileCacheUtil.clearMessageList();
        chatListView.setOnTouchListener(null);
        //释放一些其他资源
        mChatInputView.release();


    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    //撤回消息刷新界面消息事件
    public void refreshListData(NotifyChatUIRefreshEvent event) {
        chatAdapter.notifyDataSetChanged();
    }

    //初始化用户权限
    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);
        }
    }

    /**
     * 过滤原则,尽量不动原先的代码
     * 使用单独的listview来存储过滤出来的消息
     * 设置单独的的Adapter,使用完过滤功能后直接给聊天listview设置成之前的adapter即可
     *
     * @param bean
     */


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void executeFilter(FilterBean bean) {

        if (bean.type == 1) {
            initDataForFilterMessage();
            Log.e(TAG, "execute: " + bean.content);
            sql = bean.content + " limit " + filterMessageStart + "," + FILTER_MESSAGE_COUNT + ";";
//            sql = "select * from Message where hex(body) like '%" + bill16 + "%'" + " limit " + filterMessageStart + "," + FILTER_MESSAGE_COUNT + ";";
            List<IMStruct002> result = loadFilterMessage();
            filterMessages.addAll(result);

            if (filterChatAdapter == null) {
                filterChatAdapter = new JFChatAdapter(getActivity(), chatListView, filterMessages);
            }
            chatListView.setAdapter(filterChatAdapter);

            chatListView.setSelection(filterChatAdapter.getCount() - 1);
        } else {
            //恢复为未过滤装填
            if (isFiltering) {
                resetStatetoChat();
                chatListView.setAdapter(chatAdapter);
            }
        }

    }

    private void initDataForFilterMessage() {


        isFiltering = true;
        filterMessageStart = 0;
        hasMoreFilterMessage = true;
        if (filterMessages == null) {
            filterMessages = new ArrayList<IMStruct002>();

        } else {
            filterMessages.clear();
        }
    }


    /**
     * 将状态调整的正常的状态,即聊天的正常状态
     */
    public void resetStatetoChat() {

        //不再是过滤时态
        isFiltering = false;

        filterMessageStart = 0;
    }


    /**
     * 去数据库加载数据F
     *
     * @return 加载的数据, 如果到最后则返回空
     */
    public List<IMStruct002> loadFilterMessage() {

        if (!hasMoreFilterMessage) {
            return null;
        }
//        MessageDBHelper dbHelper = new MessageDBHelper(AppContext.getCurrentActivity());
//        MessageDBManager dbManager = new MessageDBManager(dbHelper);
        MessageDBManager dbManager = MessageDBManager.getInstance();

        List<IMStruct002> result = dbManager.query(sql);
        if (result.size() < FILTER_MESSAGE_COUNT) {
            hasMoreFilterMessage = false;

        }
        //说明此时数据库可能还有更多的消息

        filterMessageStart += FILTER_MESSAGE_COUNT;

        return result;

    }


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

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

    }

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


    }

    /**
     * initView
     */
    protected void initView(View view) {
        mChatInputView = (ChatInputView) view.findViewById(R.id.chat_input);
        secretInputView = (SecretInputView) view.findViewById(R.id.secret_inut);
        //必须设置
        mChatInputView.setMyRecordVoiceListener(this);
        //设置按钮回调
        mChatInputView.setMenuClickListener(this);
        //设置语音识别回调
        mChatInputView.setVoiceDictateSendListener(this);

        chatListView = (ChatListView) view.findViewById(R.id.list);
        chatListView.setOnTouchListener(new ChatListViewOnTouchListener());
        loadmorePB = (ProgressBar) view.findViewById(R.id.pb_load_more);
        toChatUserNickTextView = ((TextView) view.findViewById(R.id.name));
        animFrameLayout = (FrameLayout) view.findViewById(R.id.framelayout_anim);
        llVoicePlayTypeLayout = (LinearLayout) view.findViewById(R.id.ll_voice_play_style);
        ivVoicePlayView = (ImageView) view.findViewById(R.id.iv_voice_playtype);
        tvVoicePlayTypeView = (TextView) view.findViewById(R.id.tv_voice_type);
        smartRefreshLayout = (SmartRefreshLayout) view.findViewById(R.id.refreshLayout);
        iv_setting = (ImageView) view.findViewById(R.id.iv_setting);
        iv_setting_group = (ImageView) view.findViewById(R.id.iv_setting_group);
        iv_chat_add = (ImageView) view.findViewById(R.id.iv_chat_add);
        llMenu = (LinearLayout) view.findViewById(R.id.ll_chat_menu);
        tvGroupUserCount = (TextView) view.findViewById(R.id.group_count);
    }

    private void setUpView() {
        activityInstance = this;
        //设置草稿文字
        mChatInputView.getInputView().setText(EnvironmentVariable.getProperty(chatUserId + "" + chatType));
        mChatInputView.SetFragment(this);
        //设置语音播放方式的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(getActivity(), PublicNumerInfoActivity.class);
                intent.putExtra("id", chatUserId);
                intent.putExtra("publicchatfragment", "true");
                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(getActivity(),
                        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) {

                if (isFiltering) {
                    tryLoadFilterMessage();
                } else {

                    tryLoadHistoryMessage();

                }

            }
        });
        setupChatListView();
    }

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

    //处理语音播放显示选择播放方式的弹框
    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);
            }
        });
    }


    //刷新用户信息
    private void updateChatUser() {
        if (chatType == StructFactory.TO_USER_TYPE_PERSONAL) {
            user = WeChatDBManager.getInstance().getOneUserById(chatUserId);
            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(getActivity().getIntent().getStringExtra("nickName"));
            tvGroupUserCount.setVisibility(View.GONE);

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

    private void setupChatListView() {
        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));
            }

        }
        chatAdapter = new JFChatAdapter(getActivity(), chatListView, messageList);
        chatListView.setAdapter(chatAdapter);
        chatListView.setSelection(chatListView.getCount() - 1);
    }


    private void resumeFilterImageView() {

//        List<StubObject> stubListByElementName = EFAppAccountRegistry.getStubListByElementName(EFXmlConstants.FILTER_MODULE);
//        if (stubListByElementName != null && stubListByElementName.size() > 0) {
        if (EnvSupportManager.isSupportSearchMessage()) {
            FragmentActivity activity = getActivity();
            if (activity instanceof EFTransformFragmentActivity) {
                filterImageView = ((EFTransformFragmentActivity) activity).getEFTitleView().getFilterImageView();
                if (filterImageView != null) {
                    filterImageView.setVisibility(View.VISIBLE);

                }
            }

        }
    }


    public void sendMessage(IMStruct002 struct002) {
        try {
            if (struct002 != null) {
                // FIXME 测试发送文本
                struct002.setToUserId(chatUserId);
                struct002.setFromUserId(Integer.parseInt(EnvironmentVariable.getProperty(Constants.CHAT_USER_ID)));
                Log.i("PublicChatFragment--", EnvironmentVariable.getProperty(Constants.CHAT_USER_ID));
                struct002.setToUserType((byte) 0);
                boolean b = messageManager.sendMessage(struct002);
                Log.i(TAG, "发送 ------ sendMessage:" + struct002.toString());
                messageHandler.sendEmptyMessage(2);
//                chatAdapter.notifyDataSetChanged();
//                chatListView.setSelection(chatListView.getCount() - 1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//    @Override
//    public void preSendMessage(IMStruct002 struct002) {
//        if (struct002 != null) {
//            struct002.setToUserId(id);
//            struct002.setFromUserId(Integer.parseInt(EnvironmentVariable
//                    .getProperty(Constants.CHAT_USER_ID)));
//            struct002.putExtra("progress", 0);
//            messageManager.preSendMessage(struct002);
//            chatAdapter.notifyDataSetChanged();
//            chatListView.setSelection(chatListView.getCount() - 1);
//        }
//    }
//
//    @Override
//    public void updateProgress(IMStruct002 struct002, double percent) {
//        chatAdapter.notifyDataSetChanged();
//    }
//
//    @Override
//    public void sendPreMessage(final IMStruct002 struct002) {
//        if (struct002 != null) {
//
//            new AsyncTask<IMStruct002, Integer, String>() {
//
//                @Override
//                protected String doInBackground(IMStruct002... params) {
//                    try {
//                        messageManager.sendPreMessage(struct002);
//                        Log.i(TAG, "发送 ------ sendPreMessage:" + struct002.toString());
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//
//                    return null;
//                }
//            }.execute(struct002);
//        }
//
//    }


//    @Override
//    public void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        Log.i(TAG, TAG + "-----------requestCode:" + requestCode
//                + ",resultCode" + resultCode);
//    }


    @Subscribe
    public void onOperationMessageEvent(Map<String, Object> event) {
//        event.put("cmd","delete");
//        event.put("position",position);
        String cmd = (String) event.get("cmd");
        if ("delete".equals(cmd)) {
            int position = (int) event.get("position");
            IMStruct002 message = messageList.get(position);
            JFMessageManager.getInstance().removeMessage(message);
        } else if ("scrollLast".equals(cmd)) {
            //刷新界面，滚动到最后一条
            isScrollLast = true;
        }
    }


    private void hiddenFilterImageView() {
        Log.e(TAG, "onPause:------------ddmj ");
        if (filterImageView != null) {
            Log.e(TAG, "onPause:------------mj ");

            filterImageView.setVisibility(View.GONE);
        }
    }


    @Override
    public void netStateChange(int net_state) {
        Log.i(TAG, "netStateChange--监听网络状态--" + net_state);
        if (net_state == 0) {
            Message message = new Message();
            message.what = 4;
            this.messageHandler.sendMessage(message);
        } else {
            Message message = new Message();
            message.what = 5;

            this.messageHandler.sendMessage(message);
        }
    }

 /*   //处理网络监听状态handle
    Handler netStateChangeHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    toChatUserNickTextView.setText(toChatUserNickTextView.getText() + "(网络不可用)");
                    break;
                case 1:
                    if (getContext() == null) {
                        return;
                    }
                    toChatUserNickTextView.setText(getActivity().getIntent().getStringExtra
                            ("nickName"));

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

    //监听tcp是否可用事件
    @Override
    public void onLoginSuccess() {
        Message message = new Message();
        message.what = 5;

        this.messageHandler.sendMessage(message);
    }

    @Override
    public void onLoginFail(String errorMsg) {

    }

    private class RefreshChatBroadcastReceive extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.i("---------", "BroadcastReceiver-----------接收到广播：action=" + action);
            if (ShoppingUtils.BROADCAST_ACTION_REFRESH_CHAT.equals(action)) { //判断是否接收到广播
                //刷新聊天列表
                chatAdapter.notifyDataSetChanged();
            }
        }
    }


    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;

                default:
                    break;
            }
            return false;
        }


    }


    /***
     * 分页加载更多的过滤后的消息
     */
    private void tryLoadFilterMessage() {
        if (!hasMoreFilterMessage) {
            //如果没有数据直接返回;
            return;
        }

        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);
            new AsyncTask<String, Integer, List<IMStruct002>>() {

                @Override
                protected List<IMStruct002> doInBackground(String... params) {
                    List<IMStruct002> filterImStruct002s = loadFilterMessage();
                    return filterImStruct002s;
                }

                @Override
                protected void onPostExecute(List<IMStruct002> imStruct002s) {
                    super.onPostExecute(imStruct002s);
                    //隐藏进度条
                    loadmorePB.setVisibility(View.GONE);
                    if (imStruct002s == null) {
                        return;
                    }
                    filterMessages.addAll(imStruct002s);
                    filterChatAdapter.notifyDataSetChanged();
                    int count = imStruct002s.size();
                    chatListView.setSelection(count - 1);
                    smartRefreshLayout.finishRefresh();
                }
            }.executeOnExecutor(Executors.newCachedThreadPool());

        }


    }

    //    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);
//            new AsyncTask<String, Integer, List<IMStruct002>>() {
//
//                @Override
//                protected List<IMStruct002> doInBackground(String... params) {
//                    List<IMStruct002> historyImStruct002s = chatListManager.getHistoryMessage(StructFactory.TO_USER_TYPE_OFFICIAL_ACCOUNT, user, messageManager, null, messageList.get(0).getMessageID(), 20, null);
//                    chatListManager.solveUnRead(messageList, historyImStruct002s);
//                    return historyImStruct002s;
//                }
//
//                @Override
//                protected void onPostExecute(List<IMStruct002> imStruct002s) {
//                    super.onPostExecute(imStruct002s);
//                    chatAdapter.notifyDataSetChanged();
//                    int historyMessageCount = imStruct002s.size();
//                    chatListView.setSelection(historyMessageCount - 1);
//                    //3.隐藏显示ProgressBar
//                    loadmorePB.setVisibility(View.GONE);
//                }
//            }.executeOnExecutor(Executors.newCachedThreadPool());
//
//        }
//    }
    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 {
                            chatAdapter.notifyDataSetChanged();
                            int historyMessageCount = imStruct002s.size();
                            chatListView.setSelection(historyMessageCount - 1);
                            //3.隐藏显示ProgressBar
                            loadmorePB.setVisibility(View.GONE);
                            smartRefreshLayout.finishRefresh();
                        }
                    });


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

    //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);
                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 = StructFactory.getInstance().createTextStruct(input.toString(), chatType);
        sendMessage(struct002);
        return true;
    }

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

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

    @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(getActivity(), imStruct002);
            sendMessage(imStruct002);
        }
    }

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


    @Override
    public 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 {
            chatMessageSendManager.onActivityResult(requestCode, resultCode, data);
        }
    }
}
