package com.sjkj.base_lib.camera.dh.view;

import android.annotation.SuppressLint;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.lifecycle.ViewModelProvider;

import com.android.business.adapter.DataAdapterImpl;
import com.android.business.entity.ChannelInfo;
import com.android.business.exception.BusinessException;
import com.android.dahua.dhplaycomponent.IMediaPlayListener;
import com.android.dahua.dhplaycomponent.IOperationListener;
import com.android.dahua.dhplaycomponent.ITalkListener;
import com.android.dahua.dhplaycomponent.PlayManagerProxy;
import com.android.dahua.dhplaycomponent.camera.RTCamera.CloudBaseRTCamera;
import com.android.dahua.dhplaycomponent.camera.RTCamera.CloudBaseRTCameraParam;
import com.android.dahua.dhplaycomponent.camera.inner.Camera;
import com.android.dahua.dhplaycomponent.common.Err;
import com.android.dahua.dhplaycomponent.common.PlayStatusType;
import com.android.dahua.dhplaycomponent.common.PtzOperation;
import com.android.dahua.dhplaycomponent.windowcomponent.entity.ControlType;
import com.getkeepsafe.relinker.ReLinker;
import com.kongzue.dialogx.dialogs.BottomDialog;
import com.kongzue.dialogx.interfaces.OnBindView;
import com.sjkj.base_lib.R;
import com.sjkj.base_lib.app.BaseApp;
import com.sjkj.base_lib.camera.dh.DhUtils;
import com.sjkj.base_lib.camera.dh.async.AsyncBuilder;
import com.sjkj.base_lib.camera.dh.vm.CameraViewModel;
import com.sjkj.base_lib.databinding.ActivityCameraControlDhBinding;
import com.sjkj.base_lib.entity.Params;
import com.sjkj.base_lib.net.domain.interactor.ProcessErrorSubscriber;
import com.sjkj.base_lib.net.request.CameraControlRequest;
import com.sjkj.base_lib.utils.AppTools;
import com.sjkj.base_lib.utils.Constants;
import com.sjkj.base_lib.view.BaseActivity;
import com.sjkj.base_lib.weight.RockerView;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 摄像头详情
 */
public class DHCameraControlActivity extends BaseActivity implements View.OnTouchListener {
    static {
//        System.loadLibrary("gnustl_shared");
//        System.loadLibrary("dslalien");
//        System.loadLibrary("dsl");
//
//        System.loadLibrary("CommonSDK");
//        System.loadLibrary("DSSCloudStream");
        ReLinker.loadLibrary(BaseApp.getInstance(), "gnustl_shared", new ReLinker.LoadListener() {
            @Override
            public void success() {
                Log.e(TAG, "gnustl_shared_success");
            }

            @Override
            public void failure(Throwable t) {
                Log.e(TAG, "gnustl_shared_failure");
            }
        });

        ReLinker.loadLibrary(BaseApp.getInstance(), "dslalien", new ReLinker.LoadListener() {
            @Override
            public void success() {
                Log.e(TAG, "dslalien_success");
            }

            @Override
            public void failure(Throwable t) {
                Log.e(TAG, "dslalien_failure");
            }
        });

        ReLinker.loadLibrary(BaseApp.getInstance(), "dsl", new ReLinker.LoadListener() {
            @Override
            public void success() {
                Log.e(TAG, "dsl_success");
            }

            @Override
            public void failure(Throwable t) {
                Log.e(TAG, "dsl_failure");
            }
        });

        ReLinker.loadLibrary(BaseApp.getInstance(), "CommonSDK", new ReLinker.LoadListener() {
            @Override
            public void success() {
                Log.e(TAG, "CommonSDK_success");
            }

            @Override
            public void failure(Throwable t) {
                Log.e(TAG, "CommonSDK_failure");
            }
        });

        ReLinker.loadLibrary(BaseApp.getInstance(), "DSSCloudStream", new ReLinker.LoadListener() {
            @Override
            public void success() {
                Log.e(TAG, "DSSCloudStream_success");
            }

            @Override
            public void failure(Throwable t) {
                Log.e(TAG, "DSSCloudStream_failure");
            }
        });
    }

    private CameraViewModel viewModel;
    private ActivityCameraControlDhBinding binding;

    private static final String TAG = "DHCameraDetailsActivity";

    public static final int KEY_Handler_Stream_Played = 1;
    public static final int KEY_Handler_First_Frame = 2;
    public static final int KEY_Handler_Net_Error = 3;
    public static final int KEY_Handler_Play_Failed = 4;

    public static final int Stream_Assist_Type = 2;        //辅码流 // auxiliary stream
    public static final String KEY_PlayOnline_ChannelInfo = "channelInfo";
    protected PlayManagerProxy mPlayManager;
    private ChannelInfo mChannelInfo;
    private List<ChannelInfo> channelInfoList = new ArrayList<>();
    private int mScreenHeight;
    private int mScreenWidth;
    private boolean isFull = false;
    private boolean isStartTalk = false;
    private boolean isPlaying = false;
    //    private CameraDetailsRequest detailsRequest = new CameraDetailsRequest(App.getInstance());
    private CameraControlRequest cameraControlRequest = new CameraControlRequest(BaseApp.getInstance());
    private PtzOperation current = PtzOperation.left;

