package com.daya.live_teaching.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.cooleshow.base.router.RouterPath;
import com.cooleshow.base.ui.activity.BaseActivity;
import com.cooleshow.base.utils.KeyboardUtils;
import com.cooleshow.base.utils.LogUtils;
import com.cooleshow.base.utils.SizeUtils;
import com.cooleshow.base.utils.ToastUtil;
import com.cooleshow.base.utils.Utils;
import com.cooleshow.base.utils.helper.QMUIStatusBarHelper;
import com.daya.live_teaching.R;
import com.daya.live_teaching.common.ShowToastObserver;
import com.daya.live_teaching.databinding.ActivityLiveBinding;
import com.daya.live_teaching.model.ClassMember;
import com.daya.live_teaching.model.DeviceChangeToast;
import com.daya.live_teaching.model.DeviceControlInvite;
import com.daya.live_teaching.model.DeviceSoudValum;
import com.daya.live_teaching.model.DeviceType;
import com.daya.live_teaching.model.InviteAction;
import com.daya.live_teaching.model.LoginResult;
import com.daya.live_teaching.model.PassedTime;
import com.daya.live_teaching.model.Role;
import com.daya.live_teaching.model.ScreenDisplay;
import com.daya.live_teaching.model.StreamResource;
import com.daya.live_teaching.model.UpgradeRoleInvite;
import com.daya.live_teaching.model.UserInfo;
import com.daya.live_teaching.model.WhiteBoard;
import com.daya.live_teaching.repository.ClassRepository;
import com.daya.live_teaching.repository.OnClassEventListener;
import com.daya.live_teaching.rtc.RtcManager;
import com.daya.live_teaching.ui.adapter.WhiteBoardListAdapter;
import com.daya.live_teaching.ui.fragmnet.AccompanimentListFragment;
import com.daya.live_teaching.ui.fragmnet.BigVideoWindowFragment;
import com.daya.live_teaching.ui.fragmnet.ComplaintDialogFragment;
import com.daya.live_teaching.ui.fragmnet.GonggeModeFragment;
import com.daya.live_teaching.ui.fragmnet.MemberListFragment;
import com.daya.live_teaching.ui.fragmnet.PlayMetronomeFragment;
import com.daya.live_teaching.ui.fragmnet.ShareScreenFragment;
import com.daya.live_teaching.ui.fragmnet.TeachingToolsFragment;
import com.daya.live_teaching.ui.fragmnet.TopOperateControlFragment;
import com.daya.live_teaching.ui.fragmnet.VideoListFragment;
import com.daya.live_teaching.ui.fragmnet.VideoViewManager;
import com.daya.live_teaching.ui.fragmnet.WhiteBoardFragment;
import com.daya.live_teaching.ui.view.RadioRtcVideoView;
import com.daya.live_teaching.utils.AudioMngHelper;
import com.daya.live_teaching.utils.RTCAudioManager;
import com.daya.live_teaching.utils.ToastUtils;
import com.daya.live_teaching.viewmodel.ClassViewModel;
import com.daya.live_teaching.widget.dialog.LiveCommonDialog;

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

import cn.rongcloud.rtc.api.RCRTCAudioMixer;
import cn.rongcloud.rtc.api.RCRTCConfig;
import cn.rongcloud.rtc.api.RCRTCEngine;
import cn.rongcloud.rtc.base.RCRTCParamsType;
import io.rong.imkit.RongIM;
import io.rong.imkit.conversation.ConversationFragment;
import io.rong.imlib.model.Conversation;

/**
 * 网络教室
 */
@Route(path = RouterPath.OnlineClassroom.PATH_LIVE)
public class LiveActivity extends BaseActivity<ActivityLiveBinding> {
    //加入房间的信息 LoginResult
    public static final String EXTRA_LOGIN_RESULT = "extra_login_result";
    //是否开启相机
    public static final String EXTRA_CLOSE_CAMERA = "extra_open_camera";
    //教室ID
    public static final String CLASS_ID = "class_id";


    private ClassViewModel classViewModel;
    private LoginResult loginResult;
    private Intent intent;
    private Handler handler;
    private static final long TOAST_DEFAULT_DURATION = 3000;
    private Runnable runnableVisibilityTopFragment;
    private int visibilityTopFragmentdMillis = 5000;
    private String roomId;
    private boolean isTeacher;
    private ClassMember userInfo;
    private VideoListFragment videoListFragment;
    AlphaAnimation alphaAnimation = null;
    private FrameLayout topOperateControlFragmentViewLayout;
    private FrameLayout shareScreenFragmentViewLayout;
    private FrameLayout memberListFragmentLayout;
    private FrameLayout conversationFragmentLayout;
    private FrameLayout playMetronomeFagmentLayout;
    private FrameLayout gonggeModeFragmentLayout;
    private ConstraintLayout clLive;
    private TextView tvTime;
    ListView lvList;
    ImageView ivWhiteBoardSwitch;
    private WhiteBoardListAdapter adapter;
    private LeaveRoom leaveRoom;
    private TextView toastTv;
    private Animation toastShowAnim;
    private Animation toastDismissAnim;
    private TopOperateControlFragment topOperateControlFragment;
    private ConversationFragment conversationFragment;
    private GonggeModeFragment gonggeModeFragment;
    private BigVideoWindowFragment videoBigWidowFragment;
    private FrameLayout containerBigVideoWindow;
    private ShareScreenFragment shareScreenFragment;
    private TextView tvTeachingTools;
    private TextView tvMusicName;
    private TeachingToolsFragment teachingToolsFragment;
    private boolean isFinish = true;
    private int autoCloseNetworkRoomTime;
    private FrameLayout accompanimentListFragmentLayout;
    private AccompanimentListFragment accompanimentListFragment;
    private AudioMngHelper audioMngHelper;
    private LiveCommonDialog mLiveInviteCommonDialog;

