package com.daya.live_teaching.ui.fragmnet;


import android.content.res.Configuration;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.cooleshow.base.ui.fragment.BaseFragment;
import com.cooleshow.base.utils.LogUtils;
import com.cooleshow.base.utils.SizeUtils;
import com.cooleshow.base.utils.ToastUtil;
import com.daya.live_teaching.R;
import com.daya.live_teaching.common.ResultCallback;
import com.daya.live_teaching.common.ShowToastObserver;
import com.daya.live_teaching.databinding.FragmentShareScreenBinding;
import com.daya.live_teaching.model.ClassMember;
import com.daya.live_teaching.model.RequestState;
import com.daya.live_teaching.model.Role;
import com.daya.live_teaching.model.ScreenDisplay;
import com.daya.live_teaching.model.UserInfo;
import com.daya.live_teaching.permission.ClassPermission;
import com.daya.live_teaching.repository.UserRepository;
import com.daya.live_teaching.rtc.RtcManager;
import com.daya.live_teaching.ui.view.ClassVideoListItem;
import com.daya.live_teaching.ui.view.DisplayNullView;
import com.daya.live_teaching.ui.view.RadioRtcVideoView;
import com.daya.live_teaching.utils.ToastUtils;
import com.daya.live_teaching.utils.log.SLog;
import com.daya.live_teaching.viewmodel.ClassViewModel;
import com.daya.live_teaching.widget.OnOperateItemListener;
import com.daya.live_teaching.widget.OperateButtonGroupView;
import com.daya.live_teaching.widget.OperateItem;
import com.daya.live_teaching.widget.dialog.LiveCommonDialog;

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

import cn.rongcloud.rtc.api.RCRTCConfig;
import cn.rongcloud.rtc.api.RCRTCEngine;
import cn.rongcloud.rtc.api.stream.RCRTCAudioStreamConfig;
import cn.rongcloud.rtc.api.stream.RCRTCVideoView;
import cn.rongcloud.rtc.base.RCRTCParamsType;
import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;


/**
 * A simple {@link Fragment} subclass.
 */
public class ShareScreenFragment extends BaseFragment<FragmentShareScreenBinding> {


    RelativeLayout classShareRootView;
    ClassVideoListItem shareScreenVideoView;
    DisplayNullView displayNull;
    ClassVideoListItem shareVideoView;
    OperateButtonGroupView shareOperateView;
    TextView tvSpeech;
    ImageView iv_fragment_share_screen_onstage;
    ImageView iv_raise_hands;

    private ClassViewModel classViewModel;
    private UserInfo userInfoValue;
    private OnVideoViewChangeListenr onVideoViewChangeListenr;
    private String roomId;
    private String displayUserId;
    private TextView tvShareName;

    public ShareScreenFragment() {
        // Required empty public constructor
    }


    public enum BtnOperate { // 控制按钮类型
        /**
         * 麦克风
         */
        MIC(0),
        /**
         * 在线成员
         */
        CAMERA(1),
        /**
         * 音乐模式
         */
        MUSIC_MODE(2),
        /**
         * 节拍器
         */
        METRONOME(3),

        /**
         * 伴奏
         */
        ACCOMPANIMENT(4);

        private int value;

        BtnOperate(int value) {
            this.value = value;
        }

        public int getValue() {
            return value;
        }

        public static BtnOperate getType(int value) {
            for (BtnOperate type : BtnOperate.values()) {
                if (value == type.getValue()) {
                    return type;
                }
            }
            return MIC;
        }
    }

    //    // 按钮的资源布局
    private int[] btnBgResIds = new int[]{
            R.drawable.fragment_share_screen_operate_mic_selector,
            R.drawable.fragment_share_screen_operate_camera_selector,
            R.drawable.fragment_share_screen_music_mode_selector,
            R.drawable.fragment_share_screen_operate_metronome_selector,
            R.drawable.fragment_share_screen_operate_accompaniment_selector};

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