    @SuppressLint("HandlerLeak")
    protected Handler mPlayOnlineHander = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case KEY_Handler_Stream_Played:
                    isPlaying = true;
                    int winIndex = (Integer) msg.obj;

                    if (winIndex != mPlayManager.getSelectedWindowIndex()) return;
//                    if (channelInfoList != null && channelInfoList.size() == 1) {
//                        mPlayManager.maximizeWindow(winIndex);
//                        mPlayManager.setEZoomEnable(winIndex, true);
//                    }
//                    if (mPlayManager.isNeedOpenAudio(winIndex))
//                    openAudio(winIndex);
                    break;
                case KEY_Handler_First_Frame:
                    mPlayManager.playCurpage();
                    break;
                case KEY_Handler_Net_Error:
                case KEY_Handler_Play_Failed:
                    isPlaying = false;
                    winIndex = (Integer) msg.obj;
                    stopPlay(winIndex);
                    break;
            }
        }
    };
    //    private MapFragment mapFragment;
    private ArrayList<String> list;
    private String lat;
    private String lng;

    private Handler cameraControlHandler = new Handler();

    private int mNewWinIndex = 0;
    private int mOldWinIndex = 0;
    private int winSize = 4;
    /**
     * 流畅
     */
    private static final int CAMERA_DEFINITION_FLOW = 1;
    /**
     * 清晰
     */
    private static final int CAMERA_DEFINITION_CLEARNESS = 0;

    @Override
    protected int initLayout() {
        return R.layout.activity_camera_control_dh;
    }

    @Override
    public void initBinding() {
        binding = (ActivityCameraControlDhBinding) getViewDataBinding();
        viewModel = new ViewModelProvider(this, new ViewModelProvider.NewInstanceFactory()).get(CameraViewModel.class);
        binding.setViewModel(viewModel);
        binding.setLifecycleOwner(this);
    }

    @Override
    public void initView() {
        super.initView();
        getTitleView().setText("监控探头");
        list = getIntent().getStringArrayListExtra("list");
        lat = getIntent().getStringExtra("lat");
        lng = getIntent().getStringExtra("lng");
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        mScreenWidth = metric.widthPixels; // 屏幕宽度（像素）
        mScreenHeight = metric.heightPixels; // 屏幕高度（像素）
        mPlayManager = new PlayManagerProxy();
        //初始化窗口数量，默认显示4个窗口，最多16窗口，若设置单窗口均设置为1
        mPlayManager.init(this, 0, winSize, binding.playWindow);
        //设置播放监听
        // set play monitor.
        mPlayManager.setOnMediaPlayListener(iMediaPlayListener);
        //设置窗口操作监听
        mPlayManager.setOnOperationListener(iOperationListener);
        // set the intercom monitor.
        mPlayManager.setOnTalkListener(new ITalkListener());
        //设置云台监听
        // set the cloud monitor.
//        mPlayManager.setOnPTZListener(iptzListener);
        initCommonWindow();
        DhUtils.getInstance().initDhSDK(this, new DhUtils.OnDhListener() {
            @Override
            public void callBack() {
                startDhWinPlay();

//                ToastUtils.show("操作准备中");
                cameraControlHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        requestControlCamera();
                    }
                }, 5000);
            }
        });
        binding.rockerView.setCallBackMode(RockerView.CallBackMode.CALL_BACK_MODE_STATE_CHANGE);
        binding.rockerView.setOnShakeListener(RockerView.DirectionMode.DIRECTION_8, new RockerView.OnShakeListener() {
            @Override
            public void onStart() {
            }

            @Override
            public void direction(RockerView.Direction direction) {
                switch (direction) {
                    case DIRECTION_LEFT:
                        if (current != PtzOperation.left) {
                            sendPTZOperation(getPtzOperation(current), true);
                        }
                        current = PtzOperation.left;
                        sendPTZOperation(ChannelInfo.PtzOperation.left, false);
                        break;
                    case DIRECTION_RIGHT:
                        if (current != PtzOperation.right) {
                            sendPTZOperation(getPtzOperation(current), true);
                        }
                        current = PtzOperation.right;
                        sendPTZOperation(ChannelInfo.PtzOperation.right, false);
                        break;
                    case DIRECTION_UP:
                        if (current != PtzOperation.up) {
                            sendPTZOperation(getPtzOperation(current), true);
                        }
                        current = PtzOperation.up;
                        sendPTZOperation(ChannelInfo.PtzOperation.up, false);
                        break;
                    case DIRECTION_DOWN:
                        if (current != PtzOperation.down) {
                            sendPTZOperation(getPtzOperation(current), true);
                        }
                        current = PtzOperation.down;
                        sendPTZOperation(ChannelInfo.PtzOperation.down, false);
                        break;
                    case DIRECTION_UP_LEFT:
                        if (current != PtzOperation.leftUp) {
                            sendPTZOperation(getPtzOperation(current), true);
                        }
                        current = PtzOperation.leftUp;
                        sendPTZOperation(ChannelInfo.PtzOperation.leftUp, false);
                        break;
                    case DIRECTION_UP_RIGHT:
                        if (current != PtzOperation.rightUp) {
                            sendPTZOperation(getPtzOperation(current), true);
                        }
                        current = PtzOperation.rightUp;
                        sendPTZOperation(ChannelInfo.PtzOperation.rightUp, false);
                        break;
                    case DIRECTION_DOWN_LEFT:
                        if (current != PtzOperation.leftDown) {
                            sendPTZOperation(getPtzOperation(current), true);
                        }
                        current = PtzOperation.leftDown;
                        sendPTZOperation(ChannelInfo.PtzOperation.leftDown, false);
                        break;
                    case DIRECTION_DOWN_RIGHT:
                        if (current != PtzOperation.rightDown) {
                            sendPTZOperation(getPtzOperation(current), true);
                        }
                        current = PtzOperation.rightDown;
                        sendPTZOperation(ChannelInfo.PtzOperation.rightDown, false);
                        break;
                    default:
                        break;
                }
            }

            @Override
            public void onFinish() {
                sendPTZOperation(getPtzOperation(current), true);
            }
        });
        //摄像头控制按钮
        binding.cameraControlIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (viewModel.isShowCameraControlView.get()) {
                    viewModel.isShowCameraControlView.set(false);
                    resetMenuZoomView();
                    binding.cameraControlIv.setImageResource(R.mipmap.play_online_hor_cloud_normal);
//                    int winIndex = mPlayManager.getSelectedWindowIndex();
//                    mPlayManager.setPTZEnable(winIndex, false);

//                    closePTZ();
                } else {
                    if (mPlayManager == null || !mPlayManager.isStreamPlayed(mPlayManager.getSelectedWindowIndex()))
                        return;
                    int windowIndex = mPlayManager.getSelectedWindowIndex();
                    if (!mPlayManager.isPlaying(windowIndex)) {
                        return;
                    }
                    viewModel.isShowCameraControlView.set(true);
                    binding.cameraControlIv.setImageResource(R.mipmap.play_online_hor_cloud_press);
                    if (channelInfoList != null && channelInfoList.size() > 0) {
                        int winIndex = mPlayManager.getSelectedWindowIndex();
                        mPlayManager.maximizeWindow(winIndex);
                        mPlayManager.setEZoomEnable(winIndex, true);
//                        mPlayManager.setPTZEnable(winIndex, false);
//                        mPlayManager.setPTZEnable(winIndex, true);
                        binding.cameraOpenIv.setSelected(true);
                        winSize = 1;
                        pageCount(winSize);
                    }
//                    openPTZ();
                }
            }
        });
        /**
         * 倍率控制按钮
         */
        binding.cameraHorZoomIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (binding.cameraHorZoomIv.isSelected()) {
                    viewModel.isShowCameraZoomView.set(false);
                    viewModel.cameraZoomType.set(0);
                    binding.currentNameTv.setText("");
                    binding.cameraHorZoomIv.setSelected(false);
                } else {
                    viewModel.cameraZoomType.set(1);
                    binding.currentNameTv.setText("倍率");
                    viewModel.isShowCameraZoomView.set(true);
                    binding.cameraHorApertureIv.setSelected(false);
                    binding.cameraHorZoomIv.setSelected(true);
                    binding.cameraHorFocusIv.setSelected(false);
                }
            }
        });
        //焦点控制按钮
        binding.cameraHorFocusIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (binding.cameraHorFocusIv.isSelected()) {
                    viewModel.isShowCameraZoomView.set(false);
                    viewModel.cameraZoomType.set(0);
                    binding.currentNameTv.setText("");
                    binding.cameraHorFocusIv.setSelected(false);
                } else {
                    viewModel.cameraZoomType.set(2);
                    binding.currentNameTv.setText("焦点");
                    viewModel.isShowCameraZoomView.set(true);
                    binding.cameraHorApertureIv.setSelected(false);
                    binding.cameraHorZoomIv.setSelected(false);
                    binding.cameraHorFocusIv.setSelected(true);
                }
            }
        });
        //光圈控制按钮
        binding.cameraHorApertureIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (binding.cameraHorApertureIv.isSelected()) {
                    viewModel.isShowCameraZoomView.set(false);
                    viewModel.cameraZoomType.set(0);
                    binding.currentNameTv.setText("");
                    binding.cameraHorApertureIv.setSelected(false);
                } else {
                    viewModel.cameraZoomType.set(3);
                    binding.currentNameTv.setText("光圈");
                    viewModel.isShowCameraZoomView.set(true);
                    binding.cameraHorApertureIv.setSelected(true);
                    binding.cameraHorZoomIv.setSelected(false);
                    binding.cameraHorFocusIv.setSelected(false);
                }
            }
        });

        binding.cameraReduceIv.setOnTouchListener(this);
        binding.cameraAddIv.setOnTouchListener(this);
        binding.cameraFullIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switchScreen();
            }
        });
        binding.cameraFullBackIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switchScreen();
            }
        });
        binding.cameraFrameIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BottomDialog.build()
                        .setCustomView(new OnBindView<BottomDialog>(R.layout.custom_window_frame_layout) {
                            @Override
                            public void onBind(BottomDialog dialog, View v) {
                                RadioGroup radioGroup = v.findViewById(R.id.frameRadioGroup);
                                radioGroup.check(viewModel.selectedFrameId.get());
                                radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                                    @Override
                                    public void onCheckedChanged(RadioGroup group, int checkedId) {
                                        viewModel.selectedFrameId.set(checkedId);
                                        if (checkedId == R.id.item01_tv) {
                                            binding.cameraFrameIv.setImageResource(R.mipmap.play_online_full_frame1_d);
                                            winSize = 1;
                                            mPlayManager.setSplitMode(0, winSize);
                                            pageCount(winSize);
                                        } else if (checkedId == R.id.item04_tv) {
                                            binding.cameraFrameIv.setImageResource(R.mipmap.play_online_full_frame4_d);
                                            winSize = 4;
                                            mPlayManager.setSplitMode(0, winSize);
                                            pageCount(winSize);
                                        } else if (checkedId == R.id.item09_tv) {
                                            binding.cameraFrameIv.setImageResource(R.mipmap.play_online_full_frame9_d);
                                            winSize = 9;
                                            mPlayManager.setSplitMode(0, winSize);
                                            pageCount(winSize);
                                        } else if (checkedId == R.id.item16_tv) {
                                            binding.cameraFrameIv.setImageResource(R.mipmap.play_online_full_frame16_d);
                                            winSize = 16;
                                            mPlayManager.setSplitMode(0, winSize);
                                            pageCount(winSize);
                                        }
                                        binding.cameraOpenIv.setSelected(false);
                                        dialog.dismiss();

                                    }
                                });
                            }
                        }).show();
            }
        });
        if (AppTools.getCameraStreamType() == CAMERA_DEFINITION_CLEARNESS) {
            binding.cameraStreamIv.setImageResource(R.mipmap.play_online_pop_main_d_text);
            viewModel.selectedStreamId.set(R.id.item01_tv);
        } else {
            binding.cameraStreamIv.setImageResource(R.mipmap.play_online_pop_ss1_d_text);
            viewModel.selectedStreamId.set(R.id.item02_tv);
        }
        binding.cameraStreamIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BottomDialog.build()
                        .setCustomView(new OnBindView<BottomDialog>(R.layout.custom_window_stream_layout) {
                            @Override
                            public void onBind(BottomDialog dialog, View v) {
                                RadioGroup radioGroup = v.findViewById(R.id.streamRadioGroup);
                                radioGroup.check(viewModel.selectedStreamId.get());
                                radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                                    @Override
                                    public void onCheckedChanged(RadioGroup group, int checkedId) {
                                        viewModel.selectedStreamId.set(checkedId);
                                        if (checkedId == R.id.item01_tv) {
                                            binding.cameraStreamIv.setImageResource(R.mipmap.play_online_pop_main_d_text);
                                            AppTools.setCameraStreamType(CAMERA_DEFINITION_CLEARNESS);
                                            startDhWinPlay();
                                        } else if (checkedId == R.id.item02_tv) {
                                            binding.cameraStreamIv.setImageResource(R.mipmap.play_online_pop_ss1_d_text);
                                            AppTools.setCameraStreamType(CAMERA_DEFINITION_FLOW);
                                            startDhWinPlay();
                                        }
                                        dialog.dismiss();
                                    }
                                });
                            }
                        }).show();
            }
        });
        binding.cameraOpenIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!binding.cameraOpenIv.isSelected()) {
                    binding.cameraOpenIv.setSelected(true);
                    if (channelInfoList != null && channelInfoList.size() > 0) {
                        int winIndex = mPlayManager.getSelectedWindowIndex();
                        mPlayManager.maximizeWindow(winIndex);
                        mPlayManager.setEZoomEnable(winIndex, true);
                        winSize = 1;
                        pageCount(winSize);
                    }
                } else {
                    binding.cameraOpenIv.setSelected(false);
                    if (channelInfoList != null && channelInfoList.size() > 0) {
                        int winIndex = mPlayManager.getSelectedWindowIndex();
                        mPlayManager.resumeWindow(mPlayManager.getSelectedWindowIndex());
                        mPlayManager.setEZoomEnable(winIndex, true);
                        pageCount(winSize);
                    }
                }
            }
        });
    }

    private void openPTZ() {
        if (mPlayManager == null || !mPlayManager.isStreamPlayed(mPlayManager.getSelectedWindowIndex()))
            return;
        int windowIndex = mPlayManager.getSelectedWindowIndex();
        if (!mPlayManager.isPlaying(windowIndex)) return;
        if (!mPlayManager.isOpenPTZ(windowIndex)) {
            if (mPlayManager.setPTZEnable(windowIndex, true) == Err.OK) {
                Log.e(TAG, "开启使能成功");
                mPlayManager.maximizeWindow(windowIndex);
                mPlayManager.setEZoomEnable(windowIndex, true);
//                openAudio(windowIndex);
            }
        }
    }

    private void closePTZ() {
        if (mPlayManager == null || !mPlayManager.isStreamPlayed(mPlayManager.getSelectedWindowIndex()))
            return;
        int windowIndex = mPlayManager.getSelectedWindowIndex();
        if (!mPlayManager.isPlaying(windowIndex)) return;
        if (mPlayManager.isOpenPTZ(windowIndex)) {
            if (mPlayManager.setPTZEnable(windowIndex, false) == Err.OK) {
                Log.e(TAG, "关闭使能成功");
            }
        }
    }

    private void startDhWinPlay() {
        channelInfoList.clear();
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                mChannelInfo = new ChannelInfo();
                mChannelInfo.setChnSncode(list.get(i));
                mChannelInfo.setUuid(list.get(i));
                channelInfoList.add(mChannelInfo);
            }
            mChannelInfo = channelInfoList.get(0);

            Log.e("dh_code", "channelInfoList:" + channelInfoList.size());
            mPlayManager.addCameras(getCameras());
            startPlay(0);
        }
        viewModel.currentPageIndex.set(0);
        pageCount(winSize);
    }

    private void pageCount(int winSize) {
        int pageCount = (channelInfoList.size() + winSize - 1) / winSize;
        viewModel.pageNumberText.set((viewModel.currentPageIndex.get() + 1) + "/" + pageCount);
    }

    private void requestControlCamera() {
        if (!TextUtils.isEmpty(lat) && ("0".equals(lat) || "0.0".equals(lat) || "0.00".equals(lat))) {
            return;
        }
        if (!TextUtils.isEmpty(lng) && ("0".equals(lng) || "0.0".equals(lng) || "0.00".equals(lng))) {
            return;
        }
        Params params = new Params();
        params.put("lat", lat);
        params.put("lng", lng);
        params.put("list", list);
        cameraControlRequest.setParams(params);
        cameraControlRequest.execute(new ProcessErrorSubscriber() {
            @Override
            public void onError(Throwable e) {
                super.onError(e);
//                ToastUtils.show("" + e.getMessage());
            }

            @Override
            public void onNext(Object o) {
                super.onNext(o);
//                ToastUtils.show("操作成功");
            }
        });
    }

    @Override
    public void loadData() {
        super.loadData();
//        if (AppTools.isLeader){
//            viewModel.tip.set("");
//        }else {
        viewModel.tip.set(Constants.CAMERA_TEXT);
//        }
    }

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

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

    @Override
    protected void onStop() {
        super.onStop();
        stopAll();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPlayManager != null) {
            mPlayManager.unitPlayManager();
            mPlayManager = null;
        }
