package com.rv.im;

import android.Manifest;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.base.BaseStatusActivity;
import com.ruiwenliu.wrapper.base.presenter.CommonPresenter;
import com.ruiwenliu.wrapper.util.permission.RxPermission;
import com.ruiwenliu.wrapper.weight.TitleView;
import com.ruiwenliu.wrapper.weight.refresh.SimpleRefreshLayout;
import com.ruiwenliu.wrapper.weight.refresh.SimpleRefreshView;
import com.rv.component.utils.CacheEnum;
import com.rv.component.utils.RvCache;
import com.rv.im.adapter.ChatContentAdapter;
import com.rv.im.audio.IMRecordController;
import com.rv.im.audio.RecordListener;
import com.rv.im.audio_x.VoicePlayer;
import com.rv.im.bean.User;
import com.rv.im.db.service.ChatMessageServiceImp;
import com.rv.im.db.table.ChatMessage;
import com.rv.im.enums.MessageStatusEnum;
import com.rv.im.enums.MessageTypeEnum;
import com.rv.im.mucfile.RvDownManager;
import com.rv.im.mucfile.XfileUtils;
import com.rv.im.mvp.presenter.ChatPresenterImp;
import com.rv.im.mvp.presenter.IChatPresenter;
import com.rv.im.mvp.view.IChatView;
import com.rv.im.photopicker.PhotoPickerActivity;
import com.rv.im.util.FileUtils;
import com.rv.im.util.InputManager;
import com.rv.im.util.RvImTimerTask;
import com.rv.im.video.ChatVideoPreviewActivity;
import com.rv.im.view.ChatFaceView;
import com.rv.im.xmpp.ListenerManager;
import com.rv.im.xmpp.listener.ChatMessageListener;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;

import pub.devrel.easypermissions.AppSettingsDialog;

public class ChatActivity extends BaseStatusActivity<CommonPresenter> implements IChatView, ChatMessageListener, View.OnClickListener, RecordListener, SimpleRefreshLayout.OnSimpleRefreshListener {

    private ImageButton voiceImgBtn;
    private ImageButton ibKeyword;
    private EditText chatEdit;
    private TextView recordBtn;
    private ImageButton emotionBtn; // 表情
    private ImageButton ibPhoto;
    private Button sendBtn;
    private RecyclerView recycleContent;
    private SimpleRefreshLayout refreshLayout;
    private ViewStub mChatFaceViewStub;

    private String mLoginUserId;
    private List<ChatMessage> messages = new ArrayList<>();
    private ChatContentAdapter adapter;
    private IMRecordController mRecordController;
    private IChatPresenter presenter;
    private ChatFaceView mChatFaceView;
    private Handler mHandler = new Handler();

    private String targetUserId;
    private String targetName;
    private int customerStatus;

    private Timer timer;
    private RvImTimerTask timerTask;

