package com.cooleshow.teacher.ui.live;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.cooleshow.base.router.RouterPath;
import com.cooleshow.base.ui.activity.BaseMVPActivity;
import com.cooleshow.base.utils.LogUtils;
import com.cooleshow.base.utils.ToastUtil;
import com.cooleshow.base.utils.ToastUtils;
import com.cooleshow.base.utils.Utils;
import com.cooleshow.teacher.R;
import com.cooleshow.teacher.adapter.MessageAdapter;
import com.cooleshow.teacher.bean.LiveRoomInfoBean;
import com.cooleshow.teacher.contract.LiveRoomContract;
import com.cooleshow.teacher.databinding.ActivityTeacherLiveRoomLayoutBinding;
import com.cooleshow.teacher.presenter.live.LiveRoomPresenter;
import com.cooleshow.teacher.widgets.dialog.LiveBeautyOptionsDialog;
import com.cooleshow.teacher.widgets.helper.VideoViewManager;
import com.cooleshow.usercenter.helper.UserHelper;
import com.rong.io.live.config.LiveConfig;
import com.rong.io.live.helper.LiveEventHelper;
import com.rong.io.live.helper.LiveRTCEngineInitHelper;

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

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import cn.rongcloud.rtc.api.RCRTCAudioRouteManager;
import cn.rongcloud.rtc.api.RCRTCVideoStream;
import cn.rongcloud.rtc.api.stream.RCRTCAudioInputStream;
import cn.rongcloud.rtc.api.stream.RCRTCVideoInputStream;
import cn.rongcloud.rtc.api.stream.RCRTCVideoOutputStream;
import cn.rongcloud.rtc.api.stream.RCRTCVideoView;
import cn.rongcloud.rtc.base.RCRTCMediaType;
import cn.rongcloud.rtc.base.RCRTCResourceState;
import io.rong.imkit.IMCenter;
import io.rong.imlib.IRongCoreCallback;
import io.rong.imlib.IRongCoreEnum;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.MessageContent;

/**
 * Author by pq, Date on 2022/6/5.
 * 老师端直播间页面
 */
@Route(path = RouterPath.LiveCenter.ACTIVITY_LIVE_ROOM_TEACHER)
public class LiveRoomActivity extends BaseMVPActivity<ActivityTeacherLiveRoomLayoutBinding, LiveRoomPresenter> implements LiveRoomContract.LiveRoomView, View.OnClickListener {
    public static final String ROOMID_KEY = "roomid_key";
    private TextView mTvNumPeople;
    private TextView mTvRoomCreateName;
    private ImageView mIvAvatar;
    public String mRoomId = "";
    private VideoViewManager mVideoViewManager;
    private boolean isNeedRefresh = false;//是否需要重新刷新房间信息
    private LiveRoomInfoBean mRoomInfoBean;
    private String mUserId;
    private RongIMClient.ConnectionStatusListener connectStatusListener = new RongIMClient.ConnectionStatusListener() {
        @Override
        public void onChanged(ConnectionStatus status) {
            Log.i("pq", "LiveRoomActivity receive ConnectionStatus:" + status);
            if (status == ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT
                    || status == ConnectionStatus.SIGN_OUT || status == ConnectionStatus.TIMEOUT) {
                finish();
            }
            if (status == ConnectionStatus.CONNECTED) {
                //IM连接成功
                if (presenter != null && isNeedRefresh) {
                    presenter.init(mRoomId, true);
                }
            } else {
                //其他状态的时候需要重新刷新房间信息
                isNeedRefresh = true;
            }
        }
    };
    private MessageAdapter mMessageAdapter;
    private LinearLayoutManager mLinearLayoutManager;
    private LiveBeautyOptionsDialog mOptionsDialog;

    public static void start(Context context, String roomId) {
        Intent intent = new Intent(context, LiveRoomActivity.class);
        intent.putExtra(ROOMID_KEY, roomId);
        context.startActivity(intent);
    }

    @Override
    protected void initView() {
        viewBinding.viewCreateOptions.ivReverseCamera.setOnClickListener(this);
        viewBinding.viewCreateOptions.ivLiveBeauty.setOnClickListener(this);
        viewBinding.viewCreateOptions.ivLiveShare.setOnClickListener(this);
        viewBinding.viewCreateOptions.tvStartLive.setOnClickListener(this);
        viewBinding.viewCreateOptions.tvClose.setOnClickListener(this);
        mTvNumPeople = viewBinding.viewMainLayout.tvNumPeople;
        mTvRoomCreateName = viewBinding.viewMainLayout.tvRoomAuthorName;
        mIvAvatar = viewBinding.viewMainLayout.ivAvatar;
    }