//        unbindService(serviceConnection);
    }

    private List<Camera> getCameras() {
        List<Camera> cameras = new ArrayList<>();
        if (channelInfoList != null && channelInfoList.size() > 0) {
            for (ChannelInfo channelInfo : channelInfoList) {
                cameras.add(getCamera(channelInfo));
            }
        }
        return cameras;
    }

    public boolean openAudio(int winIndex) {
        return mPlayManager.openAudio(winIndex) == Err.OK;
    }

    private Camera getCamera(ChannelInfo channelInfo) {
        //创建播放Camera参数
        CloudBaseRTCameraParam cloudBaseCameraParam = new CloudBaseRTCameraParam();
        //设置窗口要播放的通道ID
        cloudBaseCameraParam.setCameraID(channelInfo.getChnSncode());
        //获取码流类型
//        int mStreamType = ChannelInfo.ChannelStreamType.getValue(channelInfo.getStreamType());
//        if (mStreamType > Stream_Assist_Type) mStreamType = Stream_Assist_Type;
//        cloudBaseCameraParam.setStreamType(mStreamType - 1);
        cloudBaseCameraParam.setStreamType(AppTools.getCameraStreamType());
        cloudBaseCameraParam.setDpRestToken(DhUtils.getInstance().getEnvironmentInfo().getRestToken());
        cloudBaseCameraParam.setServerIp(DhUtils.getIp());
        cloudBaseCameraParam.setServerPort(Integer.parseInt(DhUtils.getPort()));
        cloudBaseCameraParam.setRoute(false);
        cloudBaseCameraParam.setUserId("");
        cloudBaseCameraParam.setDomainId("");
        cloudBaseCameraParam.setRegionId("");
        cloudBaseCameraParam.setLocation("");
        cloudBaseCameraParam.setUseHttps(DhUtils.getInstance().getEnvironmentInfo().isHttps() ? 1 : 0);
        return new CloudBaseRTCamera(cloudBaseCameraParam);
    }

    /**
     * 开始播放
     */
    private void startPlay(int winIndex) {
        if (mPlayManager != null)
            mPlayManager.playSingle(winIndex);
    }

    /**
     * 重新播放
     */
    private void replay() {
        if (mPlayManager != null)
            mPlayManager.playCurpage();
    }

    /**
     * 停止播放
     */
    private void stopPlay(int winIndex) {
        if (mPlayManager != null)
            mPlayManager.stopSingle(winIndex);
    }

    /**
     * 所有窗口停止播放
     */
    private void stopAll() {
        if (mPlayManager != null)
            mPlayManager.stopAll();
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            //继承自AppCompatActivity时使用
            getSupportActionBar().hide();
        } else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            getSupportActionBar().show();
        }
    }

    //
