package com.ez.ertc.meeting.ui;


import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothA2dp;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothHeadset;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.res.Configuration;
import android.media.AudioManager;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.cardview.widget.CardView;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.bumptech.glide.Glide;
import com.ez.basertc.RTCConstant;
import com.ez.baselib.utils.LogUtil;
import com.ez.dclog.EZDcLogEventPresenter;
import com.ez.dclog.EZDcLogEventTypes;
import com.ez.dclog.params.event.ERTCEventVideoRotation;
import com.ez.ertc.meeting.ErtcEzmHelper;
import com.ez.ertc.meeting.R;
import com.ez.ertc.meeting.R2;
import com.ez.ertc.meeting.base.YsBaseActivity;
import com.ez.ertc.meeting.contract.ErtcRoomContract;
import com.ez.ertc.meeting.constant.MtNavigator;
import com.ez.ertc.meeting.event.MtAudioModeEvent;
import com.ez.ertc.meeting.event.MtCallStateEvent;
import com.ez.ertc.meeting.event.MtExitRoomEvent;
import com.ez.ertc.meeting.event.MtLanActionEvent;
import com.ez.ertc.meeting.event.MtSwitchMemberToastEvent;
import com.ez.ertc.meeting.event.MtSwitchStimulationEvent;
import com.ez.ertc.meeting.event.MtSwitchWaterMarkEvent;
import com.ez.ertc.meeting.event.MtToTestEvent;
import com.ez.ertc.meeting.event.MtToggleSelfAudioEvent;
import com.ez.ertc.meeting.presenter.ErtcRoomPresenter;
import com.ez.ertc.meeting.service.ErtcVideoMeetingService;
import com.ez.ertc.meeting.utils.AndroidUtil;
import com.ez.ertc.meeting.utils.ViewUtil;
import com.ez.ertc.meeting.utils.permission.PermissionHelper;
import com.ez.ertc.meeting.utils.permission.PermissionUtil;
import com.ez.ertc.meeting.widget.EZDialog;
import com.ez.ertc.meeting.widget.ErtcTextureView;
import com.ez.ertc.meeting.widget.LeaveDialog;
import com.ez.ertc.meeting.widget.MemberLeaveDialog;
import com.ez.ertc.meeting.widget.MtMoreDialog;
import com.ez.ertc.meeting.widget.MtShareDialog;
import com.ez.ertc.meeting.widget.TextCircleImageView;
import com.ez.ertcmeeting.utils.permission.PermissionDialog;
import com.gyf.immersionbar.BarHide;
import com.gyf.immersionbar.ImmersionBar;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author xiezuoyuan
 * @time 2019/9/17 19:44
 */