    @Override
    protected void initView() {
        int currentStatusBarHeight = Utils.getCurrentStatusBarHeight(this);
        ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) viewBinding.viewStatusVar.getLayoutParams();
        params.width = currentStatusBarHeight;
        viewBinding.viewStatusVar.setLayoutParams(params);
    }

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

    @Override
    protected void initData() {
        super.initData();
        audioMngHelper = new AudioMngHelper(this);
        LogUtils.i("VOLEUM_TAG", "onInitView" + audioMngHelper.getSystemCurrentMode());
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("ClassAcivityLeaveRoom");
        leaveRoom = new LeaveRoom();
        registerReceiver(leaveRoom, intentFilter);
        //顶部状态按钮
        topOperateControlFragmentViewLayout = findViewById(R.id.top_operate_control_fragment);
        //
        shareScreenFragmentViewLayout = findViewById(R.id.share_screen_fragment);
        memberListFragmentLayout = findViewById(R.id.member_list_fragment);
        conversationFragmentLayout = findViewById(R.id.conversation_fragment);
        playMetronomeFagmentLayout = findViewById(R.id.play_metronome_fragment);
        gonggeModeFragmentLayout = findViewById(R.id.gongge_mode_fragment);
        accompanimentListFragmentLayout = findViewById(R.id.accompaniment_list_fragment);
        toastTv = findViewById(R.id.toastTv);
        lvList = findViewById(R.id.lv_list);
        ivWhiteBoardSwitch = findViewById(R.id.iv_white_board_switch);
        containerBigVideoWindow = findViewById(R.id.container_big_video_window);
        tvTeachingTools = findViewById(R.id.tv_teaching_tools);
        tvMusicName = findViewById(R.id.tv_music_name);
        FrameLayout teachingToolsFragmentLayout = findViewById(R.id.teaching_tools_fragment);
        tvMusicName.setOnClickListener(v -> {
            if (accompanimentListFragment != null) {

                accompanimentListFragment.showAccompanimentDialog();
            }
        });

        ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) teachingToolsFragmentLayout.getLayoutParams();
        params.width = SizeUtils.dp2px(226);
        teachingToolsFragmentLayout.setLayoutParams(params);
        // 自定义 toast 的显示和消失动画
        toastShowAnim = AnimationUtils.loadAnimation(this, R.anim.alpha_show);
        toastDismissAnim = AnimationUtils.loadAnimation(this, R.anim.alpha_dismiss);
        toastDismissAnim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                if (toastTv != null) {
                    toastTv.setVisibility(View.GONE);
                }
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });

        ivWhiteBoardSwitch.setVisibility(View.GONE);
        lvList.setVisibility(View.GONE);
        clLive = findViewById(R.id.cl_live);
        tvTime = findViewById(R.id.tv_time);
        topOperateControlFragment = new TopOperateControlFragment();
        shareScreenFragment = new ShareScreenFragment();
        videoListFragment = new VideoListFragment();
        MemberListFragment memberListFragment = new MemberListFragment();
        videoBigWidowFragment = new BigVideoWindowFragment();

        getSupportFragmentManager().beginTransaction()
                .add(R.id.top_operate_control_fragment, topOperateControlFragment)
                .add(R.id.share_screen_fragment, shareScreenFragment)
                .add(R.id.member_list_fragment, memberListFragment)
                .add(R.id.video_list_fragment, videoListFragment)
                .add(R.id.container_big_video_window, videoBigWidowFragment)
                .commit();
        shareScreenFragmentViewLayout.post(new Runnable() {
            @Override
            public void run() {
                if (!isScreenOriatationPortrait()) {
                    int height = shareScreenFragmentViewLayout.getMeasuredHeight();
                    LogUtils.i("pq", "shareScreenFragmentViewLayout height:" + height);
                    ViewGroup.LayoutParams lp = shareScreenFragmentViewLayout.getLayoutParams();
                    if (height > 0) {
                        lp.width = (int) (height * (4 / 3d));
                        LogUtils.i("pq", "shareScreenFragmentViewLayout width:" + lp.width);
                        shareScreenFragmentViewLayout.setLayoutParams(lp);
                    }
                }
            }
        });
        topOperateControlFragment.setTopOperateControlCheckListener(new TopOperateControlFragment.TopOperateControlListener() {
            @Override
            public void onMessageOrMember(TopOperateControlFragment.RightOperate rightOperate) {
                if (TopOperateControlFragment.RightOperate.MESSAGE == rightOperate) {
                    switchAnimation(conversationFragmentLayout, memberListFragmentLayout);
                } else if (TopOperateControlFragment.RightOperate.MEMBER == rightOperate) {
                    switchAnimation(memberListFragmentLayout, conversationFragmentLayout);
                }
            }


            @Override
            public void onRefresh(Intent intent) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        initClassViewModel(intent);
                    }
                });
            }

            @Override
            public void GongGe() {
                googleSwitchAnimation();
                videoListFragment.clearVideoViewInListView();
                classViewModel.setGongGe(true);

                gonggeModeFragment = (GonggeModeFragment) getSupportFragmentManager().findFragmentById(R.id.gongge_mode_fragment);
                if (gonggeModeFragment == null) {
                    gonggeModeFragment = new GonggeModeFragment();
                    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
                    fragmentTransaction.add(R.id.gongge_mode_fragment, gonggeModeFragment, "conggeModeFragment");
                    fragmentTransaction.commitAllowingStateLoss();
                }
                gonggeModeFragmentLayout.setVisibility(View.VISIBLE);
                List<ClassMember> data = classViewModel.getMemberList().getValue();
                List<String> userIds = new ArrayList<>();
                for (ClassMember member : data) {
                    userIds.add(member.getUserId());
                }
                gonggeModeFragment.refershUserVideoView(userIds);
                gonggeModeFragment.setOnClickListener(new GonggeModeFragment.OnClickListener() {
                    @Override
                    public void onItemClick(ClassMember member) {
                        showBigVideoWindow(member, true);
                    }

                    @Override
                    public void onClose() {
                        googleSwitchAnimation();
                        if (classViewModel.isOnMetronomeIsPlay() || classViewModel.isOnMusicIsPlay()) {
                            enableRTCAVInputStream(classViewModel.getDisplay().getValue().getClassMember(), false);
                        }
                        gonggeModeFragment.clearVideoViewInListView();
                        classViewModel.setGongGe(false);

                        if (null != gonggeModeFragment) {
                            //                            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
                            //                            fragmentTransaction.remove(gonggeModeFragment);
                            //                            fragmentTransaction.commitAllowingStateLoss();
                            gonggeModeFragmentLayout.setVisibility(View.GONE);
                            ScreenDisplay display = classViewModel.getDisplay().getValue();
                            classViewModel.switchDisplay(roomId, display.getType(), display.getUserId(), false);
                            List<ClassMember> data = classViewModel.getMemberList().getValue();
                            List<String> userIds = new ArrayList<>();
                            for (ClassMember member : data) {
                                userIds.add(member.getUserId());
                            }
                            videoListFragment.refershUserVideoView(userIds);
                        }


                    }
                });

            }

            @Override
            public void complaint() {
                String timeStr = tvTime.getText().toString().trim();
                if (!TextUtils.isEmpty(timeStr) && !timeStr.contains("教室关闭")) {
                    ComplaintDialogFragment fragment = new ComplaintDialogFragment();
                    fragment.setGravity(Gravity.CENTER);
                    fragment.show(getSupportFragmentManager(), "");
                } else {
                    ToastUtils.showToast("已结束课程不可使用该功能");
                }
            }
        });

        shareScreenFragment.setOnVideoViewChangeListenr(new ShareScreenFragment.OnVideoViewChangeListenr() {
            @Override
            public void onChangeUser(List<String> userIds) {
                if (videoListFragment != null) {
                    videoListFragment.refershUserVideoView(userIds);
                }
            }

            @Override
            public void onChangeUser(ClassMember oldUser) {
                if (videoListFragment != null) {
                    videoListFragment.refershUserVideoView(oldUser);
                }
            }

            @Override
            public void onRemoveUser(ClassMember member) {
                //                if (videoListFragment != null) {
                //                    videoListFragment.removeUserVideoView(member);
                //                }
            }

            @Override
            public void onSpeech(String userIds, boolean isSpeech) {
                if (null != teachingToolsFragment) {
                    teachingToolsFragment.checkButton(TeachingToolsFragment.Operate.SHARE_VIDEO.getValue());
                }
                classViewModel.switchDisplay(roomId, isSpeech ? ScreenDisplay.Display.STUDENT : ScreenDisplay.Display.LECTURER, userIds, true);
                WhiteBoardFragment whiteBoardFragment = (WhiteBoardFragment) getSupportFragmentManager().findFragmentByTag("whiteBoardFragment");
                if (null != whiteBoardFragment) {
                    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                    ivWhiteBoardSwitch.setVisibility(View.GONE);
                    transaction.remove(whiteBoardFragment);
                }
            }

            @Override
            public void onSpeechIsShowHint(boolean isShow) {
                topOperateControlFragment.speechIsShowHint(isShow);
            }
        });
        videoListFragment.setOnVideoViewItemClickListener(member -> {
            if (userInfo.getRole() != Role.LECTURER) {
                return;
            }
            ScreenDisplay.Display type;
            if (member.getRole() == Role.LECTURER) {
                type = ScreenDisplay.Display.LECTURER;
                //                if (!classViewModel.isOnMetronomeIsPlay()) {
                //                    enableRTCAVInputStream(null, true);
                //                }
            } else {
                type = ScreenDisplay.Display.STUDENT;
                if (classViewModel.isOnMetronomeIsPlay() || classViewModel.isOnMusicIsPlay()) {
                    enableRTCAVInputStream(member, false);
                }
            }

            classViewModel.switchDisplay(roomId, type, member.getUserId(), false);
        });

        videoBigWidowFragment.setOnWindowCloseListener(new BigVideoWindowFragment.OnWindowCloseListener() {
            @Override
            public void onClosed(ClassMember member) {
                showBigVideoWindow(member, false);
                if (gonggeModeFragment != null) {
                    gonggeModeFragment.refershUserVideoView(member);
                }
            }

            @Override
            public void onUpdate(ClassMember member) {
                if (gonggeModeFragment != null) {
                    gonggeModeFragment.refershUserVideoView(member);
                }
            }
        });

        initClassViewModel();
    }

    private void switchWhiteBorardOrVideo(TeachingToolsFragment.Operate operate, boolean isPostDisplay) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.setCustomAnimations(R.anim.slid_left_in, R.anim.slid_left_out);
        if (TeachingToolsFragment.Operate.SHARE_WHITE_BOARD == operate) {
            WhiteBoardFragment whiteBoardFragment;
            whiteBoardFragment = (WhiteBoardFragment) getSupportFragmentManager().findFragmentByTag("whiteBoardFragment");
            if (whiteBoardFragment == null) {
                whiteBoardFragment = new WhiteBoardFragment();
                whiteBoardFragment.setWhiteBoardListener(new WhiteBoardFragment.onWhiteBoardListener() {
                    @Override
                    public void onClick() {
                        isVisibilityTopFragmentAnimation(visibilityTopFragmentdMillis);
                        switchAnimation(null, memberListFragmentLayout);
                        switchAnimation(null, conversationFragmentLayout);
                    }

                    @Override
                    public void onWhiteBoardList(List<WhiteBoard> reverseList) {
                        if (adapter != null) {
                            adapter.setWhiteBoardList(reverseList);
                        }
                    }
                });
                if (userInfo.getRole() == Role.LECTURER) {
                    ivWhiteBoardSwitch.setVisibility(View.VISIBLE);
                    ivWhiteBoardSwitch.setOnClickListener(view -> switchAnimation());
                    adapter = new WhiteBoardListAdapter();
                    lvList.setAdapter(adapter);
                    WhiteBoardFragment finalWhiteBoardFragment = whiteBoardFragment;
                    lvList.setOnItemClickListener((adapterView, view, position, id) -> {
                        if (finalWhiteBoardFragment != null) {
                            WhiteBoard item = adapter.getItem(position);
                            finalWhiteBoardFragment.loadWhiteBoard(item.getWhiteboardId());
                            if (finalWhiteBoardFragment.isHidden()) {
                                switchWhiteBorardOrVideo(TeachingToolsFragment.Operate.SHARE_WHITE_BOARD, false);
                            }
                        }
                    });
                }
                transaction.add(R.id.share_screen_fragment, whiteBoardFragment, "whiteBoardFragment");

            } else {
                if (userInfo.getRole() == Role.LECTURER) {
                    ivWhiteBoardSwitch.setVisibility(View.VISIBLE);
                    if (whiteBoardFragment != null) {
                        whiteBoardFragment.isConnect(true);
                    }
                }
                transaction.show(whiteBoardFragment);
                ClassMember member = classViewModel.getDisplay().getValue().getClassMember();
                if (null != member) {
                    ScreenDisplay screenDisplay = classViewModel.getDisplay().getValue();
                    screenDisplay.setType(ScreenDisplay.Display.WHITEBOARD);
                    videoListFragment.refershUserVideoView(member);
                }
            }
            transaction.commitNowAllowingStateLoss();
            switchAnimation(false);
            tvMusicName.setVisibility(View.GONE);//白板不显示显示伴奏下载按钮
        } else if (TeachingToolsFragment.Operate.SHARE_VIDEO == operate) {
            WhiteBoardFragment whiteBoardFragment = (WhiteBoardFragment) getSupportFragmentManager().findFragmentByTag("whiteBoardFragment");
            if (null != whiteBoardFragment) {
                if (isPostDisplay || userInfo.getRole() == Role.STUDENT) {
                    ivWhiteBoardSwitch.setVisibility(View.GONE);
                    transaction.remove(whiteBoardFragment);
                } else {
                    if (whiteBoardFragment != null) {
                        whiteBoardFragment.isConnect(false);
                    }
                    transaction.hide(whiteBoardFragment);
                }
                transaction.commitNowAllowingStateLoss();
            }
            switchAnimation(false);
            if (accompanimentListFragment != null && !isRefreshClassViewModel) {
                tvMusicName.setVisibility(View.VISIBLE);//视频显示伴奏下载按钮
            }
        }
        if (isPostDisplay) {
            classViewModel.switchDisplay(roomId, operate == TeachingToolsFragment.Operate.SHARE_VIDEO ? ScreenDisplay.Display.LECTURER : ScreenDisplay.Display.WHITEBOARD
                    , userInfo.getUserId(), true);
        }
    }

    public void initClassViewModel() {
        intent = getIntent();
        if (intent == null) {
            finish();
        }
        loginResult = (LoginResult) intent.getSerializableExtra(EXTRA_LOGIN_RESULT);
        boolean isCloseCamera = intent.getBooleanExtra(EXTRA_CLOSE_CAMERA, true);
        // 需要由登录进入此界面，当不含登录信息时关闭
        if (loginResult == null) {
            finish();
            return;
        }
        roomId = loginResult.getRoomId();
        userInfo = loginResult.roomMember;
        autoCloseNetworkRoomTime = Integer.parseInt(loginResult.autoCloseNetworkRoomTime);

        handler = new Handler();
        classViewModel = ViewModelProviders.of(this, new ClassViewModel.Factory(loginResult, this.getApplication())).get(ClassViewModel.class);
        classViewModel.setClassId(loginResult.roomId);

        showFirstMemberToast();
        observeModel();
//        enableKeyboardStateListener(true);
        isVisibilityTopFragmentAnimation(visibilityTopFragmentdMillis);

        clLive.setOnClickListener(view -> {
            isVisibilityTopFragmentAnimation(visibilityTopFragmentdMillis);
            if (KeyboardUtils.isSoftInputVisible(LiveActivity.this)) {
                KeyboardUtils.hideSoftInput(LiveActivity.this);
            }
            switchAnimation(null, memberListFragmentLayout);
            switchAnimation(null, conversationFragmentLayout);
        });
        if (userInfo.getRole() == Role.STUDENT) {
            playMetronomeFagmentLayout.setVisibility(View.VISIBLE);
            PlayMetronomeFragment playMetronomeFragment = new PlayMetronomeFragment();
            getSupportFragmentManager().beginTransaction().add(R.id.play_metronome_fragment, playMetronomeFragment).commit();
        }
        if (userInfo.getRole() == Role.LECTURER) {
            tvTeachingTools.setVisibility(View.VISIBLE);
        }
        tvTeachingTools.setOnClickListener(view -> {
            showTeachingToosFragment();
        });

    }

    public boolean teachingToosFragmentIsHidden;
    public boolean accompanimentListFragmentIsHidden;

    private void showTeachingToosFragment() {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.setCustomAnimations(
                R.anim.slid_right_in, R.anim.slid_right_out, R.anim.slid_right_in, R.anim.slid_right_out);
        teachingToolsFragment = (TeachingToolsFragment) getSupportFragmentManager().findFragmentByTag("teachingToolsFragment");
        if (teachingToolsFragment == null) {
            teachingToolsFragment = new TeachingToolsFragment();
            teachingToolsFragment.setOperateControlCheckListener(new TeachingToolsFragment.OperateControlListener() {

                @Override
                public void onShareWhiteBoardOrVideo(TeachingToolsFragment.Operate
                                                             operate) {
                    List<ClassMember> memberList = classViewModel.getMemberList().getValue();
                    if (operate == TeachingToolsFragment.Operate.SHARE_WHITE_BOARD && memberList != null && memberList.size() > 1) {
                        for (ClassMember member : memberList) {
                            member.setOnStage(false);
                        }
                    }
                    if (ivWhiteBoardSwitch.getVisibility() == View.VISIBLE && TeachingToolsFragment.Operate.SHARE_WHITE_BOARD == operate) {
                        switchWhiteBorardOrVideo(TeachingToolsFragment.Operate.SHARE_WHITE_BOARD, false);
                    } else if (TeachingToolsFragment.Operate.SHARE_WHITE_BOARD == operate) {
                        showLoading();
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                switchWhiteBorardOrVideo(operate, true);
                                hideLoading();
                            }
                        }, 2000);
                    } else {
                        switchWhiteBorardOrVideo(operate, true);
                    }
                    tvTeachingTools.callOnClick();
                }


                @Override
                public void onMetronomeOrAccompanimentIsPlay(boolean isPlay) {
                    if (isPlay) {
                        List<ClassMember> memberList = classViewModel.getMemberList().getValue();
                        if (null != memberList && memberList.size() >= 2) {
                            ClassMember member = memberList.get(1);
                            //                        ClassMember.PlayMidiJsonBean bean = member.getPlayMidiJson();
                            //                        if (bean == null) {
                            //                            ClassMember.PlayMidiJsonBean midiBean = new ClassMember.PlayMidiJsonBean();
                            //                            midiBean.setEnable(isPlay);
                            //                            member.setPlayMidiJson(midiBean);
                            //                        } else {
                            //                            bean.setEnable(isPlay);
                            //                        }
                            ScreenDisplay.Display type;
                            if (member.getRole() == Role.LECTURER) {
                                type = ScreenDisplay.Display.LECTURER;
                            } else {
                                type = ScreenDisplay.Display.STUDENT;
                            }

                            classViewModel.switchDisplay(roomId, type, member.getUserId(), false);

                            enableRTCAVInputStream(member, false);
                        }

                    } else {
                        //                    ClassMember member = classViewModel.getLecturer().getValue();
                        //                    ScreenDisplay.Display type = ScreenDisplay.Display.LECTURER;
                        //                    classViewModel.switchDisplay(roomId, type, member.getUserId(), false);
                        enableRTCAVInputStream(null, true);
                    }
                }

                @Override
                public void showAccompaniment() {
                    isRefreshClassViewModel = false;
                    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                    accompanimentListFragment = (AccompanimentListFragment) getSupportFragmentManager().findFragmentByTag("accompanimentListFragment");
                    if (accompanimentListFragment == null) {
                        accompanimentListFragment = new AccompanimentListFragment();
                        accompanimentListFragment.setOnClickListener(new AccompanimentListFragment.OnListener() {
                            @Override
                            public void onClose() {
                                accompanimentListFragmentLayout.setVisibility(View.GONE);
                                accompanimentListFragmentIsHidden = false;
                            }

                            @Override
                            public void onMetronomeOrAccompanimentIsPlay(boolean isPlay) {
                                if (isPlay) {
                                    List<ClassMember> memberList = classViewModel.getMemberList().getValue();
                                    if (null != memberList && memberList.size() >= 2) {
                                        ClassMember member = memberList.get(1);
                                        //                        ClassMember.PlayMidiJsonBean bean = member.getPlayMidiJson();
                                        //                        if (bean == null) {
                                        //                            ClassMember.PlayMidiJsonBean midiBean = new ClassMember.PlayMidiJsonBean();
                                        //                            midiBean.setEnable(isPlay);
                                        //                            member.setPlayMidiJson(midiBean);
                                        //                        } else {
                                        //                            bean.setEnable(isPlay);
                                        //                        }
                                        ScreenDisplay.Display type;
                                        if (member.getRole() == Role.LECTURER) {
                                            type = ScreenDisplay.Display.LECTURER;
                                        } else {
                                            type = ScreenDisplay.Display.STUDENT;
                                        }

                                        classViewModel.switchDisplay(roomId, type, member.getUserId(), false);

                                        enableRTCAVInputStream(member, false);
                                    }

                                } else {
                                    //                    ClassMember member = classViewModel.getLecturer().getValue();
                                    //                    ScreenDisplay.Display type = ScreenDisplay.Display.LECTURER;
                                    //                    classViewModel.switchDisplay(roomId, type, member.getUserId(), false);
                                    enableRTCAVInputStream(null, true);
                                }
                            }

                            @Override
                            public void showMusicNameView(String musicName) {
                                if (TextUtils.isEmpty(musicName)) {
                                    tvMusicName.setVisibility(View.GONE);
                                } else {
                                    tvMusicName.setVisibility(View.VISIBLE);
                                    tvMusicName.setText(musicName);
                                }

                            }
                        });
                        transaction.add(R.id.accompaniment_list_fragment, accompanimentListFragment, "accompanimentListFragment");
                        transaction.show(accompanimentListFragment);
                        transaction.commitNowAllowingStateLoss();
                    }
                    accompanimentListFragmentLayout.setVisibility(accompanimentListFragmentIsHidden ? View.GONE : View.VISIBLE);
                    accompanimentListFragmentIsHidden = !accompanimentListFragmentIsHidden;
                }


            });
            transaction.add(R.id.teaching_tools_fragment, teachingToolsFragment, "teachingToolsFragment");
        }
        if (teachingToosFragmentIsHidden) {
            teachingToosFragmentIsHidden = false;
            transaction.hide(teachingToolsFragment);
        } else {
            teachingToosFragmentIsHidden = true;
            transaction.show(teachingToolsFragment);
        }
        transaction.commitNowAllowingStateLoss();
    }

    public void initClassViewModel(Intent intent) {
        isRefreshClassViewModel = true;

        this.intent = intent;
        if (intent == null) {
            finish();
        }
        loginResult = (LoginResult) intent.getSerializableExtra(EXTRA_LOGIN_RESULT);
        boolean isCloseCamera = (Boolean) intent.getBooleanExtra(EXTRA_CLOSE_CAMERA, true);
        // 需要由登录进入此界面，当不含登录信息时关闭
        if (loginResult == null) {
            finish();
        }

        userInfo = loginResult.roomMember;
        if (userInfo != null) {
            userInfo.setCamera(!isCloseCamera);
        }
        if (userInfo.getRole() == Role.LECTURER && topOperateControlFragment != null) {
            classViewModel.setMusicScoreAccompanimentId(null);
            classViewModel.setOnMusicIsPlay(false);
            classViewModel.setOnMetronomeIsPlay(false);
            switchWhiteBorardOrVideo(TeachingToolsFragment.Operate.SHARE_VIDEO, true);
            tvMusicName.setVisibility(View.GONE);
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.setCustomAnimations(
                    R.anim.slid_right_in, R.anim.slid_right_out, R.anim.slid_right_in, R.anim.slid_right_out);
            teachingToolsFragment = (TeachingToolsFragment) getSupportFragmentManager().findFragmentByTag("teachingToolsFragment");
            teachingToosFragmentIsHidden = false;
            if (teachingToolsFragment != null) {
                teachingToolsFragment.clearChecked();
                transaction.hide(teachingToolsFragment);
                transaction.commitNowAllowingStateLoss();
            }

            if (accompanimentListFragment != null) {
                accompanimentListFragment.clearChecked();
                accompanimentListFragmentLayout.setVisibility(View.GONE);
            }
        }


        classViewModel.onCleared();
        classViewModel.refreshClassViewModel(loginResult, this.getApplication());
        classViewModel.updateWhiteBoardList();
        showToast("线路切换成功");
    }

    private boolean isRefreshClassViewModel;
    private OnClassEventListener eventListener;

    private void observeModel() {


        // 课堂 id
        classViewModel.getRoomId().observe(this, new Observer<String>() {
            @Override
            public void onChanged(String classId) {
                roomId = classId;
                if (!TextUtils.isEmpty(roomId) && conversationFragment == null) {
                    conversationFragment = (ConversationFragment) getSupportFragmentManager().findFragmentById(R.id.conversation_fragment);
                    if (conversationFragment == null) {
                        conversationFragment = new ConversationFragment();
                        conversationFragment.initConversation(classId, Conversation.ConversationType.GROUP, null);
                        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
                        fragmentTransaction.add(R.id.conversation_fragment, conversationFragment, "conversationFragment");
                        fragmentTransaction.commitAllowingStateLoss();

                    }

//                    Uri uri = Uri.parse("rong://" + getApplicationInfo().processName).buildUpon()
//                            .appendPath("conversation")
//                            .appendPath(Conversation.ConversationType.GROUP.getName().toLowerCase(Locale.US))// TODO 小班课设置通信类型CHATROOM
//                            .appendQueryParameter("targetId", roomId)
//                            .build();
//                    conversationFragment.setUri(uri);
                }
            }
        });

        classViewModel.getPassedTime().observe(this, new Observer<PassedTime>() {
            @Override
            public void onChanged(PassedTime passedTime) {
                String time = passedTime.getPassedTime();
                tvTime.setText(time);
                if ("00:00:00".equals(time) && isFinish && autoCloseNetworkRoomTime > 0) {
                    classViewModel.startQuitRoomPaseedTime(autoCloseNetworkRoomTime * 60);
                }
                if (passedTime.isTwinkle()) {
                    tvTime.setTextColor(getResources().getColor(R.color.text_green_2D));
                    if (alphaAnimation == null) {
                        alphaAnimation = new AlphaAnimation(1.0f, 0.0f);
                        alphaAnimation.setDuration(600);
                        alphaAnimation.setRepeatCount(Animation.INFINITE);
                        alphaAnimation.setRepeatMode(Animation.REVERSE);
                        alphaAnimation.setFillBefore(true);
                        tvTime.startAnimation(alphaAnimation);
                        alphaAnimation.start();
                    }
                } else {
                    if (null != alphaAnimation) {
                        alphaAnimation.cancel();
                        alphaAnimation = null;
                    }
                    tvTime.setTextColor(getResources().getColor(R.color.colorRoleLecturer));
                }

            }
        });
        classViewModel.getQuitRoomPaseedTime().observe(this, new Observer<PassedTime>() {
            @Override
            public void onChanged(PassedTime passedTime) {
                String time = passedTime.getPassedTime();
                tvTime.setText("教室关闭：" + time);
                if (time.equals("00:00:00")) {
                    ToastUtil.getInstance().show(getApplicationContext(), "课程已结束");
                    isFinish = false;
                    VideoViewManager.getInstance().clear();
                    classViewModel.leaveRoom(roomId, userInfo.getUserId());
                    classViewModel.quitRtcRoom(roomId);
                    finish();
                }
            }
        });

        classViewModel.getDisplay().observe(this, new Observer<ScreenDisplay>() {
            @Override
            public void onChanged(ScreenDisplay screenDisplay) {
                if (screenDisplay.getType() == ScreenDisplay.Display.LECTURER ||
                        screenDisplay.getType() == ScreenDisplay.Display.STUDENT || screenDisplay.getType() == ScreenDisplay.Display.WHITEBOARD) {
                    switchWhiteBorardOrVideo(screenDisplay.getType() == ScreenDisplay.Display.WHITEBOARD ?
                            TeachingToolsFragment.Operate.SHARE_WHITE_BOARD : TeachingToolsFragment.Operate.SHARE_VIDEO, false);
                }
            }
        });
        // 设备状态变化
        classViewModel.getDeviceChangeToast().observe(this, new Observer<DeviceChangeToast>() {
            @Override
            public void onChanged(DeviceChangeToast deviceChange) {
                List<ClassMember> memberList = classViewModel.getMemberList().getValue();
                if (null == userInfo) {
                    userInfo = classViewModel.getUserInfo().getValue();
                }
                String userName = null;
                for (ClassMember member : memberList) {
                    if (deviceChange.userId.equals(member.getUserId()) && !userInfo.getUserId().equals(deviceChange.userId) && userInfo.getRole() == Role.LECTURER) {
                        userName = member.getUserName();
                        if (deviceChange.deviceType == DeviceType.Camera && deviceChange.isEnable) {
                            showToast(userName + "的摄像头已开启");
                        } else if (deviceChange.deviceType == DeviceType.Camera && !deviceChange.isEnable) {
                            showToast(userName + "的摄像头已关闭");
                        } else if (deviceChange.deviceType == DeviceType.Microphone && deviceChange.isEnable) {
                            showToast(userName + "的麦克风已开启");
                        } else if (deviceChange.deviceType == DeviceType.Microphone && !deviceChange.isEnable) {
                            showToast(userName + "的麦克风已关闭");
                        } else if (deviceChange.deviceType == DeviceType.musicMode && deviceChange.isEnable) {
                            //                            showToast(userName + "的音乐模式已开启");
                        } else if (deviceChange.deviceType == DeviceType.musicMode && !deviceChange.isEnable) {
                            //                            showToast(userName + "的音乐模式已关闭");
                        }
                    }
                    if (deviceChange.userId.equals(member.getUserId()) && deviceChange.senderUserId.equals(deviceChange.userId)
                            && !userInfo.getUserId().equals(deviceChange.userId) && userInfo.getRole() == Role.LECTURER) {
                        if (deviceChange.deviceType == DeviceType.handUpOn && deviceChange.isEnable) {
                            showToast(userName + "已举手");
                        } else if (deviceChange.deviceType == DeviceType.handUpOn && !deviceChange.isEnable) {
                            showToast(userName + "已取消举手");
                        }
                    }
                }
                if (deviceChange.userId.equals(classViewModel.getUserInfo().getValue().getUserId()) && !deviceChange.senderUserId.equals(deviceChange.userId) && classViewModel.getUserInfo().getValue().getRole() != Role.LECTURER) {
                    if (deviceChange.deviceType == DeviceType.Camera && !deviceChange.isEnable) {
                        showToast("老师关闭了你的摄像头");
                    } else if (deviceChange.deviceType == DeviceType.Microphone && !deviceChange.isEnable) {
                        showToast("老师关闭了你的麦克风");
                    }
                    //                    else if (deviceChange.deviceType == DeviceType.musicMode && !deviceChange.isEnable) {
                    //                        showToast("老师关闭了你的音乐模式");
                    //                    }
                }
            }
        });
        classViewModel.getSoundValum().observe(this, new Observer<DeviceSoudValum>() {
            @Override
            public void onChanged(DeviceSoudValum deviceSoudValum) {
                if (deviceSoudValum.deviceType == null) {
                    return;
                }
                DeviceType deviceType = deviceSoudValum.deviceType;
                switch (deviceType) {
                    case MusicScore:
                    case MusicScoreAccompaniment:
                        if (!TextUtils.isEmpty(deviceSoudValum.musicScoreAccompanimentId)) {
                            Integer soundValue = deviceSoudValum.soundValue;
                            if (soundValue == 0) {
                                //停止伴奏
                                LogUtils.i("VOLEUM_TAG", "停止伴奏");
                                classViewModel.setAccompanyVolume(false);
                            } else {
                                int mode = audioMngHelper.getSystemCurrentMode();
                                LogUtils.i("VOLEUM_TAG", "getMode" + mode);
                                int setVolume = audioMngHelper.setVoice100(soundValue);
                                LogUtils.i("VOLEUM_TAG", "修改后的音量" + setVolume + "-修改前的音量-" + soundValue);
                            }

                        }
                        break;
                    default:
                }

            }
        });

        classViewModel.getUpgradeRoleInvite().

                observe(this, new Observer<UpgradeRoleInvite>() {
                    @Override
                    public void onChanged(UpgradeRoleInvite upgradeRoleInvite) {
                        InviteAction action = upgradeRoleInvite.getAction();
                        switch (action) {
                            case APPROVE:
                                // 同意
                                showToast(R.string.toast_other_side_accept_your_request);
                                break;
                            case REJECT:
                                // 拒绝
                                showToast(R.string.toast_other_side_reject_your_request);
                                break;
                            default:
                                break;
                        }
                    }
                });
        // 设备控制请求
        classViewModel.getDeviceControlInvite().

                observe(this, new Observer<DeviceControlInvite>() {
                    @Override
                    public void onChanged(DeviceControlInvite deviceControlInvite) {
                        InviteAction action = deviceControlInvite.getAction();
                        switch (action) {
                            case INVITE: // 助教控制设备请求
                                DeviceType deviceType = deviceControlInvite.getDeviceType();
                                inviteOpenedDevicesDialog(deviceType, deviceControlInvite.getTicket());
                                break;
                            case REJECT:
                                // 拒绝操作提示
                                showToast(deviceControlInvite.getOpUserName() + "拒绝了你的请求");
                                break;
                            case APPROVE:
                                //                        // 同意操作提示
                                //                        showToast(  deviceControlInvite.getOpUserName()+""+R.string.toast_other_side_accept_your_request);
                                break;
                            default:
                                break;
                        }

                    }

                });
        classViewModel.getAddClassMember().

                observe(this, new Observer<ClassMember>() {
                    @Override
                    public void onChanged(ClassMember classMember) {
                        if (userInfo.getRole() == Role.STUDENT && classMember.getRole() == Role.LECTURER) {
                            showToast("老师" + classMember.getUserName() + "已经进入教室");
                        } else if (userInfo.getRole() == Role.LECTURER && classMember.getRole() == Role.STUDENT) {
                            showToast("学生" + classMember.getUserName() + "已经进入教室");
                        }

                    }
                });
        classViewModel.getRemoveClassMember().

                observe(this, new Observer<ClassMember>() {
                    @Override
                    public void onChanged(ClassMember classMember) {
                        if (userInfo.getRole() == Role.LECTURER && classMember.getRole() == Role.STUDENT) {
                            showToast("学生" + classMember.getUserName() + "已经离开教室");
                        }
                    }
                });
        classViewModel.getVideoRemovedUser().

                observe(this, new Observer<StreamResource>() {
                    @Override
                    public void onChanged(StreamResource streamResource) {
                        if (null != videoBigWidowFragment && containerBigVideoWindow.getVisibility() == View.VISIBLE) {
                            ClassMember member = videoBigWidowFragment.getMember();
                            if (null != member && member.getUserId().equals(streamResource.userId))
                                videoBigWidowFragment.closeBigWindow();
                        }
                    }
                });

    }


    // 设备控制请求 dialog
    private void inviteOpenedDevicesDialog(DeviceType deviceType, final String ticket) {
        if (deviceType == DeviceType.musicMode || deviceType == DeviceType.Microphone) {
            if (deviceType == DeviceType.Microphone) {
                showToast("老师开启了你的麦克风");
                deviceApprove(roomId, ClassRepository.PARAM_MICROPHONE_TYPE);
            } else {
                deviceApprove(roomId, ClassRepository.PARAM_MUSIC_MODE_TYPE);
            }
            return;
        }
        int contentMessage = R.string.class_dialog_request_invite_camera_connect;
        String toast = "老师开启了你的摄像头";
        int finalContentMessage = contentMessage;
        if (mLiveInviteCommonDialog == null) {
            mLiveInviteCommonDialog = new LiveCommonDialog(this);
        }
        if (!mLiveInviteCommonDialog.isShowing()) {
            mLiveInviteCommonDialog.show();
        }
        mLiveInviteCommonDialog.setTitle("提示");
        mLiveInviteCommonDialog.setConfirmBtnText("同意");
        mLiveInviteCommonDialog.setCancelBtnText("拒绝");
        mLiveInviteCommonDialog.setContent(getString(finalContentMessage));
        mLiveInviteCommonDialog.setOnConfirmClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mLiveInviteCommonDialog.dismiss();
                deviceApprove(roomId, ClassRepository.PARAM_CAMERA_TYPE);
            }
        });
        mLiveInviteCommonDialog.setOnCancelClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mLiveInviteCommonDialog.dismiss();
                deviceReject(roomId, ClassRepository.PARAM_CAMERA_TYPE);
            }
        });
    }

    // deviceReject
    private void deviceApprove(String roomId, String deviceType) {
        if (classViewModel != null) {
            classViewModel.deviceApprove(roomId, deviceType).observe(this, new ShowToastObserver(this));
        }

    }

    //拒绝设备开启请求
    private void deviceReject(String roomId, String deviceType) {
        if (classViewModel != null) {
            classViewModel.deviceReject(roomId, deviceType).observe(this, new ShowToastObserver(this));
        }

    }

    /**
     * 如果是房间中只有自己则根据身份不同弹出不同提示
     */
    private void showFirstMemberToast() {
        List<ClassMember> memberList = classViewModel.getMemberList().getValue();
        if (memberList != null && memberList.size() == 1) {
            UserInfo userInfo = classViewModel.getUserInfo().getValue();
            if (userInfo.getRole() == Role.LISTENER) {
                showToast(R.string.toast_tips_role_is_listener);
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        showToast(R.string.toast_only_self_in_room);
                    }
                }, TOAST_DEFAULT_DURATION);
            } else {
                showToast(R.string.toast_only_self_in_room);
            }
        }
    }

    private void googleSwitchAnimation() {
        if (null != gonggeModeFragmentLayout && gonggeModeFragmentLayout.getVisibility() == View.VISIBLE) {
            TranslateAnimation hideAnim = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
                    Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 1.0f);
            hideAnim.setDuration(150);
            gonggeModeFragmentLayout.startAnimation(hideAnim);
            hideAnim.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {

                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    gonggeModeFragmentLayout.setVisibility(View.GONE);
                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });
        } else if (null != gonggeModeFragmentLayout) {
            TranslateAnimation showAnim = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
                    Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 1.0f, Animation.RELATIVE_TO_SELF, 0.0f);
            showAnim.setDuration(150);
            gonggeModeFragmentLayout.startAnimation(showAnim);
            gonggeModeFragmentLayout.setVisibility(View.VISIBLE);
        }
    }

    private void switchAnimation(FrameLayout visibleLayout, FrameLayout goneLayout) {
        if (null != goneLayout && goneLayout.getVisibility() == View.VISIBLE) {
            topOperateControlFragment.setIsHasMesageButton(false);
            TranslateAnimation hideAnim = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
                    Animation.RELATIVE_TO_SELF, 1.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f);
            hideAnim.setDuration(100);
            goneLayout.startAnimation(hideAnim);
            hideAnim.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {

                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    goneLayout.setVisibility(View.GONE);
                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });
        }
        if (null != visibleLayout) {
            TranslateAnimation showAnim = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 1.0f,
                    Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f);
            showAnim.setDuration(100);
            visibleLayout.startAnimation(showAnim);
            visibleLayout.setVisibility(View.VISIBLE);
        }
    }

    private void isVisibilityTopFragmentAnimation(int time) {
        if (topOperateControlFragmentViewLayout.getVisibility() == View.VISIBLE) {
            handler.removeCallbacks(runnableVisibilityTopFragment);
            handler.postDelayed(runnableVisibilityTopFragment, time);
            return;
        }
        runnableVisibilityTopFragment = new Runnable() {
            @Override
            public void run() {
                if (null != topOperateControlFragmentViewLayout && topOperateControlFragmentViewLayout.getVisibility() == View.VISIBLE) {
                    TranslateAnimation hideAnim = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
                            Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, -1.0f);
                    hideAnim.setDuration(100);
                    topOperateControlFragmentViewLayout.startAnimation(hideAnim);
                    hideAnim.setAnimationListener(new Animation.AnimationListener() {
                        @Override
                        public void onAnimationStart(Animation animation) {

                        }

                        @Override
                        public void onAnimationEnd(Animation animation) {
                            topOperateControlFragmentViewLayout.setVisibility(View.GONE);
                            runnableVisibilityTopFragment = null;
                        }

                        @Override
                        public void onAnimationRepeat(Animation animation) {

                        }
                    });
                } else if (null != topOperateControlFragmentViewLayout && topOperateControlFragmentViewLayout.getVisibility() == View.GONE) {
                    TranslateAnimation showAnim = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
                            Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, -1.0f, Animation.RELATIVE_TO_SELF, 0.0f);
                    showAnim.setDuration(100);
                    topOperateControlFragmentViewLayout.startAnimation(showAnim);
                    topOperateControlFragmentViewLayout.setVisibility(View.VISIBLE);
                    handler.postDelayed(runnableVisibilityTopFragment, time);
                }
            }
        };
        handler.postDelayed(runnableVisibilityTopFragment, 0);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        int orientation = newConfig.orientation;
        if (orientation == 2) {

        } else {

        }

    }

    /**
     * 1.打开节拍器默认只播放第一个学生的流 学生member ，false;
     * 2.关闭节拍器，打开所有人的流null ，true;
     * 3.老师点击切换时，关闭上一个学生的音频，打开现在的学生的音频 newMember ，false
     * 是否播放其它人员音频流
     *
     * @param member
     * @param enable
     */
    private void enableRTCAVInputStream(ClassMember member, boolean enable) {
        if (null != classViewModel) {
            List<ClassMember> memberList = classViewModel.getMemberList().getValue();
            if (Role.LECTURER == loginResult.getUserInfo().getRole()) {
                for (ClassMember listMemberMode : memberList) {
                    if (listMemberMode.getRole() != Role.LECTURER) {
                        if (null == member) {
                            classViewModel.enableRTCAVInputStream(listMemberMode.getUserId(), enable);
                        } else if (member.getRole() != Role.LECTURER && !member.getUserId().equals(listMemberMode.getUserId())) {
                            classViewModel.enableRTCAVInputStream(listMemberMode.getUserId(), enable);
                        } else if (member.getRole() != Role.LECTURER) {
                            classViewModel.enableRTCAVInputStream(listMemberMode.getUserId(), !enable);
                        }

                    }
                }
            }
        }
    }

    private void switchAnimation() {
        if (null != lvList && lvList.getVisibility() == View.VISIBLE) {
            lvList.setVisibility(View.GONE);
            ivWhiteBoardSwitch.setImageResource(R.drawable.ic_white_board_open);
        } else if (null != lvList) {
            lvList.setVisibility(View.VISIBLE);
            ivWhiteBoardSwitch.setImageResource(R.drawable.ic_white_board_close);
        }
    }

    private void switchAnimation(boolean isVisibility) {
        if (null != lvList && lvList.getVisibility() == View.VISIBLE && !isVisibility) {
            lvList.setVisibility(View.GONE);
            ivWhiteBoardSwitch.setImageResource(R.drawable.ic_white_board_open);
        } else if (null != lvList && isVisibility) {
            lvList.setVisibility(View.VISIBLE);
            ivWhiteBoardSwitch.setImageResource(R.drawable.ic_white_board_close);
        }
    }

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

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
    }


    class LeaveRoom extends BroadcastReceiver {
        //实现接收到广播的处理
        @Override
        public void onReceive(Context context, Intent intent) {
            VideoViewManager.getInstance().clear();
            classViewModel.leaveRoom(roomId, userInfo.getUserId());
            classViewModel.quitRtcRoom(roomId);
            finish();
        }
    }

    /**
     * 取消 toast 显示用 runnable
     * 声明变量用于 handler 移除回调使用
     */
    private Runnable toastDismissRunnable = new Runnable() {
        @Override
        public void run() {
            if (toastTv == null)
                return;
            toastTv.startAnimation(toastDismissAnim);
            if (null != toastList && toastList.size() > 0) {
                toastTvShow(toastList.get(0), 1000);
                toastList.remove(0);
            }
        }
    };
    List<String> toastList = new ArrayList<String>();

    public void showToast(String content, long duration) {
        if (toastTv == null || TextUtils.isEmpty(content)) {
            toastList.clear();
            return;
        }
        if (toastTv.getVisibility() == View.VISIBLE) {
            toastList.add(content);
            handler.postDelayed(toastDismissRunnable, 1000);
        } else {
            toastTvShow(content, duration);
        }

    }

    private void toastTvShow(String content, long duration) {
        toastTv.setText(content);
        toastShowAnim.reset();
        toastDismissAnim.reset();
        handler.removeCallbacks(toastDismissRunnable);
        toastTv.setVisibility(View.VISIBLE);
        toastTv.startAnimation(toastShowAnim);
        if (duration == 0) {
            duration = TOAST_DEFAULT_DURATION;
        }
        handler.postDelayed(toastDismissRunnable, duration);
    }

    public void showToast(String content) {
        showToast(content, TOAST_DEFAULT_DURATION);
    }

    public void showToast(int resId, long duration) {
        showToast(getString(resId), duration);
    }

    public void showToast(int resId) {
        showToast(resId, TOAST_DEFAULT_DURATION);
    }


    Handler onStopHandler = null;
    Runnable onStoprunnable = null;

    @Override
    protected void onResume() {
        super.onResume();
        if (null != onStopHandler && null != onStoprunnable) {
            onStopHandler.removeCallbacks(onStoprunnable);
            onStopHandler = null;
            onStoprunnable = null;
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        try {
            onStopHandler = new Handler();
            onStoprunnable = new Runnable() {
                @Override
                public void run() {
                    if (null != classViewModel) {

                        VideoViewManager.getInstance().clear();
                        classViewModel.leaveRoom(roomId, userInfo.getUserId());
                        classViewModel.quitRtcRoom(roomId);
                        LiveActivity.this.finish();
                    }
                }
            };
            onStopHandler.postDelayed(onStoprunnable, 1000 * 60 * 3);
        } catch (Exception e) {
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            if (null != onStopHandler && null != onStoprunnable) {
                onStopHandler.removeCallbacks(onStoprunnable);
                onStopHandler = null;
                onStoprunnable = null;
            }
            RCRTCEngine.getInstance().getDefaultAudioStream().changeAudioScenario(RCRTCParamsType.AudioScenario.DEFAULT, () -> {
                RCRTCEngine.getInstance().init(getApplicationContext(), RCRTCConfig.Builder.create().enableStereo(true).build());
            });
            VideoViewManager.getInstance().clear();
            RongIM.getInstance().clearMessagesUnreadStatus(Conversation.ConversationType.GROUP, roomId, null);
            RTCAudioManager.setDefaultAudioMode(getApplicationContext());
            unregisterReceiver(leaveRoom);
            RCRTCAudioMixer.getInstance().stop();
        } catch (Exception e) {
        }
    }

    private void showBigVideoWindow(ClassMember member, boolean show) {
        RadioRtcVideoView videoView = VideoViewManager.getInstance().get(member.getUserId());
        if (videoBigWidowFragment != null) {
            if (show && null != videoView) {
                if ((classViewModel.isOnMetronomeIsPlay() || classViewModel.isOnMusicIsPlay()) && member.getRole() == Role.STUDENT) {
                    enableRTCAVInputStream(member, false);
                }
                RtcManager.getInstance().switchStream(member.getUserId(), true);
                videoBigWidowFragment.show(member);
                containerBigVideoWindow.setVisibility(View.VISIBLE);
            } else {
                RtcManager.getInstance().switchStream(member.getUserId(), false);
                containerBigVideoWindow.setVisibility(View.GONE);
            }
        }

    }

    @Override
    public void onBackPressed() {
    }

}