//    /**
//     * 云台
//     */
//    protected void onClickPTZ() {
//        if (mPlayManager == null || !mPlayManager.isStreamPlayed(mPlayManager.getSelectedWindowIndex()))
//            return;
//        int windowIndex = mPlayManager.getSelectedWindowIndex();
//        if (!mPlayManager.isPlaying(windowIndex)) return;
//        if (mPlayManager.isOpenPTZ(windowIndex)) {
//            if (mPlayManager.setPTZEnable(windowIndex, false) == Err.OK) {
//                binding.tvPtz.setChecked(false);
//                binding.nestedScrollView.setVisibility(View.GONE);
//            }
//        } else {
//            if (mPlayManager.setPTZEnable(windowIndex, true) == Err.OK) {
//                binding.tvPtz.setChecked(true);
//                binding.nestedScrollView.setVisibility(View.VISIBLE);
//            }
//        }
//    }
    private ExecutorService ptzSingleExecutor = Executors.newSingleThreadExecutor();

    /**
     * 云台控制
     */
    protected void sendPTZOperation(final ChannelInfo.PtzOperation operation, final boolean isStop) {
        ptzSingleExecutor.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    DataAdapterImpl.getInstance().operatePTZ(operation, mChannelInfo.getUuid(), 4, isStop);
                    Log.e(TAG, "sendPTZOperation_" + operation.name() + "_" + (isStop ? "stop" : ""));
                } catch (BusinessException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        //        AsyncBuilder.createTask(new AsyncBuilder.BusinessTask<Integer>() {
//            @Override
//            public Integer doInBackground() throws Exception {
//                Log.e(TAG, "sendPTZOperation_" + operation.name() + "_" + (isStop ? "stop" : ""));
//                /**
//                 * var1 操作类型（变焦、光圈、焦距...）
//                 * var2 uuid
//                 * var3 云台步长
//                 * var4 操作是否结束
//                 */
//                return DataAdapterImpl.getInstance().operatePTZ(operation, mChannelInfo.getUuid(), 4, isStop);
//            }
//        }).resultInMain(this, new AsyncBuilder.ResultListener<Integer>() {
//            @Override
//            public void onSuccess(Integer integer) {
//
//            }
//
//            @Override
//            public void onError(BusinessException e) {
//
//            }
//        });
    }

    public ChannelInfo.PtzOperation getPtzOperation(PtzOperation oprType) {
        ChannelInfo.PtzOperation operation = ChannelInfo.PtzOperation.stop;
        if (oprType == PtzOperation.up) operation = ChannelInfo.PtzOperation.up;
        if (oprType == PtzOperation.down) operation = ChannelInfo.PtzOperation.down;
        if (oprType == PtzOperation.left) operation = ChannelInfo.PtzOperation.left;
        if (oprType == PtzOperation.right) operation = ChannelInfo.PtzOperation.right;
        if (oprType == PtzOperation.leftUp) operation = ChannelInfo.PtzOperation.leftUp;
        if (oprType == PtzOperation.leftDown) operation = ChannelInfo.PtzOperation.leftDown;
        if (oprType == PtzOperation.rightUp) operation = ChannelInfo.PtzOperation.rightUp;
        if (oprType == PtzOperation.rightDown) operation = ChannelInfo.PtzOperation.rightDown;
        return operation;
        // 若想用摄像头的放大和缩小，operation可以按如下设置：
        // operation = ChannelInfo.PtzOperation.zoomAdd; 放大
        // operation = ChannelInfo.PtzOperation.zoomReduce;缩小
    }

    /**
     * 初始化视频窗口
     */
    public void initCommonWindow() {
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) binding.playWindow.getLayoutParams();
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) binding.flPlayWindow.getLayoutParams();
        lp.width = isFull ? mScreenHeight : mScreenWidth;
        lp.height = isFull ? mScreenWidth : mScreenHeight / 3;
        layoutParams.width = isFull ? mScreenHeight : mScreenWidth;
        layoutParams.height = isFull ? mScreenWidth : mScreenHeight / 3;
        binding.flPlayWindow.setLayoutParams(layoutParams);
        binding.playWindow.setLayoutParams(lp);
        binding.playWindow.forceLayout(lp.width, lp.height);
    }

    /**
     * 切换横竖屏
     */
    public void switchScreen() {
        if (isFull) {
            viewModel.isShowCameraControlView.set(false);
//            int winIndex = mPlayManager.getSelectedWindowIndex();
//            mPlayManager.setPTZEnable(winIndex, false);

            resetMenuZoomView();
            viewModel.isShowCameraControlBtn.set(false);
            viewModel.isShowBackBtn.set(false);
            isFull = false;
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        } else {
            viewModel.isShowCameraControlBtn.set(true);
            binding.cameraControlIv.setImageResource(R.mipmap.play_online_hor_cloud_normal);
            viewModel.isShowBackBtn.set(true);
            isFull = true;
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
        }
        initCommonWindow();
    }

    /**
     * 重置倍率/焦距/光圈菜单
     */
    private void resetMenuZoomView() {
        binding.cameraHorFocusIv.setSelected(false);
        binding.cameraHorZoomIv.setSelected(false);
        binding.cameraHorApertureIv.setSelected(false);
        viewModel.isShowCameraZoomView.set(false);
    }

    @Override
    public void onBackPressed() {
        if (isFull) {
            switchScreen();
        } else {
            this.finish();
        }
    }


    private IMediaPlayListener iMediaPlayListener = new IMediaPlayListener() {
        @Override
        public void onPlayeStatusCallback(int winIndex, PlayStatusType type, int code) {
            Message msg = Message.obtain();
            msg.obj = winIndex;
            if (type == PlayStatusType.eStreamPlayed) {
                msg.what = KEY_Handler_Stream_Played;
                if (mPlayOnlineHander != null) mPlayOnlineHander.sendMessage(msg);
            } else if (type == PlayStatusType.ePlayFirstFrame) {
                msg.what = KEY_Handler_First_Frame;
                if (mPlayOnlineHander != null) mPlayOnlineHander.sendMessage(msg);
            } else if (type == PlayStatusType.eNetworkaAbort) {
                msg.what = KEY_Handler_Net_Error;
                if (mPlayOnlineHander != null) mPlayOnlineHander.sendMessage(msg);
            } else if (type == PlayStatusType.ePlayFailed) {
                msg.what = KEY_Handler_Play_Failed;
                if (mPlayOnlineHander != null) mPlayOnlineHander.sendMessage(msg);
            }
        }
    };

    private IOperationListener iOperationListener = new IOperationListener() {
        @Override
        public void onWindowSelected(int position) {
            mNewWinIndex = position;
            if (channelInfoList.size() > 0 && position < channelInfoList.size()) {
                mChannelInfo = channelInfoList.get(position);
            }
            Log.d(TAG, "onWindowSelected____" + position + "_______uuid:" + mChannelInfo.getUuid());

//            if (mOldWinIndex != mNewWinIndex) {
//                if (mPlayManager == null || !mPlayManager.isStreamPlayed(mNewWinIndex))
//                    return;
//                if (!mPlayManager.isPlaying(mNewWinIndex)) return;
//                mChannelInfo = channelInfoList.get(position);
//            Log.d(TAG, "onWindowSelected_" + position + "_mChannelInfo:" + mChannelInfo.getUuid());
//            }
        }

        @Override
        public void onPageChange(int newPage, int prePage, int type) {
            Log.d(TAG, "onPageChange____" + newPage + "____" + prePage + "____" + type);
//            if (type == 0) {
////                if (mPlayManager != null & mPlayManager.getPageCellNumber() == 1) {
////                    mPlayManager.setEZoomEnable(prePage, false);
////                    mPlayManager.setEZoomEnable(newPage, true);
////                }
//            }
            viewModel.currentPageIndex.set(newPage);
            pageCount(winSize);
        }

        @Override
        public void onSplitNumber(int nCurCellNumber, int nCurPage, int nPreCellNumber, int nPrePage) {
            Log.d(TAG, "onSplitNumber__nCurCellNumber__" + nCurCellNumber + "__nCurPage__" + nCurPage + "__nPreCellNumber__" + nPreCellNumber + "__nPrePage__" + nPrePage);
            viewModel.currentPageIndex.set(nCurPage);
            pageCount(winSize);
        }

        @Override
        public void onControlClick(int nWinIndex, ControlType type) {
            Log.d(TAG, "onControlClick" + type);
            if (type == ControlType.Control_Reflash) {
                startPlay(nWinIndex);
            }
        }

        @Override
        public void onSelectWinIndexChange(int newWinIndex, int oldWinIndex) {
            mNewWinIndex = newWinIndex;
            mOldWinIndex = oldWinIndex;
            if (mPlayManager != null) {
                Log.d(TAG, "onSelectWinIndexChange:" + newWinIndex /*+ ":" + oldWinIndex*/);
                if (!mPlayManager.hasTalking()) {
                    if (mPlayManager.isOpenAudio(oldWinIndex)) {
                        mPlayManager.closeAudio(oldWinIndex);
                        mPlayManager.setNeedOpenAudio(oldWinIndex, true);
                    }

                    if (mPlayManager.isPlaying(newWinIndex) && mPlayManager.isNeedOpenAudio(newWinIndex))
                        mPlayManager.openAudio(newWinIndex);
                }
            }
        }

        @Override
        public boolean onWindowDBClick(int winIndex, int type) {
            Log.d(TAG, "onWindowDBClick" + type + " winIndex:" + winIndex + " isWindowMax:" + mPlayManager.isWindowMax(winIndex));
            if (mPlayManager.isOpenPTZ(winIndex)) {
                if (mPlayManager.setPTZEnable(winIndex, false) == Err.OK) {
                    mPlayManager.setResumeFlag(winIndex, false);
                }
            }
            return false;
        }

        @Override
        public void onMoveWindowBegin(int winIndex) {
            Log.d(TAG, "onMoveWindowBegin");
        }

        @Override
        public void onMovingWindow(int winIndex, float x, float y) {
            Log.d(TAG, "onMovingWindow x:" + x + " y:" + y);
        }

        @Override
        public boolean onMoveWindowEnd(int winIndex, float x, float y) {
            Log.d(TAG, "onMoveWindowEnd x:" + x + " y:" + y);
            return false;
        }
    };

