package com.daya.live_teaching.ui.fragmnet;


import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.cooleshow.base.constanst.Constants;
import com.cooleshow.base.ui.fragment.BaseFragment;
import com.cooleshow.base.utils.FileUtils;
import com.cooleshow.base.utils.LogUtils;
import com.cooleshow.base.utils.PermissionUtils;
import com.cooleshow.base.utils.SPUtils;
import com.cooleshow.base.utils.SizeUtils;
import com.cooleshow.base.utils.ToastUtil;
import com.cooleshow.base.widgets.dialog.CommonDialog;
import com.cooleshow.usercenter.helper.UserHelper;
import com.daya.live_teaching.R;
import com.daya.live_teaching.api.WhiteBoardApi;
import com.daya.live_teaching.databinding.FragmentWhiteBoardBinding;
import com.daya.live_teaching.model.InsertImageBean;
import com.daya.live_teaching.model.Role;
import com.daya.live_teaching.model.UserInfo;
import com.daya.live_teaching.model.WhiteBoard;
import com.daya.live_teaching.model.WhiteCreateBean;
import com.daya.live_teaching.model.WhiteSdkRoomInfo;
import com.daya.live_teaching.utils.GlideEngine;
import com.daya.live_teaching.viewmodel.ClassViewModel;
import com.daya.live_teaching.widget.MyWhiteBoardView;
import com.herewhite.sdk.AbstractRoomCallbacks;
import com.herewhite.sdk.Room;
import com.herewhite.sdk.RoomParams;
import com.herewhite.sdk.WhiteSdk;
import com.herewhite.sdk.WhiteSdkConfiguration;
import com.herewhite.sdk.domain.Appliance;
import com.herewhite.sdk.domain.CameraConfig;
import com.herewhite.sdk.domain.ImageInformationWithUrl;
import com.herewhite.sdk.domain.MemberState;
import com.herewhite.sdk.domain.Promise;
import com.herewhite.sdk.domain.RoomPhase;
import com.herewhite.sdk.domain.RoomState;
import com.herewhite.sdk.domain.SDKError;
import com.herewhite.sdk.domain.Scene;
import com.herewhite.sdk.domain.SceneState;
import com.herewhite.sdk.domain.ViewMode;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.tbruyelle.rxpermissions3.RxPermissions;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.app.Activity.RESULT_OK;

/**
 * A simple {@link Fragment} subclass.
 */
public class WhiteBoardFragment extends BaseFragment<FragmentWhiteBoardBinding> implements View.OnClickListener {

    private onWhiteBoardListener listener;

    Button btnPencil;
    Button btnEraser;
    Button btnEllipse;
    Button btnCleanScene;
    Button btnRemoveScenes;
    Button btnCreateScenes;
    Button btnInsertImage;
    Button btnInsertPractice;
    LinearLayout llToolButton;
    MyWhiteBoardView mWebView;
    RelativeLayout classShareRootView;

    private HashMap<String, Button> appliances;
    private HashMap<String, Button> appliancesEnable;
    private WhiteSdk whiteSdk;
    public Room room;
    private ClassViewModel classViewModel;
    private String roomId;
    private int[] sdkColor = new int[]{236, 52, 85};

    private final int QU_LIBRAY_REQUEST_CODE = 1000;
    private List<WhiteBoard> reverseList;
    private Promise promise;
    private AbstractRoomCallbacks abstractRoomCallbacks;
    public UserInfo userInfo;
    //    private       WhiteBoardListAdapter   adapter;
    WhiteSdkRoomInfo whiteSdkRoomInfo = null;
    private RoomParams roomParams;

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


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

