package com.daya.live_teaching.ui.fragmnet;


import android.app.Activity;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothHeadset;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.Handler;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

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.cooleshow.base.utils.ToastUtils;
import com.cooleshow.usercenter.helper.UserHelper;
import com.daya.live_teaching.R;
import com.daya.live_teaching.audioManager.AppRTCAudioManager;
import com.daya.live_teaching.audioManager.BluetoothUtil;
import com.daya.live_teaching.common.ResultCallback;
import com.daya.live_teaching.databinding.FragmentTopOperateControlBinding;
import com.daya.live_teaching.model.ClassMember;
import com.daya.live_teaching.model.LoginResult;
import com.daya.live_teaching.model.RequestState;
import com.daya.live_teaching.model.Role;
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.LiveActivity;
import com.daya.live_teaching.utils.HeadsetPlugReceiver;
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.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import cn.rongcloud.rtc.api.RCRTCConfig;
import cn.rongcloud.rtc.api.RCRTCEngine;
import cn.rongcloud.rtc.api.callback.IRCRTCStatusReportListener;
import cn.rongcloud.rtc.api.report.StatusBean;
import cn.rongcloud.rtc.api.report.StatusReport;
import cn.rongcloud.rtc.api.stream.RCRTCAudioStreamConfig;
import cn.rongcloud.rtc.base.RCRTCParamsType;


/**
 * A simple {@link Fragment} subclass.
 */
public class TopOperateControlFragment extends BaseFragment<FragmentTopOperateControlBinding> implements HeadsetPlugReceiver.OnHeadsetPlugListener {

    private TopOperateControlListener listener;

    ImageView ivNetworkSignalStrength;
    TextView tvTime;
    TextView tvSpeechHint;
    OperateButtonGroupView leftOperateView;
    OperateButtonGroupView rightOperateView;
    private ClassViewModel classViewModel;
    private UserInfo userInfoValue;
    private String roomId;
    private HeadsetPlugReceiver headsetPlugReceiver;
    private AppRTCAudioManager audioManager;
    AlphaAnimation alphaAnimation = null;
    private boolean isFinish = true;
    /**
     * true 关闭扬声器； false 打开扬声器
     */
    private boolean muteSpeaker = false;
    private boolean allowRefresh = true;
    private boolean isPlayMetronme = false;
    //    private String  tenant_id;
    private boolean isHasMesageButton = false;

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


    public enum RightOperate { // 控制按钮类型
        /**
         * 聊天
         */
        MESSAGE(0),

        /**
         * 在线成员
         */
        MEMBER(1),
        /**
         * 刷新
         */
        REFRESH(2),
        /**
         * 申诉
         */
        COMPLAINT(3),

        /**
         * 退出
         */
        HANGUP(4);

        private int value;

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

        public int getValue() {
            return value;
        }

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

    //    // 按钮的资源布局
    private int[] rightBtnBgResIds = new int[]{
            R.drawable.fragment_top_operate_message_change_selector,
            R.drawable.fragment_top_operate_member_change_selector,
            R.drawable.fragment_top_operate_refresh_selector,
            R.drawable.ic_live_complaint,
            R.drawable.fragment_top_operate_hangup_selector};

    public enum LeftOperate { // 控制按钮类型


        /**
         * 切换摄像头
         */
        CAMERA_CHANGE(0),

        /**
         * 麦克风
         */
        MIC(1),
        /**
         * 摄像头
         */
        CAMERA(2),
        /**
         * 开关外放
         */
        BANED_SOUND(3),
        /**
         * 宫格模式
         */
        GONG_GE(4);

        private int value;

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

        public int getValue() {
            return value;
        }

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

    //    // 按钮的资源布局
    private int[] leftbBtnBgResIds = new int[]{
            R.drawable.fragment_top_operate_camera_change_selector,
            R.drawable.fragment_top_operate_mic_selector,
            R.drawable.fragment_top_operate_camera_selector,
            R.drawable.fragment_top_operate_sound_selector,
            R.drawable.fragment_top_operate_gongge
    };

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

    @Override
    protected void initView(View rootView) {
        ivNetworkSignalStrength = mViewBinding.ivNetworkSignalStrength;
        tvTime = mViewBinding.tvTime;
        tvSpeechHint = mViewBinding.tvSpeechHint;
        leftOperateView = mViewBinding.leftOperateView;
        rightOperateView = mViewBinding.rightOperateView;
        initRightOperateItem();
        initLeftOperateItem();
    }