    private ChatContentAdapter.OnClickItemListener clickItemListener = new ChatContentAdapter.OnClickItemListener() {
        @Override
        public void onClick(int resId, ChatMessage message) {
            if (message.getMessageType() == MessageTypeEnum.PIC.getType()) {
                Intent intent = new Intent(getApplicationContext(), SingleImagePreviewActivity.class);
                intent.putExtra(Constants.EXTRA_IMAGE_URI, message.getContent());
                intent.putExtra("image_path", message.getFilePath());
                startActivity(intent);
            } else if (message.getMessageType() == MessageTypeEnum.FILE.getType()) {
                onShowLoading();
                if (!TextUtils.isEmpty(message.getFilePath())) {
                    File file = new File(message.getFilePath());
                    if (file.exists()) {
                        onHideLoading();
                        open(message);
                    } else {
                        // 下载 文件
                        if (!TextUtils.isEmpty(message.getContent()))
                            RvDownManager.instance().download(message, new RvDownManager.DownListener() {
                                @Override
                                public void downSuccess() {
                                    runOnUiThread(() -> {
                                        onHideLoading();
                                        ChatMessageServiceImp.getInstance(getApplicationContext()).addMessage(message);
                                        open(message);
                                    });
                                }

                                @Override
                                public void downFailure() {
                                    runOnUiThread(() -> {
                                        RvDownManager.instance().detele(message);
                                        onHideLoading();
                                        Toast.makeText(getApplicationContext(), "下载失败", Toast.LENGTH_SHORT).show();
                                    });
                                }
                            });
                    }
                } else if (!TextUtils.isEmpty(message.getContent())) {
                    // 下载文件
                    // 下载 文件
                    RvDownManager.instance().download(message, new RvDownManager.DownListener() {
                        @Override
                        public void downSuccess() {
                            runOnUiThread(() -> {
                                onHideLoading();
                                ChatMessageServiceImp.getInstance(getApplicationContext()).addMessage(message);
                                open(message);
                            });
                        }

                        @Override
                        public void downFailure() {
                            runOnUiThread(() -> {
                                RvDownManager.instance().detele(message);
                                onHideLoading();
                                Toast.makeText(getApplicationContext(), "下载失败", Toast.LENGTH_SHORT).show();
                            });
                        }
                    });
                }

            }
        }

        private void open(ChatMessage message) {
            String filePath = message.getFilePath();
            int start = filePath.lastIndexOf(".");
            String suffix = start > -1 ? filePath.substring(start + 1).toLowerCase() : "";
            int fileType = XfileUtils.getFileType(suffix);
            Intent intent = null;
            switch (fileType) {

                case 1:// 图片
                    intent = new Intent(getApplicationContext(), SingleImagePreviewActivity.class);
                    intent.putExtra(Constants.EXTRA_IMAGE_URI, message.getContent());
                    intent.putExtra("image_path", message.getFilePath());
                    startActivity(intent);
                    break;
                case 2:// 音乐
                    intent = new Intent(getApplicationContext(), ChatVideoPreviewActivity.class);
                    intent.putExtra(Constants.EXTRA_VIDEO_FILE_PATH, filePath);
                    startActivity(intent);
                    break;
                case 3: // 视频
                    intent = new Intent(getApplicationContext(), ChatVideoPreviewActivity.class);
                    intent.putExtra(Constants.EXTRA_VIDEO_FILE_PATH, filePath);
                    startActivity(intent);
                    break;
                default:
                    Toast.makeText(getApplicationContext(), "暂不支持该类型文件预览", Toast.LENGTH_SHORT).show();
                    break;

            }
        }

        @Override
        public void reSend(ChatMessage message) {
            if (messages.contains(message)) {
                message.setMessageStatus(MessageStatusEnum.SENDING.SENDING);
                int position = messages.lastIndexOf(message);
                if (position > 0)
                    adapter.notifyItemChanged(position);
            }
            presenter.readySend(message);
        }

        @Override
        public void voicePlay(ChatMessage message) {
            if (messages.contains(message)) {
                int position = messages.lastIndexOf(message);
                message.setVoiceStatus(1);
                if (position > 0)
                    adapter.notifyItemChanged(position);
            }
        }

        @Override
        public void call(boolean isVoice) {
            presenter.realDial(isVoice ? 1 : 2, null);
        }

        @Override
        public void sendCancel(ChatMessage message) {
            message.setMessageType(MessageTypeEnum.CANCEL);
            presenter.readySend(message);
        }
    };

    public static Intent getIntent(Context context, String targetUserId, String targetName, int customerStatus) {
        Intent intent = new Intent(context, ChatActivity.class);
        intent.putExtra("targetUserId", targetUserId);
        intent.putExtra("targetName", targetName);
        intent.putExtra("customerStatus", customerStatus);
        return intent;
    }

    @Override
    protected int setLayout() {
        return R.layout.activity_chat;
    }

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        ListenerManager.getInstance().addChatMessageListener(this);
        targetUserId = getIntent().getStringExtra("targetUserId");
        targetName = getIntent().getStringExtra("targetName");
        customerStatus = getIntent().getIntExtra("customerStatus", 0);
        if (!TextUtils.isEmpty(targetName))
            titleView.setTitle(targetName);
//            titleView.setTitle(targetName + (customerStatus == 0 ? "(离线)" : "(在线)"));
        mInputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        mLoginUserId = ImSetting.getUserId();
        presenter = new ChatPresenterImp(this, this);
        presenter.setChatInfo(mLoginUserId, ImSetting.getUserName(), targetUserId, targetName);