    @Override
    protected void initView(View rootView) {
        classShareRootView = mViewBinding.classShareVideoview;
        shareScreenVideoView = mViewBinding.classShareScreenVideoview;
        displayNull = mViewBinding.classShareScreenNull;
        shareVideoView = mViewBinding.classShareVideoview;
        shareOperateView = mViewBinding.shareOperateView;
        tvSpeech = mViewBinding.tvSpeech;
        iv_fragment_share_screen_onstage = mViewBinding.ivFragmentShareScreenOnstage;
        iv_raise_hands = mViewBinding.ivRaiseHands;
        tvShareName = mViewBinding.tvShareName;

        shareVideoView.setHideRole(true);
        shareScreenVideoView.setHideRole(true);
        //清理资源
        shareVideoView.clear();
        shareScreenVideoView.clear();
        initOperateItem();
        tvSpeech.setOnClickListener(v -> {
            if ("上台".equals(tvSpeech.getText().toString())) {
                //                DialogUtil.showInCenter(getChildFragmentManager(), R.layout.speech_select_popu, new DialogUtil.ShowListener() {
                //                    @Override
                //                    public void onShow(ViewHolder holder, BaseDialog dialog) {
                //                        RadioButton rbAudio = holder.getView(R.id.rb_audio);
                //                        TextView btnCommit = holder.getView(R.id.btn_commit);
                //
                //                        btnCommit.setOnClickListener(v1 -> {
                //                            if (rbAudio.isChecked()) {
                //                                LOG.e("音频");
                //
                //                            } else {
                //                                LOG.e("视频");
                ScreenDisplay display = classViewModel.getDisplay().getValue();
                displayUserId = display.getUserId();
                if (onVideoViewChangeListenr != null) {
                    onVideoViewChangeListenr.onSpeech(displayUserId, true);
                }
                if (display.getClassMember() != null && display.getClassMember().isHandUpOn()) {
                    classViewModel.controlHandUpOn(roomId, displayUserId, false);
                }
                List<ClassMember> memberList = classViewModel.getMemberList().getValue();
                List<String> userIds = new ArrayList<>();
                for (ClassMember member : memberList) {
                    if (displayUserId.equals(member.getUserId())) {
                        member.setOnStage(true);
                    } else if (!member.getUserId().equals(userInfoValue.getUserId()) && member.getPlayMidiJson() != null && member.getPlayMidiJson().isEnable()) {
                        userIds.add(member.getUserId());
                        member.setOnStage(false);
                    } else if (!member.getUserId().equals(userInfoValue.getUserId())) {
                        List<ClassMember.ScheduleStudentMusicScoresBean> musicScoresBeans = member.getScheduleStudentMusicScores();
                        if (musicScoresBeans != null && musicScoresBeans.size() > 0) {
                            boolean isMusicPlay = false;
                            for (ClassMember.ScheduleStudentMusicScoresBean bean : musicScoresBeans) {
                                if (bean != null && (bean.getPlayStatus() == 1 || bean.getAccompanimentPlayStatus() == 1)) {
                                    isMusicPlay = true;
                                    break;
                                }
                            }
                            if (isMusicPlay) {
                                userIds.add(member.getUserId());
                            }

                        }
                        member.setOnStage(false);
                    } else {
                        member.setOnStage(false);
                    }
                }
                List<ClassMember> noJoinStuList = classViewModel.getQueryNoJoinStu().getValue();
                if (noJoinStuList != null && noJoinStuList.size() > 0) {
                    for (ClassMember member : noJoinStuList) {
                        if (!member.getUserId().equals(userInfoValue.getUserId())) {
                            userIds.add(member.getUserId());
                        }
                    }
                }
                if (userIds.size() > 0) {
                    if (classViewModel.isOnMetronomeIsPlay()) {
                        setMetronome(false, TextUtils.join(",", userIds));
                    }
                    if (classViewModel.isOnMusicIsPlay()) {
                        setAccompaniment(false, TextUtils.join(",", userIds));
                    }
                }

                //                classViewModel.setMemberList(memberList);
                //                            }

                iv_fragment_share_screen_onstage.setImageResource(R.drawable.ic_student_down_stage);
                tvSpeech.setText("下台");
                //                            dialog.dismiss();
                //                        });
                //                    }
                //                });
            } else {
                tvSpeech.setText("上台");
                iv_fragment_share_screen_onstage.setImageResource(R.drawable.ic_student_on_stage);
                if (onVideoViewChangeListenr != null) {
                    onVideoViewChangeListenr.onSpeech(userInfoValue.getUserId(), false);

                }
                List<ClassMember> memberList = classViewModel.getMemberList().getValue();
                //                boolean isPlayMidi=false;
                for (ClassMember member : memberList) {
                    if (!TextUtils.isEmpty(displayUserId) && displayUserId.equals(member.getUserId())) {
                        member.setOnStage(false);
                        //                        if (member.getPlayMidiJson()!=null&&member.getPlayMidiJson().isEnable()) {
                        //                                isPlayMidi=true;
                        //                        }
                        break;
                    }
                }
                classViewModel.setMemberList(memberList);
                //                if (isPlayMidi) {
                //                    setMetronome(false, displayUserId);
                //                }
            }
        });

        iv_fragment_share_screen_onstage.setOnClickListener(v -> tvSpeech.callOnClick());

        iv_raise_hands.setOnClickListener(view -> {
            String content = "确认举手吗？";
            if (userInfoValue.isHandUpOn()) {
                content = "确认取消举手吗";
            }
            LiveCommonDialog dialog = new LiveCommonDialog(getContext());
            dialog.show();
            dialog.setTitle("提示");
            dialog.setContent(content);
            dialog.setOnConfirmClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (userInfoValue.isHandUpOn()) {
                        classViewModel.deviceSyncHandUpOn(roomId, null, false);
                    } else {
                        classViewModel.deviceSyncHandUpOn(roomId, null, true);
                    }
                    dialog.dismiss();
                }
            });
            dialog.setOnCancelClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });
        });
    }

    @Override
    protected void initData() {
        classViewModel = ViewModelProviders.of(getActivity()).get(ClassViewModel.class);
        classViewModel.getRoomId().observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                roomId = s;
            }
        });
        // 用户信息变化
        classViewModel.getUserInfo().observe(this, new Observer<UserInfo>() {
            @Override
            public void onChanged(final UserInfo userInfo) {
                userInfoValue = userInfo;
                if (userInfo.getRole() != Role.LECTURER) {
                    shareOperateView.setVisibility(View.GONE);
                    tvSpeech.setVisibility(View.GONE);
                    iv_fragment_share_screen_onstage.setVisibility(View.INVISIBLE);
                    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                    lp.addRule(RelativeLayout.ALIGN_TOP, R.id.iv_fragment_share_screen_onstage);
                    shareOperateView.setLayoutParams(lp);
                    if (userInfo.isHandUpOn()) {
//                        iv_raise_hands.setText("已举手");
                        iv_raise_hands.setImageResource(R.drawable.ic_live_student_hands_up);
                    } else {
//                        iv_raise_hands.setText("举手");
                        iv_raise_hands.setImageResource(R.drawable.ic_living_raise_hand);
                    }
                } else if (classViewModel.getDisplay().getValue().getClassMember() != null && classViewModel.getDisplay().getValue().getClassMember().getRole() == Role.LECTURER) {
                    setViewStatus(userInfo);
                }
                // 初始化操作布局

                // 为了统一管理本地的音视频资源发布， 所以在此处统一发布和取消发布资源。如果设计到视频列表的刷新，
                // 则直接回调到 OnVideoViewChangeListenr#onChangeUser 方法即可。
                // 首先判断当前的用户是否有音视频的权限。
                // 当前助教，老师，学员都有音视频权限。
                if (userInfo.getRole().hasPermission(ClassPermission.VIDEO_CHAT)) {
                    // 首先查询是否有对应的 VideoView 控件
                    RadioRtcVideoView videoView = null;
                    if (!VideoViewManager.getInstance().containsKey(userInfo.getUserId())) {
                        // 如果没有则需要创建
                        videoView = new RadioRtcVideoView(getActivity());
                        VideoViewManager.getInstance().put(userInfo.getUserId(), videoView);
                    } else {
                        videoView = VideoViewManager.getInstance().get(userInfo.getUserId());
                    }
                    // 然后查看一下， videoview 是否进行了资源绑定
                    if (!videoView.isBindVideo()) {
                        //没有绑定则进行绑定
                        videoView.setBindVideo(true);
                        classViewModel.startRtcChat(videoView).observe(ShareScreenFragment.this, new ShowToastObserver(getActivity()) {
                            @Override
                            public void onChanged(RequestState state) {
                                super.onChanged(state);
                                // 假如非旁听用户， 登陆时， 选择关闭摄像头则， 这里即可设置
                                if (!userInfo.isCamera()) {
                                    classViewModel.setLocalVideoEnable(userInfo.isCamera());
                                }
                            }
                        });
                        // 通知视频列表刷新
                        if (onVideoViewChangeListenr != null) {
                            onVideoViewChangeListenr.onChangeUser(userInfo);
                        }

                    }

                } else {
                    // 没有音视频权限
                    // 检测有没有VideoView, 没有的话，则不用处理
                    if (VideoViewManager.getInstance().containsKey(userInfo.getUserId())) {
                        RadioRtcVideoView videoView = VideoViewManager.getInstance().get(userInfo.getUserId());
                        videoView.setBindVideo(false);
                        // 停止资源发布
                        classViewModel.stopRtcChat();
                        // 通知视频列表刷新
                        if (onVideoViewChangeListenr != null) {
                            onVideoViewChangeListenr.onChangeUser(userInfo);
                        }
                    }
                }
            }
        });

        classViewModel.getRoleChangeUser().observe(this, new Observer<ClassMember>() {
            @Override
            public void onChanged(ClassMember member) {

                // 白板和空布局
                // 是对视频中的用户信息的更新
                ClassMember data = shareVideoView.getData();

                ScreenDisplay screenDisplay = classViewModel.getDisplay().getValue();
                if (data != null && screenDisplay != null) {

                    if (data.getUserId().equals(member.getUserId())) { // 刷新
                        // 如果现在的角色是助教或者讲师， 则需要对视频的信息更新
                        if (member.getRole() == Role.LECTURER) {
                            shareVideoView.setData(member);
                        } else {
                            // 如果其他的用户， 则移除
                            shareVideoView.removeVideoView();
                            //                            通知视频列表刷新
                            if (onVideoViewChangeListenr != null) {
                                onVideoViewChangeListenr.onChangeUser(member);
                            }
                        }
                    }

                }
            }
        });
        // 共享区显示资源的变化
        classViewModel.getDisplay().observe(this, new Observer<ScreenDisplay>() {
            @Override
            public void onChanged(ScreenDisplay screenDisplay) {
                LogUtils.d("Display , screenDisplay ==" + screenDisplay);
                if (null == userInfoValue) {
                    userInfoValue = classViewModel.getUserInfo().getValue();
                }
                tvShareName.setText("");
                if (screenDisplay.getClassMember() != null) {
                    tvShareName.setText(screenDisplay.getClassMember().getUserName());
                }
                // 前一个显示是视频， 所以当前显示资源的时候要把上一个视频资源记录， 并通知
                List<String> userIds = new ArrayList<>();
                userIds.clear();
                ClassMember data = shareVideoView.getData();
                if (data != null) {
                    userIds.add(data.getUserId());
                }
                shareVideoView.removeVideoView();
                shareVideoView.setData(null);
                ScreenDisplay.Display type = screenDisplay.getType();

                if (type == ScreenDisplay.Display.LECTURER) {
                    String userId = screenDisplay.getUserId();
                    if (Role.LECTURER == userInfoValue.getRole()) {
                        shareOperateView.setVisibility(View.VISIBLE);
                        tvSpeech.setVisibility(View.GONE);
                        iv_fragment_share_screen_onstage.setVisibility(View.INVISIBLE);
                        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                        lp.addRule(RelativeLayout.ALIGN_TOP, R.id.iv_fragment_share_screen_onstage);
                        shareOperateView.setLayoutParams(lp);
                        shareOperateView.setItemVisibility(BtnOperate.METRONOME.getValue(), View.GONE);
                        shareOperateView.setItemVisibility(BtnOperate.ACCOMPANIMENT.getValue(), View.GONE);
                        clearshareOperateView();
                        setViewStatus(screenDisplay.getClassMember());
                    } else if (userIds.size() > 0 && userIds.get(0).equals(userInfoValue.getUserId())) {
                        if (onVideoViewChangeListenr != null) {
                            onVideoViewChangeListenr.onSpeechIsShowHint(false);

                        }
                        iv_raise_hands.setVisibility(View.VISIBLE);
                    } else {
                        iv_raise_hands.setVisibility(View.VISIBLE);
                    }
                    //根据userId，切换到对应的视频
                    RtcManager.getInstance().switchStream(userId, true);
                    if (userIds.size() > 0) {
                        RtcManager.getInstance().switchStream(userIds.get(0), false);
                    }
                    shareVideoView.setVisibility(View.VISIBLE);
                    displayNull.setVisibility(View.GONE);
                    shareScreenVideoView.setVisibility(View.GONE);


                    if (!VideoViewManager.getInstance().containsKey(userId)) {
                        VideoViewManager.getInstance().put(userId, new RadioRtcVideoView(getContext()));
                    }

                    RadioRtcVideoView videoView = VideoViewManager.getInstance().get(userId);
                    if (videoView.isHasParent()) {
                        ((ViewGroup) videoView.getParent()).removeAllViews();
                    }

                    shareVideoView.addVideoView(videoView, getItemLayoutParams());
                    shareVideoView.setData(screenDisplay.getClassMember());
                    // 设置 VideoView 的图层
                    videoView.setZOrderOnTop(false);
                    videoView.setZOrderMediaOverlay(false);

                } else if (type == ScreenDisplay.Display.SCREEN) { // 视频共享
                    RtcManager.getInstance().switchStream(screenDisplay.getUserId(), true);

                    shareVideoView.setVisibility(View.GONE);
                    displayNull.setVisibility(View.GONE);
                    shareScreenVideoView.setData(screenDisplay.getClassMember());
                    shareScreenVideoView.setVisibility(View.VISIBLE);

                    // 获取共享桌面的 VideoView， 并设置
                    RadioRtcVideoView shareScreenRtcVideoView = VideoViewManager.getInstance().getShareScreenVideoView();
                    if (shareScreenRtcVideoView == null) {
                        shareScreenRtcVideoView = new RadioRtcVideoView(getActivity());
                        final RadioRtcVideoView finalShareScreenVideoView = shareScreenRtcVideoView;
                        shareScreenRtcVideoView.setOnSizeChangedListener(new RCRTCVideoView.OnSizeChangedListener() {
                            @Override
                            public void onChanged(RCRTCVideoView.Size size) {
                                if (size != null) {
                                    float radio = (float) size.with / (float) size.height;
                                    SLog.d("video_size", "size == " + size.with + ", " + size.height + ", " + radio);
                                    finalShareScreenVideoView.setRadio(radio);
                                }
                            }
                        });
                        VideoViewManager.getInstance().setShareScreenVideoView(shareScreenRtcVideoView);
                    }

                    if (shareScreenRtcVideoView.isHasParent()) {
                        ((ViewGroup) shareScreenRtcVideoView.getParent()).removeAllViews();
                    }
                    shareScreenVideoView.addVideoView(shareScreenRtcVideoView, getItemLayoutParams());

                    // 设置浮层

                    shareScreenRtcVideoView.setZOrderOnTop(false);
                    shareScreenRtcVideoView.setZOrderMediaOverlay(false);

                } else if (type == ScreenDisplay.Display.STUDENT) {
                    String userId = screenDisplay.getUserId();
                    if (Role.LECTURER == userInfoValue.getRole()) {
                        shareOperateView.setVisibility(View.VISIBLE);
//                        tvSpeech.setVisibility(View.VISIBLE);
                        iv_fragment_share_screen_onstage.setVisibility(View.VISIBLE);
                        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                        lp.addRule(RelativeLayout.ALIGN_TOP, R.id.iv_fragment_share_screen_onstage);
                        lp.addRule(RelativeLayout.RIGHT_OF, R.id.iv_fragment_share_screen_onstage);
                        shareOperateView.setLayoutParams(lp);
                        shareOperateView.setItemVisibility(BtnOperate.METRONOME.getValue(), View.VISIBLE);
                        clearshareOperateView();
                        setStudentViewStatus(screenDisplay.getClassMember());
                    } else if (userId.equals(userInfoValue.getUserId())) {
                        iv_raise_hands.setVisibility(View.GONE);
                        if (onVideoViewChangeListenr != null) {
                            onVideoViewChangeListenr.onSpeechIsShowHint(true);

                        }
                    } else if (!userId.equals(userInfoValue.getUserId())) {
                        iv_raise_hands.setVisibility(View.VISIBLE);
                        if (onVideoViewChangeListenr != null) {
                            onVideoViewChangeListenr.onSpeechIsShowHint(false);

                        }
                    }
                    if (userIds.size() > 0) {
                        RtcManager.getInstance().switchStream(userIds.get(0), false);
                    }
                    //根据userId，切换到对应的视频
                    RtcManager.getInstance().switchStream(userId, true);
                    shareVideoView.setVisibility(View.VISIBLE);
                    displayNull.setVisibility(View.GONE);
                    shareScreenVideoView.setVisibility(View.GONE);
                    if (!VideoViewManager.getInstance().containsKey(userId)) {
                        VideoViewManager.getInstance().put(userId, new RadioRtcVideoView(getContext()));
                    }
                    RadioRtcVideoView videoView = VideoViewManager.getInstance().get(userId);
                    if (videoView.isHasParent()) {
                        ((ViewGroup) videoView.getParent()).removeAllViews();
                    }
                    shareVideoView.addVideoView(videoView, getItemLayoutParams());
                    shareVideoView.setData(screenDisplay.getClassMember());
                    // 设置 VideoView 的图层
                    videoView.setZOrderOnTop(false);
                    videoView.setZOrderMediaOverlay(false);

                } else if (type == null || type == ScreenDisplay.Display.NONE) {
                    if (Role.LECTURER == userInfoValue.getRole()) {
                        shareOperateView.setVisibility(View.GONE);
                        tvSpeech.setVisibility(View.GONE);
                        iv_fragment_share_screen_onstage.setVisibility(View.INVISIBLE);
                        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                        lp.addRule(RelativeLayout.ALIGN_TOP, R.id.iv_fragment_share_screen_onstage);
                        shareOperateView.setLayoutParams(lp);
                        iv_raise_hands.setVisibility(View.GONE);
                    }

                    if (data != null) {
                        shareVideoView.setData(data);
                    }
                    // 空资源
                    shareVideoView.setVisibility(View.GONE);
                    shareScreenVideoView.setData(null);
                    shareScreenVideoView.setVisibility(View.GONE);
                    displayNull.setVisibility(View.VISIBLE);
                    displayNull.setContent(classViewModel.getUserInfo().getValue());
                } else if (type == null || type == ScreenDisplay.Display.WHITEBOARD) {
                    if (userIds.size() > 0) {
                        RtcManager.getInstance().switchStream(userIds.get(0), false);
                    }
                    if (data != null) {
                        shareVideoView.setData(data);
                    }
                    if (onVideoViewChangeListenr != null) {
                        onVideoViewChangeListenr.onSpeechIsShowHint(false);
                    }
                }
                //通知刷新视频列表的
                if (onVideoViewChangeListenr != null) {
                    userIds.add(screenDisplay.getUserId());
                    onVideoViewChangeListenr.onChangeUser(userIds);
                    //                    if (type != ScreenDisplay.Display.WHITEBOARD && type != ScreenDisplay.Display.NONE && userIds.size() > 0) {
                    //                        onVideoViewChangeListenr.onRemoveUser(screenDisplay.getClassMember());
                    //                    }
                }
            }
        });
        classViewModel.getMemberList().observe(this, new Observer<List<ClassMember>>() {
            @Override
            public void onChanged(List<ClassMember> classMembers) {
                if (userInfoValue == null || userInfoValue.getRole() != Role.LECTURER) {
                    return;
                }
                ScreenDisplay display = classViewModel.getDisplay().getValue();
                ScreenDisplay.Display type = display.getType();
                if (type == ScreenDisplay.Display.STUDENT) {
                    for (ClassMember member : classMembers) {
                        if (member.getUserId().equals(display.getUserId())) {
                            setStudentViewStatus(member);
                            break;
                        }
                    }
                }
            }
        });
    }


    public boolean isScreenOriatationPortrait() {
        return getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
    }

    private void initOperateItem() {
        // 初始化动态添加控制按钮
        List<OperateItem> rightItems = new ArrayList<>();
        int width = SizeUtils.dp2px(34);
        int marginLeft = SizeUtils.dp2px(5);
        for (BtnOperate operate : BtnOperate.values()) {
            OperateItem item = new OperateItem();
            item.id = operate.getValue();
            item.bgResId = btnBgResIds[operate.getValue()];
            item.width = width;
            item.height = width;
            item.left = marginLeft;
            item.type = OperateItem.Type.CHECKBOX;
            rightItems.add(item);
        }

        // 初始化操作布局
        shareOperateView.initView(rightItems, new OnOperateItemListener() {
            @Override
            public void onItemClicked(View v, OperateItem item) {
            }

            @Override
            public void onCheckedChanged(View v, OperateItem item, boolean isChecked) {
                BtnOperate type = BtnOperate.getType(item.id);
                CheckBox checkBox = shareOperateView.getView(type.getValue());
                if (checkBox.isPressed()) {
                    ScreenDisplay display = classViewModel.getDisplay().getValue();
                    boolean isPostCahaged = false;
                    if (userInfoValue != null && display != null) {
                        if (!userInfoValue.getUserId().equals(display.getUserId()))
                            isPostCahaged = true;
                    }
                    switch (type) {
                        case MIC:
                            //麦克风
                            checkBox.setChecked(!isChecked);
                            if (isPostCahaged) {
                                showMemListOperteDialog(!isChecked ? 0 : 1, display.getUserId(), isChecked, checkBox);
                            } else {
                                if (!isChecked) {
                                    deviceSyncMic(roomId, !isChecked);
                                    return;
                                }
                                showMicDialog(isChecked, checkBox);
                            }

                            break;
                        case CAMERA:
                            //是否关闭摄像头
                            checkBox.setChecked(!isChecked);
                            if (isPostCahaged) {
                                showMemListOperteDialog(!isChecked ? 2 : 3, display.getUserId(), isChecked, checkBox);

                            } else {
                                if (!isChecked) {
                                    deviceSyncCamera(roomId, !isChecked);
                                    return;
                                }
                                showCmaeraDialog(isChecked, checkBox);
                            }
                            break;
                        case MUSIC_MODE:
                            //音乐模式切换
                            checkBox.setChecked(!isChecked);
                            if (isPostCahaged) {
                                showMemListOperteDialog(isChecked ? 4 : 5, display.getUserId(), isChecked, checkBox);
                            } else {
                                setAudioScenrio(isChecked, true);
                            }
                            break;
                        case METRONOME:
                            checkBox.setChecked(!isChecked);
                            CheckBox cbAccompaniment = shareOperateView.getView(BtnOperate.ACCOMPANIMENT.getValue());
                            if (classViewModel.isOnMusicIsPlay() || cbAccompaniment.isChecked()) {
                                //学生伴奏已开启，确定关闭伴奏并打开学生节拍器吗
                                showMemListOperteDialog(7, display.getUserId(), isChecked, checkBox);
                            } else {
                                //确定打开学生节拍器吗
                                showMemListOperteDialog(isChecked ? 6 : 8, display.getUserId(), isChecked, checkBox);
                            }
                            break;
                        case ACCOMPANIMENT:
                            if (TextUtils.isEmpty(classViewModel.getMusicScoreAccompanimentId())) {
                                checkBox.setChecked(false);
                                ToastUtil.getInstance().show(getActivity(), "请选择伴奏");
                                return;
                            }
                            checkBox.setChecked(!isChecked);
                            if (classViewModel.isOnMetronomeIsPlay()) {
                                //学生节拍器已开启，确定关闭节拍器并打开学生伴奏吗
                                showMemListOperteDialog(10, display.getUserId(), isChecked, checkBox);
                            } else {
//                                确定打开学生伴奏吗
                                showMemListOperteDialog(isChecked ? 9 : 11, display.getUserId(), isChecked, checkBox);
                            }

                            break;
                    }
                }
            }
        });

    }

    private LinearLayout.LayoutParams getItemLayoutParams() {
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        return params;
    }

    /**
     * 设置显示布局监听
     *
     * @param listenr
     */
    public void setOnVideoViewChangeListenr(OnVideoViewChangeListenr listenr) {
        this.onVideoViewChangeListenr = listenr;
    }

    /**
     * 显示变化，通知刷新的监听接口
     */
    public interface OnVideoViewChangeListenr {
        void onChangeUser(List<String> userIds);

        void onChangeUser(ClassMember oldUser);

        void onRemoveUser(ClassMember userIds);

        void onSpeech(String userIds, boolean isSpeech);

        void onSpeechIsShowHint(boolean isShow);

    }

    // 同步话筒状态
    private void deviceSyncMic(String roomId, boolean on) {
        classViewModel.setLocalMicEnable(on);
        if (classViewModel != null) {
            classViewModel.deviceSyncMic(roomId, on);
        }
    }

    // 确定要关闭麦克风吗
    private void showMicDialog(boolean isChecked, CheckBox checkBox) {
        LiveCommonDialog dialog = new LiveCommonDialog(getContext());
        dialog.show();
        dialog.setTitle("提示");
        dialog.setContent("确定要关闭麦克风吗");
        dialog.setOnConfirmClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                deviceSyncMic(roomId, !isChecked);
                dialog.dismiss();
            }
        });
        dialog.setOnCancelClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkBox.setChecked(!isChecked);
                dialog.dismiss();
            }
        });
    }

    // 同步摄像头方法
    private void deviceSyncCamera(String roomId, boolean on) {
        classViewModel.setLocalVideoEnable(on);

        if (classViewModel != null) {
            classViewModel.deviceSyncCamera(roomId, on);
        }
    }

    // 关闭摄像头dialog
    private void showCmaeraDialog(boolean isChecked, CheckBox checkBox) {
        LiveCommonDialog dialog = new LiveCommonDialog(getContext());
        dialog.show();
        dialog.setTitle("提示");
        dialog.setContent("确定要关闭摄像头吗");
        dialog.setOnConfirmClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                deviceSyncCamera(roomId, !isChecked);
                dialog.dismiss();
            }
        });
        dialog.setOnCancelClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkBox.setChecked(!isChecked);
                dialog.dismiss();
            }
        });
    }

    /**
     * 各种按钮的提示
     *
     * @param type      <item>确定打开学生麦克风吗？</item> 0
     *                  <item>确定关闭学生麦克风吗？</item>1
     *                  <item>邀请学生打开摄像头吗？</item>2
     *                  <item>确定关闭学生摄像头吗？</item>3
     *                  <item>确定打开学生音乐模式吗？</item>4
     *                  <item>确定关闭学生音乐模式吗？</item>5
     *                  <item>确定打开学生节拍器吗？</item>6
     *                  <item>学生伴奏已开启，确定关闭伴奏并打开学生节拍器吗？</item>7
     *                  <item>确定关闭学生节拍器吗？</item>8
     *                  <item>确定打开学生伴奏吗？</item>9
     *                  <item>学生节拍器已开启，确定关闭节拍器并打开学生伴奏吗？</item>10
     *                  <item>确定关闭学生伴奏吗？</item>11
     * @param userId
     * @param isChecked
     * @param checkBox
     */
    private void showMemListOperteDialog(final int type, final String userId, boolean isChecked, CheckBox checkBox) {
        String[] stringArray = getResources().getStringArray(R.array.class_member_list_operate_dialog_content);
        String content = stringArray[type];

        LiveCommonDialog dialog = new LiveCommonDialog(getContext());
        dialog.show();
        dialog.setTitle("提示");
        dialog.setContent(content);
        dialog.setOnConfirmClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (type) {
                    case 0: // 麦克风
                    case 1:
                        classViewModel.controlMicrophone(roomId, userId, !isChecked);
                        break;
                    case 2: //摄像头
                    case 3:
                        classViewModel.controlCamera(roomId, userId, !isChecked);
                        break;
                    case 4: //音乐模式
                    case 5:
                        classViewModel.controlMusicMode(roomId, userId, isChecked);
                        break;
                    case 6: //节拍器
                    case 8:
                        if(isChecked){
                            checkBox.setChecked(true);
                        }else{
                            checkBox.setChecked(false);
                        }
                        setMetronome(isChecked, userId);
                        break;
                    case 7: //学生伴奏已开启，确定关闭伴奏并打开学生节拍器吗
                        String musicScoreOn = null;
                        String accompanimentOn = null;
                        musicScoreOn = classViewModel.isAccompaniment() ? null : String.valueOf(false);
                        accompanimentOn = classViewModel.isAccompaniment() ? String.valueOf(false) : null;
                        classViewModel.batchControlExamSong(roomId, null, musicScoreOn, accompanimentOn, classViewModel.getMusicScoreAccompanimentId());
                        setMetronome(isChecked, userId);
                        break;
                    case 9:  //学生伴奏
                    case 11:
                        setAccompaniment(isChecked, userId);
                        break;
                    case 10://学生节拍器已开启，确定关闭节拍器并打开学生伴奏吗
                        classViewModel.sendImPlayMidiMessage(null, roomId, false, new ResultCallback<Boolean>() {
                            @Override
                            public void onSuccess(Boolean aBoolean) {
                                setAccompaniment(isChecked, userId);
                            }

                            @Override
                            public void onFail(int errorCode, String errorStr) {
                                ToastUtil.getInstance().show(getActivity(), TextUtils.isEmpty(errorStr) ? "ERROR:" + errorCode : errorStr);
                            }
                        });

                        break;

                    default:
                        break;
                }
                dialog.dismiss();
            }
        });
        dialog.setOnCancelClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

    private void clearshareOperateView() {
        for (BtnOperate type : BtnOperate.values()) {
            CheckBox box = shareOperateView.getView(type.getValue());
            box.setChecked(false);
        }
    }

    // 设置控制按钮的状态
    private void setViewStatus(ClassMember userInfo) {
        if (userInfo == null) {
            return;
        }
        boolean hasVideoPermssion = userInfo.getRole().hasPermission(ClassPermission.VIDEO_CHAT);
        boolean hasAudioPermssion = userInfo.getRole().hasPermission(ClassPermission.AUDIO_CHAT);
        // 首先判断是否有音视频权限
        // 然后判断用户的音视频状态， 如果是关闭的则直接显示关闭
        if (hasVideoPermssion) {
            shareOperateView.setItemEnabled(BtnOperate.CAMERA.getValue(), true);
            CheckBox banedCameraBox = shareOperateView.getView(BtnOperate.CAMERA.getValue());
            // 因为按钮 false 是否代表不禁止， true 待变禁止， 所以和 用户信息携带的状态值相反
            if (banedCameraBox.isChecked() == userInfo.isCamera()) {
                banedCameraBox.setChecked(!userInfo.isCamera());
                classViewModel.setLocalVideoEnable(userInfo.isCamera());
            }
            shareOperateView.getView(BtnOperate.CAMERA.getValue()).setEnabled(true);
        } else {
            shareOperateView.setItemEnabled(BtnOperate.CAMERA.getValue(), false);
        }

        if (hasAudioPermssion) {
            shareOperateView.setItemEnabled(BtnOperate.MIC.getValue(), true);
            CheckBox banedMicBox = shareOperateView.getView(BtnOperate.MIC.getValue());
            // 因为按钮 false 是否代表不禁止， true 待变禁止， 所以和 用户信息携带的状态值相反
            if (banedMicBox.isChecked() == userInfo.isMicrophone()) {
                banedMicBox.setChecked(!userInfo.isMicrophone());
                classViewModel.setLocalMicEnable(userInfo.isMicrophone());
            }
        } else {
            shareOperateView.setItemEnabled(BtnOperate.MIC.getValue(), false);
        }
        CheckBox checkBox = shareOperateView.getView(BtnOperate.MUSIC_MODE.getValue());
        if (checkBox.isChecked() != userInfo.isMusicMode()) {
            checkBox.setChecked(userInfo.isMusicMode());
            setAudioScenrio(userInfo.isMusicMode(), false);
        }
    }

    // 设置控制按钮的状态
    public void setStudentViewStatus(ClassMember userInfo) {
        if (userInfo == null) {
            return;
        }
        CheckBox banedCameraBox = shareOperateView.getView(BtnOperate.CAMERA.getValue());
        if (banedCameraBox.isChecked() == userInfo.isCamera()) {
            banedCameraBox.setChecked(!userInfo.isCamera());
        }
        CheckBox banedMicBox = shareOperateView.getView(BtnOperate.MIC.getValue());
        // 因为按钮 false 是否代表不禁止， true 待变禁止， 所以和 用户信息携带的状态值相反
        if (banedMicBox.isChecked() == userInfo.isMicrophone()) {
            banedMicBox.setChecked(!userInfo.isMicrophone());
        }
        CheckBox musicModeBox = shareOperateView.getView(BtnOperate.MUSIC_MODE.getValue());
        if (musicModeBox.isChecked() != userInfo.isMusicMode()) {
            musicModeBox.setChecked(userInfo.isMusicMode());
        }
        if (userInfo.isOnStage()) {
            tvSpeech.setText("下台");
            iv_fragment_share_screen_onstage.setImageResource(R.drawable.ic_student_down_stage);
        } else {
            tvSpeech.setText("上台");
            iv_fragment_share_screen_onstage.setImageResource(R.drawable.ic_student_on_stage);
        }
        CheckBox metronomeBox = shareOperateView.getView(BtnOperate.METRONOME.getValue());
        if (null != userInfo.getPlayMidiJson() && metronomeBox.isChecked() != userInfo.getPlayMidiJson().isEnable()) {
            metronomeBox.setChecked(userInfo.getPlayMidiJson().isEnable());
        }

        CheckBox accompanimentBox = shareOperateView.getView(BtnOperate.ACCOMPANIMENT.getValue());
        boolean isMusicPlay = false;
        List<ClassMember.ScheduleStudentMusicScoresBean> musicScoresBeans = userInfo.getScheduleStudentMusicScores();
        if (musicScoresBeans != null && musicScoresBeans.size() > 0) {
            for (ClassMember.ScheduleStudentMusicScoresBean bean : musicScoresBeans) {
                if (bean != null && bean.getPlayStatus() == 1 || bean.getAccompanimentPlayStatus() == 1) {
                    isMusicPlay = true;
                    break;
                }
            }

        }
        if (accompanimentBox.isChecked() != isMusicPlay) {
            accompanimentBox.setChecked(isMusicPlay);
        }

    }

    private void setAudioScenrio(boolean isChecked, boolean deviceSync) {

        try {
            RCRTCEngine.getInstance().getDefaultAudioStream().changeAudioScenario(isChecked ? RCRTCParamsType.AudioScenario.MUSIC_CLASSROOM : RCRTCParamsType.AudioScenario.DEFAULT, () -> {
                int nsLevel = RtcManager.getInstance().getNsLevel();
                if (nsLevel == 0) {
                    if (isChecked) {
                        RCRTCEngine.getInstance().getDefaultAudioStream().setAudioConfig(RCRTCAudioStreamConfig.Builder.create().setNoiseSuppressionLevel(RCRTCParamsType.NSLevel.NS_VERYHIGH)
                                .setEchoCancel(RCRTCParamsType.AECMode.AEC_MODE2)
                                .enableAGCControl(false)
                                .setNoiseSuppression(RCRTCParamsType.NSMode.NS_MODE0)
                                .enableHighPassFilter(false).build());
                    } else {
                        RCRTCEngine.getInstance().getDefaultAudioStream().setAudioConfig(RCRTCAudioStreamConfig.Builder.create().setNoiseSuppressionLevel(RCRTCParamsType.NSLevel.NS_VERYHIGH).build());
                    }

                }
                RCRTCEngine.getInstance().init(getContext(), RCRTCConfig.Builder.create().enableStereo(true).build());
            });
        } catch (Exception e) {
            e.printStackTrace();
            RongIM.connect(UserRepository.imToken, new RongIMClient.ConnectCallback() {
                @Override
                public void onSuccess(String s) {
                    RCRTCEngine.getInstance().getDefaultAudioStream().changeAudioScenario(isChecked ? RCRTCParamsType.AudioScenario.MUSIC_CLASSROOM : RCRTCParamsType.AudioScenario.DEFAULT, () -> {
                        int nsLevel = RtcManager.getInstance().getNsLevel();
                        if (nsLevel == 0) {
                            if (isChecked) {
                                RCRTCEngine.getInstance().getDefaultAudioStream().setAudioConfig(RCRTCAudioStreamConfig.Builder.create().setNoiseSuppressionLevel(RCRTCParamsType.NSLevel.NS_VERYHIGH)
                                        .setEchoCancel(RCRTCParamsType.AECMode.AEC_MODE2)
                                        .enableAGCControl(false)
                                        .setNoiseSuppression(RCRTCParamsType.NSMode.NS_MODE0)
                                        .enableHighPassFilter(false).build());
                            } else {
                                RCRTCEngine.getInstance().getDefaultAudioStream().setAudioConfig(RCRTCAudioStreamConfig.Builder.create().setNoiseSuppressionLevel(RCRTCParamsType.NSLevel.NS_VERYHIGH).build());
                            }

                        }
                        RCRTCEngine.getInstance().init(getContext(), RCRTCConfig.Builder.create().enableStereo(true).build());
                    });
                }

                @Override
                public void onError(RongIMClient.ConnectionErrorCode connectionErrorCode) {

                }

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

                }
            });
        }


        if (isChecked) {
            ToastUtil.getInstance().show(getContext(), "音乐模式已开启");
        } else {
            ToastUtil.getInstance().show(getContext(), "音乐模式已关闭");
        }
        if (deviceSync && classViewModel != null) {
            classViewModel.deviceSyncMusicMode(roomId, isChecked);
        }
    }

    private void setMetronome(boolean isChecked, String userId) {

        classViewModel.sendImPlayMidiMessage(userId, roomId, isChecked, new ResultCallback<Boolean>() {
            @Override
            public void onSuccess(Boolean aBoolean) {

            }

            @Override
            public void onFail(int errorCode, String errorStr) {

            }
        });

    }

    private void setAccompaniment(boolean isChecked, String userId) {
        String musicScoreOn = null;
        String accompanimentOn = null;
        musicScoreOn = classViewModel.isAccompaniment() ? null : String.valueOf(isChecked);
        accompanimentOn = classViewModel.isAccompaniment() ? String.valueOf(isChecked) : null;
        classViewModel.batchControlExamSong(roomId, userId, musicScoreOn, accompanimentOn, classViewModel.getMusicScoreAccompanimentId());
    }

    // 取消订阅
    private synchronized void unSubscribe(String userId) {
        if (classViewModel != null) {
            classViewModel.unSubscribeResource(userId);
        }
    }

    // 移除videoView
    private void removeVideoView(String userId) {
        if (VideoViewManager.getInstance().containsKey(userId)) {
            RadioRtcVideoView remoteVideoView = VideoViewManager.getInstance().remove(userId);
            remoteVideoView.setBindVideo(false);
            remoteVideoView.clearScreen();

        }
    }

    // 创建 VideoView
    private void createVideoView(String userId) {
        if (!VideoViewManager.getInstance().containsKey(userId)) {
            RadioRtcVideoView videoView = new RadioRtcVideoView(getContext());
            VideoViewManager.getInstance().put(userId, videoView);
        }
    }

    // 订阅
    private synchronized void subscribe(String userId, final RadioRtcVideoView videoView) {
        if (classViewModel != null) {
            classViewModel.subscribeResource(userId, videoView).observe(this, new Observer<RequestState>() {
                @Override
                public void onChanged(RequestState requestState) {
                    if (requestState.getState() == RequestState.State.FAILED) {
                        videoView.setBindVideo(false);
                        ToastUtils.showToast("远端资源获取失败");
                    } else if (requestState.getState() == RequestState.State.SUCCESS) {
                    }
                }
            });
        }
    }


}
