package com.cooleshow.student.presenter.live;

import android.text.TextUtils;
import android.util.Log;

import com.cooleshow.base.data.net.BaseResponse;
import com.cooleshow.base.presenter.BasePresenter;
import com.cooleshow.base.rx.BaseObserver;
import com.cooleshow.base.utils.RequestBodyUtil;
import com.cooleshow.student.api.APIService;
import com.cooleshow.student.bean.FriendInfoBean;
import com.rong.io.live.bean.ImUserState;
import com.cooleshow.student.bean.LiveRoomInfoBean;
import com.cooleshow.student.contract.LiveRoomContract;
import com.rong.io.live.helper.LiveRTCEngineInitHelper;
import com.cooleshow.usercenter.helper.UserHelper;
import com.google.gson.Gson;
import com.rong.io.live.LiveRoomMsgConstants;
import com.rong.io.live.callback.ClickCallback;
import com.rong.io.live.callback.IRoomCallBack;
import com.rong.io.live.helper.LiveEventHelper;
import com.rong.io.live.manager.RCChatRoomMessageManager;
import com.rong.io.live.message.RCChatJoinRoomMessage;
import com.rong.io.live.message.RCChatModeMessage;
import com.rong.io.live.message.RCChatRoomCloseMessage;
import com.rong.io.live.message.RCChatRoomMemberNumMessage;
import com.rong.io.live.message.RCChatroomLocationMessage;
import com.rong.io.live.message.RCLiveBlackUserBlockMessage;
import com.rong.io.live.message.RCLiveBlackUserUnBlockMessage;
import com.rong.io.live.message.RCLiveGoodsChangeMessage;
import com.rong.io.live.message.RCOnSnappingUpMessage;
import com.rong.io.live.message.RCUserAddLikeMessage;
import com.rong.io.live.message.RCUserKickOutMessage;
import com.rong.io.live.message.RCUserLeaveRoomMessage;
import com.rong.io.live.message.RCUserLogOutUnusualMessage;
import com.rong.io.live.message.RCUserMicLeaveMessage;
import com.rong.io.live.message.RCUserSeatApplyMessage;
import com.rong.io.live.message.RCUserSeatResponseMessage;
import com.rong.io.live.message.RCUserSeatsCtrlMessage;
import com.rong.io.live.message.RCUserSyncAddLikeCountMessage;

import java.util.ArrayList;
import java.util.List;

import cn.rongcloud.rtc.api.RCRTCEngine;
import cn.rongcloud.rtc.api.RCRTCRemoteUser;
import cn.rongcloud.rtc.api.RCRTCRoom;
import cn.rongcloud.rtc.api.callback.IRCRTCResultCallback;
import cn.rongcloud.rtc.api.callback.IRCRTCResultDataCallback;
import cn.rongcloud.rtc.api.callback.IRCRTCRoomEventsListener;
import cn.rongcloud.rtc.api.callback.IRCRTCSwitchRoleCallback;
import cn.rongcloud.rtc.api.callback.IRCRTCSwitchRoleDataCallback;
import cn.rongcloud.rtc.api.stream.RCRTCAudioInputStream;
import cn.rongcloud.rtc.api.stream.RCRTCAudioOutputStream;
import cn.rongcloud.rtc.api.stream.RCRTCInputStream;
import cn.rongcloud.rtc.api.stream.RCRTCLiveInfo;
import cn.rongcloud.rtc.api.stream.RCRTCOutputStream;
import cn.rongcloud.rtc.api.stream.RCRTCVideoInputStream;
import cn.rongcloud.rtc.api.stream.RCRTCVideoOutputStream;
import cn.rongcloud.rtc.base.RCRTCLiveRole;
import cn.rongcloud.rtc.base.RCRTCMediaType;
import cn.rongcloud.rtc.base.RTCErrorCode;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.observers.DisposableObserver;
import io.reactivex.rxjava3.schedulers.Schedulers;
import io.rong.imkit.IMCenter;
import io.rong.imlib.IRongCoreCallback;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.MessageContent;
import okhttp3.RequestBody;

/**
 * Author by pq, Date on 2022/3/29.
 */
