package com.hyphenate.helpdesk.easeui.ui;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.ClipboardManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.fragment.app.FragmentTransaction;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.hyphenate.chat.AgoraMessage;
import com.hyphenate.chat.ChatClient;
import com.hyphenate.chat.ChatManager;
import com.hyphenate.chat.Conversation;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMFileMessageBody;
import com.hyphenate.chat.EMImageMessageBody;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.chat.Message;
import com.hyphenate.chat.OfficialAccount;
import com.hyphenate.helpdesk.R;
import com.hyphenate.helpdesk.callback.ValueCallBack;
import com.hyphenate.helpdesk.easeui.UIProvider;
import com.hyphenate.helpdesk.easeui.adapter.MessageAdapter;
import com.hyphenate.helpdesk.easeui.provider.CustomChatRowProvider;
import com.hyphenate.helpdesk.easeui.recorder.MediaManager;
import com.hyphenate.helpdesk.easeui.util.EaseUiReportUtils;
import com.hyphenate.helpdesk.easeui.util.CommonUtils;
import com.hyphenate.helpdesk.easeui.util.Config;
import com.hyphenate.helpdesk.easeui.widget.AlertDialog;
import com.hyphenate.helpdesk.easeui.widget.AlertDialog.AlertDialogUser;
import com.hyphenate.helpdesk.easeui.widget.EaseChatInputMenu;
import com.hyphenate.helpdesk.easeui.widget.EaseChatInputMenu.ChatInputMenuListener;
import com.hyphenate.helpdesk.easeui.widget.ExtendMenu.EaseChatExtendMenuItemClickListener;
import com.hyphenate.helpdesk.easeui.widget.MessageList;
import com.hyphenate.helpdesk.easeui.widget.MessageList.MessageListItemClickListener;
import com.hyphenate.helpdesk.easeui.widget.ToastHelper;
import com.hyphenate.helpdesk.emojicon.Emojicon;
import com.hyphenate.helpdesk.manager.EmojiconManager;
import com.hyphenate.helpdesk.model.AgentIdentityInfo;
import com.hyphenate.helpdesk.model.QueueIdentityInfo;
import com.hyphenate.helpdesk.model.VisitorInfo;
import com.hyphenate.helpdesk.util.AdapterFileUtils;
import com.hyphenate.helpdesk.util.Log;
import com.hyphenate.util.EMLog;
import com.hyphenate.util.ImageUtils;
import com.hyphenate.util.PathUtil;
import com.hyphenate.util.UriUtils;
import com.hyphenate.util.VersionUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import pub.devrel.easypermissions.EasyPermissions;

/**
 * 可以直接new出来使用的聊天对话页面fragment，
 * 使用时需调用setArguments方法传入IM服务号
 * app也可继承此fragment续写
 * 参数传入示例可查看demo里的ChatActivity
 */
public class ChatFragment extends BaseFragment implements ChatManager.MessageListener, EmojiconManager.EmojiconManagerDelegate, EasyPermissions.PermissionCallbacks {

    protected static final String TAG = ChatFragment.class.getSimpleName();
    private static final String STATE_SAVE_IS_HIDDEN = "STATE_SAVE_IS_HIDDEN";
//    protected static final int REQUEST_CODE_CAMERA = 1;
    protected static final int REQUEST_CODE_LOCAL = 2;
    private static final int REQUEST_CODE_SELECT_VIDEO = 3;
//
    public static final int REQUEST_CODE_EVAL = 5;
    public static final int REQUEST_CODE_SELECT_FILE = 6;

    protected static final int REQUEST_CODE_SELECT_MAP = 11;

    private static final int REQUEST_CODE_CAMERA = 110;
    private static final int REQUEST_CODE_STORAGE_PICTURE = 111;
    private static final int REQUEST_CODE_STORAGE_VIDEO = 112;
    private static final int REQUEST_CODE_STORAGE_FILE = 113;
    protected static final int REQUEST_CODE_LOCATION = 114;
    private static final int REQUEST_CODE_VOICE = 115;
    /**
     * 传入fragment的参数
     */
    protected Bundle fragmentArgs;
    protected String toChatUsername;
    protected boolean showUserNick;
    protected MessageList messageList;
    protected EaseChatInputMenu inputMenu;

    protected Conversation conversation;
    protected InputMethodManager inputManager;
    protected ClipboardManager clipboard;
    protected File cameraFilePath = null;
    protected SwipeRefreshLayout swipeRefreshLayout;
    protected ListView listView;

    protected boolean isloading;
    protected boolean haveMoreData = true;
    protected int pagesize = 20;
    protected Message contextMenuMessage;

    protected static final int ITEM_TAKE_PICTURE = 1;
    protected static final int ITEM_PICTURE = 2;
    protected static final int ITEM_VIDEO = 3;
    protected static final int ITEM_FILE = 4;

    protected int[] itemStrings = {R.string.attach_take_pic, R.string.attach_picture, R.string.attach_video, R.string.attach_file};
    protected int[] itemdrawables = {R.drawable.hd_chat_takepic_selector, R.drawable.hd_chat_image_selector, R.drawable.hd_chat_video_selector, R.drawable.hd_chat_file_selector};

    protected int[] itemIds = {ITEM_TAKE_PICTURE, ITEM_PICTURE, ITEM_VIDEO, ITEM_FILE};
    protected int[] itemResIds = {R.id.chat_menu_take_pic, R.id.chat_menu_pic, R.id.chat_menu_video, R.id.chat_menu_file};

    private boolean isMessageListInited;
    protected MyMenuItemClickListener extendMenuItemClickListener;
    private VisitorInfo visitorInfo;
    private AgentIdentityInfo agentIdentityInfo;
    private QueueIdentityInfo queueIdentityInfo;
    private String titleName;
    protected TextView tvTipWaitCount;