    @Override
    public void initData() {
        super.initData();
        mRoomId = getIntent().getStringExtra(ROOMID_KEY);
        if (TextUtils.isEmpty(mRoomId)) {
            ToastUtil.getInstance().show(this, "房间id不可为空");
            finish();
            return;
        }
        String userToken = UserHelper.getUserToken();
        if (TextUtils.isEmpty(userToken)) {
            finish();
            return;
        }
        mUserId = UserHelper.getUserId();
        if (LiveConfig.isNeedReInitRTC) {
            //检查是否需要重新初始化RTC
            LiveRTCEngineInitHelper.initRTC();
        }
        //开启美颜
        LiveRTCEngineInitHelper.openBeauty();

        // 初始化音频路由管理类
        RCRTCAudioRouteManager.getInstance().init(Utils.getApp());
        viewBinding.flLiveView.post(new Runnable() {
            @Override
            public void run() {
                checkVideoViewManager();
            }
        });
        mMessageAdapter = new MessageAdapter(this);
        mLinearLayoutManager = new LinearLayoutManager(this, RecyclerView.VERTICAL, false);
        viewBinding.viewMainLayout.recyclerMsg.setLayoutManager(mLinearLayoutManager);
        viewBinding.viewMainLayout.recyclerMsg.setAdapter(mMessageAdapter);
        IMCenter.getInstance().addConnectionStatusListener(connectStatusListener);
//        SoftKeyboardUtil.registerSoftInputChangedListener(getWindow(), this);
        prepareInitRoom();
    }

    private void prepareInitRoom() {
        //根据融云的IM连接状态判断是否需要获取房间信息
        RongIMClient.ConnectionStatusListener.ConnectionStatus currentConnectionStatus = RongIMClient.getInstance().getCurrentConnectionStatus();
        if (currentConnectionStatus == RongIMClient.ConnectionStatusListener.ConnectionStatus.CONNECTED) {
            isNeedRefresh = false;
            if (presenter != null) {
                presenter.init(mRoomId, true);
            }
        } else {
            //如果IM未连接,等待connectStatusListener回调
            isNeedRefresh = true;
        }
    }