public class LiveRoomPresenter extends BasePresenter<LiveRoomContract.view> implements LiveRoomContract.Presenter {
    private boolean isInRoom;//是否已经在房间
    private LiveRoomInfoBean currentRoomInfo;
    private int addLikeCount = 0;
    private List<String> shields = new ArrayList<>();//当前屏蔽词
    private List<Disposable> disposablesManager = new ArrayList<>();//监听管理器
    private final IRCRTCRoomEventsListener mRoomEventsListener = new IRCRTCRoomEventsListener() {
        @Override
        public void onRemoteUserPublishResource(RCRTCRemoteUser rcrtcRemoteUser, List<RCRTCInputStream> list) {
            Log.i("pq", "onRemoteUserPublishResource:");
            if (getView() != null) {
                getView().onRemoteUserPublishResource(rcrtcRemoteUser.getUserId());
            }
        }

        @Override
        public void onRemoteUserMuteAudio(RCRTCRemoteUser rcrtcRemoteUser, RCRTCInputStream rcrtcInputStream, boolean b) {
            Log.i("pq", "onRemoteUserMuteAudio:" + b);
            if (getView() != null) {
                getView().syncAudioStatus(b);
            }
        }

        @Override
        public void onRemoteUserMuteVideo(RCRTCRemoteUser rcrtcRemoteUser, RCRTCInputStream rcrtcInputStream, boolean b) {
        }

        @Override
        public void onRemoteUserUnpublishResource(RCRTCRemoteUser rcrtcRemoteUser, List<RCRTCInputStream> list) {
            Log.i("pq", "onRemoteUserUnpublishResource");
            if (getView() != null) {
                getView().showCloseVideoView();
            }
        }

        @Override
        public void onUserJoined(RCRTCRemoteUser rcrtcRemoteUser) {
            //当房间中用户使用RCRTCLocalUser#switchToBroadcaster 方法上麦成功时
            // ，房间中观众会收到IRCRTCRoomEventsListener#onUserJoined 回调。
            if (null != getView()) {
                getView().onUserJoinRoom(rcrtcRemoteUser);
            }
        }

        @Override
        public void onSwitchRole(String userId, RCRTCLiveRole role) {
            super.onSwitchRole(userId, role);
            //当房间内的用户使用 RCRTCLocalUser#switchToBroadcaster 或 RCRTCLocalUser#switchToAudience 方法上下麦时
            // ，同房间内的其他主播会收到 IRCRTCRoomEventsListener#onSwitchRole 回调。
            if (getView() != null) {
                getView().onSwitchRole(userId, role);
            }
        }

        @Override
        public void onUserLeft(RCRTCRemoteUser rcrtcRemoteUser) {
            if (getView() != null) {
                getView().onUserLeftRoomMic(rcrtcRemoteUser);
            }
        }

        @Override
        public void onUserOffline(RCRTCRemoteUser rcrtcRemoteUser) {
            if (getView() != null) {
                getView().onUserOfflineRoomMic(rcrtcRemoteUser);
            }
        }

        @Override
        public void onPublishLiveStreams(List<RCRTCInputStream> list) {
            Log.i("pq", "onPublishLiveStreams");
        }

        @Override
        public void onUnpublishLiveStreams(List<RCRTCInputStream> list) {
            Log.i("pq", "onUnpublishLiveStreams");
            if (getView() != null) {
                getView().showRestView();
            }
        }


        /**
         * 自己退出房间。 例如断网退出等
         * @param i 状态码
         */
        @Override
        public void onLeaveRoom(int i) {
            Log.i("pq", "onLeaveRoom:" + i);
        }
    };

    public void init(String roomId, boolean isCreate) {
//        LiveEventHelper.getInstance().addLiveRoomListeners(this);
        isInRoom = TextUtils.equals(LiveEventHelper.getInstance().getRoomId(), roomId);
        RongIMClient.ConnectionStatusListener.ConnectionStatus currentConnectionStatus = RongIMClient.getInstance().getCurrentConnectionStatus();
        if (currentConnectionStatus == RongIMClient.ConnectionStatusListener.ConnectionStatus.CONNECTED) {
            Log.i("pq", "LiveRoomActivity init getRoomInfo");
            getRoomInfo(roomId);
        }else {
            connectIM();
        }

    }

    public void connectIM() {
        String imtoken = UserHelper.getUserIMToken();
        Log.i("pq", "im未连接,申请连接token:" + imtoken);
        if (TextUtils.isEmpty(imtoken)) {
            return;
        }
        IMCenter.getInstance().connect(imtoken, new RongIMClient.ConnectCallback() {
            @Override
            public void onSuccess(String t) {
                Log.i("pq", "连接成功");
            }

            @Override
            public void onError(RongIMClient.ConnectionErrorCode e) {
                Log.i("pq", "connect error" + e);
            }

            @Override
            public void onDatabaseOpened(RongIMClient.DatabaseOpenStatus code) {

            }
        });
    }

    public void setAddLikeCount(int addLikeCount) {
        this.addLikeCount = addLikeCount;
    }


    /**
     * 获取房间信息
     *
     * @param roomId
     */
    @Override
    public void getRoomInfo(String roomId) {
        addSubscribe(create(APIService.class).getLiveRoomInfo(roomId), new BaseObserver<LiveRoomInfoBean>(getView()) {
            @Override
            protected void onSuccess(LiveRoomInfoBean data) {
                Log.i("pq", "getRoomInfo success" + data);
                currentRoomInfo = data;
                setObMessageListener(data.roomUid);
                if (getView() != null) {
                    getView().getRoomInfoSuccess(data);
                }
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                e.printStackTrace();
                if (getView() != null) {
                    getView().getRoomInfoError(e);
                }
            }
        });
    }

    @Override
    public void notifyJoinRoomAction(String roomId, String userId) {
        //主进程调用,因为BaseObserver onStart show了loading控件,防止在子线程创建
        addSubscribe(create(APIService.class).notifyJoinRoomAction(roomId, userId), new DisposableObserver() {
            @Override
            public void onNext(Object o) {
                //通知服务端加入成功即可,无须关注结果
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
            }

            @Override
            public void onComplete() {

            }
        });
    }