    private final ActivityResultLauncher<String[]> requestImagePermission = registerForActivityResult(new ActivityResultContracts.RequestMultiplePermissions()
            , result -> onRequestResult(result, REQUEST_CODE_STORAGE_PICTURE));
    private final ActivityResultLauncher<String[]> requestVideoPermission = registerForActivityResult(new ActivityResultContracts.RequestMultiplePermissions()
            , result -> onRequestResult(result, REQUEST_CODE_STORAGE_VIDEO));
    private final ActivityResultLauncher<String[]> requestFilePermission = registerForActivityResult(new ActivityResultContracts.RequestMultiplePermissions()
            , result -> onRequestResult(result, REQUEST_CODE_STORAGE_FILE));

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState != null) {
            boolean isSupportedHidden = savedInstanceState.getBoolean(STATE_SAVE_IS_HIDDEN);
            FragmentTransaction ft = getFragmentManager().beginTransaction();
            if (isSupportedHidden) {
                ft.hide(this);
            } else {
                ft.show(this);
            }
            ft.commit();
        }
        ChatClient.getInstance().emojiconManager().addDelegate(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.hd_fragment_chat, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {

        fragmentArgs = getArguments();
        // IM服务号
        toChatUsername = fragmentArgs.getString(Config.EXTRA_SERVICE_IM_NUMBER);

        // 是否显示用户昵称
        showUserNick = fragmentArgs.getBoolean(Config.EXTRA_SHOW_NICK, false);
        //指定技能组
        queueIdentityInfo = fragmentArgs.getParcelable(Config.EXTRA_QUEUE_INFO);
        //指定客服
        agentIdentityInfo = fragmentArgs.getParcelable(Config.EXTRA_AGENT_INFO);
        visitorInfo = fragmentArgs.getParcelable(Config.EXTRA_VISITOR_INFO);

        titleName = fragmentArgs.getString(Config.EXTRA_TITLE_NAME);
        //在父类中调用了initView和setUpView两个方法
        super.onActivityCreated(savedInstanceState);
        if (savedInstanceState != null) {
            cameraFilePath = new File(savedInstanceState.getString("cameraFilePath"));
        }
        ChatClient.getInstance().chatManager().bindChat(toChatUsername);
        ChatClient.getInstance().chatManager().addAgentInputListener(agentInputListener);

        // 为测试获取账号用，无实际意义
        setUserNameView();

    }

    /**
     * 获取机器人欢迎语
     * 此方法放到放到setUpView()方法里，保证messageList被创建完
     */
    public void getCurrentSessionId(){
        try {
            String userName = ChatClient.getInstance().currentUserName();

            if (messageList == null){
                throw new RuntimeException("messageList is null.");
            }

            if (TextUtils.isEmpty(toChatUsername)){
                throw new RuntimeException("toChatUsername is null.");
            }

            if (TextUtils.isEmpty(userName)){
                throw new RuntimeException("visitorUserName is null.");
            }

            ChatClient.getInstance().chatManager().getCurrentSessionId(toChatUsername, new ValueCallBack<String>() {
                @Override
                public void onSuccess(String value) {
                    EMLog.d(TAG, "getCurrentSession " + value);
                    //当返回value不为空时，则返回的当前会话的会话ID，也就是说会话正在咨询中，不需要发送欢迎语
                    if (value.isEmpty()){
                        // 获取机器人欢迎语
                        requestRobotWelcome(toChatUsername, userName, new ValueCallBack<String>() {
                            @Override
                            public void onSuccess(String value) {
                                Log.e(TAG,"getRobotWelcome success 刷新页面");
                                if (messageList != null && !isDetached()){
                                    messageList.refresh();
                                }
                            }

                            @Override
                            public void onError(int error, String errorMsg) {
                                Log.e(TAG,"getRobotWelcome errorMsg = "+errorMsg);
                            }
                        });

                        // 获取企业欢迎语
                        requestEnterpriseWelcome();

                    }else {
                        Log.e(TAG,"会话正在咨询中，不需要发送欢迎语");
                    }
                }

                @Override
                public void onError(int i, String errorMsg) {
                    Log.e(TAG,"getCurrentSessionId error = "+errorMsg);
                }
            });
        }catch (Exception e){
            Log.e(TAG, "getCurrentSessionId is error = "+e.getMessage());
            e.printStackTrace();
        }
    }

    private void requestRobotWelcome(String toChatUsername, String visitorUserName, ValueCallBack<String> valueCallBack){
        ChatClient.getInstance().chatManager().getRobotWelcome(toChatUsername, visitorUserName, new ValueCallBack<JSONObject>() {
            @Override
            public void onSuccess(JSONObject value) {
                EMLog.d(TAG, "requestRobotWelcome " + value);
                try {
                    if (value.has("entity")) {
                        JSONObject greeting = value.getJSONObject("entity");
                        int type = value.getJSONObject("entity").getInt("greetingTextType");
                        String rob_welcome = greeting.getString("greetingText");
                        if(TextUtils.isEmpty(rob_welcome)){
                            if (valueCallBack != null){
                                valueCallBack.onError(-1,"greetingText is null");
                            }
                            return;
                        }
                        // final String strs = rob_welcome.replaceAll("&amp;quot;", "\"");
                        showRobotWelcome(toChatUsername, type, rob_welcome, valueCallBack);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    if (valueCallBack != null){
                        valueCallBack.onError(-1,e.getMessage());
                    }
                    Log.e(TAG,"getRobotWelcome error = "+e.getMessage());
                }
            }

            @Override
            public void onError(int error, String errorMsg) {
                if (valueCallBack != null){
                    valueCallBack.onError(error,errorMsg);
                }
                Log.e(TAG,"getRobotWelcome errorMsg error = "+errorMsg);
            }
        });
    }


    private void requestEnterpriseWelcome(){
        ChatClient.getInstance().chatManager().getEnterpriseWelcome(new ValueCallBack<String>() {
            @Override
            public void onSuccess(String value) {
                EMLog.d(TAG, "getEnterpriseWelcome " + value);
                ChatClient.getInstance().chatManager().saveMessage(createReceiveTxtMessage(value));
                if (messageList != null && !isDetached()){
                    messageList.refresh();
                }
            }

            @Override
            public void onError(int error, String errorMsg) {
                Log.e(TAG,"getEnterpriseWelcome errorMsg error = "+errorMsg);
            }
        });
    }

    private void showRobotWelcome(String toChatUsername, final int type, final String rob_welcome, ValueCallBack<String> valueCallBack){
        //type为0代表是文字消息的机器人欢迎语
        //type为1代表是菜单消息的机器人欢迎语
        //type为2代表是图片消息的机器人欢迎语
        //type为4代表是图文消息的机器人欢迎语
        //type为5代表是答案组消息的机器人欢迎语
        final String str = rob_welcome.replaceAll("&amp;quot;", "\"");
        if(TextUtils.isEmpty(str) || "null".equals(str)){
            if (valueCallBack != null){
                valueCallBack.onError(-1,"rob_welcome is null");
            }
            return;
        }
        try {
            if (type == 0) {
                ChatClient.getInstance().chatManager().saveMessage(createReceiveTxtMessage(str));
                if (valueCallBack != null){
                    valueCallBack.onSuccess(rob_welcome);
                }
            } else if (type == 1) {
                JSONObject json = new JSONObject(str);
                JSONObject ext = json.getJSONObject("ext");
                final JSONObject msgtype = ext.getJSONObject("msgtype");

                Message message = createReceiveTxtMessage("[机器人菜单欢迎语]");
                message.setAttribute("msgtype",msgtype);
                ChatClient.getInstance().chatManager().saveMessage(message);
                if (valueCallBack != null){
                    valueCallBack.onSuccess(msgtype.toString());
                }
            }else if (type == 2){
                JSONObject msgtype = new JSONObject(str);
                Message message = Message.createReceiveMessage(Message.Type.IMAGE);
                String host = ChatClient.getInstance().kefuRestServer();
                String urlPath = msgtype.getString("urlPath");
                final String name = msgtype.getString("name");
                //String types = msgtype.getString("type");

                String path = host.concat(urlPath);
                JSONObject objectMeta = msgtype.getJSONObject("objectMeta");
                final int width = objectMeta.getInt("width");
                final int height = objectMeta.getInt("height");
                EMImageMessageBody body = new EMImageMessageBody(Uri.parse(path));
                body.setDownloadStatus(EMFileMessageBody.EMDownloadStatus.DOWNLOADING);
                final String thumbLocalPath = new File(PathUtil.getInstance().getImagePath(),name).getPath();
                body.setThumbnailSize(width, height);
                body.setThumbnailLocalPath(thumbLocalPath);
                body.setLocalUrl(thumbLocalPath);
                body.setRemoteUrl(path);
                body.setFileName(name);

                message.setFrom(toChatUsername);
                message.addBody(body);
                message.setMsgTime(System.currentTimeMillis());
                message.setStatus(Message.Status.SUCCESS);
                message.setMsgId(UUID.randomUUID().toString());

                JSONObject data = new JSONObject();
                data.put("greetingTextType",type);
                // greetingTextType
                message.setAttribute("msgtype",data);

                ChatClient.getInstance().chatManager().saveMessage(message);
                if (valueCallBack != null){
                    valueCallBack.onSuccess(msgtype.toString());
                }
            }else if (type == 3){
                JSONObject json = new JSONObject(str);
                JSONObject ext = json.getJSONObject("ext");
                final JSONObject msgtype = ext.getJSONObject("msgtype");

                Message message = createReceiveTxtMessage("[机器人菜单欢迎语]");
                message.setAttribute("msgtype",msgtype);
                ChatClient.getInstance().chatManager().saveMessage(message);
                if (valueCallBack != null){
                    valueCallBack.onSuccess(msgtype.toString());
                }
            }else if (type == 4){
                JSONObject json = new JSONObject(str);
                if (json.has("news")){
                    JSONObject msgtype = json.getJSONObject("news");

                    Message message = createReceiveTxtMessage("[机器人图文欢迎语]");
                    message.setAttribute("msgtype",msgtype);
                    ChatClient.getInstance().chatManager().saveMessage(message);
                    if (valueCallBack != null){
                        valueCallBack.onSuccess(msgtype.toString());
                    }
                }
            } else if (type == 5){
                JSONArray jsonArray = new JSONArray(str);
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    int interType = jsonObject.getInt("greetingTextType");
                    String rob_welcome_item = jsonObject.getString("greetingText");
                    if(i == jsonArray.length() - 1){
                        showRobotWelcome(toChatUsername, interType, rob_welcome_item, valueCallBack);
                    } else {
                        showRobotWelcome(toChatUsername, interType, rob_welcome_item, valueCallBack);
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            if (valueCallBack != null){
                valueCallBack.onError(-1,e.getMessage());
            }
            Log.e(TAG,"showRobotWelcome onError:"+e.getMessage());
        }
    }

    Message createReceiveTxtMessage(String textContent){
        Message message = Message.createReceiveMessage(Message.Type.TXT);
        EMTextMessageBody body = new EMTextMessageBody(textContent);
        message.setFrom(toChatUsername);
        message.addBody(body);
        message.setMsgTime(System.currentTimeMillis());
        message.setStatus(Message.Status.SUCCESS);
        message.setMsgId(UUID.randomUUID().toString());
//        {"official_account_id":"106c58b7-9db9-42f7-8e47-4b702b0c9fb6","name":"客服","type":"SYSTEM"}
//        putTmpOfficialAccount(message);
        return message;
    }

    void putTmpOfficialAccount(Message message){
        try {
            JSONObject weichatObj = new JSONObject();
            JSONObject officialAccountObj = new JSONObject();
            officialAccountObj.put("type","SYSTEM");
            officialAccountObj.put("name",toChatUsername);
            officialAccountObj.put("official_account_id",UUID.randomUUID());
            weichatObj.put("official_account", officialAccountObj);
            message.setAttribute(Message.KEY_WEICHAT, weichatObj);
        } catch (JSONException e){
            e.printStackTrace();
        }
    }

    private void setUserNameView() {
        if (ChatClient.getInstance().isLoggedInBefore()) {
            String currentUsername = ChatClient.getInstance().currentUserName();
            if (getView() != null) {
                TextView tvUname = (TextView) getView().findViewById(R.id.tv_username);
                if (tvUname != null) {
                    tvUname.setText(currentUsername);
                }
            }
        }
    }



    /**
     * init view
     */
    @Override
    protected void initView() {
        // 消息列表layout
        messageList = (MessageList) getView().findViewById(R.id.message_list);
        messageList.setShowUserNick(showUserNick);
        listView = messageList.getListView();
        tvTipWaitCount = (TextView) getView().findViewById(R.id.tv_tip_waitcount);
        extendMenuItemClickListener = new MyMenuItemClickListener();
        inputMenu = (EaseChatInputMenu) getView().findViewById(R.id.input_menu);
        registerExtendMenuItem();
        // init input menu
        inputMenu.init();
        inputMenu.setChatInputMenuListener(new ChatInputMenuListener() {

            @Override
            public void onSendMessage(String content) {
                // 发送文本消息
                sendTextMessage(content);
            }

            @Override
            public void onBigExpressionClicked(Emojicon emojicon) {
                if (!TextUtils.isEmpty(emojicon.getBigIconRemotePath())) {
                    sendCustomEmojiMessage(emojicon.getBigIconRemotePath());
                } else if (!TextUtils.isEmpty(emojicon.getIconRemotePath())) {
                    sendCustomEmojiMessage(emojicon.getIconRemotePath());
                } else if (!TextUtils.isEmpty(emojicon.getBigIconPath())) {
                    sendImageMessage(emojicon.getBigIconPath());
                } else if (!TextUtils.isEmpty(emojicon.getIconPath())) {
                    sendImageMessage(emojicon.getIconPath());
                }
            }

            @Override
            public void onRecorderCompleted(float seconds, String filePath) {
                // 发送语音消息
                int time = seconds > 1 ? (int) seconds : 1;
                sendVoiceMessage(filePath, time);
            }
        });
        inputMenu.setHasSendButton(true);

        swipeRefreshLayout = messageList.getSwipeRefreshLayout();
        swipeRefreshLayout.setColorSchemeResources(R.color.holo_blue_bright, R.color.holo_green_light,
                R.color.holo_orange_light, R.color.holo_red_light);

        inputManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        ChatClient.getInstance().chatManager().addVisitorWaitListener(visitorWaitListener);
    }

    ChatManager.VisitorWaitListener visitorWaitListener = new ChatManager.VisitorWaitListener() {
        @Override
        public void waitCount(final int num) {
            if (getActivity() == null) {
                return;
            }
//            EMLog.d(TAG, "waitCount--num:" + num);
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (num > 0) {
                        tvTipWaitCount.setVisibility(View.VISIBLE);
                        tvTipWaitCount.setText(getString(R.string.current_wait_count, num));
                    } else {
                        tvTipWaitCount.setVisibility(View.GONE);
                    }
                }
            });
        }
    };

    ChatManager.AgentInputListener agentInputListener = new ChatManager.AgentInputListener() {
        @Override
        public void onInputState(final String input) {
            if (getActivity() == null) {
                return;
            }
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (input != null) {
                        titleBar.setTitle(input);
                    } else {
                        if (!TextUtils.isEmpty(titleName)) {
                            titleBar.setTitle(titleName);
                        } else {
                            titleBar.setTitle(toChatUsername);
                        }
                    }
                }
            });

        }
    };

    private void readMessage(Message message) {
        String sessionId = AgoraMessage.getSessionIdFromMessage(message);
        if (TextUtils.isEmpty(sessionId)) {
            return;
        }
        EMLog.e("asyncMarkAllMessagesAsRead","sessionId = "+sessionId);
        String tenantId = ChatClient.getInstance().tenantId();
        ChatClient.getInstance().chatManager().asyncMarkAllMessagesAsRead(tenantId, sessionId, new ValueCallBack<String>() {
            @Override
            public void onSuccess(String value) {
                EMLog.e("asyncMarkAllMessagesAsRead","value = "+value);
            }

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

    }

    /**
     * 设置属性，监听等
     */
    @Override
    protected void setUpView() {
        if (!TextUtils.isEmpty(titleName)) {
            titleBar.setTitle(titleName);
        } else {
            titleBar.setTitle(toChatUsername);
        }

        titleBar.setRightImageResource(R.drawable.hd_mm_title_remove);

        onConversationInit();
        onMessageListInit();

        // 设置标题栏点击事件
        titleBar.setLeftLayoutClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (getActivity() != null) {
                    getActivity().finish();
                }
            }
        });
        titleBar.setRightLayoutClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                emptyHistory();
            }
        });
        setRefreshLayoutListener();

        // test api