public class ErtcRoomActivity extends YsBaseActivity implements ErtcRoomContract.View {
    private static final int REQUEST_CODE_ALBUM = 1005;
    public static final int AUDIO_LEVEL_OFF = 10000;
    @BindView(R2.id.ivSoundState)
    AppCompatImageView ivSoundState;
    @BindView(R2.id.ivSwitchCamera)
    AppCompatImageView ivSwitchCamera;
    @BindView(R2.id.tvId)
    TextView tvId;
    @BindView(R2.id.tvFlow)
    TextView tvFlow;
    @BindView(R2.id.tvLeave)
    TextView tvLeave;
    @BindView(R2.id.viewTop)
    ConstraintLayout viewTop;
    @BindView(R2.id.tvCurrentName)
    TextView tvCurrentName;
    @BindView(R2.id.ivKpsLevel)
    AppCompatImageView ivKpsLevel;
    @BindView(R2.id.ivWindowAudioState)
    AppCompatImageView ivWindowAudioState;
    @BindView(R2.id.cvFloat)
    CardView cvFloat;
    @BindView(R2.id.clCallingNumber)
    CardView clCallingNumber;
    @BindView(R2.id.tvCallingNumber)
    TextView tvCallingNumber;
    @BindView(R2.id.ivMicroState)
    AppCompatImageView ivMicroState;
    @BindView(R2.id.tvMicroState)
    TextView tvMicroState;
    @BindView(R2.id.llMicro)
    LinearLayout llMicro;
    @BindView(R2.id.ivCameraState)
    AppCompatImageView ivCameraState;
    @BindView(R2.id.tvCameraState)
    TextView tvCameraState;
    @BindView(R2.id.llCamera)
    LinearLayout llCamera;
    @BindView(R2.id.ivShare)
    AppCompatImageView ivShare;
    @BindView(R2.id.tvShare)
    TextView tvShare;
    @BindView(R2.id.llShare)
    LinearLayout llShare;
    @BindView(R2.id.llPictureInPicture)
    LinearLayout llPictureInPicture;
    @BindView(R2.id.ivConfManage)
    AppCompatImageView ivConfManage;
    @BindView(R2.id.tvConfManage)
    TextView tvConfManage;
    @BindView(R2.id.llManage)
    LinearLayout llManage;
    @BindView(R2.id.viewBottom)
    LinearLayout viewBottom;
    @BindView(R2.id.flRoot)
    FrameLayout flRoot;
    @BindView(R2.id.vcsTextureView)
    ErtcTextureView vcsTextureView;
    @BindView(R2.id.ivShareDesktopCover)
    ImageView ivShareDesktopCover;
    @BindView(R2.id.llItemParent)
    LinearLayout llItemParent;
    @BindView(R2.id.clScreenVideoOff)
    LinearLayout clScreenVideoOff;
    @BindView(R2.id.ivScreenAvatar)
    TextCircleImageView ivScreenAvatar;
    @BindView(R2.id.tvScreenAccountStreamId)
    TextView tvScreenAccountStreamId;
    @BindView(R2.id.tvScreenName)
    TextView tvScreenName;
    @BindView(R2.id.ivScreenAudioState)
    AppCompatImageView ivScreenAudioState;
    @BindView(R2.id.ivScreenLevelState)
    AppCompatImageView ivScreenLevelState;
    @BindView(R2.id.ivScale)
    AppCompatImageView ivScale;
    @BindView(R2.id.viewPoint)
    View viewPoint;
    @BindView(R2.id.viewStatusBar)
    View viewStatusBar;
    @BindView(R2.id.llViewTop)
    LinearLayout llViewTop;
    @BindView(R2.id.llLeftFloat)
    View llLeftFloat;
    private int viewTopHeight;
    private ErtcRoomContract.GroupView mGroupView;
    private MtMoreDialog mtMoreDialog;
    private MtShareDialog mtShareDialog;
    private PermissionHelper permissionHelperCamera,permissionHelperMicrophone;
//    private PhoneReceiver phoneReceiver;
    private ErtcRoomContract.Presenter mPresenter;

    private LeaveDialog mHostDialog;
    private MemberLeaveDialog mMemberDialog;

    private RTCConstant.EnterParam localUserInfo = null;

    public static void start(Activity activity, RTCConstant.EnterParam localUserInfo, boolean isAudioOn, boolean isVideoOn) {
        Intent intent = new Intent(activity, ErtcRoomActivity.class);
        intent.putExtra(MtNavigator.Extras.EXTRA_ROOM_INFO, localUserInfo);
        intent.putExtra(MtNavigator.Extras.EXTRA_ROOM_AUDIO, isAudioOn);
        intent.putExtra(MtNavigator.Extras.EXTRA_ROOM_VIDEO, isVideoOn);
        activity.startActivity(intent);
    }