        ChatMessageServiceImp.getInstance(getApplicationContext()).setMsgRead(targetUserId);
        initWidget();
        initListener();

//        timer = new Timer();
//        timerTask = new RvImTimerTask(timerListener);
//        timer.schedule(timerTask, 100, 10000);
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    protected void loadData(Bundle savedInstanceState, Intent intent) {
        super.loadData(savedInstanceState, intent);
        getData();
    }

    @Override
    public void onShowResult(int requestType, BaseBean result) {

        if (requestType == 1) {
            User user = (User) result;
            if (user != null && user.getData() != null) {
                if (!TextUtils.isEmpty(targetName))
                    titleView.setTitle(targetName + (user.getData().getOnlinestate() == 0 ? "(离线)" : "(在线)"));
            }
        }
    }

    private void initWidget() {
        refreshLayout = findViewById(R.id.refresh);
        voiceImgBtn = findViewById(R.id.voice_img_btn);
        ibKeyword = findViewById(R.id.ib_keyword);
        chatEdit = findViewById(R.id.chat_edit);
        recordBtn = findViewById(R.id.record_btn);
        emotionBtn = findViewById(R.id.emotion_btn);
        ibPhoto = findViewById(R.id.ib_photo);
        sendBtn = findViewById(R.id.send_btn);
        mChatFaceViewStub = findViewById(R.id.chat_face_view_stub);
        recycleContent = findViewById(R.id.recyclerView);
        recycleContent.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        recycleContent.setItemAnimator(new DefaultItemAnimator());
        adapter = new ChatContentAdapter(getApplicationContext(), mLoginUserId, messages, clickItemListener);
        recycleContent.setAdapter(adapter);
        refreshLayout.setHeaderView(new SimpleRefreshView(this));
        refreshLayout.setOnSimpleRefreshListener(this);
    }