//    private IPTZListener iptzListener = new IPTZListener() {
//        @Override
//        public void onPTZControl(int winIndex, PtzOperation oprType, boolean isStop, boolean isLongPress) {
//            sendPTZOperation(getPtzOperation(oprType), isStop);
//        }
//
//        @Override
//        public void onPTZZooming(int winIndex, float scale, PtzOperation oprType, PtzZoomState state) {
//
//        }
//    };

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                int id = v.getId();
                if (id == R.id.camera_reduce_iv) {
                    binding.cameraReduceIv.setPressed(true);
//                        Log.e(TAG, "reduce_" + viewModel.cameraZoomType.get());
                    switch (viewModel.cameraZoomType.get()) {
                        case 1:
                            sendPTZOperation(ChannelInfo.PtzOperation.zoomReduce, false);
                            break;
                        case 2:
                            sendPTZOperation(ChannelInfo.PtzOperation.focusReduce, false);
                            break;
                        case 3:
                            sendPTZOperation(ChannelInfo.PtzOperation.apertureReduce, false);
                            break;
                        default:
                            break;
                    }
                } else if (id == R.id.camera_add_iv) {
                    binding.cameraAddIv.setPressed(true);
//                        Log.e(TAG, "add_" + viewModel.cameraZoomType.get());
                    switch (viewModel.cameraZoomType.get()) {
                        case 1:
                            sendPTZOperation(ChannelInfo.PtzOperation.zoomAdd, false);
                            break;
                        case 2:
                            sendPTZOperation(ChannelInfo.PtzOperation.focusAdd, false);
                            break;
                        case 3:
                            sendPTZOperation(ChannelInfo.PtzOperation.apertureAdd, false);
                            break;
                        default:
                            break;
                    }
                }
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                int vId = v.getId();
                if (vId == R.id.camera_reduce_iv) {
                    binding.cameraReduceIv.setPressed(false);
//                        Log.e(TAG, "reduce_stop" + viewModel.cameraZoomType.get());
                    switch (viewModel.cameraZoomType.get()) {
                        case 1:
                            sendPTZOperation(ChannelInfo.PtzOperation.zoomReduce, true);
                            break;
                        case 2:
                            sendPTZOperation(ChannelInfo.PtzOperation.focusReduce, true);
                            break;
                        case 3:
                            sendPTZOperation(ChannelInfo.PtzOperation.apertureReduce, true);
                            break;
                        default:
                            break;
                    }
                } else if (vId == R.id.camera_add_iv) {
                    binding.cameraAddIv.setPressed(false);
//                        Log.e(TAG, "add_stop" + viewModel.cameraZoomType.get());
                    switch (viewModel.cameraZoomType.get()) {
                        case 1:
                            sendPTZOperation(ChannelInfo.PtzOperation.zoomAdd, true);
                            break;
                        case 2:
                            sendPTZOperation(ChannelInfo.PtzOperation.focusAdd, true);
                            break;
                        case 3:
                            sendPTZOperation(ChannelInfo.PtzOperation.apertureAdd, true);
                            break;
                        default:
                            break;
                    }
                }
                break;
        }

        return true;
    }
}