    @Override
    protected void preOnCreate() {
//        phoneReceiver = new PhoneReceiver();
        IntentFilter mIntentFilter=new IntentFilter();
        mIntentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        mIntentFilter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
        mIntentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        mIntentFilter.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED);
        mIntentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        mIntentFilter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
        mIntentFilter.addAction(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED);
        mIntentFilter.addAction(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED);
        mIntentFilter.addAction(BluetoothA2dp.ACTION_PLAYING_STATE_CHANGED);
        mIntentFilter.addAction(Intent.ACTION_HEADSET_PLUG);
        mIntentFilter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
        mIntentFilter.addAction(Intent.ACTION_NEW_OUTGOING_CALL);
//        registerReceiver(phoneReceiver,mIntentFilter);
    }

    @Override
    protected boolean registerEventBus() {
        return true;
    }

    @Override
    protected int provideLayoutId() {
        return R.layout.ertc_activity_room;
    }

    @SuppressLint("NewApi")
    @Override
    protected void initView() {
        ButterKnife.bind(this);

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        updateMemberCount(1);
        initBar();
        vcsTextureView.getVideoCanvasView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toggleCoverShow();
            }
        });
    }

    private void initBar(){
        ImmersionBar.with(this).init();
        int statusBarHeight = ImmersionBar.getStatusBarHeight(this);
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) viewStatusBar.getLayoutParams();
        layoutParams.height = statusBarHeight;
        viewTopHeight = statusBarHeight + ViewUtil.dp2px(this,64);
        FrameLayout.LayoutParams ll = (FrameLayout.LayoutParams) cvFloat.getLayoutParams();
        ll.topMargin = viewTopHeight + ViewUtil.dp2px(this,16);
        FrameLayout.LayoutParams llTalking = (FrameLayout.LayoutParams) llLeftFloat.getLayoutParams();
        llTalking.topMargin = viewTopHeight + ViewUtil.dp2px(this,20);
        updateScreenNameMaxLength();
    }

    private void updateScreenNameMaxLength(){
        //更新名字的最大宽度
        tvScreenName.setMaxWidth(AndroidUtil.getScreenWidth(this) - ViewUtil.dp2px(this,82));
    }

    @RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
    @Override
    protected void initData() {
        localUserInfo = (RTCConstant.EnterParam) getIntent().getSerializableExtra(MtNavigator.Extras.EXTRA_ROOM_INFO);
        new ErtcRoomPresenter(this,
                mGroupView = new ErtcRoomViewHolder(llItemParent));
        //拦截修改权限页面重启问题
        if (ErtcEzmHelper.ertcEngine == null) {
            LogUtil.d("EZRTCImpl", "initApi ErtcEzmHelper.ertcEngine == null");
            mPresenter.setErtcEngineIsNullLeaveState(true);
            mPresenter.onDestroy();
            return;
        }
        mGroupView.setPresenter(mPresenter);
        init();
    }

    private void init(){
        flRoot.post(new Runnable() {
            @SuppressLint("NewApi")
            @Override
            public void run() {
                mGroupView.init(getResources().getConfiguration(),vcsTextureView.getWidth(),vcsTextureView.getHeight());
                mPresenter.initApi(localUserInfo,
                        getIntent().getBooleanExtra(MtNavigator.Extras.EXTRA_ROOM_AUDIO,true),
                        getIntent().getBooleanExtra(MtNavigator.Extras.EXTRA_ROOM_VIDEO,true),
                        getIntent().getBooleanExtra(MtNavigator.Extras.EXTRA_ROOM_SOUND,true)
                );
            }
        });
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        connectToService();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        mPresenter.onNewIntent();
    }

    @Override
    public void onConfigurationChanged(final Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        updateScreenNameMaxLength();
        mPresenter.onConfigurationChanged(newConfig.orientation);
        mGroupView.onConfigurationChanged(newConfig.orientation);
        EZDcLogEventPresenter.getInstance().submitEvent(this, EZDcLogEventTypes.EVENT_VIDEO_ROTATION, 0L, null,
                ERTCEventVideoRotation.getInstance()
//                        .setRotationType()
                        .setAngle(newConfig.orientation));
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (permissionHelperCamera != null) {
            permissionHelperCamera.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
        if (permissionHelperMicrophone != null) {
            permissionHelperMicrophone.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    @SuppressLint("NewApi")
    @Override
    public void toggleCoverShow(){
        if (llViewTop.getTranslationY() == 0){
            animCoverHide();
        } else {
            animCoverShow();
        }
    }

    @SuppressLint("NewApi")
    @Override
    public void animCoverShow() {
        if (llViewTop.getTranslationY() == 0){
            return;
        }
        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                ImmersionBar.with(ErtcRoomActivity.this).reset().init();
            }
        });
        ObjectAnimator topAnimator = ObjectAnimator.ofFloat(llViewTop, "translationY", -viewTopHeight, 0);
        ObjectAnimator floatAnimator = ObjectAnimator.ofFloat(cvFloat, "translationY", -viewTopHeight, 0);
        ObjectAnimator scaleAnimator = ObjectAnimator.ofFloat(llLeftFloat, "translationY", -viewTopHeight, 0);
        ObjectAnimator bottomAnimator = ObjectAnimator.ofFloat(viewBottom, "translationY", viewBottom.getHeight(), 0);
        animatorSet.play(topAnimator).with(bottomAnimator).with(floatAnimator).with(scaleAnimator);
        animatorSet.setDuration(300);
        animatorSet.start();
    }

    @SuppressLint("NewApi")
    @Override
    public void animCoverHide() {
        mPresenter.cancelCoverHandler();
        if (llViewTop.getTranslationY() < 0){
            return;
        }
        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                ImmersionBar.with(ErtcRoomActivity.this).reset().hideBar(BarHide.FLAG_HIDE_STATUS_BAR).init();
                //如果别人发起了共享之类的操作，需要关闭PopupWindow，否则可能错位
                if (mtMoreDialog != null && mtMoreDialog.isShowing()){
                    mtMoreDialog.dismiss();
                }
                if (mtShareDialog != null && mtShareDialog.isShowing()){
                    mtShareDialog.dismiss();
                }
            }
        });
        ObjectAnimator topAnimator = ObjectAnimator.ofFloat(llViewTop, "translationY", 0, -viewTopHeight);
        ObjectAnimator floatAnimator = ObjectAnimator.ofFloat(cvFloat, "translationY", 0, -viewTopHeight);
        ObjectAnimator scaleAnimator = ObjectAnimator.ofFloat(llLeftFloat, "translationY", 0, -viewTopHeight);
        ObjectAnimator bottomAnimator = ObjectAnimator.ofFloat(viewBottom, "translationY", 0, viewBottom.getHeight());
        animatorSet.play(topAnimator).with(bottomAnimator).with(floatAnimator).with(scaleAnimator);
        animatorSet.setDuration(300);
        animatorSet.start();
    }

    @Override
    public void onFlow(String txt) {
        tvFlow.setText(txt);
    }

    @Override
    public void setRoomId(String id) {
        tvId.setText(id);
    }

    @Override
    public void setScreenAccountStreamId(String userId, boolean visibility) {
        if(visibility){
            tvScreenAccountStreamId.setVisibility(View.VISIBLE);
            tvScreenAccountStreamId.setText(userId);
        } else {
            tvScreenAccountStreamId.setVisibility(View.GONE);
        }
    }

    @Override
    public void setMicroState(boolean on) {
        if (on) {
            ivMicroState.getDrawable().setLevel(0);
            tvMicroState.setText(R.string.ys_mt_room_mem_manage_audio_close);
        } else {
            ivMicroState.getDrawable().setLevel(AUDIO_LEVEL_OFF);
            tvMicroState.setText(R.string.ys_mt_room_mem_manage_audio_open);
        }
    }

    @Override
    public void setCameraState(boolean on) {
        if (on) {
            ivSwitchCamera.setVisibility(View.VISIBLE);
            ivCameraState.setImageResource(R.drawable.ys_mt_svg_video_on_33_30dp);
            tvCameraState.setText(R.string.ys_mt_room_mem_manage_video_close);
        } else {
            ivSwitchCamera.setVisibility(View.GONE);
            ivCameraState.setImageResource(R.drawable.ys_mt_svg_video_off_33_30dp);
            tvCameraState.setText(R.string.ys_mt_room_mem_manage_video_open);
        }
    }

    @Override
    public void setSoundState(boolean on) {
        if (on) {
            ivSoundState.setImageResource(R.drawable.ys_mt_svg_sound_on_24dp);
            showToast(R.string.ys_mt_room_toast_sound_on);
        } else {
            ivSoundState.setImageResource(R.drawable.ys_mt_svg_sound_off_24dp);
            showToast(R.string.ys_mt_room_toast_sound_off);
        }
    }

    @Override
    public void setShareState(boolean on,boolean disable) {
        if (on){
            ivShare.setImageResource(disable ? R.drawable.ys_mt_svg_share_on_disable_22_21dp : R.drawable.ys_mt_svg_share_on_22_21dp);
            tvShare.setText(R.string.ys_mt_imm_btn_share_on);
            //恢复画中画可点击
            if (mtMoreDialog != null && mtMoreDialog.isShowing()){
                mtMoreDialog.enableClick();
            }
        } else {
            ivShare.setImageResource(R.drawable.ys_mt_svg_share_off_23_21dp);
            tvShare.setText(R.string.ys_mt_imm_btn_share_off);
        }
    }

    @Override
    public void setSelfAudioLevel(int level) {
        ivMicroState.getDrawable().setLevel(level);
    }

    @Override
    public void setScreenAudioLevel(int level) {
        ivScreenAudioState.getDrawable().setLevel(level);
        ivWindowAudioState.getDrawable().setLevel(level);
    }

    @Override
    public void showHostLeaveDialog() {
        if (mHostDialog == null){
            mHostDialog = new LeaveDialog(this, new LeaveDialog.OnLeaveListener() {
                @Override
                public void onEnd() {
                    new EZDialog.Builder(ErtcRoomActivity.this)
                            .setTitle(R.string.ys_mt_room_dialog_end_meeting)
                            .setMessage(R.string.ys_mt_room_dialog_end_meeting_msg)
                            .setPositiveButton(R.string.ezm_confirm, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    mPresenter.endMeeting();
                                }
                            })
                            .setNegativeButton(R.string.ezm_cancel,null)
                            .show();
                }

                @Override
                public void onLeave() {
                    mPresenter.release("showHostLeaveDialog===onLeave");
                }
            });
        }
        mHostDialog.show();
    }

    @Override
    public void showMemberLeaveDialog() {
        if (mMemberDialog == null){
            mMemberDialog = new MemberLeaveDialog(this, new MemberLeaveDialog.OnLeaveListener() {
                @Override
                public void onLeave() {
                    mPresenter.release("showMemberLeaveDialog===onLeave");
                }
            });
        }
        mMemberDialog.show();
    }

    @Override
    public void setCallingNumber(int number) {
        if (number > 0){
            clCallingNumber.setVisibility(View.VISIBLE);
            tvCallingNumber.setText(String.format(getResources().getString(R.string.ys_mt_room_calling_number_format),number));
        } else {
            clCallingNumber.setVisibility(View.GONE);
        }
    }

    @Override
    public void disableManageButton() {
        llManage.setEnabled(false);
        ivConfManage.setEnabled(false);
        tvConfManage.setEnabled(false);
    }

    @Override
    public ErtcTextureView getScreenTextureView() {
        return vcsTextureView;
    }

    @Override
    public void showShareDesktopCover(boolean show) {
        ivShareDesktopCover.setVisibility(show ? View.VISIBLE : View.GONE);
    }

    @Override
    public ImageView getShareDesktopCover() {
        return ivShareDesktopCover;
    }

    @Override
    public void showFlowView(boolean show) {
        if (show){
            cvFloat.setVisibility(View.VISIBLE);
        } else if (!show){
            cvFloat.setVisibility(View.GONE);
        }
    }

    @Override
    public void updateFlowViewName(String name) {
        tvCurrentName.setText(name);
    }

    @Override
    public void updateFlowViewAudio(boolean on) {
        ivWindowAudioState.getDrawable().setLevel(on ? 0 : AUDIO_LEVEL_OFF);
    }

    @Override
    public void updateFlowViewLevel(final int level) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ivKpsLevel.getDrawable().setLevel(Math.max(level, 0));
            }
        });
    }

    @Override
    public void updateMemberCount(int count) {
        tvConfManage.setText(String.format(getString(R.string.ys_mt_imm_btn_manage_format),count));
    }

    @Override
    public void updateScreenAccountView(String avatar, String userId, boolean isAudioOn) {
        tvScreenName.setText(userId);
        ivScreenAvatar.setImageDrawable(null);
        ivScreenAvatar.setText(userId);
        if (!TextUtils.isEmpty(avatar)  && !mPresenter.isDestroy()){
            Glide.with(this)
                    .load(avatar)
                    .into(ivScreenAvatar);
        }
        ivScreenAudioState.getDrawable().setLevel(isAudioOn ? 0 : AUDIO_LEVEL_OFF);
    }

    @Override
    public void updateScreenKpsLevel(final int level) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ivScreenLevelState.getDrawable().setLevel(level);
            }
        });
    }

    @Override
    public void hideScreenAccountVideo() {
        vcsTextureView.cleanLastFrame();
        vcsTextureView.setVisibility(View.INVISIBLE);
        clScreenVideoOff.setVisibility(View.VISIBLE);
    }

    @Override
    public void showScreenAccountVideo() {
        LogUtil.d("EZRTCImpl", "self bindView showScreenAccountVideo");
        vcsTextureView.setVisibility(View.VISIBLE);
        clScreenVideoOff.setVisibility(View.GONE);
    }

    @Override
    public void showMsgBubble() {
        viewPoint.setVisibility(View.VISIBLE);
    }

    @Override
    public void hideMsgBubble() {
        viewPoint.setVisibility(View.GONE);
    }

    @Override
    public void startSharePhoto(final String address, final int port, final String roomId, final String userId, final boolean canWrite, String photo) {
        showToast("暂未实现");
    }


    @Override
    public void startShareBoard(String address,int port,String roomId,String userId,boolean canWrite) {
        showToast("暂未实现");
    }

    @Override
    public void showDesktopPInPButton(boolean show) {
        ivScale.setVisibility( show ? View.VISIBLE : View.GONE);
    }

    @SuppressLint("NewApi")
    @OnClick({R2.id.ivSoundState, R2.id.ivSwitchCamera, R2.id.tvLeave, R2.id.llMicro, R2.id.llCamera,
            R2.id.llShare, R2.id.llManage,R2.id.vcsTextureView,R2.id.clScreenVideoOff,R2.id.viewBottom,
            R2.id.llPictureInPicture,R2.id.ivScale,R2.id.clCallingNumber,R2.id.tvId,R2.id.ivShareDesktopCover})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.vcsTextureView || id == R.id.clScreenVideoOff || id == R.id.ivShareDesktopCover){
            LogUtil.d("EZRTCImpl", "self bindView vcsTextureView click toggleCoverShow");
            toggleCoverShow();
        } else if (id == R.id.tvLeave) {
            mPresenter.onLeave();
        } else if (id == R.id.llMicro) {
            mPresenter.toggleMicro();
        } else if (id == R.id.llCamera) {
            ivCameraState.setEnabled(false);
            mPresenter.toggleCamera();
            ivCameraState.setEnabled(true);
        } else if (id == R.id.ivSoundState) {
            mPresenter.toggleSound();
        } else if (id == R.id.llManage) {
            mPresenter.toMemberManage();
        } else if (id == R.id.ivSwitchCamera) {
            mPresenter.switchCamera();
        } else if (id == R.id.llShare){
            if (!mPresenter.closeShare()) {
                showShareWindow(llShare);
            }
        } else if (id == R.id.viewBottom){

        } else if (id == R.id.llPictureInPicture){
            mPresenter.cancelCoverHandler();
            showMoreWindow();
        } else if (id == R.id.ivScale){
            if (PermissionUtil.getInstance().isGrandFloating(ErtcRoomActivity.this)) {
                mPresenter.startDesktopPInP();
            } else {
                PermissionUtil.getInstance().setPermissionFloat(ErtcRoomActivity.this, new PermissionUtil.PermissionCallBack() {
                    @Override
                    public void onResult(boolean success) {
                        //成功授权
                        if (success) {
                            mPresenter.startDesktopPInP();
                        }
                    }
                });
            }
        } else if (id == R.id.clCallingNumber){
            mPresenter.toMemberManageCalling();
        } else if (id == R.id.tvId){
            mPresenter.showMonitor();
        }
    }

    @Override
    public void requestToggleCameraPermission() {
        if (permissionHelperCamera == null){
            permissionHelperCamera = new PermissionHelper(this,
                    new String[]{Manifest.permission.CAMERA}, 301);
        }
        permissionHelperCamera.requestCamera(new PermissionHelper.PermissionCallback() {
            @Override
            public void onPermissionGranted() {
                mPresenter.toggleCamera();
            }

            @Override
            public void onPermissionDenied() {
                PermissionDialog.Companion.requestCameraSets(ErtcRoomActivity.this);
            }
        });
    }

    @Override
    public void requestToggleMicrophonePermission() {
        if (permissionHelperMicrophone == null){
            permissionHelperMicrophone = new PermissionHelper(this,
                    new String[]{Manifest.permission.RECORD_AUDIO}, 302);
        }
        permissionHelperMicrophone.requestMicrophone(new PermissionHelper.PermissionCallback() {
            @Override
            public void onPermissionGranted() {
                mPresenter.toggleMicro();
            }

            @Override
            public void onPermissionDenied() {
                PermissionDialog.Companion.requestMicrophoneSets(ErtcRoomActivity.this);
            }
        });
    }

    @SuppressLint("NewApi")
    private void showShareWindow(View parent) {
        if (mtShareDialog == null){
            mtShareDialog = new MtShareDialog(this, new MtShareDialog.OnClickListener() {
                @Override
                public void onScreen() {
                    if (PermissionUtil.getInstance().isGrandFloating(ErtcRoomActivity.this)) {
                        mPresenter.startRecord();
                    } else {
                        PermissionUtil.getInstance().setPermissionFloat(ErtcRoomActivity.this, new PermissionUtil.PermissionCallBack() {
                            @Override
                            public void onResult(boolean success) {
                                //成功授权
                                if (success) {
                                    mPresenter.startRecord();
                                }
                            }
                        });
                    }
                }

                @Override
                public void onImage() {
                    mPresenter.toAlbumProxy();
                }

                @Override
                public void onWhiteboard() {
                    mPresenter.openWhiteBoard();
                }
            });
        }
        mtShareDialog.show();
    }

    @SuppressLint("NewApi")
    private void showMoreWindow(){
        if (mtMoreDialog == null){
            mtMoreDialog = new MtMoreDialog(this, new MtMoreDialog.OnClickListener() {
                @Override
                public void onPip() {
                    mPresenter.setPInP(!mPresenter.isPInP());
                    if (mPresenter.isPInP()){
                        mGroupView.showGroupView();
                        mtMoreDialog.setPipOn();
                    } else {
                        mGroupView.hideGroupView();
                        mtMoreDialog.setPipOff();
                    }
                }

                @Override
                public void onBeauty() {
                    if (permissionHelperCamera == null){
                        permissionHelperCamera = new PermissionHelper(ErtcRoomActivity.this,
                                new String[]{Manifest.permission.CAMERA}, 301);
                    }
                    permissionHelperCamera.requestCamera(new PermissionHelper.PermissionCallback() {
                        @Override
                        public void onPermissionGranted() {
                            mPresenter.toBeautyConfig();
                        }
                        @Override
                        public void onPermissionDenied() {
                            PermissionDialog.Companion.requestCameraSets(ErtcRoomActivity.this);
                        }
                    });
                }

                @Override
                public void onMore() {
                    mPresenter.toMeetingSets();
                }
            });
        }
        mtMoreDialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                if (mPresenter.isPInP()){
                    mtMoreDialog.setPipOff();
                } else {
                    mtMoreDialog.setPipOn();
                }
                if (mPresenter.isSharing()){
                    mtMoreDialog.disableClick();
                } else {
                    mtMoreDialog.enableClick();
                }
            }
        });
        mtMoreDialog.show();
    }

    @Override
    public void setPresenter(ErtcRoomContract.Presenter presenter) {
        mPresenter = presenter;
    }

    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    public void setLeaveTxt(int resId) {
        tvLeave.setText(resId);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MtExitRoomEvent event) {
        mPresenter.onMessageEvent(event);
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MtSwitchStimulationEvent event) {
        mPresenter.onMessageEvent(event);
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MtSwitchMemberToastEvent event) {
        mPresenter.onMessageEvent(event);
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MtSwitchWaterMarkEvent event) {
        mPresenter.onMessageEvent(event);
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MtToggleSelfAudioEvent event) {
        mPresenter.onMessageEvent(event);
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MtAudioModeEvent event) {
        mPresenter.onMessageEvent(event);
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MtToTestEvent event) {
        mPresenter.onMessageEvent(event);
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MtCallStateEvent event) {
        mPresenter.onMessageEvent(event);
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MtLanActionEvent event) {
        mPresenter.onMessageEvent(event);
    }

    @Override
    public void onBackPressed() {
        mPresenter.onLeave();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mPresenter.onStop();
    }
    @Override
    protected void onRestart() {
        super.onRestart();
        mPresenter.onRestart();
    }
    @Override
    protected void onPause() {
        super.onPause();
        mPresenter.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mPresenter.onResume();
    }

    @SuppressLint("NewApi")
    @Override
    protected void onDestroy() {
//        unregisterReceiver(phoneReceiver);
        if (mtShareDialog != null && mtShareDialog.isShowing()) {
            mtShareDialog.dismiss();
        }
        mPresenter.stopShareService();
        unbindService();
        mPresenter.onDestroy();
        super.onDestroy();
    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ErtcRoomPresenter.REQUEST_MEDIA_PROJECTION && resultCode == RESULT_OK) {
            LogUtil.d("EZRTCImpl", "录屏成功，开始共享");
            Intent service = new Intent(this, ErtcVideoMeetingService.class);
            service.putExtra(
                    ErtcVideoMeetingService.SCREEN_PARAM_TYPE,
                    ErtcVideoMeetingService.SCREEN_RECORDER_CREATE
            );
            service.putExtra(ErtcVideoMeetingService.SCREEN_PARAM_CODE, resultCode);
            service.putExtra(ErtcVideoMeetingService.SCREEN_PARAM_REQUEST, requestCode);
            service.putExtra(ErtcVideoMeetingService.SCREEN_PARAM_DATA, data);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                if(Settings.canDrawOverlays(ErtcRoomActivity.this)) {
                    startForegroundService(service);
                }
            } else {
                startService(service);
            }
            mPresenter.createScreenRecorder(requestCode, resultCode, data);
        }
    }


    //service
    private boolean isRecovery = false;
    private ServiceConnection mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    private void connectToService() {
        isRecovery = getIntent().getBooleanExtra(ErtcVideoMeetingService.LAUNCH_FROM_NOTIFICATION, false);
        Intent service = new Intent(this, ErtcVideoMeetingService.class);
        if (!isRecovery) {
            service.putExtra(
                    ErtcVideoMeetingService.SCREEN_PARAM_TYPE,
                    ErtcVideoMeetingService.CONFLUENCE_INIT
            );
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startForegroundService(service);
            } else {
                startService(service);
            }
        }

        bindService(service, mServiceConnection, 0);
    }
    private void unbindService(){
        unbindService(mServiceConnection);
    }
}