    @Override
    public void notifyLeaveRoomAction() {
        handleAction(LiveRoomMsgConstants.ACTION_SEND_LEAVE_ROOM);
        ImUserState imUserState = new ImUserState();
        imUserState.setStatus(ImUserState.ACTION_LEAVE_LIVE_ROOM);
        imUserState.setUserid(UserHelper.getUserId());
        ArrayList<ImUserState> imUserStates = new ArrayList();
        imUserStates.add(imUserState);
        RequestBody body = RequestBodyUtil.convertToRequestBodyJson(new Gson().toJson(imUserStates));
        create(APIService.class).notifyLeaveRoomAction(body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseResponse<Object>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(BaseResponse<Object> objectBaseResponse) {
                        //通知服务端离开即可,无须关注结果
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                        //通知服务端离开即可,无须关注结果
                    }
                });
    }

    @Override
    public void getUserInfoByUserId(String userId) {
        addSubscribe(create(APIService.class).queryFriendDetail(userId), new DisposableObserver<BaseResponse<FriendInfoBean>>() {
            @Override
            public void onNext(BaseResponse<FriendInfoBean> friendInfoBeanBaseResponse) {
                if (getView() != null && friendInfoBeanBaseResponse != null) {
                    getView().getFriendInfoSuccess(friendInfoBeanBaseResponse.getData());
                }
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
            }

            @Override
            public void onComplete() {

            }
        });
    }

    /**
     * 处理直播间的行为
     *
     * @param action
     */
    @Override
    public void handleAction(int action) {
        switch (action) {
            case LiveRoomMsgConstants.ACTION_SEND_JOIN_ROOM:
                //发送加入房间成功消息
                RCChatJoinRoomMessage rcChatJoinRoomMessage = new RCChatJoinRoomMessage();
                sendMessage(rcChatJoinRoomMessage, true);
                break;
            case LiveRoomMsgConstants.ACTION_SEND_ADD_LIKE_COUNT:
                //发送点赞数量
                RCUserAddLikeMessage addLikeMessage = new RCUserAddLikeMessage();
                addLikeMessage.setCounts(addLikeCount);
                sendMessage(addLikeMessage, false);
                break;
            case LiveRoomMsgConstants.ACTION_SEND_LEAVE_ROOM:
                //退出直播间消息
                RCUserLeaveRoomMessage rcUserLeaveRoomMessage = new RCUserLeaveRoomMessage();
                rcUserLeaveRoomMessage.setUserId(UserHelper.getUserId());
                rcUserLeaveRoomMessage.setUserName(UserHelper.getUserName());
                sendMessage(rcUserLeaveRoomMessage, false);
                break;
            case LiveRoomMsgConstants.ACTION_SEND_SEAT_APPLY:
                //申请连麦
                RCUserSeatApplyMessage rcUserSeatApplyMessage = new RCUserSeatApplyMessage();
                rcUserSeatApplyMessage.setType(LiveRoomMsgConstants.MIC_ACTION_SEAT_BY_USER);
                if (currentRoomInfo != null) {
                    rcUserSeatApplyMessage.setTeacherId(currentRoomInfo.speakerId);
                    rcUserSeatApplyMessage.setTeacherName(currentRoomInfo.speakerName);
                }
                rcUserSeatApplyMessage.setAudienceId(UserHelper.getUserId());
                rcUserSeatApplyMessage.setAudienceName(UserHelper.getUserName());
                rcUserSeatApplyMessage.setAudienceAvatar(UserHelper.getUserAvatar());
                sendMessage(rcUserSeatApplyMessage, true);
                break;
            case LiveRoomMsgConstants.ACTION_SEND_CANCEL_SEAT_APPLY:
                //取消连麦申请
                RCUserSeatApplyMessage cancelApplyMessage = new RCUserSeatApplyMessage();
                cancelApplyMessage.setType(LiveRoomMsgConstants.MIC_ACTION_CANCEL_SEAT_BY_USER);
                if (currentRoomInfo != null) {
                    cancelApplyMessage.setTeacherId(currentRoomInfo.speakerId);
                    cancelApplyMessage.setTeacherName(currentRoomInfo.speakerName);
                }
                cancelApplyMessage.setAudienceId(UserHelper.getUserId());
                cancelApplyMessage.setAudienceName(UserHelper.getUserName());
                sendMessage(cancelApplyMessage, true);
                break;
            case LiveRoomMsgConstants.ACTION_SEND_DOWN_SEAT_MIC:
                //观众下麦消息
                RCUserMicLeaveMessage rcUserMicLeaveMessage = new RCUserMicLeaveMessage();
                rcUserMicLeaveMessage.setAudienceId(UserHelper.getUserId());
                rcUserMicLeaveMessage.setAudienceName(UserHelper.getUserName());
                sendMessage(rcUserMicLeaveMessage, false);
                break;
            case LiveRoomMsgConstants.ACTION_SEND_CANCEL_SEAT_AGREE_RESPONSE:
                //被邀请上麦->观众同意上麦
                RCUserSeatResponseMessage rcUserSeatResponseMessage = new RCUserSeatResponseMessage();
                rcUserSeatResponseMessage.setType(LiveRoomMsgConstants.MIC_RESPONSE_AGREE_BY_USER);
                if (currentRoomInfo != null) {
                    rcUserSeatResponseMessage.setTeacherId(currentRoomInfo.speakerId);
                    rcUserSeatResponseMessage.setTeacherName(currentRoomInfo.speakerName);
                }
                rcUserSeatResponseMessage.setAudienceId(UserHelper.getUserId());
                rcUserSeatResponseMessage.setAudienceName(UserHelper.getUserName());
                sendMessage(rcUserSeatResponseMessage, true);
                break;
            case LiveRoomMsgConstants.ACTION_SEND_CANCEL_SEAT_DISAGREE_RESPONSE:
                //被邀请上麦->观众不同意上麦
                RCUserSeatResponseMessage disAgreeSeatResponseMessage = new RCUserSeatResponseMessage();
                disAgreeSeatResponseMessage.setType(LiveRoomMsgConstants.MIC_RESPONSE_DISAGREE_BY_USER);
                if (currentRoomInfo != null) {
                    disAgreeSeatResponseMessage.setTeacherId(currentRoomInfo.speakerId);
                    disAgreeSeatResponseMessage.setTeacherName(currentRoomInfo.speakerName);
                }
                disAgreeSeatResponseMessage.setAudienceId(UserHelper.getUserId());
                disAgreeSeatResponseMessage.setAudienceName(UserHelper.getUserName());
                sendMessage(disAgreeSeatResponseMessage, true);
                break;
            case LiveRoomMsgConstants.ACTION_SEND_ON_SNAP_UP:
                //发送正在抢购消息
                RCOnSnappingUpMessage rcOnSnappingUpMessage = new RCOnSnappingUpMessage();
                rcOnSnappingUpMessage.setUserId(UserHelper.getUserId());
                rcOnSnappingUpMessage.setUserName(UserHelper.getUserName());
                sendMessage(rcOnSnappingUpMessage, true);
                break;
        }
    }

    public void joinChartRoom(String chatroomId, final IRongCoreCallback.OperationCallback callback) {
        LiveEventHelper.getInstance().joinChatRoom(chatroomId, callback);
    }

    /**
     * 先退出上次房间，再加入房间
     *
     * @param roomId
     * @param isCreate
     * @param isExit
     */
    public void leaveRoom(String roomId, boolean isCreate, boolean isExit) {
        LiveEventHelper.getInstance().leaveRoom(new IRoomCallBack() {
            @Override
            public void onSuccess() {
                if (isExit) {
                    getView().getContentView().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            joinRoom(roomId, isCreate);
                        }
                    }, 1000);
                }
            }

            @Override
            public void onError(int code, String message) {
                Log.i("pq", "leaveRoom onError:" + code + "-msg:" + message);
                if (isExit) {
                    joinRoom(roomId, isCreate);
                }
            }
        });
    }

    /**
     * 加入房间
     *
     * @param roomId
     * @param isCreate
     */
    private void joinRoom(String roomId, boolean isCreate) {
        //如果是观众就直接加入房间
        Log.i("pq", "joinRoom");
        LiveEventHelper.getInstance().joinRoom(roomId,RCRTCLiveRole.AUDIENCE,new ClickCallback<Boolean>() {
            @Override
            public void onResult(Boolean result, String msg) {
                Log.i("pq", "joinRoom onResult:" + result+"->"+msg);
                if (result) {
                    setCurrentRoom(currentRoomInfo, isCreate);
                    refreshMusicView(true);
                } else {
                    //加入直播房间失败
                    if (getView() != null) {
                        getView().showFinishView();
                    }
                    leaveRoom(roomId, isCreate, false);
                }
            }
        });
    }

    /**
     * 下麦
     */
    public void exitMic() {
        // 开始切换为观众身份
        RCRTCEngine.getInstance().getRoom().getLocalUser().switchToAudience(new IRCRTCSwitchRoleCallback() {

            /**
             * 当切换失败且SDK处于无法回退状态时回调，该角色已经无法使用当前角色继续进行音视频。
             * SDK内部会退出房间并清理所有资源，该用户只能重新加入房间才能继续音视频。
             */
            @Override
            public void onKicked() {
                Log.i("pq", "下麦身份切换onKicked");
            }

            @Override
            public void onSuccess() {
                // 该用户切换为观众成功，可以以观众身份进行音视频
                Log.i("pq", "下麦身份切换成功");
                if (getView() != null) {
                    getView().onExitSeatMicSuccess();
                    subscribeAVStream();
                }
            }

            /**
             * 当切换失败且不影响当前角色继续音视频时回调
             * @param errorCode 失败错误码
             */
            @Override
            public void onFailed(RTCErrorCode errorCode) {
                Log.i("pq", "下麦身份切换failed" + errorCode);
            }
        });
    }

    /**
     * 上麦
     */
    public void joinMic() {
        //连麦
        ArrayList<RCRTCOutputStream> streams = new ArrayList<>();
        streams.add(RCRTCEngine.getInstance().getDefaultAudioStream());
        // 开始切换为主播身份
        RCRTCEngine.getInstance().getRoom().getLocalUser().switchToBroadcaster(streams, new IRCRTCSwitchRoleDataCallback<RCRTCLiveInfo>() {
            /**
             * 当切换失败且SDK处于无法回退状态时回调，该角色已经无法使用当前角色继续进行音视频。
             * SDK内部会退出房间并清理所有资源，该用户只能重新加入房间才能继续音视频。
             */
            @Override
            public void onKicked() {
                Log.i("pq", "上麦身份切换kick");
            }

            @Override
            public void onSuccess(RCRTCLiveInfo data) {
                //该用户切换为主播成功，可以以主播身份进行音视频
                Log.i("pq", "上麦身份切换成功");
                if (getView() != null) {
                    getView().onSeatMicSuccess();
                    subscribeAVStream();
                }
            }

            /**
             * 当切换失败且不影响当前角色继续音视频时回调
             * @param errorCode 失败错误码
             */
            @Override
            public void onFailed(RTCErrorCode errorCode) {
                Log.i("pq", "上麦身份切换失败:" + errorCode);
                if (getView() != null) {
                    getView().onSeatMicFail();
                }
            }
        });
    }

    /**
     * 设置当前房间
     *
     * @param roomInfo
     * @param isCreate
     */
    public void setCurrentRoom(LiveRoomInfoBean roomInfo, boolean isCreate) {
        initLiveRoomListener(roomInfo.roomUid);
        if (isInRoom) {
            //恢复一下当前信息就可以了
            List<MessageContent> messageList = LiveEventHelper.getInstance().getMessageList();
            getView().addMessageList(messageList, true);
        } else {
            // 发送默认消息
            sendDefaultMessage();
        }
        //初次进入的时候，获取房间内的人数信息
//        MemberCache.getInstance().fetchData(currentRoomInfo.getRoomId());
        //设置创建者id
        LiveEventHelper.getInstance().setCreateUserId(roomInfo.speakerId);
        //最好在订阅流之前再设置一次扬声器模式,不然可能有部分手机有问题,
        // 在初始化的时候设置扬声器的状态相当于给扬声器一个初始值，时机过于早，
        // 很可能硬件层还没有准备好。在需要用到扬声器的时候，再设置一下就好了
        LiveRTCEngineInitHelper.setRTCSpeakerMode(true);
//        getShield();获取敏感词汇
        subscribeAVStream();
        getView().setRoomData(currentRoomInfo);
    }

    /**
     * 加入房间后，开始摄像头采集并发布音视频流。
     */
    private void startPublish() {
        RCRTCRoom rcrtcRoom = LiveEventHelper.getInstance().getRtcRoom();
        RCRTCEngine.getInstance().getDefaultVideoStream().startCamera(null);
        rcrtcRoom.getLocalUser().publishDefaultLiveStreams(new IRCRTCResultDataCallback<RCRTCLiveInfo>() {
            @Override
            public void onSuccess(RCRTCLiveInfo liveInfo) {
                if (getView() != null) {
                    getView().onPublishSuccess();
                }
            }

            @Override
            public void onFailed(RTCErrorCode code) {
                Log.i("pq", "publishDefaultLiveStreamError:" + code);
            }
        });
    }

    /**
     * 进入房间后发送默认的消息
     */
    private void sendDefaultMessage() {
        if (currentRoomInfo != null) {
//            getView().addMessageContent(null, true);
            // 默认消息
//            RCChatroomLocationMessage welcome = new RCChatroomLocationMessage();
//            welcome.setContent(String.format("欢迎来到 %s", currentRoomInfo.roomTitle));
//            sendMessage(welcome);
            RCChatroomLocationMessage tips = new RCChatroomLocationMessage();
            tips.setContent("欢迎进入直播课堂，请遵守相关法规，禁止传播低俗、暴力等不良信息。为孩子创造健康绿色的学习环境。");
            sendMessage(tips);
        }
    }

    /**
     * 发送消息
     * 默认显示在本地
     *
     * @param messageContent
     */
    public void sendMessage(MessageContent messageContent) {
        sendMessage(messageContent, true);
    }

    /**
     * 发送消息
     *
     * @param messageContent 消息体
     * @param isShowLocation 是否显示在本地
     */
    public void sendMessage(MessageContent messageContent, boolean isShowLocation) {
        if (!isContainsShield(messageContent)) {
            LiveEventHelper.getInstance().sendMessage(messageContent, isShowLocation);
        }
    }

    /**
     * 是否包含屏蔽词
     *
     * @return
     */
    private boolean isContainsShield(MessageContent messageContent) {
        boolean isContains = false;
//        if (shields != null) {
//            for (String shield : shields) {
//                if (messageContent instanceof RCChatroomBarrage) {
//                    if (((RCChatroomBarrage) messageContent).getContent().contains(shield)) {
//                        isContains = true;
//                        break;
//                    }
//                }
//            }
//            if (isContains) {
//                //如果是包含了敏感词'
//                mView.addMessageContent(messageContent, false);
//                return true;
//            }
//        }
        return false;
    }

    /**
     * 设置直播房的各种监听
     *
     * @param roomId
     */
    public void initLiveRoomListener(String roomId) {
        LiveEventHelper.getInstance().getRtcRoom().registerRoomListener(mRoomEventsListener);
        //添加消息监听
//        setObShieldListener();
//        //监听房间里面的人
//        MemberCache.getInstance().getMemberList()
//                .observe( new Observer<List<User>>() {
//                    @Override
//                    public void onChanged(List<User> users) {
//                        getView().setOnlineCount(users.size());
//                        LiveEventHelper.getInstance().getRequestLiveVideoIds(null);
//                        onInviteLiveVideoIds(users);
//                    }
//                });
//        //监听管理员变化
//        MemberCache.getInstance().getAdminList()
//                .observe(((LiveRoomFragment) mView).getViewLifecycleOwner(), new Observer<List<String>>() {
//                    @Override
//                    public void onChanged(List<String> strings) {
//                        mView.refreshMessageList();
//                    }
//                });
    }

    /**
     * 监听接收房间的所有信息
     *
     * @param roomId
     */
    public void setObMessageListener(String roomId) {
        if (disposablesManager.size() != 0) {
            return;
        }
        Disposable subscribe = RCChatRoomMessageManager.
                obMessageReceiveByRoomId(roomId)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Message>() {
                    @Override
                    public void accept(Message message) {
//                        //将消息显示到列表上
                        if (LiveEventHelper.getInstance().isShowingMessage(message.getContent())) {
                            if (null != getView()) {
                                getView().addMessageContent(message, false);
                            }
                        }

                        if (TextUtils.equals(message.getObjectName(), LiveRoomMsgConstants.TAG_CHAT_ROOM_ENTER)) {
                            //加入房间消息
                            if (null != getView() && message.getContent() != null) {
                                RCChatJoinRoomMessage joinRoomMessage = (RCChatJoinRoomMessage) message.getContent();
                                getView().receiveJoinMessage(joinRoomMessage);
                            }
                            return;
                        }

                        if (TextUtils.equals(message.getObjectName(), LiveRoomMsgConstants.TAG_LIVE_ON_SNAP_UP)) {
                            //抢购消息
                            if (null != getView() && message.getContent() != null) {
                                RCOnSnappingUpMessage rcOnSnappingUpMessage = (RCOnSnappingUpMessage) message.getContent();
                                getView().receiveSnapUpMessage(rcOnSnappingUpMessage);
                            }
                            return;
                        }


                        //以下为行为消息逻辑
                        //行为消息
                        MessageContent content = message.getContent();
                        if (content instanceof RCChatRoomCloseMessage) {
                            //关闭直播间
                            if (null != getView()) {
                                getView().liveRoomOffline();
                            }
                            return;
                        }

                        if (TextUtils.equals(message.getObjectName(), LiveRoomMsgConstants.TAG_LIVE_GOODS_CHANGE)) {
                            //直播间商品变化
                            if (message.getContent() != null) {
                                RCLiveGoodsChangeMessage liveGoodsChangeMessage = (RCLiveGoodsChangeMessage) message.getContent();
                                if (getView() != null && liveGoodsChangeMessage != null) {
                                    getView().liveGoodsChange(liveGoodsChangeMessage.getContent());
                                }
                            }
                            return;
                        }

                        //连麦模式控制消息
                        if (TextUtils.equals(message.getObjectName(), LiveRoomMsgConstants.TAG_CHAT_ROOM_SEAT_CTRL)) {
                            if (message.getContent() != null) {
                                RCUserSeatsCtrlMessage userSeatsCtrlMessage = (RCUserSeatsCtrlMessage) message.getContent();
                                if (getView() != null && userSeatsCtrlMessage != null) {
                                    getView().changeMicControlMode(userSeatsCtrlMessage.isSeatBan());
                                }
                            }
                            return;
                        }

                        //控制聊天模式
                        if (TextUtils.equals(message.getObjectName(), LiveRoomMsgConstants.TAG_CHAT_ROOM_CHAT_MODE_CTRL)) {
                            if (message.getContent() != null) {
                                RCChatModeMessage chatModeMessage = (RCChatModeMessage) message.getContent();
                                if (getView() != null && chatModeMessage != null) {
                                    getView().switchChatMode(chatModeMessage.isChatBan());
                                }
                            }
                            return;
                        }

                        if (TextUtils.equals(message.getObjectName(), LiveRoomMsgConstants.TAG_CHAT_ROOM_ADD_LIKE_COUNT)) {
                            //同步点赞消息
                            RCUserSyncAddLikeCountMessage addLikeMessage = (RCUserSyncAddLikeCountMessage) content;
                            if (getView() != null) {
                                getView().onAddLikeMessage(message, addLikeMessage);
                            }
                            return;
                        }

                        if (content instanceof RCChatRoomMemberNumMessage) {
                            //同步成员数量
                            if (null != getView()) {
                                RCChatRoomMemberNumMessage rcChatRoomMemberNumMessage = (RCChatRoomMemberNumMessage) content;
                                getView().syncMemberCount(rcChatRoomMemberNumMessage.getCount());
                            }
                            return;
                        }

                        if (content instanceof RCUserKickOutMessage) {
                            //用户被踢出房间消息
                            if (null != getView()) {
                                RCUserKickOutMessage userKickOutMessage = (RCUserKickOutMessage) content;
                                getView().onUserKickOutMsg(userKickOutMessage);
                            }
                            return;
                        }

                        if (content instanceof RCUserSeatResponseMessage) {
                            //连麦回复消息
                            if (null != getView()) {
                                RCUserSeatResponseMessage rcUserSeatResponseMessage = (RCUserSeatResponseMessage) content;
                                if (rcUserSeatResponseMessage == null || TextUtils.isEmpty(rcUserSeatResponseMessage.getAudienceId())) {
                                    return;
                                }
                                if (TextUtils.equals(rcUserSeatResponseMessage.getAudienceId(), UserHelper.getUserId())) {
                                    getView().seatResponse(rcUserSeatResponseMessage);
                                }
                                return;
                            }
                        }

                        if (TextUtils.equals(message.getObjectName(), LiveRoomMsgConstants.TAG_CHAT_ROOM_MIC_APPLY)) {
                            //主播邀请上麦
                            RCUserSeatApplyMessage seatApplyMessage = (RCUserSeatApplyMessage) content;
                            if (getView() != null) {
                                getView().onInviteSeatMic(seatApplyMessage);
                            }
                            return;
                        }

                        if (TextUtils.equals(message.getObjectName(), LiveRoomMsgConstants.TAG_CHAT_ROOM_UNUSUAL_LOGOUT)) {
                            //观众异常退出消息
                            RCUserLogOutUnusualMessage loginOutUnusualMessage = (RCUserLogOutUnusualMessage) content;
                            if (getView() != null) {
                                getView().onUserUnusualLogout(loginOutUnusualMessage);
                            }
                            return;
                        }

                        if (TextUtils.equals(message.getObjectName(), LiveRoomMsgConstants.TAG_LIVE_PAUSE)) {
                            //暂停直播,进行下麦操作
                            if (getView() != null) {
                                getView().onLivePause();
                            }
                            return;
                        }

                        if (TextUtils.equals(message.getObjectName(), LiveRoomMsgConstants.TAG_LIVE_ADD_BLACK_USER)) {
                            //添加黑名单用户
                            RCLiveBlackUserBlockMessage blackUserBlockMessage = (RCLiveBlackUserBlockMessage) content;
                            if (getView() != null) {
                                getView().changeBlackUserStatus(blackUserBlockMessage.getUserId(), true);
                            }
                            return;
                        }

                        if (TextUtils.equals(message.getObjectName(), LiveRoomMsgConstants.TAG_LIVE_REMOVE_BLACK_USER)) {
                            //解除黑名单用户
                            RCLiveBlackUserUnBlockMessage userUnBlockMessage = (RCLiveBlackUserUnBlockMessage) content;
                            if (getView() != null) {
                                getView().changeBlackUserStatus(userUnBlockMessage.getUserId(), false);
                            }
                            return;
                        }
                    }
                });
        disposablesManager.add(subscribe);
    }

    /**
     * 刷新音乐播放的小窗UI
     *
     * @param show 是否显示
     */
    private void refreshMusicView(boolean show) {
//        if (show) {
//            MusicApi.getPlayingMusic(getRoomId(), new IResultBack<MusicBean>() {
//                @Override
//                public void onResult(MusicBean musicBean) {
//                    if (musicBean != null) {
//                        mView.refreshMusicView(true, musicBean.getNameAndAuthor(), musicBean.getBackgroundUrl());
//                    } else {
//                        mView.refreshMusicView(false, "", "");
//                    }
//                }
//            });
//        } else {
//            mView.refreshMusicView(false, "", "");
//        }
    }

    /**
     * 获得当前视频流
     */
    public void getVideoStream(List<RCRTCVideoOutputStream> outputStreams, List<RCRTCVideoInputStream> inputStreams, List<RCRTCAudioInputStream> audioinputstream) {
        RCRTCRoom mRtcRoom = LiveEventHelper.getInstance().getRtcRoom();
        if (mRtcRoom == null) {
            return;
        }
        for (final RCRTCRemoteUser remoteUser : mRtcRoom.getRemoteUsers()) {
            if (remoteUser.getStreams().size() == 0) {
                continue;
            }
            List<RCRTCInputStream> userStreams = remoteUser.getStreams();
            for (RCRTCInputStream i : userStreams) {
                if (i.getMediaType() == RCRTCMediaType.VIDEO) {
                    inputStreams.add((RCRTCVideoInputStream) i);
                }
                if (i.getMediaType() == RCRTCMediaType.AUDIO) {
                    audioinputstream.add((RCRTCAudioInputStream) i);
                }
            }
        }

        for (RCRTCOutputStream o : mRtcRoom.getLocalUser().getStreams()) {
            if (o.getMediaType() == RCRTCMediaType.VIDEO) {
                outputStreams.add((RCRTCVideoOutputStream) o);
            }
        }
    }

    /**
     * 获得当前房间所有的视频流和音频流
     */
    public void getAllStreams(List<RCRTCVideoOutputStream> outputStreams, List<RCRTCVideoInputStream> inputStreams, List<RCRTCAudioInputStream> audioinputstream, List<RCRTCAudioOutputStream> audioOutputStreams) {
        RCRTCRoom mRtcRoom = LiveEventHelper.getInstance().getRtcRoom();
        if (mRtcRoom == null) {
            return;
        }
        for (final RCRTCRemoteUser remoteUser : mRtcRoom.getRemoteUsers()) {
            if (remoteUser.getStreams().size() == 0) {
                continue;
            }
            List<RCRTCInputStream> userStreams = remoteUser.getStreams();
            for (RCRTCInputStream i : userStreams) {
                if (i.getMediaType() == RCRTCMediaType.VIDEO) {
                    inputStreams.add((RCRTCVideoInputStream) i);
                }
                if (i.getMediaType() == RCRTCMediaType.AUDIO) {
                    audioinputstream.add((RCRTCAudioInputStream) i);
                }
            }
        }

        for (RCRTCOutputStream o : mRtcRoom.getLocalUser().getStreams()) {
            if (o.getMediaType() == RCRTCMediaType.VIDEO) {
                outputStreams.add((RCRTCVideoOutputStream) o);
            }
            if (o.getMediaType() == RCRTCMediaType.AUDIO) {
                audioOutputStreams.add((RCRTCAudioOutputStream) o);
            }
        }
    }

    /**
     * 获取房间所有的音频流
     *
     * @param audioinputstream
     * @param audioOutputStreams
     */
    public void getAudioStreams(List<RCRTCAudioInputStream> audioinputstream, List<RCRTCAudioOutputStream> audioOutputStreams) {
        RCRTCRoom mRtcRoom = LiveEventHelper.getInstance().getRtcRoom();
        if (mRtcRoom == null) {
            return;
        }

        for (final RCRTCRemoteUser remoteUser : mRtcRoom.getRemoteUsers()) {
            if (remoteUser.getStreams().size() == 0) {
                continue;
            }
            List<RCRTCInputStream> userStreams = remoteUser.getStreams();
            for (RCRTCInputStream i : userStreams) {
                if (i.getMediaType() == RCRTCMediaType.AUDIO) {
                    audioinputstream.add((RCRTCAudioInputStream) i);
                }
            }
        }

        for (RCRTCOutputStream o : mRtcRoom.getLocalUser().getStreams()) {
            if (o.getMediaType() == RCRTCMediaType.AUDIO) {
                audioOutputStreams.add((RCRTCAudioOutputStream) o);
            }
        }
    }


    /**
     * 主动订阅远端用户发布的流
     * 视频流需要用户设置用于显示载体的videoview
     */
    public void subscribeAVStream() {
        RCRTCRoom rcrtcRoom = LiveEventHelper.getInstance().getRtcRoom();
        if (rcrtcRoom == null) {
            Log.i("pq", "rcrtcRoom is null");
            return;
        }
        List<RCRTCRemoteUser> remoteUsers = rcrtcRoom.getRemoteUsers();
        final List<RCRTCInputStream> inputStreams = new ArrayList<>();
        for (int i = 0; i < remoteUsers.size(); i++) {
            RCRTCRemoteUser rcrtcRemoteUser = remoteUsers.get(i);
            List<RCRTCInputStream> streams = rcrtcRemoteUser.getStreams();
            if (streams == null || streams.size() == 0) {
                continue;
            }
            inputStreams.addAll(streams);
        }
        //合流模式,画面会出现问题,画面放大,裁剪,可能是合流模式布局问题
//        final List<RCRTCInputStream> otherInputStreams = rcrtcRoom.getLiveStreams();
        if (inputStreams != null && inputStreams.size() != 0) {
            rcrtcRoom.getLocalUser().subscribeStreams(inputStreams, new IRCRTCResultCallback() {
                @Override
                public void onSuccess() {
                    Log.i("pq", "subscribeStreams onSuccess:" + inputStreams.size());
                    try {
                        getView().subscribeAVStreamSuccess(inputStreams);
                    } catch (IllegalStateException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailed(RTCErrorCode code) {
                    Log.i("pq", "subscribeStreams code:" + code);
                    try {
                        getView().onSubscribeFailed();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } else {
            Log.i("pq", "当前房间还没有主播");
            try {
                getView().showEmptyStatusView();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void detachView() {
        super.detachView();
        unInitListener();
    }

    /**
     * 回收掉对房间的各种监听
     */
    public void unInitListener() {
        clearDisposables();
    }

    public void clearDisposables() {
        for (Disposable disposable : disposablesManager) {
            Log.i("pq", "disposable" + disposable);
            disposable.dispose();
        }
        disposablesManager.clear();
    }
}