    @Override
    protected void initView(View rootView) {

        btnPencil = mViewBinding.btnPencil;
        btnEraser = mViewBinding.btnEraser;
        btnEllipse = mViewBinding.btnEllipse;
        btnCleanScene = mViewBinding.btnCleanScene;
        btnRemoveScenes = mViewBinding.btnRemoveScenes;
        btnCreateScenes = mViewBinding.btnCreateScenes;
        btnInsertImage = mViewBinding.btnInsertImage;
        btnInsertPractice = mViewBinding.btnInsertPractice;
        llToolButton = mViewBinding.llToolButton;
        mWebView = mViewBinding.classWhiteboardDisplay;
        classShareRootView = mViewBinding.classShareRootView;

        llToolButton.setVisibility(View.GONE);

        btnPencil.setOnClickListener(this);
        btnEraser.setOnClickListener(this);
        btnEllipse.setOnClickListener(this);
        btnCleanScene.setOnClickListener(this);
        btnRemoveScenes.setOnClickListener(this);
        btnCreateScenes.setOnClickListener(this);
        btnInsertImage.setOnClickListener(this);
        btnInsertPractice.setOnClickListener(this);

        appliances = new HashMap<String, Button>() {{
            this.put("pencil", btnPencil);
            this.put("eraser", btnEraser);
            this.put("ellipse", btnEllipse);
        }};
        appliancesEnable = new HashMap<String, Button>() {{
            this.put("pencil", btnPencil);
            this.put("eraser", btnEraser);
            this.put("ellipse", btnEllipse);
            this.put("btnCleanScene", btnCleanScene);
            this.put("btnRemoveScenes", btnRemoveScenes);
            this.put("btnCreateScenes", btnCreateScenes);
            this.put("btnInsertImage", btnInsertImage);
            this.put("btnInsertImage", btnInsertPractice);
        }};

        for (Map.Entry<String, Button> e : this.appliancesEnable.entrySet()) {
            Button button = e.getValue();
            button.setEnabled(false);
            this.setColorWithButton(button, 0xFF000000);
        }
        for (Map.Entry<String, Button> e : this.appliances.entrySet()) {
            Button button = e.getValue();
            this.setColorWithButton(button, colorGray);
        }

        mWebView.setWhiteBoardClickListener(new MyWhiteBoardView.onWhiteBoardClickListener() {
            @Override
            public void onClick() {
                if (listener != null) {
                    listener.onClick();
                }
            }
        });
    }