    /**
     * 检查VideoViewManager是否未null;
     */
    private void checkVideoViewManager() {
        if (mVideoViewManager == null) {
            mVideoViewManager = new VideoViewManager(viewBinding.flLiveView, viewBinding.flLiveView.getWidth(), viewBinding.flLiveView.getHeight());
            mVideoViewManager.setRetryClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (presenter != null) {
                        //重新订阅房间的流信息
//                        presenter.subscribeAVStream();
                    }
                }
            });
        }
    }

    @Override
    protected ActivityTeacherLiveRoomLayoutBinding getLayoutView() {
        return ActivityTeacherLiveRoomLayoutBinding.inflate(getLayoutInflater());
    }

    @Override
    protected LiveRoomPresenter createPresenter() {
        return new LiveRoomPresenter();
    }

    /**
     * 获取房间信息成功
     *
     * @param roomInfoBean
     */
    @Override
    public void getRoomInfoSuccess(LiveRoomInfoBean roomInfoBean) {
        if (isFinishing() || isDestroyed()) {
            return;
        }
        if (roomInfoBean == null) {
            ToastUtils.showShort("获取房间信息失败,请退出重试");
            finish();
            return;
        }
        mRoomInfoBean = roomInfoBean;
        if (mMessageAdapter != null) {
            mMessageAdapter.setRoomAuthorId(roomInfoBean.speakerId);
        }
        int peopleCount = roomInfoBean.lookNum + 1;//加上自己
        mTvNumPeople.setText(peopleCount + "人");
        //创建人头像
        Glide.with(LiveRoomActivity.this).load(roomInfoBean.speakerPic).placeholder(R.drawable.icon_teacher_default_head).error(R.drawable.icon_teacher_default_head).into(mIvAvatar);
        //创建人昵称
        mTvRoomCreateName.setText(roomInfoBean.speakerName);
        if (presenter != null) {
            //加入聊天室
            //加入直播间
            showLoading();
            LiveEventHelper.getInstance().register(roomInfoBean.roomUid);
            presenter.openVideoPreview();
//            presenter.joinChartRoom(mRoomInfoBean.roomUid, new IRongCoreCallback.OperationCallback() {
//                @Override
//                public void onSuccess() {
//                    Log.i("pq", "加入聊天房间成功");
//                    if (presenter != null) {
////                        presenter.handleAction(LiveRoomMsgConstants.ACTION_SEND_JOIN_ROOM);
//                        presenter.sendDefaultMessage();
//                    }
//                }
//
//                @Override
//                public void onError(IRongCoreEnum.CoreErrorCode coreErrorCode) {
//                    Log.i("pq", "加入聊天房间fail:" + coreErrorCode);
//                    Toast.makeText(LiveRoomActivity.this, "加入聊天房间fail:" + coreErrorCode, Toast.LENGTH_SHORT).show();
//                }
//            });
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_reverse_camera) {
            //翻转摄像头
            presenter.reverseCamera();
            return;
        }
        if (id == R.id.iv_live_beauty) {
            //美颜
            showBeautyOptionsDialog();
            return;
        }

        if (id == R.id.tv_start_live) {
            //开始直播
            if (mRoomInfoBean != null) {
                presenter.prepareJoinRoom(mRoomInfoBean.roomUid, true);
            }
        }
    }

    /**
     * 获取房间信息失败
     *
     * @param throwable
     */
    @Override
    public void getRoomInfoError(Throwable throwable) {
        if (isFinishing() || isDestroyed()) {
            return;
        }
        ToastUtils.showShort("获取房间信息失败,请退出重试");
        finish();
    }

    @Override
    public void showFinishView() {

    }

    @Override
    public void addMessageList(List<MessageContent> messageContents, boolean isReset) {

    }

    @Override
    public void addMessageContent(Message message, boolean isReset) {
        //添加单条消息至页面
        Log.i("pq", "收到需要显示msg:" + message);
        //只处理直播间消息,以及本直播间消息
        if (mMessageAdapter != null) {
            mMessageAdapter.addMessage(message);
            if (mLinearLayoutManager != null) {
                viewBinding.viewMainLayout.recyclerMsg.post(new Runnable() {
                    @Override
                    public void run() {
                        if (viewBinding.viewMainLayout.recyclerMsg != null) {
                            viewBinding.viewMainLayout.recyclerMsg.scrollToPosition(mMessageAdapter.getItemCount() - 1);
                        }
                    }
                });
            }
        }
    }

    @Override
    public void setRoomData(LiveRoomInfoBean roomInfoBean) {
        //加入聊天房间
        presenter.joinChartRoom(roomInfoBean.roomUid, new IRongCoreCallback.OperationCallback() {
            @Override
            public void onSuccess() {
                Log.i("pq", "加入聊天房间成功");
                presenter.sendDefaultMessage();
            }

            @Override
            public void onError(IRongCoreEnum.CoreErrorCode coreErrorCode) {
                Log.i("pq", "加入聊天房间fail:" + coreErrorCode);
            }
        });
    }

    @Override
    public void onPublishSuccess() {
        refresh();
    }

    @Override
    public View getContentView() {
        return viewBinding.flLiveView;
    }

    /**
     * 预览模式
     *
     * @param videoView
     */
    @Override
    public void addVideoPreview(RCRTCVideoView videoView) {
        checkVideoViewManager();
        if (mVideoViewManager != null) {
            ArrayList<RCRTCVideoView> videoViews = new ArrayList<>();
            videoViews.add(videoView);
            mVideoViewManager.update(videoViews, false);
        } else {
            LogUtils.i("pq", "mVideoViewManager == null");
        }
    }

    @Override
    public void openCameraSuccess(Boolean data) {
        Log.i("pq", "openCameraSuccess:" + data);
    }

    @Override
    public void openCameraError(String errorMsg) {
        viewBinding.flLiveView.post(new Runnable() {
            @Override
            public void run() {
                ToastUtil.getInstance().show(LiveRoomActivity.this, errorMsg);
            }
        });
    }


    private void refresh() {
        List<RCRTCVideoOutputStream> outputStreams = new ArrayList<>();
        List<RCRTCVideoInputStream> input = new ArrayList<>();
        List<RCRTCAudioInputStream> audioinputstream = new ArrayList<>();
        presenter.getVideoStream(outputStreams, input, audioinputstream);
        updateVideoView(outputStreams, input, audioinputstream);
    }

    public void updateVideoView(List<RCRTCVideoOutputStream> outputStreams, List<RCRTCVideoInputStream> inputStreams, List<RCRTCAudioInputStream> audioInputStreams) {
        viewBinding.flLiveView.post(new Runnable() {
            @Override
            public void run() {
                //隐藏配置页
                if (viewBinding.viewCreateOptions.getRoot().getVisibility() == View.VISIBLE) {
                    viewBinding.viewCreateOptions.getRoot().setVisibility(View.GONE);
                    viewBinding.viewMainLayout.getRoot().setVisibility(View.VISIBLE);
                }
                ArrayList<RCRTCVideoStream> videoStreams = new ArrayList<RCRTCVideoStream>();
                videoStreams.addAll(outputStreams);
                videoStreams.addAll(inputStreams);
                ArrayList<RCRTCVideoView> list = new ArrayList<>();
                ArrayList<String> otherAudioUserIds = new ArrayList<>();
                boolean isNormalCreateAudioStatus = true;

                //视频流
                for (int i = 0; i < videoStreams.size(); i++) {
                    RCRTCVideoStream rcrtcVideoStream = videoStreams.get(i);
                    RCRTCVideoView rongRTCVideoView = new RCRTCVideoView(LiveRoomActivity.this);
                    rcrtcVideoStream.setVideoView(rongRTCVideoView);
                    list.add(rongRTCVideoView);
                }

                //音频流
                for (int i = 0; i < audioInputStreams.size(); i++) {
                    RCRTCAudioInputStream audioInputStream = audioInputStreams.get(i);
                    if (audioInputStream.getMediaType() == RCRTCMediaType.AUDIO) {
                        //音频流判断显示上麦用户
                        String userId = audioInputStream.getUserId();
                        if (TextUtils.equals(mUserId, userId)) {
                            continue;
                        }
                        if (mRoomInfoBean != null) {
                            if (!TextUtils.equals(mRoomInfoBean.speakerId, userId)) {
                                otherAudioUserIds.add(userId);
                            } else {
                                //主播的音频流
                                RCRTCResourceState resourceState = audioInputStream.getResourceState();
                                isNormalCreateAudioStatus = resourceState == RCRTCResourceState.NORMAL;
                            }
                        }
                    }
                }
                mVideoViewManager.update(list, true);

//                if (otherAudioUserIds.size() != 0) {
//                    mLlMicContainer.delAllExcludeOwn();
//                    for (int i = 0; i < otherAudioUserIds.size(); i++) {
//                        String onMicUserId = otherAudioUserIds.get(i);
//                        notifyMicContainerAdd(onMicUserId, "");
//                    }
//                } else {
//                    mLlMicContainer.delAllExcludeOwn();
//                }
//                if (list.size() != 0) {
//                    creatorIsCloseVideoStream = false;
//                    mViewLiveStatus.setVisibility(View.GONE);
//                    checkVideoViewManager();
//                    mVideoViewManager.update(list, 0, true);
//                } else {
//                    creatorIsCloseVideoStream = true;
//                    if (isNormalCreateAudioStatus) {
//                        showCloseVideoView();
//                    } else {
//                        //主播关闭了视频流,同时音频流的状态也不是normal状态时
//                        showRestView();
//                    }
//                }
            }
        });
    }

    private void showBeautyOptionsDialog() {
        if (mOptionsDialog == null) {
            mOptionsDialog = new LiveBeautyOptionsDialog(this);
            mOptionsDialog.setFragmentActivity(this);
            mOptionsDialog.setOnShowListener(new DialogInterface.OnShowListener() {
                @Override
                public void onShow(DialogInterface dialog) {
                    viewBinding.viewCreateOptions.getRoot().setVisibility(View.GONE);
                }
            });

            mOptionsDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    viewBinding.viewCreateOptions.getRoot().setVisibility(View.VISIBLE);
                }
            });
        }
        if (!mOptionsDialog.isShowing()) {
            mOptionsDialog.show();
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mVideoViewManager != null) {
            mVideoViewManager.onRelease();
        }
    }

}