    private void initListener() {
        chatEdit.addTextChangedListener(watcher);
        sendBtn.setOnClickListener(this);
        ibPhoto.setOnClickListener(this);
        voiceImgBtn.setOnClickListener(this);
        emotionBtn.setOnClickListener(this);
        ibKeyword.setOnClickListener(this);
        mRecordController = new IMRecordController(this);
        mRecordController.setRecordListener(this);
        recordBtn.setOnTouchListener(mRecordController);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.send_btn) { // 发送消息
            if (TextUtils.isEmpty(chatEdit.getText().toString().trim())) {
                Toast.makeText(getApplicationContext(), "发送的消息不能为空", Toast.LENGTH_SHORT).show();
                return;
            }
            presenter.sendText(chatEdit.getText().toString().trim());
            chatEdit.getEditableText().clear();
        } else if (id == R.id.ib_photo) {
            openPhotoDialog();
            closeKeyboard();
            if (isFaceShown()) {// 表情布局在显示,那么点击则是隐藏表情，显示键盘
                closeKeyboard();
                mHandler.postDelayed(() -> {
                    changeChatFaceView(false);
                }, 0);
            }
        } else if (id == R.id.tv_pic) {
            isCamera = false;
            presenter.clickPicPicker(isCamera);
        } else if (id == R.id.tv_photo) {
            isCamera = true;
            presenter.clickPicPicker(isCamera);
        } else if (id == R.id.voice_img_btn) {

            /**
             * 6.0以上手机做权限处理
             */
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                new RxPermission(mActivity).request(
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.RECORD_AUDIO,
                        Manifest.permission.READ_EXTERNAL_STORAGE).subscribe(aBoolean -> {
                    if (aBoolean == true) {
                        changeChatFaceView(false);
                        chatEdit.setVisibility(View.GONE);
                        recordBtn.setVisibility(View.VISIBLE);
                        ibKeyword.setVisibility(View.VISIBLE);
                        voiceImgBtn.setVisibility(View.GONE);
                        closeKeyboard();
                    } else {
                        new AppSettingsDialog.Builder(ChatActivity.this).
                                setTitle("需要获取麦克风权限、存储权限")
                                .setRationale("如果没有此权限，此应用程序可能无法正常工作,是否打开设置修改该应用权限")
                                .build().show();
                    }
                });
            } else {
                changeChatFaceView(false);
                chatEdit.setVisibility(View.GONE);
                recordBtn.setVisibility(View.VISIBLE);
                ibKeyword.setVisibility(View.VISIBLE);
                voiceImgBtn.setVisibility(View.GONE);
                closeKeyboard();
            }
        } else if (id == R.id.ib_keyword) {
            changeChatFaceView(false);
            chatEdit.setVisibility(View.VISIBLE);
            recordBtn.setVisibility(View.GONE);
            ibKeyword.setVisibility(View.GONE);
            voiceImgBtn.setVisibility(View.VISIBLE);
        } else if (id == R.id.tv_file) {

            presenter.clickFile();
        } else if (id == R.id.tv_vilte) {
            callType = 1;

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                new RxPermission(mActivity).request(
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.RECORD_AUDIO,
                        Manifest.permission.READ_EXTERNAL_STORAGE).subscribe(aBoolean -> {
                    if (aBoolean == true) {
                        presenter.realDial(callType, null);
                    } else {
                        new AppSettingsDialog.Builder(ChatActivity.this).
                                setTitle("需要录音权限")
                                .setRationale("如果没有此权限，此应用程序可能无法正常工作,是否打开设置修改该应用权限")
                                .build().show();
                    }
                });
            } else {
                presenter.realDial(callType, null);
            }
        } else if (id == R.id.tv_video) {
            callType = 2;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                new RxPermission(mActivity).request(
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.RECORD_AUDIO,
                        Manifest.permission.READ_EXTERNAL_STORAGE).subscribe(aBoolean -> {
                    if (aBoolean == true) {
                        presenter.realDial(callType, null);
                    } else {
                        new AppSettingsDialog.Builder(ChatActivity.this).
                                setTitle("需要视频权限")
                                .setRationale("如果没有此权限，此应用程序可能无法正常工作,是否打开设置修改该应用权限")
                                .build().show();
                    }
                });
            } else {
                presenter.realDial(callType, null);
            }
        } else if (id == R.id.emotion_btn) {
            if (isFaceShown()) {// 表情布局在显示,那么点击则是隐藏表情，显示键盘
//                showKeyboard();
                changeChatFaceView(false);
            } else {// 表情布局没有显示,那么点击则是显示表情，隐藏键盘、录音、更多布局
                closeKeyboard();
                mHandler.postDelayed(() -> {
                    closeKeyboard();
                    changeChatFaceView(true);
                    changeRecordBtn(false);
                }, 0);
            }
        } else if (id == R.id.iv_title_left) {
            finish();
        }
    }

    private int callType;

    private boolean isFaceShown() {
        return mChatFaceView != null && mChatFaceView.getVisibility() != View.GONE;
    }

    private void closeKeyboard() {
        mInputManager.hideSoftInputFromWindow(chatEdit.getApplicationWindowToken(), 0);
    }

    private void openPhotoDialog() {
        Dialog bottomDialog = new Dialog(this, R.style.BottomDialog);
        View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_select_media, null);
        bottomDialog.setContentView(contentView);
        ViewGroup.LayoutParams layoutParams = contentView.getLayoutParams();
        layoutParams.width = getResources().getDisplayMetrics().widthPixels;
        contentView.setLayoutParams(layoutParams);
        bottomDialog.getWindow().setGravity(Gravity.BOTTOM);
        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
        bottomDialog.show();
        TextView textView = contentView.findViewById(R.id.dialog_select_voice);
        textView.setText("拍照");
        TextView textView_02 = contentView.findViewById(R.id.dialog_select_video);
        textView_02.setText("手机相册");
        contentView.findViewById(R.id.dialog_select_cancel).setOnClickListener(v -> bottomDialog.dismiss());
        contentView.findViewById(R.id.dialog_select_voice_ll).setOnClickListener(v -> {
            isCamera = true;
            presenter.clickPicPicker(isCamera);
            bottomDialog.dismiss();
        });
        contentView.findViewById(R.id.dialog_select_video_ll).setOnClickListener(v -> {
            isCamera = false;
            presenter.clickPicPicker(isCamera);
            bottomDialog.dismiss();
        });
    }

    private void changeRecordBtn(boolean show) {
        boolean isShowing = recordBtn.getVisibility() != View.GONE;
        if (isShowing == show) {
            return;
        }
        if (show) {
            chatEdit.setVisibility(View.GONE);
            recordBtn.setVisibility(View.VISIBLE);
            voiceImgBtn.setBackgroundResource(R.drawable.im_keyboard);
        } else {
            chatEdit.setVisibility(View.VISIBLE);
            recordBtn.setVisibility(View.GONE);
            voiceImgBtn.setBackgroundResource(R.drawable.im_voice);
        }
    }

    /**
     * 显示或隐藏表情布局
     */
    private void changeChatFaceView(boolean show) {
        ibKeyword.setVisibility(View.GONE);
        voiceImgBtn.setVisibility(View.VISIBLE);
        boolean isShowing = isFaceShown();
        if (isShowing == show) {
            return;
        }
        if (show) {
            if (mChatFaceView == null) {
                mChatFaceView = (ChatFaceView) mChatFaceViewStub.inflate();
                mChatFaceView.setEmotionClickListener(ss -> {

                    int index = chatEdit.getSelectionStart();
                    if ("[del]".equals(ss.toString())) {
                        InputManager.backSpaceChatEdit(chatEdit);
                    } else {
                        if (chatEdit.hasFocus()) {
                            chatEdit.getText().insert(index, ss);
                        } else {
                            chatEdit.getText().insert(chatEdit.getText().toString().length(), ss);
                        }
                    }
                });
            }
            mChatFaceView.setVisibility(View.VISIBLE);
//            emotionBtn.setBackgroundResource(R.drawable.im_btn_keyboard_bg);
        } else {
            mChatFaceView.setVisibility(View.GONE);
//            emotionBtn.setBackgroundResource(R.drawable.im_btn_emotion_bg);
        }
    }

    private boolean isCamera = false;
    private InputMethodManager mInputManager;

    @Override
    public void onDestroy() {
        super.onDestroy();
        ListenerManager.getInstance().removeChatMessageListener(this);
        if (timer != null)
            timer.cancel();
        if (timerTask != null)
            timerTask.cancel();
    }

    private long pullTime = 0L;

    private void getData() {
        List<ChatMessage> lists;
        if (pullTime == 0L) {  // 加载前20条
            lists = ((ChatPresenterImp) presenter).getDbService().getFirstPageMessage(targetUserId);
        } else {
            lists = ((ChatPresenterImp) presenter).getDbService().loadMoreMessage(targetUserId, pullTime);
        }
        if (lists == null || lists.size() == 0) {
            refreshLayout.setPullDownEnable(false);
            return;
        }

        if (lists.size() < 20) {
            refreshLayout.setPullDownEnable(false);
        }
        messages.addAll(0, lists);
        adapter.notifyDataSetChanged();
        if (messages.size() > 0 && pullTime == 0L) {
            recycleContent.smoothScrollToPosition(lists.size() - 1);
        }
        pullTime = lists.get(0).getTimeSend();
    }

    private TextWatcher watcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (s == null) {
                sendBtn.setVisibility(View.GONE);
                return;
            }
            if (s.length() == 0) {
                sendBtn.setVisibility(View.GONE);
            } else {
                sendBtn.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_PICK_PHOTO:
                    if (data != null) {
                        boolean isOriginal = data.getBooleanExtra(PhotoPickerActivity.EXTRA_RESULT_ORIGINAL, false);
                        presenter.album(data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT), isOriginal);
                    } else {
                        Toast.makeText(this, R.string.c_photo_album_failed, Toast.LENGTH_SHORT).show();
                    }
                    break;
                case REQUEST_CODE_CAMERA:
                    presenter.sendImage(null);
                    break;
                case REQUEST_CODE_SELECT_FILE:
                    String file_path = FileUtils.getPath(ChatActivity.this, data.getData());
                    Log.e("xuan", "conversionFile: " + file_path);
                    if (file_path == null) {
                        Toast.makeText(getApplicationContext(), R.string.tip_file_not_supported, Toast.LENGTH_SHORT).show();
                    } else {
                        presenter.sendFile(new File(file_path));
                    }
                    break;
            }
        }
    }


    @Override
    public void sendMessSuccess(String receiptId) {
        if (!TextUtils.isEmpty(receiptId) && messages != null && messages.size() > 0) {
            for (int i = messages.size() - 1; i >= 0; i--) {
                ChatMessage chatMessage = messages.get(i);
                if (receiptId.equals(chatMessage.getPackId())) {
                    chatMessage.setMessageStatus(MessageStatusEnum.SUCCESS);
                    adapter.notifyItemChanged(i);
                    break;
                }
            }
        }
    }

    @Override
    public void addMessage(ChatMessage message) {
        messages.add(message);
        adapter.notifyDataSetChanged();
        recycleContent.smoothScrollToPosition(messages.size() - 1);
    }

    @Override
    public void upSuccess(String toUserId, ChatMessage message) {
        if (messages.contains(message)) {
            int i = messages.lastIndexOf(message);
            adapter.notifyItemChanged(i);
            presenter.sendMsgBroad(message);
        }
    }

    @Override
    public void upFailure(String toUserId, ChatMessage message) {
        if (messages.contains(message)) {
            int i = messages.lastIndexOf(message);
            adapter.notifyItemChanged(i);
        }
    }

    @Override
    public void upProgress(String toUserId, ChatMessage message) {
        if (messages.contains(message)) {
            int i = messages.lastIndexOf(message);
            adapter.notifyItemChanged(i);
        }
    }

    @Override
    public void receiverMsg(ChatMessage message) {
        if (message != null && !TextUtils.isEmpty(targetUserId) && targetUserId.equals(message.getFromUserId())) {
            ChatMessageServiceImp.getInstance(getApplicationContext()).setMsgRead(targetUserId);
            messages.add(message);
            adapter.notifyDataSetChanged();
            if (messages.size() > 0) {
                recycleContent.smoothScrollToPosition(messages.size() - 1);
            }
        }
    }

    @Override
    public void sendMessFailure(String receiptId) {
        if (!TextUtils.isEmpty(receiptId) && messages != null && messages.size() > 0) {
            for (int i = messages.size() - 1; i >= 0; i--) {
                ChatMessage chatMessage = messages.get(i);
                if (receiptId.equals(chatMessage.getPackId())) {
                    chatMessage.setMessageStatus(MessageStatusEnum.FAIL);
                    adapter.notifyItemChanged(i);
                    break;
                }
            }
        }
    }


    @Override
    public void onMessageSendStateChange(int messageState, String msgId) {
        switch (messageState) {
            case ChatMessageListener.MESSAGE_SEND_SUCCESS:
                sendMessSuccess(msgId);
                break;
            case ChatMessageListener.MESSAGE_SEND_FAILED:
                sendMessFailure(msgId);
                break;
        }
    }

    @Override
    public void onNewMessage(String fromUserId, ChatMessage message, boolean isGroupMsg) {
        if (message != null && TextUtils.equals(message.getFromUserId(), targetUserId)) {
            receiverMsg(message);
        }
    }

    @Override
    public void onRecordStart() {
        VoicePlayer.instance().stop();
        // 录音开始
        recordBtn.setText(R.string.motalk_voice_chat_tip_2);
        recordBtn.setBackgroundResource(R.drawable.im_voice_button_pressed2);
    }

    @Override
    public void onRecordCancel() {
        // 录音取消
        recordBtn.setText(R.string.motalk_voice_chat_tip_1);
        recordBtn.setBackgroundResource(R.drawable.im_voice_button_normal2);
    }

    @Override
    public void onRecordSuccess(String filePath, int timeLen) {
        // 录音成功，返回录音文件的路径
        recordBtn.setText(R.string.motalk_voice_chat_tip_1);
        recordBtn.setBackgroundResource(R.drawable.im_voice_button_normal2);
        if (timeLen < 1) {
            return;
        }
        presenter.sendVoice(filePath, timeLen);
    }

    private RvImTimerTask.TimerListener timerListener = () -> runOnUiThread(() -> {
        AppConfig appConfig = (AppConfig) RvCache.getInstance().get(CacheEnum.IM_CONFIG);
        if (appConfig != null && !TextUtils.isEmpty(appConfig.USER_GET_URL))
            initFriendState(appConfig.USER_GET_URL);
    });

    private void initFriendState(String url) {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", ImSetting.getImToken());
        params.put("userId", targetUserId);
        mPresenter.getData(1, url, User.class, params, false);
    }

    @Override
    public void onRefresh() {
        handler.sendEmptyMessageDelayed(0, 1000);
    }

    private Handler handler = new Handler(Looper.getMainLooper()) {

        @Override
        public void handleMessage(Message msg) {
            if (!isFinishing()) {
                refreshLayout.onRefreshComplete();
                getData();
            }
        }
    };
}