    @Override
    protected void initData() {
        classViewModel = ViewModelProviders.of(getActivity()).get(ClassViewModel.class);
        classViewModel.getUploadFileUrl().observe(this, new Observer<InsertImageBean>() {
            @Override
            public void onChanged(InsertImageBean s) {
                try {
                    ImageInformationWithUrl imageUrl = new ImageInformationWithUrl(0d, 0d, s.getImageWidt(), s.getImageHidtht(), s.getFileUrl());
                    room.insertImage(imageUrl);
                    WindowManager manager = getActivity().getWindowManager();
                    DisplayMetrics outMetrics = new DisplayMetrics();
                    manager.getDefaultDisplay().getMetrics(outMetrics);
                    int displayHeigth = outMetrics.heightPixels;
                    int imageHeight = (int) SizeUtils.px2dp((displayHeigth - SizeUtils.dp2px(90)));
                    double scale = imageHeight / Double.valueOf(s.getImageHidtht());

                    if (scale >= 1) {
                        scale = 1;
                    }
                    moveCamera(scale);
                } catch (Exception e) {

                }
            }
        });

        // 房间 id
        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) {
                WhiteBoardFragment.this.userInfo = userInfo;
                if (llToolButton != null && userInfo.getRole() == Role.LECTURER && llToolButton.getVisibility() != View.VISIBLE) {
                    llToolButton.setVisibility(View.VISIBLE);
                }
            }
        });
        // 设置点击事件拦截
        whiteSdk = new WhiteSdk(mWebView, getContext(), new WhiteSdkConfiguration("614/YXPRtKkVCBOBjQ"));
        initWhiteSdkRoomInfoMode();
    }

    private void initWhiteSdkRoomInfoMode() {
        if (TextUtils.isEmpty(roomId)) {
            roomId = classViewModel.getRoomId().getValue();
        }
        whiteSdkRoomInfo = null;
        classViewModel.createWhiteBoard(roomId).observe(this, new Observer<WhiteCreateBean>() {


            @Override
            public void onChanged(WhiteCreateBean whiteCreateBean) {
                if (whiteSdkRoomInfo != null) {
                    return;
                }
                whiteSdkRoomInfo = new WhiteSdkRoomInfo();
                whiteSdkRoomInfo.setUuid(whiteCreateBean.getUuid());
                whiteSdkRoomInfo.setRoomToken(whiteCreateBean.getRoomToken());
                showLoading();
                roomParams = new RoomParams(whiteSdkRoomInfo.getUuid(), whiteSdkRoomInfo.getRoomToken(), UserHelper.getUserId());
                UserInfo userInfo = classViewModel.getUserInfo().getValue();
                if (userInfo != null && userInfo.getRole() == Role.STUDENT) {
                    roomParams.setWritable(false);
                }
                roomParams.setDisableEraseImage(true);
                abstractRoomCallbacks = new AbstractRoomCallbacks() {
                    @Override
                    public void onPhaseChanged(RoomPhase phase) {
                        super.onPhaseChanged(phase);
                        hideLoading();
                        if (phase == RoomPhase.disconnected && room != null && !room.getDisconnectedBySelf()) {
                            if (whiteSdk != null) {
                                whiteSdk.joinRoom(roomParams, abstractRoomCallbacks, promise);
                            }
                            //                            ToastUtil.getInstance().show(getActivity(), "白板服务连接断开");
                        } else if (phase == RoomPhase.reconnecting) {
                            //                            ToastUtil.getInstance().show(getActivity(), "白板服务连接断开，重新建立连接");
                        } else if (phase == RoomPhase.connected) {
                            //                            ToastUtil.getInstance().show(getActivity(), "白板服务连接成功");
                        }
                    }

                    @Override
                    public void onRoomStateChanged(RoomState modifyState) {
                        MemberState memberState = modifyState.getMemberState();
                        if (memberState != null) {
                            final String applianceName = memberState.getCurrentApplianceName();
                            setState(applianceName, sdkColor);
                        }

                    }
                };
                promise = new Promise<Room>() {

                    @Override
                    public void then(Room room) {

                        UserInfo userInfo = classViewModel.getUserInfo().getValue();
                        if (userInfo != null && userInfo.getRole() == Role.LECTURER) {
                            room.setViewMode(ViewMode.Broadcaster);
                            classViewModel.setWhiteSdkRoom(room);
                            WhiteBoardFragment.this.room = room;
                            double zoomScale = classViewModel.getZoomScale();
                            if (zoomScale != 0) {
                                moveCamera(zoomScale);
                            }
                            MemberState memberState = room.getMemberState();
                            for (Map.Entry<String, Button> e : appliancesEnable.entrySet()) {
                                Button button = e.getValue();
                                button.setEnabled(true);
                                setColorWithButton(button, colorGray);
                            }
                            if (memberState != null) {
                                memberState.setStrokeColor(sdkColor);
                                memberState.setCurrentApplianceName(Appliance.PENCIL);
                                room.setMemberState(memberState);

                                final String applianceName = memberState.getCurrentApplianceName();
                                final int[] sdkColor = memberState.getStrokeColor();
                                setState(applianceName, sdkColor);
                            }

                            room.getSceneState(new Promise<SceneState>() {
                                @Override
                                public void then(SceneState sceneState) {
                                    if (sceneState != null) {
                                        if (sceneState.getScenePath().equals(WhiteBoardApi.WHITE_BOARD_INIT_SCENE_PATH)) {
                                            classViewModel.createOneWhiteBoard();
                                            additionSetStaff();
                                        } else {
                                            if (!TextUtils.isEmpty(showWhiteUlr) && !sceneState.getScenePath().contains(showWhiteUlr)) {
                                                room.setScenePath(WhiteBoardApi.WHITE_BOARD_SCENE_PATH + "/" + showWhiteUlr);
                                                showWhiteUlr = null;
                                            }
                                        }
                                    }
                                }

                                @Override
                                public void catchEx(SDKError sdkError) {
                                    LogUtils.e("here white joinRoom and then getSceneState error = " + sdkError.getMessage());
                                }
                            });
                            if (userInfo.getRole() == Role.LECTURER) {
                                updateWhiteBoardList();
                            }
                        } else {
                            room.setViewMode(ViewMode.Follower);
                            room.disableDeviceInputs(true);// 禁止教具操作
                            room.disableOperations(true);// 禁止用户教具操作
                            room.disableCameraTransform(true);//禁止用户视角变化
                            room.setWritable(false, null);
                        }

                    }

                    @Override
                    public void catchEx(SDKError sdkError) {
                        if (whiteSdk != null) {
                            whiteSdk.releaseRoom();
                            ToastUtil.getInstance().show(getActivity(), "白板连接失败");
                        }
                    }
                };
                whiteSdk.joinRoom(roomParams, abstractRoomCallbacks, promise);
            }
        });
    }

    private void updateWhiteBoardList() {
        room.getScenes(new Promise<Scene[]>() {
            @Override
            public void then(Scene[] scenes) {
                reverseList = new ArrayList<>();
                reverseList.clear();
                for (int i = 0; i < scenes.length; i++) {
                    WhiteBoard whiteBoard = new WhiteBoard();
                    whiteBoard.setName("白板");
                    whiteBoard.setWhiteboardId(scenes[i].getName());
                    reverseList.add(whiteBoard);
                }
                if (listener != null) {
                    listener.onWhiteBoardList(reverseList);
                }
            }

            @Override
            public void catchEx(SDKError sdkError) {

            }
        });
    }

    private String showWhiteUlr;
    int staffRes = 0;

    public void loadWhiteBoard(String showWhiteUlr) {
        LogUtils.i("loadWhiteBoard === " + showWhiteUlr);
        this.showWhiteUlr = showWhiteUlr;
        if (null != room) {
            room.setScenePath(WhiteBoardApi.WHITE_BOARD_SCENE_PATH + "/" + showWhiteUlr);
        }
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.btnPencil) {
            onClickApplianceButton("pencil");
        } else if (id == R.id.btnEraser) {
            onClickApplianceButton("eraser");
        } else if (id == R.id.btnEllipse) {
            onClickApplianceButton("ellipse");
        } else if (id == R.id.btn_clean_scene) {
            cleanScenen();
        } else if (id == R.id.btn_remove_scenes) {
            removeScenes();
        } else if (id == R.id.btn_create_scenes) {
            if (null == room) {
                ToastUtil.getInstance().show(getActivity(), "白板功能初始化中，请稍后");
                return;
            }
            String PAGE = String.valueOf(System.currentTimeMillis());
            if (room != null) {
                room.putScenes(WhiteBoardApi.WHITE_BOARD_SCENE_PATH, new Scene[]{
                        new Scene(PAGE)}, reverseList == null ? 0 : reverseList.size());
                updateWhiteBoardList();
                loadWhiteBoard(PAGE);
                additionSetStaff();
            }
        } else if (id == R.id.btn_insert_image) {
            insertImage();

        } else if (id == R.id.btn_insert_practice) {
            if (null == room) {
                return;
            }
            //
//            Postcard postcard = ARouter.getInstance()
//                    .build(ARouterConstace.ACTIVITY_QU_LIBRAY)
//                    .withString("subjectId", SharedPreferenceUtil.read(Constants.SUBJECTID, ""));
//            LogisticsCenter.completion(postcard);
//            Intent intent = new Intent(getActivity(), postcard.getDestination());
//            intent.putExtras(postcard.getExtras());
//            startActivityForResult(intent, QU_LIBRAY_REQUEST_CODE);
        }

    }

    private void additionSetStaff() {
        Dialog dialog = new Dialog(getContext(), com.cooleshow.base.R.style.DialogStyle);
        View contentView = getLayoutInflater().inflate(R.layout.live_white_board_staff_pop, null);
        staffRes = R.drawable.img_staff_high;
        TextView btnCancel = contentView.findViewById(R.id.btn_cancel);
        TextView btnCommit = contentView.findViewById(R.id.btn_commit);
        ImageView iv_close = contentView.findViewById(R.id.iv_close);
        ImageView iv_live_white_board_staff_pop_high = contentView.findViewById(R.id.iv_live_white_board_staff_pop_high);
        ImageView iv_live_white_board_staff_pop_low = contentView.findViewById(R.id.iv_live_white_board_staff_pop_low);
        LinearLayout cll_live_white_board_staff_pop_high = contentView.findViewById(R.id.cll_live_white_board_staff_pop_high);
        LinearLayout cll_live_white_board_staff_pop_low = contentView.findViewById(R.id.cll_live_white_board_staff_pop_low);
        iv_live_white_board_staff_pop_high.setOnClickListener(view -> {
            iv_live_white_board_staff_pop_high.setImageResource(R.drawable.ic_staff_high_selected);
            cll_live_white_board_staff_pop_high.setBackgroundResource(R.drawable.bg_white_board_selected);
            iv_live_white_board_staff_pop_low.setImageResource(R.drawable.ic_staff_low_unselect);
            cll_live_white_board_staff_pop_low.setBackgroundResource(R.drawable.bg_white_board_unselect);
            staffRes = R.drawable.img_staff_high;
        });
        iv_live_white_board_staff_pop_low.setOnClickListener(view -> {
            iv_live_white_board_staff_pop_high.setImageResource(R.drawable.ic_staff_high_unselect);
            cll_live_white_board_staff_pop_high.setBackgroundResource(R.drawable.bg_white_board_unselect);
            iv_live_white_board_staff_pop_low.setImageResource(R.drawable.ic_staff_low_selected);
            cll_live_white_board_staff_pop_low.setBackgroundResource(R.drawable.bg_white_board_selected);
            staffRes = R.drawable.img_staff_low;
        });
        btnCommit.setOnClickListener(view -> {
            dialog.dismiss();
            ToastUtil.getInstance().show(getContext(), "白板创建成功");
            String avatar;
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = false;
            Bitmap bm = BitmapFactory.decodeResource(WhiteBoardFragment.this.getResources(), staffRes, options);
            double imageWidth = options.outWidth;
            double imageHidtht = options.outHeight;
            imageWidth = bm.getWidth() * 0.6;
            imageHidtht = bm.getHeight() * 0.6;
            avatar = FileUtils.getFilePath(bm);
            bm.recycle();
            bm = null;
            classViewModel.WhiteBoardInsertImage(avatar, imageWidth, imageHidtht);
        });
        btnCancel.setOnClickListener(view -> {
            dialog.dismiss();
            ToastUtil.getInstance().show(getContext(), "白板创建成功");
        });
        iv_close.setOnClickListener(view -> {
            dialog.dismiss();
            ToastUtil.getInstance().show(getContext(), "白板创建成功");
        });

        dialog.setContentView(contentView);
        dialog.show();
    }

    private void insertImage() {
        new RxPermissions(this)
                .request(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE)
                .subscribe(permission -> {
                    if (permission) {
                        PictureSelector.create(this)
                                .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                                .loadImageEngine(GlideEngine.createGlideEngine())
                                .theme(com.cooleshow.base.R.style.picture_daya_style)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style
                                .selectionMode(PictureConfig.SINGLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                                .enableCrop(true)// 是否裁剪 true or false
                                .showCropGrid(true)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false    true or false
                                .compress(true)// 是否压缩 true or false
                                .scaleEnabled(true)
                                .rotateEnabled(true)
                                .freeStyleCropEnabled(true)
                                .circleDimmedLayer(false)// 是否圆形裁剪 true or false
                                .forResult(PictureConfig.CHOOSE_REQUEST);
                    } else {
                        CommonDialog dialog = new CommonDialog(getContext());
                        dialog.show();
                        dialog.setTitle("提示");
                        dialog.setContent("上传照片需要相机权限，是否去设置？");
                        dialog.setOnCancelClickListener(view1 -> {
                            dialog.dismiss();
                        });

                        dialog.setOnConfirmClickListener(view1 -> {
                            PermissionUtils.toSelfSetting(getActivity());
                            dialog.dismiss();
                        });
                    }
                });

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    LocalMedia localMedia = selectList.get(0);
                    LogUtils.e(localMedia.getCompressPath());
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    String avatar = localMedia.getCompressPath();
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inJustDecodeBounds = false;
                    Bitmap bm = BitmapFactory.decodeFile(avatar, options);
                    double imageWidth = options.outWidth;
                    double imageHidtht = options.outHeight;
                    String orientation = SPUtils.getInstance().getString(Constants.WHITE_BOARD_ORIENTATION, "");
                    if (orientation.equals("horizontal")) {
                        Matrix matrix = new Matrix();
                        matrix.setRotate(270);
                        Bitmap bm1 = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
                        bm.recycle();
                        bm = null;
                        imageWidth = bm1.getWidth();
                        imageHidtht = bm1.getHeight();
                        avatar = FileUtils.getFilePath(bm1);
                        bm1.recycle();
                        bm1 = null;
                    }

                    classViewModel.WhiteBoardInsertImage(avatar, imageWidth, imageHidtht);
                    break;
                case QU_LIBRAY_REQUEST_CODE:
                    String url = data.getStringExtra("imageUrl");
                    if (TextUtils.isEmpty(url)) {
                        break;
                    }
                    Glide.with(getActivity())
                            .asBitmap()
                            .load(url)
                            .into(new SimpleTarget<Bitmap>() {
                                @Override
                                public void onResourceReady(@NonNull Bitmap bitmap, @Nullable Transition<? super Bitmap> transition) {
                                    try {
                                        int width = bitmap.getWidth();
                                        int height = bitmap.getHeight();
                                        ImageInformationWithUrl imageUrl = new ImageInformationWithUrl();
                                        imageUrl.setUrl(url);
                                        imageUrl.setCenterX(0);
                                        imageUrl.setCenterY(0);
                                        imageUrl.setHeight(height);
                                        imageUrl.setWidth(width);
                                        room.insertImage(imageUrl);
                                        //                                        //3、获取屏幕的默认分辨率
                                        WindowManager manager = getActivity().getWindowManager();
                                        DisplayMetrics outMetrics = new DisplayMetrics();
                                        manager.getDefaultDisplay().getMetrics(outMetrics);
                                        int displayHeigth = outMetrics.heightPixels;
                                        int imageHeight = (int) SizeUtils.px2dp((displayHeigth - SizeUtils.dp2px(90)));
                                        double scale = imageHeight / Double.valueOf(height);
                                        if (scale >= 1) {
                                            scale = 1;
                                        }
                                        moveCamera(scale);
                                    } catch (Exception e) {
                                    }
                                }
                            });
                    break;
            }
        }
    }

    private void moveCamera(double scale) {
        CameraConfig cameraConfig = new CameraConfig();
        cameraConfig.setCenterX(0d);
        cameraConfig.setCenterY(0d);
        cameraConfig.setScale(scale);
        if (room != null) {
            room.moveCamera(cameraConfig);
        }
    }

    private void removeScenes() {
        if (room.getScenes().length > 1) {
            room.removeScenes(room.getSceneState().getScenePath());
            //            classViewModel.updateWhiteBoardList();
            updateWhiteBoardList();
            ToastUtil.getInstance().show(getContext(), "白板删除成功");
        } else {
            ToastUtil.getInstance().show(getContext(), "最后一张啦！");
        }
    }

    private void cleanScenen() {
        room.cleanScene(true);
    }

    private static int colorGray = 0xFF444444;
    private String currentApplianceName;

    public void setState(String currentApplianceName, int[] sdkColor) {
        String originalApplianceName = this.currentApplianceName;
        this.currentApplianceName = currentApplianceName;
        if (originalApplianceName != null) {
            Button originalButton = (Button) this.appliances.get(originalApplianceName);
            this.setColorWithButton(originalButton, colorGray);
        }
        Button currentButton = (Button) this.appliances.get(currentApplianceName);
        if (sdkColor != null) {
            int color = 0xff << 24 | (sdkColor[0] & 0xff) << 16 | (sdkColor[1] & 0xff) << 8 | (sdkColor[2] & 0xff);
            this.setColorWithButton(currentButton, color);
        }
    }


    private void setColorWithButton(Button button, int color) {
        Drawable drawable = button.getCompoundDrawablesRelative()[0];
        drawable.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
    }

    private void onClickApplianceButton(String applianceName) {
        MemberState memberState = new MemberState();
        memberState.setCurrentApplianceName(applianceName);
        this.room.setMemberState(memberState);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != room) {
            room.getZoomScale(new Promise<Number>() {
                @Override
                public void then(Number number) {
                    if (classViewModel != null) {
                        classViewModel.setWhiteBoardScale(number.doubleValue());
                    }
                }

                @Override
                public void catchEx(SDKError t) {
                    t.printStackTrace();
                }
            });

            whiteSdk.releaseRoom();
            whiteSdk = null;
            room.disconnect();
            room = null;
        }
        if (null != mWebView) {
            mWebView.removeAllViews();
            mWebView.destroy();
        }
    }

    /**
     * 设置 Button 点击监听
     *
     * @param listener
     */
    public void setWhiteBoardListener(onWhiteBoardListener listener) {
        this.listener = listener;
    }

    boolean isConnect;

    public void isConnect(boolean isConnect) {
        if (room != null && whiteSdk != null && this.isConnect != isConnect) {
            if (isConnect) {
                whiteSdk.joinRoom(roomParams, abstractRoomCallbacks, promise);
            } else if (!isConnect) {
                if (null != room) {
                    room.getZoomScale(new Promise<Number>() {
                        @Override
                        public void then(Number number) {
                            classViewModel.setWhiteBoardScale(number.doubleValue());
                        }

                        @Override
                        public void catchEx(SDKError t) {
                            t.printStackTrace();
                        }
                    });

                }
                room.disconnect();

            }
        }
        this.isConnect = isConnect;
    }


    public interface onWhiteBoardListener {

        /**
         * 点击事件
         */
        void onClick();

        /**
         * 白板列表
         */
        void onWhiteBoardList(List<WhiteBoard> reverseList);

    }
}