//        ChatClient.getInstance().chatManager().getTransferGuideMenu(toChatUsername, new ValueCallBack<JSONObject>() {
//            @Override
//            public void onSuccess(JSONObject value) {
//                EMLog.d(TAG, "onsuccess" + value.toString());
//                Message message = Message.createReceiveMessage(Message.Type.TXT);
//                message.setBody(new EMTextMessageBody("test guide"));
//                message.setMsgId(UUID.randomUUID().toString());
//                message.setStatus(Message.Status.SUCCESS);
//                message.setFrom(toChatUsername);
//                message.setMessageTime(System.currentTimeMillis());
//                try {
//                    message.setAttribute(Message.KEY_MSGTYPE, value.getJSONObject(Message.KEY_MSGTYPE));
//                    ChatClient.getInstance().chatManager().saveMessage(message);
//                    messageList.refreshSelectLast();
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//
//
//            @Override
//            public void onError(int error, String errorMsg) {
//
//            }
//        });


        /*try {
            String userName = ChatClient.getInstance().currentUserName();
            // 获取机器人欢迎语
            getRobotWelcome(toChatUsername, userName, new ValueCallBack<String>() {
                @Override
                public void onSuccess(String value) {
                    if (messageList != null && !isDetached()){
                        messageList.refresh();
                    }
                }

                @Override
                public void onError(int error, String errorMsg) {
                }
            });
        }catch (Exception e){
            Log.e(TAG, "getRobotWelcome is error = "+e.getMessage());
            e.printStackTrace();
        }*/

        //获取是否有进行中会话
        getCurrentSessionId();


        /*ChatClient.getInstance().chatManager().getRobotWelcome(toChatUsername, new ValueCallBack<JSONObject>() {
            @Override
            public void onSuccess(JSONObject value) {
                Log.e("aaaaaaaaaaaaa","value = "+value);
            }

            @Override
            public void onError(int error, String errorMsg) {
                Log.e("aaaaaaaaaaaaa","error = "+error);
                Log.e("aaaaaaaaaaaaa","errorMsg = "+errorMsg);
            }
        });*/


    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        ChatClient.getInstance().emojiconManager().removeDelegate(this);
        EaseUiReportUtils.getEaseUiReportUtils().closeReport();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ChatClient.getInstance().chatManager().unbindChat();
        ChatClient.getInstance().chatManager().removeAgentInputListener(agentInputListener);
        ChatClient.getInstance().chatManager().removeVisitorWaitListener(visitorWaitListener);
    }

    /**
     * 注册底部菜单扩展栏item; 覆盖此方法时如果不覆盖已有item，item的id需大于3
     */
    protected void registerExtendMenuItem() {
        for (int i = 0; i < itemStrings.length; i++) {
            inputMenu.registerExtendMenuItem(itemStrings[i], itemdrawables[i], itemIds[i], itemResIds[i], extendMenuItemClickListener);
        }
    }

    protected void onConversationInit() {
        // 获取当前conversation对象
        conversation = ChatClient.getInstance().chatManager().getConversation(toChatUsername);

        if (this.conversation != null) {
            // 把此会话的未读数置为0
            this.conversation.markAllMessagesAsRead();
            final List<Message> msgs = this.conversation.getAllMessages();
            if (msgs != null && msgs.size() > 0) {
                for (Message message : msgs) {
                    Message.Direct direct = message.direct();
                    if (direct == Message.Direct.RECEIVE) {
                        readMessage(message);
                        break;
                    }
                }
            }

            int msgCount = msgs != null ? msgs.size() : 0;
            if (msgCount < this.conversation.getAllMsgCount() && msgCount < pagesize) {
                String msgId = null;
                if (msgs != null && msgs.size() > 0) {
                    msgId = msgs.get(0).messageId();
                }
                this.conversation.loadMessages(msgId, pagesize - msgCount);
            }
        }

    }

    protected void onMessageListInit() {
        messageList.init(toChatUsername, chatFragmentListener != null ?
                chatFragmentListener.onSetCustomChatRowProvider() : null, callback);
        //设置list item里的控件的点击事件
        setListItemClickListener();

        messageList.getListView().setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (!inputMenu.isVoiceRecording()) {//录音时，点击列表不做操作
                    hideKeyboard();
                    inputMenu.hideExtendMenuContainer();
                }
                return false;
            }
        });

        isMessageListInited = true;
    }

    protected void setListItemClickListener() {
        messageList.setItemClickListener(new MessageListItemClickListener() {

            @Override
            public void onUserAvatarClick(String username) {
                if (chatFragmentListener != null) {
                    chatFragmentListener.onAvatarClick(username);
                }
            }

            @Override
            public void onResendClick(final Message message) {
                new AlertDialog(getActivity(), R.string.resend, R.string.confirm_resend, null, new AlertDialogUser() {
                    @Override
                    public void onResult(boolean confirmed, Bundle bundle) {
                        if (!confirmed) {
                            return;
                        }
                        ChatClient.getInstance().chatManager().resendMessage(message);
                    }
                }, true).show();
            }

            @Override
            public void onBubbleLongClick(Message message) {
                contextMenuMessage = message;
                if (chatFragmentListener != null) {
                    chatFragmentListener.onMessageBubbleLongClick(message);
                }
            }

            @Override
            public boolean onBubbleClick(Message message) {
                if (chatFragmentListener != null) {
                    return chatFragmentListener.onMessageBubbleClick(message);
                }
                return false;
            }

            @Override
            public void onMessageItemClick(Message message, MessageList.ItemAction action) {
                contextMenuMessage = message;
                if (chatFragmentListener != null) {
                    chatFragmentListener.onMessageItemClick(message, action);
                }
            }
        });
    }

    protected void setRefreshLayoutListener() {
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        if (getActivity() == null || getActivity().isFinishing()) {
                            return;
                        }
                        if (listView.getFirstVisiblePosition() == 0 && !isloading && haveMoreData) {
                            List<Message> messages = null;
                            try {
                                messages = conversation.loadMessages(messageList.getItem(0).messageId(),
                                        pagesize);
                            } catch (Exception e1) {
                                swipeRefreshLayout.setRefreshing(false);
                                return;
                            }
                            if (messages != null && messages.size() > 0) {
                                messageList.refreshSeekTo(messages.size() - 1);
                                if (messages.size() != pagesize) {
                                    haveMoreData = false;
                                }
                            } else {
                                haveMoreData = false;
                            }

                            isloading = false;

                        } else {
                            ToastHelper.show(getActivity(), R.string.no_more_messages);
                        }
                        swipeRefreshLayout.setRefreshing(false);
                    }
                }, 600);
            }
        });
    }

   /* @SuppressLint("NewApi")
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQUEST_CODE_CAMERA) { // 发送照片
                sendImageMessage(cameraFilePath);
            } else if (requestCode == REQUEST_CODE_LOCAL) { // 发送本地图片
                if (data != null) {
                    Uri selectedImage = data.getData();
                    if (selectedImage != null) {
                        sendPicByUri(selectedImage);
                    }
                }
            } else if (requestCode == REQUEST_CODE_SELECT_FILE) {
                if (data != null) {
                    Uri uri = data.getData();
                    if (uri != null) {
                        sendFileByUri(uri);
                    }
                }
            } else if (requestCode == REQUEST_CODE_SELECT_VIDEO) {
                if (data != null) {
                    int duration = data.getIntExtra("dur", 0);
                    String videoPath = data.getStringExtra("path");
                    String uriString = data.getStringExtra("uri");
                    EMLog.d(TAG, "path = " + videoPath + " uriString = " + uriString);

                    if (!TextUtils.isEmpty(videoPath)) {
                        sendVideoMessage(Uri.parse(videoPath), duration);
                    } else {
                        Uri videoUri = UriUtils.getLocalUriFromString(uriString);
                        sendVideoMessage(videoUri, duration);
                    }
                }
            }
        }
    }*/

    @Override
    public void onResume() {
        super.onResume();
        if (isMessageListInited)
            messageList.refresh();
        MediaManager.resume();
        UIProvider.getInstance().pushActivity(getActivity());
        // register the event listener when enter the foreground
        ChatClient.getInstance().chatManager().addMessageListener(this);
    }


    @Override
    public void onStop() {
        super.onStop();
        // unregister this event listener when this activity enters the
        // background
        ChatClient.getInstance().chatManager().removeMessageListener(this);
        // 把此activity 从foreground activity 列表里移除
        UIProvider.getInstance().popActivity(getActivity());
    }

    @Override
    public void onStart() {
        super.onStart();
        EaseUiReportUtils.getEaseUiReportUtils().startReport(toChatUsername);
    }


    public void onBackPressed() {
        inputMenu.onBackPressed();
    }

    @Override
    public void onEmojiconChanged() {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ToastHelper.show(getActivity(), R.string.emoji_icon_update);
                if (inputMenu != null) {
                    inputMenu.onEmojiconChanged();
                }
            }
        });
    }

    /**
     * 扩展菜单栏item点击事件
     */
    class MyMenuItemClickListener implements EaseChatExtendMenuItemClickListener {

        @Override
        public void onExtendMenuItemClick(int itemId, View view) {
            if (getActivity() == null) {
                return;
            }
            if (chatFragmentListener != null) {
                if (chatFragmentListener.onExtendMenuItemClick(itemId, view)) {
                    return;
                }
            }
            switch (itemId) {
                case ITEM_TAKE_PICTURE: // 拍照
                    if(checkIfHasPermissions(Manifest.permission.CAMERA, REQUEST_CODE_CAMERA)) {
                        selectPicFromCamera();
                    }
                    break;
                case ITEM_PICTURE:
                    if(checkPhotosPermission(getActivity())) {
                        selectPicFromLocal();
                    }
                    break;
                case ITEM_VIDEO:
                    if(checkVideosPermission(getActivity())){
                        selectVideoFromLocal();
                    }
//                    PermissionsManager.getInstance().requestPermissionsIfNecessaryForResult(ChatFragment.this, new String[]{Manifest.permission.CAMERA}, new PermissionsResultAction() {
//                        @Override
//                        public void onGranted() {
//                            selectVideoFromLocal();
//                        }
//
//                        @Override
//                        public void onDenied(String permission) {
//
//                        }
//                    });

                    break;
                case ITEM_FILE:
                    //一般文件
                    //demo这里是通过系统api选择文件，实际app中最好是做成qq那种选择发送文件
                    if(checkFilesPermission(getActivity())){
                        selectFileFromLocal();
                    }
                    break;
                default:
                    break;
            }
        }

    }

   /* private void selectVideoFromLocal() {
        Intent intent = new Intent(getActivity(), ImageGridActivity.class);
        startActivityForResult(intent, REQUEST_CODE_SELECT_VIDEO);
    }*/

    /**
     * 选择文件
     */