    @Override
    protected void initData() {
        classViewModel = ViewModelProviders.of(getActivity()).get(ClassViewModel.class);
        classViewModel.registerStatusReportListener(statusReportListener);
        classViewModel.setEnableSpeakerphone(true);

        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(UserInfo userInfo) {
                if (userInfo != null) {
                    userInfoValue = userInfo;
                    setViewStatus(userInfo);
                }
            }
        });


        classViewModel.getUnReadMessage().observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer integer) {
                if (integer > 0) {
                    showHasMessageButton();
                }
            }
        });

    }

    /**
     * 当有消息时， 但是没有在聊天界面， 就会显示有消息的按钮提醒
     */
    private void showHasMessageButton() {
        Button BtnMessage = rightOperateView.getView(RightOperate.MESSAGE.getValue());
        if (!isHasMesageButton) {
            BtnMessage.setBackgroundResource(R.drawable.ic_top_operate_message_red);
        }
    }

    public void setIsHasMesageButton(boolean isHasMesageButton) {
        this.isHasMesageButton = isHasMesageButton;
    }

    private void initLeftOperateItem() {
        // 初始化动态添加控制按钮
        List<OperateItem> items = new ArrayList<>();
        int value = SizeUtils.dp2px(34);
        int marginLeft = SizeUtils.dp2px(11);
        for (LeftOperate operate : LeftOperate.values()) {
            OperateItem item = new OperateItem();
            item.id = operate.getValue();
            item.bgResId = leftbBtnBgResIds[operate.getValue()];
            item.width = value;
            item.height = value;
            item.left = marginLeft;
            if (operate == LeftOperate.MIC ||
                    operate == LeftOperate.CAMERA || operate == LeftOperate.BANED_SOUND) {
                item.type = OperateItem.Type.CHECKBOX;
            } else {
                item.type = OperateItem.Type.CHECKBOX;
            }
            items.add(item);

        }
        // 初始化操作布局
        leftOperateView.initView(items, new OnOperateItemListener() {
            @Override
            public void onItemClicked(View v, OperateItem item) {
                LeftOperate type = LeftOperate.getType(item.id);
                switch (type) {
                    default:
                        break;
                }
            }

            @Override
            public void onCheckedChanged(View v, OperateItem item, boolean isChecked) {
                if (v.isPressed()) {
                    LeftOperate type = LeftOperate.getType(item.id);
                    CheckBox checkBox = leftOperateView.getView(type.getValue());
                    switch (type) {

                        case MIC:
                            checkBox.setChecked(!isChecked);
                            if (!isChecked) {
                                deviceSyncMic(roomId, !isChecked);
                                return;
                            }
                            showMicDialog(isChecked, checkBox);
                            break;
                        case CAMERA:
                            checkBox.setChecked(!isChecked);
                            if (!isChecked) {
                                deviceSyncCamera(roomId, !isChecked);
                                return;
                            }
                            showCmaeraDialog(isChecked, checkBox);
                            break;

                        case BANED_SOUND:
                            classViewModel.setEnableSpeakerphone(!isChecked);
                            onToggleSpeaker(isChecked);
                            break;
                        case CAMERA_CHANGE:
                            classViewModel.switchCamera();
                            break;
                        case GONG_GE:
                            if (listener != null) {
                                listener.GongGe();
                            }
                            break;
                        default:
                            break;
                    }
                }
            }
        });
        leftOperateView.setItemVisibility(LeftOperate.BANED_SOUND.getValue(), View.GONE);
        leftOperateView.setItemVisibility(LeftOperate.GONG_GE.getValue(), View.GONE);

        initAudioManager();
        isBluetoothAndWire();
        HeadsetPlugReceiver.setOnHeadsetPlugListener(this);
        if (BluetoothUtil.isSupportBluetooth()) {
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction("android.intent.action.HEADSET_PLUG");
            intentFilter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
            intentFilter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
            headsetPlugReceiver = new HeadsetPlugReceiver();
            getActivity().registerReceiver(headsetPlugReceiver, intentFilter);
        }
    }


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

    // 关闭摄像头dialog
    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();
            }
        });
    }

    private void initRightOperateItem() {
        // 初始化动态添加控制按钮
        List<OperateItem> rightItems = new ArrayList<>();
        int value = SizeUtils.dp2px(34);
        int marginLeft = SizeUtils.dp2px(11);
        for (RightOperate operate : RightOperate.values()) {
            OperateItem item = new OperateItem();
            item.id = operate.getValue();
            item.bgResId = rightBtnBgResIds[operate.getValue()];
            item.width = value;
            if (item.bgResId == R.drawable.fragment_top_operate_hangup_selector) {
                item.height = value * 3;
            } else {
                item.height = value;
            }
            item.left = marginLeft;
            item.type = OperateItem.Type.CHECKBOX;
            rightItems.add(item);
        }

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


            }

            @Override
            public void onCheckedChanged(View v, OperateItem item, boolean isChecked) {
                RightOperate type = RightOperate.getType(item.id);
                switch (type) {
                    case MEMBER:
                        listener.onMessageOrMember(type);
                        break;
                    case MESSAGE:
                        isHasMesageButton = true;
                        listener.onMessageOrMember(type);
                        Button BtnMessage = rightOperateView.getView(type.value);
                        BtnMessage.setBackgroundResource(R.drawable.ic_top_operate_message_pressed);
                        break;
                    case REFRESH:
                        if (allowRefresh) {
                            allowRefresh = false;
                            showRefreshDialog();
                        } else {
                            ToastUtil.getInstance().showShort("线路切换中，请稍后");
                        }
                        break;
                    case COMPLAINT:
                        if (listener != null) {
                            listener.complaint();
                        }
                        break;
                    case HANGUP:
                        showExitDialog();
                        break;
                }
            }
        });
        rightOperateView.setItemVisibility(RightOperate.MEMBER.getValue(), View.GONE);
        rightOperateView.setItemVisibility(RightOperate.COMPLAINT.getValue(), View.GONE);

    }

    private void initAudioManager() {
        // Create and audio manager that will take care of audio routing,
        // audio modes, audio device enumeration etc.
        audioManager = AppRTCAudioManager.create(getActivity(), new Runnable() {
                    // This method will be called each time the audio state (number and
                    // type of devices) has been changed.
                    @Override
                    public void run() {
                        onAudioManagerChangedState();
                    }
                }
        );
        // Store existing audio settings and change audio mode to
        // MODE_IN_COMMUNICATION for best possible VoIP performance.
        audioManager.init();
    }

    private void isBluetoothAndWire() {
        int type = -1;
        if (BluetoothUtil.hasBluetoothA2dpConnected()) {
            type = 0;
        } else if (BluetoothUtil.isWiredHeadsetOn(getContext())) {
            type = 1;
        }
        if (type != -1) {
            onNotifyHeadsetState(true, type);
        }
    }

    @Override
    public void onNotifyHeadsetState(boolean connected, int type) {
        try {
            if (connected) {
                if (type == 0) {
                    AudioManager am = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);

                    if (am.getMode() != AudioManager.MODE_IN_COMMUNICATION) {
                        am.setMode(AudioManager.MODE_IN_COMMUNICATION);
                    }
                    am.startBluetoothSco();
                    am.setBluetoothScoOn(true);
                    am.setSpeakerphoneOn(false);
                }
                setbanedSound(true);
                CheckBox cb = leftOperateView.getView(LeftOperate.BANED_SOUND.getValue());
                cb.setEnabled(false);
                cb.setClickable(false);
            } else {
                if (type == 1 && BluetoothUtil.hasBluetoothA2dpConnected()) {
                    return;
                }
                AudioManager am = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);
                if (am.getMode() != AudioManager.MODE_IN_COMMUNICATION) {
                    am.setMode(AudioManager.MODE_IN_COMMUNICATION);
                }
                if (type == 0) {
                    am.stopBluetoothSco();
                    am.setBluetoothScoOn(false);
                    am.setSpeakerphoneOn(true);
                }
                setbanedSound(false);
                CheckBox cb = leftOperateView.getView(LeftOperate.BANED_SOUND.getValue());
                cb.setEnabled(true);
                cb.setClickable(true);
            }
        } catch (Exception e) {
            e.printStackTrace();
            LogUtils.e(e.getMessage());
        }
    }

    public void setbanedSound(boolean b) {
        CheckBox cb = leftOperateView.getView(LeftOperate.BANED_SOUND.getValue());
        cb.setChecked(b);
    }

    private void onAudioManagerChangedState() {
        // TODO(henrika): disable video if AppRTCAudioManager.AudioDevice.EARPIECE
        // is active.
    }

    public boolean onToggleSpeaker(boolean mute) {
        try {
            this.muteSpeaker = mute;
            audioManager.onToggleSpeaker(mute);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mute;
    }

    private void showRefreshDialog() {
        LiveCommonDialog dialog = new LiveCommonDialog(getContext());
        dialog.show();
        dialog.setTitle("提示");
        dialog.setContent("确认切换线路吗?");
        dialog.setOnConfirmClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                leaveRoom(roomId, true);
                dialog.dismiss();
            }
        });
        dialog.setOnCancelClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                allowRefresh = true;
                dialog.dismiss();
            }
        });
    }

    private void showExitDialog() {

        LiveCommonDialog dialog = new LiveCommonDialog(getContext());
        dialog.show();
        dialog.setTitle("提示");
        dialog.setContent("是否退出课堂?");
        dialog.setOnConfirmClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                leaveRoom(roomId);
                dialog.dismiss();
            }
        });
        dialog.setOnCancelClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

    // 切换线路
    public void leaveRoom(final String roomId, boolean isRefresh) {
        ToastUtil.getInstance().showShort("线路切换中，请稍后");
        VideoViewManager.getInstance().clear();
        if (classViewModel != null) {
            classViewModel.leaveRoom(roomId, userInfoValue.getUserId());
            classViewModel.quitRtcRoom(roomId).observe(TopOperateControlFragment.this, new Observer<RequestState>() {
                @Override
                public void onChanged(RequestState requestState) {
                    if (isRefresh && requestState.getState() != RequestState.State.LOADING) {
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                new UserRepository(getContext()).login(classViewModel.getClassId(), false, UserHelper.getUserName(), new ResultCallback<LoginResult>() {
                                    @Override
                                    public void onSuccess(LoginResult loginResult) {

                                        Intent intent = new Intent();
                                        intent.putExtra(LiveActivity.EXTRA_LOGIN_RESULT, loginResult);
                                        intent.putExtra(LiveActivity.EXTRA_CLOSE_CAMERA, false);
                                        listener.onRefresh(intent);
                                        allowRefresh();
                                    }

                                    @Override
                                    public void onFail(int errorCode, String errorStr) {
                                        allowRefresh();
                                    }
                                });
                            }
                        }, 1000);
                    } else {
                        allowRefresh();
                    }
                }
            });
        }
    }

    private void allowRefresh() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                allowRefresh = true;
            }
        }, 2000);
    }

    // 离开房间操作
    public void leaveRoom(final String roomId) {
        VideoViewManager.getInstance().clear();
        if (classViewModel != null) {
            classViewModel.leaveRoom(roomId, userInfoValue.getUserId());
            classViewModel.quitRtcRoom(roomId).observe(TopOperateControlFragment.this, new Observer<RequestState>() {
                @Override
                public void onChanged(RequestState requestState) {
                    getActivity().finish();
                }
            });
        }

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (headsetPlugReceiver != null) {
            getActivity().unregisterReceiver(headsetPlugReceiver);
            headsetPlugReceiver = null;
        }
        if (audioManager != null) {
            audioManager.close();
            audioManager = null;
        }
        if (networkObserverTimer != null) {
            networkObserverTimer.cancel();
            networkObserverTimer = null;
        }
    }

    // 设置控制按钮的状态
    private void setViewStatus(UserInfo userInfo) {
        if (userInfo == null) {
            return;
        }
        if (userInfo.getRole() == Role.LECTURER) {
            rightOperateView.setItemVisibility(RightOperate.MEMBER.getValue(), View.VISIBLE);
            leftOperateView.setItemVisibility(LeftOperate.BANED_SOUND.getValue(), View.VISIBLE);
            leftOperateView.setItemVisibility(LeftOperate.GONG_GE.getValue(), View.VISIBLE);
        }

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

    }

    private void setAudioScenrio(boolean isChecked, boolean deviceSync) {
        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());
        });
        if (isChecked) {
            ToastUtil.getInstance().show(getContext(), "音乐模式已开启");
        } else {
            ToastUtil.getInstance().show(getContext(), "音乐模式已关闭");
        }
        if (deviceSync && classViewModel != null) {
            classViewModel.deviceSyncMusicMode(roomId, isChecked);
        }
    }

    private IRCRTCStatusReportListener statusReportListener = new IRCRTCStatusReportListener() {
        @Override
        public void onAudioReceivedLevel(HashMap<String, String> hashMap) {
            super.onAudioReceivedLevel(hashMap);
        }

        @Override
        public void onAudioInputLevel(String s) {
            super.onAudioInputLevel(s);
        }

        @Override
        public void onConnectionStats(final StatusReport statusReport) {
            super.onConnectionStats(statusReport);
            unstableNetworkToast(statusReport);
        }
    };


    /**
     * 根据丢包率信息，提示弱网
     */
    private int lossRateSum = 0;
    private List<Integer> statusReportList = new ArrayList<>();

    private void unstableNetworkToast(StatusReport statusReport) {
        float averageLossRate = (float) lossRateSum / statusReportList.size();
        networkObserverTimer(averageLossRate);
        setNetworkSignalStrength(averageLossRate);
        for (Map.Entry<String, StatusBean> entry : statusReport.statusVideoSends.entrySet()) {
            int lossRate = (int) entry.getValue().packetLostRate;
            if (statusReportList.size() == 10) {
                lossRateSum -= statusReportList.remove(0);
            }

            lossRateSum += lossRate;
            statusReportList.add(lossRate);
        }
    }

    private Timer networkObserverTimer = null;
    private int timerPeriod = 5 * 1000;
    private boolean playSound = true;

    /**
     * 丟包>15%的情况下，会每 {@link }检查一下当前丢包率
     */
    private void networkObserverTimer(final float lossRate) {
        if (lossRate < 15) {
            if (networkObserverTimer != null) {
                networkObserverTimer.cancel();
                networkObserverTimer = null;
            }
        } else {
            if (classViewModel != null) {
                List<ClassMember> memberList = classViewModel.getMemberList().getValue();
                if (networkObserverTimer == null && memberList != null && memberList.size() > 1) {
                    networkObserverTimer = new Timer("NetWorkObserverTimer");
                    networkObserverTimer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            playTipsSound(lossRate);
                        }
                    }, 0, timerPeriod);
                }
            }
        }
    }

    private void playTipsSound(final float lossRate) {
        Activity activity = getActivity();
        if (null == activity) {
            return;
        }
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (lossRate >= 15) {
                    LogUtils.e("loss rate > 15, play Sound !");
                    //                    if (mSoundPool != null) {
                    //                        mSoundPool.release();
                    //                    }
                    if (playSound) {
                        playSound = false;
                        //                        mSoundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
                        //                        mSoundPool.load(ClassActivity.this, R.raw.voip_network_error_sound, 0);
                        //                        mSoundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
                        //                            @Override
                        //                            public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
                        //                                soundPool.play(sampleId, 1F, 1F, 0, 0, 1F);
                        //                            }
                        //                        });
                        Toast.makeText(activity.getApplicationContext(), "当前通话连接质量不佳", Toast.LENGTH_SHORT).show();
                        playSound = true;
                    }
                }
            }
        });
    }


    private void setNetworkSignalStrength(final float lossRate) {
        Activity activity = getActivity();
        if (null == activity) {
            return;
        }
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (lossRate >= 20) {
                    ivNetworkSignalStrength.setImageResource(R.drawable.ic_network_signal_strength1);
                } else if (lossRate >= 15) {
                    ivNetworkSignalStrength.setImageResource(R.drawable.ic_network_signal_strength2);
                } else if (lossRate >= 10) {
                    ivNetworkSignalStrength.setImageResource(R.drawable.ic_network_signal_strength3);
                } else if (lossRate >= 5) {
                    ivNetworkSignalStrength.setImageResource(R.drawable.ic_network_signal_strength4);
                }
            }
        });
    }


    public void speechIsShowHint(boolean isShow) {
        tvSpeechHint.setVisibility(isShow ? View.VISIBLE : View.GONE);
    }

    /**
     * 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 == userInfoValue.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);
                        }

                    }
                }
            }
        }
    }

    /**
     * 设置 Button 选择监听
     *
     * @param listener
     */
    public void setTopOperateControlCheckListener(TopOperateControlListener listener) {
        this.listener = listener;
    }

    /**
     * Button 选择监听
     */
    public interface TopOperateControlListener {

        /**
         * 聊天消息
         */
        void onMessageOrMember(RightOperate rightOperate);


        /**
         * 线路切换
         */
        void onRefresh(Intent intent);


        void GongGe();

        void complaint();

    }

}