//    protected void selectFileFromLocal() {
//        Intent intent = new Intent();
//        if (VersionUtils.isTargetQ(getActivity())) {
//            intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
//        } else {
//            intent.setAction(Intent.ACTION_GET_CONTENT);
//        }
//        intent.addCategory(Intent.CATEGORY_OPENABLE);
//        intent.setType("*/*");
//
//        startActivityForResult(intent, REQUEST_CODE_SELECT_FILE);
//    }


    /**
     * 根据图库图片uri发送图片
     *
     * @param selectedImage
     */
    protected void sendPicByUri(Uri selectedImage) {
        sendImageMessage(selectedImage);
    }

    /**
     * 根据uri发送文件
     *
     * @param uri uri
     */
    protected void sendFileByUri(Uri uri) {
        sendFileMessage(uri);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBoolean(STATE_SAVE_IS_HIDDEN, isHidden());
        if (cameraFilePath != null) {
            outState.putString("cameraFile", cameraFilePath.getAbsolutePath());
        }
    }

    /**
     * 照相获取图片
     */
    /*protected void selectPicFromCamera() {
        if (!CommonUtils.isExitsSdcard()) {
            ToastHelper.show(getActivity(), R.string.sd_card_does_not_exist);
            return;
        }
        try {
            File cameraFile = new File(PathUtil.getInstance().getImagePath(), ChatClient.getInstance().currentUserName()
                    + System.currentTimeMillis() + ".jpg");
            cameraFilePath = cameraFile.getAbsolutePath();
            if (!cameraFile.getParentFile().exists()) {
                cameraFile.getParentFile().mkdirs();
            }
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile));
            } else {
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(getContext().getApplicationContext(), getContext().getPackageName() + ".fileProvider", cameraFile));
            }
            startActivityForResult(intent, REQUEST_CODE_CAMERA);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/

    /**
     * 从图库获取图片
     */
    protected void selectPicFromLocal() {
        Intent intent = null;
        if (VersionUtils.isTargetQ(getActivity())) {
            intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
        } else {
            if (Build.VERSION.SDK_INT < 19) {
                intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
            } else {
                intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            }
        }
        intent.setType("image/*");
        startActivityForResult(intent, REQUEST_CODE_LOCAL);
    }


    /**
     * 点击清空聊天记录
     */
    protected void emptyHistory() {
        String msg = getResources().getString(R.string.Whether_to_empty_all_chats);
        new AlertDialog(getActivity(), null, msg, null, new AlertDialogUser() {

            @Override
            public void onResult(boolean confirmed, Bundle bundle) {
                if (confirmed) {
                    MediaManager.release();
                    ChatClient.getInstance().chatManager().clearConversation(toChatUsername);
                    messageList.refresh();
                }
            }
        }, true).show();
    }


    /**
     * 隐藏软键盘
     */
    protected void hideKeyboard() {
        if (getActivity().getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getActivity().getCurrentFocus() != null)
                inputManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    protected EaseChatFragmentListener chatFragmentListener;

    protected MessageAdapter.IGuideMenuItemCallVideo callback;

    public void setChatFragmentListener(EaseChatFragmentListener chatFragmentListener) {
        this.chatFragmentListener = chatFragmentListener;
    }


    public void setGuideMenuItemCallVideo(MessageAdapter.IGuideMenuItemCallVideo callback){
        this.callback = callback;
    }

    public interface EaseChatFragmentListener {
        /**
         * 用户头像点击事件
         *
         * @param username
         */
        void onAvatarClick(String username);

        /**
         * 消息气泡框点击事件
         */
        boolean onMessageBubbleClick(Message message);

        /**
         * 消息气泡框长按事件
         */
        void onMessageBubbleLongClick(Message message);

        /**
         * 扩展输入栏item点击事件,如果要覆盖EaseChatFragment已有的点击事件，return true
         *
         * @param view
         * @param itemId
         * @return
         */
        boolean onExtendMenuItemClick(int itemId, View view);

        /**
         * 菜单消息被点击有具体的跳转要求时执行下面的回调
         */
        void onMessageItemClick(Message message, MessageList.ItemAction action);

        /**
         * 设置自定义chatrow提供者
         *
         * @return
         */
        CustomChatRowProvider onSetCustomChatRowProvider();
    }

    @Override
    public void onMessage(List<Message> msgs) {

        for (Message message : msgs) {
            // TODO 测试

            String username = null;
            username = message.from();
            // 如果是当前会话的消息，刷新聊天页面
            if (username != null && username.equals(toChatUsername)) {
                messageList.refreshSelectLast();
                // 声音和震动提示有新消息
                UIProvider.getInstance().getNotifier().viberateAndPlayTone(message);
                // TODO 测试，通知座席端 消息已读
                readMessage(message);
            } else {
                // 如果消息不是和当前聊天ID的消息
                UIProvider.getInstance().getNotifier().onNewMsg(message);
            }
        }

    }

    @Override
    public void onCmdMessage(List<Message> msgs) {

    }


    @Override
    public void onMessageStatusUpdate() {
        messageList.refreshSelectLast();
    }

    @Override
    public void onMessageSent() {
        messageList.refreshSelectLast();
    }

    // 发送消息方法
    //=============================================
    protected void sendTextMessage(String content) {
        if (content != null && content.length() > 1500) {
            ToastHelper.show(getActivity(), R.string.message_content_beyond_limit);
            return;
        }
        Message message = Message.createTxtSendMessage(content, toChatUsername);
        // Message message = Message.createTxtSendMessage(content, "kefuchannelimid_248171");
        attachMessageAttrs(message);
        ChatClient.getInstance().chatManager().sendMessage(message);
        messageList.refreshSelectLast();
    }

    protected void sendVoiceMessage(String filePath, int length) {
        if (TextUtils.isEmpty(filePath)) {
            return;
        }
        Message message = Message.createVoiceSendMessage(filePath, length, toChatUsername);
        attachMessageAttrs(message);
        ChatClient.getInstance().chatManager().sendMessage(message);
        messageList.refreshSelectLast();
    }

    protected void sendImageMessage(String imagePath) {
        if (TextUtils.isEmpty(imagePath)) {
            return;
        }
        File imageFile = new File(imagePath);
        if (!imageFile.exists()) {
            return;
        }

        Message message = Message.createImageSendMessage(imagePath, false, toChatUsername);
        attachMessageAttrs(message);
        ChatClient.getInstance().chatManager().sendMessage(message);
        messageList.refreshSelectLastDelay(MessageList.defaultDelay);
    }

    protected void sendImageMessage(Uri imageUri) {
        Message message = Message.createImageSendMessage(imageUri, false, toChatUsername);
        if (message != null) {
            attachMessageAttrs(message);
            ChatClient.getInstance().chatManager().sendMessage(message);
            messageList.refreshSelectLastDelay(MessageList.defaultDelay);
        }
    }

    protected void sendCustomEmojiMessage(String imagePath) {
        if (TextUtils.isEmpty(imagePath)) {
            return;
        }

        Message message = Message.createCustomEmojiSendMessage(imagePath, toChatUsername);
        message.setMessageTime(System.currentTimeMillis());
        attachMessageAttrs(message);
        ChatClient.getInstance().chatManager().sendMessage(message);
        messageList.refreshSelectLastDelay(MessageList.defaultDelay);
    }

    protected void sendFileMessage(String filePath) {
        Message message = Message.createFileSendMessage(filePath, toChatUsername);
        attachMessageAttrs(message);
        ChatClient.getInstance().chatManager().sendMessage(message);
        messageList.refreshSelectLastDelay(MessageList.defaultDelay);
    }

    protected void sendFileMessage(Uri fileUri) {
        Message message = Message.createFileSendMessage(fileUri, toChatUsername);
        attachMessageAttrs(message);
        ChatClient.getInstance().chatManager().sendMessage(message);
        messageList.refreshSelectLastDelay(MessageList.defaultDelay);
    }

    protected void sendLocationMessage(double latitude, double longitude, String locationAddress, String toChatUsername) {
        Message message = Message.createLocationSendMessage(latitude, longitude, locationAddress, toChatUsername);
        attachMessageAttrs(message);
        ChatClient.getInstance().chatManager().sendMessage(message);
        messageList.refreshSelectLastDelay(MessageList.defaultDelay);
    }

    protected void sendVideoMessage(String videoPath, String thumbPath, int videoLength) {
        Message message = Message.createVideoSendMessage(videoPath, thumbPath, videoLength, toChatUsername);
        attachMessageAttrs(message);
        ChatClient.getInstance().chatManager().sendMessage(message);
        messageList.refreshSelectLastDelay(MessageList.defaultDelay);
    }

    protected void sendVideoMessage(Uri videoUri, int videoLength) {
        String thumbPath = getThumbPath(videoUri);
        Message message = Message.createVideoSendMessage(videoUri, thumbPath, videoLength, toChatUsername);
        attachMessageAttrs(message);

        // send message
        ChatClient.getInstance().chatManager().sendMessage(message);
        messageList.refreshSelectLastDelay(MessageList.defaultDelay);
    }

    public void attachMessageAttrs(Message message) {
        if (visitorInfo != null) {
            message.addContent(visitorInfo);
        }
        if (queueIdentityInfo != null) {
            message.addContent(queueIdentityInfo);
        }
        if (agentIdentityInfo != null) {
            message.addContent(agentIdentityInfo);
        }
    }

    /**
     * 获取视频封面
     *
     * @param videoUri
     * @return
     */
    private String getThumbPath(Uri videoUri) {
        if (!AdapterFileUtils.isFileExistByUri(getContext(), videoUri)) {
            return "";
        }
        String filePath = UriUtils.getFilePath(getContext(), videoUri);
        File file = new File(PathUtil.getInstance().getVideoPath(), "thvideo" + System.currentTimeMillis() + ".jpeg");
        boolean createSuccess = true;
        if (!TextUtils.isEmpty(filePath) && new File(filePath).exists()) {
            try {
                FileOutputStream fos = new FileOutputStream(file);
                Bitmap ThumbBitmap = ThumbnailUtils.createVideoThumbnail(filePath, 3);
                ThumbBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                fos.close();
            } catch (Exception e) {
                e.printStackTrace();
                EMLog.e(TAG, e.getMessage());
                createSuccess = false;
            }
        } else {
            try {
                FileOutputStream fos = new FileOutputStream(file);
                MediaMetadataRetriever media = new MediaMetadataRetriever();
                media.setDataSource(getContext(), videoUri);
                Bitmap frameAtTime = media.getFrameAtTime();
                frameAtTime.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                fos.close();
            } catch (Exception e) {
                e.printStackTrace();
                EMLog.e(TAG, e.getMessage());
                createSuccess = false;
            }
        }
        return createSuccess ? file.getAbsolutePath() : "";
    }

    @Override
    public void onPause() {
        super.onPause();
        MediaManager.pause();
        Log.e("ReportDataUtils","onPause");
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQUEST_CODE_CAMERA) { // capture new image
                onActivityResultForCamera(data);
            } else if (requestCode == REQUEST_CODE_LOCAL) { // send local image
                onActivityResultForLocalPhotos(data);
            } else if (requestCode == REQUEST_CODE_SELECT_MAP) { // location
                onActivityResultForMapLocation(data);
            } else if(requestCode == REQUEST_CODE_SELECT_FILE) {
                onActivityResultForLocalFiles(data);
            }else if(requestCode == REQUEST_CODE_SELECT_VIDEO) {
                onActivityResultForLocalVideos(data);
            }
        }
    }

    /**
     * select picture from camera
     */
    protected void selectPicFromCamera() {
        if (!CommonUtils.isExitsSdcard()) {
            ToastHelper.show(getActivity(), R.string.sd_card_does_not_exist);
            return;
        }
        cameraFilePath = new File(PathUtil.getInstance().getImagePath(), EMClient.getInstance().getCurrentUser()
                + System.currentTimeMillis() + ".jpg");
        //noinspection ResultOfMethodCallIgnored
        cameraFilePath.getParentFile().mkdirs();
        startActivityForResult(
                new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT, CommonUtils.getUriForFile(getContext(), cameraFilePath)),
                REQUEST_CODE_CAMERA);
    }

    protected void selectVideoFromLocal() {
        Intent intent = new Intent();
        if(VersionUtils.isTargetQ(getActivity())) {
            intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
        }else {
            if(Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                intent.setAction(Intent.ACTION_GET_CONTENT);
            }else {
                intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
            }
        }
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("video/*");

        startActivityForResult(intent, REQUEST_CODE_SELECT_VIDEO);

    }

    /**
     * select local file
     */
    protected void selectFileFromLocal() {
        Intent intent = new Intent();
        if(VersionUtils.isTargetQ(getActivity())) {
            intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
        }else {
            if(Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                intent.setAction(Intent.ACTION_GET_CONTENT);
            }else {
                intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
            }
        }
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("*/*");

        startActivityForResult(intent, REQUEST_CODE_SELECT_FILE);
    }

    /**
     * 相机返回处理结果
     * @param data
     */
    protected void onActivityResultForCamera(Intent data) {
        if (cameraFilePath != null && cameraFilePath.exists()) {
            //检查图片是否被旋转并调整回来
            Uri restoreImageUri = ImageUtils.checkDegreeAndRestoreImage(getActivity(), Uri.parse(cameraFilePath.getAbsolutePath()));
            sendImageMessage(restoreImageUri);
        }
    }

    /**
     * 选择本地图片处理结果
     * @param data
     */
    protected void onActivityResultForLocalPhotos(@Nullable Intent data) {
        if (data != null) {
            Uri selectedImage = data.getData();
            if (selectedImage != null) {
                String filePath = UriUtils.getFilePath(getActivity(), selectedImage);
                if(!TextUtils.isEmpty(filePath) && new File(filePath).exists()) {
                    sendImageMessage(Uri.parse(filePath));
                }else {
                    AdapterFileUtils.saveUriPermission(getActivity(), selectedImage, data);
                    sendImageMessage(selectedImage);
                }
            }
        }
    }

    /**
     * 地图定位结果处理
     * @param data
     */
    protected void onActivityResultForMapLocation(@Nullable Intent data) {
        if(data != null) {
            double latitude = data.getDoubleExtra("latitude", 0);
            double longitude = data.getDoubleExtra("longitude", 0);
            String locationAddress = data.getStringExtra("address");
            if (locationAddress != null && !locationAddress.equals("")) {
                sendLocationMessage(latitude, longitude, locationAddress, toChatUsername);
            } else {
                ToastHelper.show(getActivity(), R.string.unable_to_get_loaction);
            }
        }
    }

    /**
     * 本地文件选择结果处理
     * @param data
     */
    protected void onActivityResultForLocalFiles(@Nullable Intent data) {
        if (data != null) {
            Uri uri = data.getData();
            if (uri != null) {
                String filePath = UriUtils.getFilePath(getActivity(), uri);
                if(!TextUtils.isEmpty(filePath) && new File(filePath).exists()) {
                    sendFileMessage(Uri.parse(filePath));
                }else {
                    AdapterFileUtils.saveUriPermission(getActivity(), uri, data);
                    sendFileMessage(uri);
                }
            }
        }
    }

    private void onActivityResultForLocalVideos(Intent data) {
        if (data != null) {
            Uri uri = data.getData();
            MediaPlayer mediaPlayer = new MediaPlayer();
            try {
                mediaPlayer.setDataSource(getActivity(),uri);
                mediaPlayer.prepare();
            } catch (IOException e) {
                e.printStackTrace();
            }
            int duration = mediaPlayer.getDuration();
            EMLog.d(TAG, "path = "+uri.getPath()+",duration="+duration );
            AdapterFileUtils.saveUriPermission(getActivity(), uri, data);
            sendVideoMessage(uri, duration);
        }
    }

    private boolean checkPhotosPermission(Context context) {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.TIRAMISU) {
            if(!EasyPermissions.hasPermissions(context, Manifest.permission.READ_MEDIA_IMAGES, Manifest.permission.READ_MEDIA_VISUAL_USER_SELECTED)) {
                requestImagePermission.launch(new String[]{Manifest.permission.READ_MEDIA_IMAGES, Manifest.permission.READ_MEDIA_VISUAL_USER_SELECTED});
                return false;
            }
        }else if(Build.VERSION.SDK_INT == Build.VERSION_CODES.TIRAMISU) {
            if(!EasyPermissions.hasPermissions(context, Manifest.permission.READ_MEDIA_IMAGES)) {
                requestImagePermission.launch(new String[]{Manifest.permission.READ_MEDIA_IMAGES});
                return false;
            }
        }else {
            if(!EasyPermissions.hasPermissions(context, Manifest.permission.READ_EXTERNAL_STORAGE)) {
                requestImagePermission.launch(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE});
                return false;
            }
        }
        return true;
    }

    private boolean checkVideosPermission(Context context) {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.TIRAMISU) {
            if(!EasyPermissions.hasPermissions(context, Manifest.permission.READ_MEDIA_VIDEO, Manifest.permission.READ_MEDIA_VISUAL_USER_SELECTED)) {
                requestVideoPermission.launch(new String[]{Manifest.permission.READ_MEDIA_VIDEO, Manifest.permission.READ_MEDIA_VISUAL_USER_SELECTED});
                return false;
            }
        }else if(Build.VERSION.SDK_INT == Build.VERSION_CODES.TIRAMISU) {
            if(!EasyPermissions.hasPermissions(context, Manifest.permission.READ_MEDIA_VIDEO)) {
                requestVideoPermission.launch(new String[]{Manifest.permission.READ_MEDIA_VIDEO});
                return false;
            }
        }else {
            if(!EasyPermissions.hasPermissions(context, Manifest.permission.READ_EXTERNAL_STORAGE)) {
                requestVideoPermission.launch(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE});
                return false;
            }
        }
        return true;
    }

    private boolean checkFilesPermission(Context context) {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.TIRAMISU) {
            if(!EasyPermissions.hasPermissions(context, Manifest.permission.READ_MEDIA_IMAGES, Manifest.permission.READ_MEDIA_VIDEO, Manifest.permission.READ_MEDIA_VISUAL_USER_SELECTED)) {
                requestFilePermission.launch(new String[]{Manifest.permission.READ_MEDIA_IMAGES, Manifest.permission.READ_MEDIA_VIDEO, Manifest.permission.READ_MEDIA_VISUAL_USER_SELECTED});
                return false;
            }
        }else if(Build.VERSION.SDK_INT == Build.VERSION_CODES.TIRAMISU) {
            if(!EasyPermissions.hasPermissions(context, Manifest.permission.READ_MEDIA_IMAGES, Manifest.permission.READ_MEDIA_VIDEO)) {
                requestFilePermission.launch(new String[]{Manifest.permission.READ_MEDIA_IMAGES, Manifest.permission.READ_MEDIA_VIDEO});
                return false;
            }
        }else {
            if(!EasyPermissions.hasPermissions(context, Manifest.permission.READ_EXTERNAL_STORAGE)) {
                requestFilePermission.launch(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE});
                return false;
            }
        }
        return true;
    }

    protected boolean checkIfHasPermissions(String permission, int requestCode) {
        if(!EasyPermissions.hasPermissions(getActivity(), permission)) {
            String rationale = "";
            if(requestCode == REQUEST_CODE_CAMERA) {
                rationale = getString(R.string.demo_chat_request_camera_permission);
            }else if(requestCode == REQUEST_CODE_STORAGE_PICTURE) {
                rationale = getString(R.string.demo_chat_request_read_external_storage_permission, getString(R.string.demo_chat_photo));
            }else if(requestCode == REQUEST_CODE_STORAGE_VIDEO) {
                rationale = getString(R.string.demo_chat_request_read_external_storage_permission, getString(R.string.demo_chat_video));
            }else if(requestCode == REQUEST_CODE_STORAGE_FILE) {
                rationale = getString(R.string.demo_chat_request_read_external_storage_permission, getString(R.string.demo_chat_file));
            }else if(requestCode == REQUEST_CODE_LOCATION) {
                rationale = getString(R.string.demo_chat_request_location_permission);
            }else if(requestCode == REQUEST_CODE_VOICE) {
                rationale = getString(R.string.demo_chat_request_audio_permission);
            }
            EasyPermissions.requestPermissions(this, rationale, requestCode, permission);
            return false;
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        if(requestCode == REQUEST_CODE_CAMERA) {
            selectPicFromCamera();
        }else if(requestCode == REQUEST_CODE_STORAGE_PICTURE) {
            selectPicFromLocal();
        }else if(requestCode == REQUEST_CODE_STORAGE_VIDEO) {
            selectVideoFromLocal();
        }else if(requestCode == REQUEST_CODE_STORAGE_FILE) {
            selectFileFromLocal();
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {

    }

    private void onRequestResult(Map<String, Boolean> result, int requestCode) {
        if(result != null && result.size() > 0) {
            for (Map.Entry<String, Boolean> entry : result.entrySet()) {
                android.util.Log.e("TAG", "onRequestResult: " + entry.getKey() + "  " + entry.getValue());
            }
            if(getStorageAccess(getActivity()) != StorageAccess.Denied) {
                if(requestCode == REQUEST_CODE_STORAGE_PICTURE) {
                    selectPicFromLocal();
                }else if(requestCode == REQUEST_CODE_STORAGE_VIDEO) {
                    selectVideoFromLocal();
                }else if(requestCode == REQUEST_CODE_STORAGE_FILE) {
                    selectFileFromLocal();
                }
            }
        }
    }

    private StorageAccess getStorageAccess(Context context) {
        if (EasyPermissions.hasPermissions(context, Manifest.permission.READ_MEDIA_IMAGES) ||
                EasyPermissions.hasPermissions(context, Manifest.permission.READ_MEDIA_VIDEO)) {
            // Full access on Android 13+
            return StorageAccess.Full;
        }else if(EasyPermissions.hasPermissions(context, Manifest.permission.READ_MEDIA_VISUAL_USER_SELECTED)) {
            // Partial access on Android 13+
            return StorageAccess.Partial;
        }else if(EasyPermissions.hasPermissions(context, Manifest.permission.READ_EXTERNAL_STORAGE)) {
            // Full access up to Android 12
            return StorageAccess.Full;
        }else {
            return StorageAccess.Denied;
        }
    }

    public enum StorageAccess {
        Full, Partial, Denied
    }
}
