package com.beanpodtech.allinone.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.PaintDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewParent;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alivc.rtc.AliRtcAuthInfo;
import com.alivc.rtc.AliRtcEngine;
import com.alivc.rtc.AliRtcEngineEventListener;
import com.alivc.rtc.AliRtcEngineNotify;
import com.alivc.rtc.AliRtcRemoteUserInfo;
import com.aliyun.svideo.common.utils.ToastUtils;
import com.beanpodtech.allinone.R;
import com.beanpodtech.allinone.adapter.QuestionAdapter;
import com.beanpodtech.allinone.adapter.SmartQAAdapter;
import com.beanpodtech.allinone.adapter.TestQuestionAdapter;
import com.beanpodtech.allinone.bean.AliRtcAuthBean;
import com.beanpodtech.allinone.bean.AnswerBean;
import com.beanpodtech.allinone.bean.ChartUserBean;
import com.beanpodtech.allinone.bean.QuestionBean;
import com.beanpodtech.allinone.bean.SmartQABean;
import com.beanpodtech.allinone.bean.TestQuestionBean;
import com.beanpodtech.allinone.http.UrlConfig;
import com.beanpodtech.allinone.utils.ChatUiHelper;
import com.beanpodtech.allinone.utils.Contants;
import com.beanpodtech.allinone.utils.HttpUtils;
import com.beanpodtech.allinone.utils.OkGoBuilder;
import com.beanpodtech.allinone.utils.OkGoUtil;
import com.beanpodtech.allinone.utils.SpUtil;
import com.beanpodtech.allinone.widget.IndicatorView;
import com.beanpodtech.allinone.widget.StateButton;
import com.bumptech.glide.request.RequestOptions;
import com.lzy.okgo.model.Response;

import org.webrtc.sdk.SophonSurfaceView;

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

import static com.alivc.rtc.AliRtcEngine.AliRtcAudioTrack.AliRtcAudioTrackNo;
import static com.alivc.rtc.AliRtcEngine.AliRtcRenderMode.AliRtcRenderModeAuto;
import static com.alivc.rtc.AliRtcEngine.AliRtcVideoTrack.AliRtcVideoTrackBoth;
import static com.alivc.rtc.AliRtcEngine.AliRtcVideoTrack.AliRtcVideoTrackCamera;
import static com.alivc.rtc.AliRtcEngine.AliRtcVideoTrack.AliRtcVideoTrackNo;
import static com.alivc.rtc.AliRtcEngine.AliRtcVideoTrack.AliRtcVideoTrackScreen;
import static org.webrtc.alirtcInterface.ErrorCodeEnum.ERR_ICE_CONNECTION_HEARTBEAT_TIMEOUT;
import static org.webrtc.alirtcInterface.ErrorCodeEnum.ERR_SESSION_REMOVED;

public class QAActivity extends Activity {
    /**
     * 视频Id
     */
    private static final String VIDEOID = "videoId";
    private PopupWindow popupWindowSmartQA;
    private RecyclerView rvChatList;
    private EditText etContent;
    private ImageView iv_head;
    private ImageView ivEmoji;
    private StateButton btnSend;
    private RelativeLayout bottomLayout;
    private LinearLayout rlEmotion;
    private LinearLayout llContent;
    private TextView tv_title;
    private LinearLayout homeEmoji;
    private RequestOptions requestOptions;
    private ViewPager vpEmoji;
    private IndicatorView indEmoji;
    private SmartQAAdapter smartQAAdapter;
    private List<SmartQABean.ListBean> listSmartQA = new ArrayList<>();
    private SmartQABean.ListBean sendBean;
    private ChatUiHelper mUiHelper;
    private ListView lvSmartqaData;
    private EditText etMinute;
    private EditText etSecond;
    private TextView tvFindbypoint;
    private View llFootview;
    private ImageView tvManualAnswering;
    private RecyclerView rcvTestquestion;
    private TextView tvFindbytest;
    private EditText edKeyword;
    private TextView tvFindbykeyword;
    private TextView tvAnswerTitle;
    private LinearLayout llAnswer;
    private TextView tvAnswerTitleAnswer;
    private TextView tvAnswerContent;
    private TestQuestionAdapter adapterTestQuestion;
    private List<TestQuestionBean.ListBean> listTestQuestion = new ArrayList<>();
    private String testQuestionId;
    private QuestionAdapter adapterQuestion;
    private List<QuestionBean.ListBean> listQuestion = new ArrayList<>();
    private final static int POPUPWINDOW_WIDTH = 400;
    private final static int POPUPWINDOW_HEIGHT = 600;
    private final static int POPUPWINDOW_MIN_HEIGHT = 300;
    private final Context mContext = this;
    private RelativeLayout rlRoot;
    private String videoId;
    private FrameLayout fl_data;

    public static void startAlivcPlayerActivity(Context context, String videoId) {
        Intent intent = new Intent(context, QAActivity.class);
//        intent.putExtra(INTENT_PLAY_MEDIA, bean);
//        intent.putExtra(COURSEID, courseId);
        intent.putExtra(VIDEOID, videoId);
//        intent.putExtra(ISTRY, isTry);
//        intent.putExtra(ISNEEDTIMING, isNeedTiming);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_q_a);
        rlRoot = findViewById(R.id.rl_root);
        videoId = getIntent().getStringExtra(VIDEOID);
        initSmartQAPopupwindow();
    }

    @Override
    protected void onResume() {
        super.onResume();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                popupWindowSmartQA.showAtLocation(rlRoot, Gravity.TOP + Gravity.RIGHT, 0, 0);
            }
        }, 500);

    }

    private void initSmartQAPopupwindow() {
        SmartQAClick smartQAClick = new SmartQAClick();
        LayoutInflater inflater = LayoutInflater.from(this);
        View contentView = inflater.inflate(R.layout.popupwindow_smart_q_a, null);
        View headView = inflater.inflate(R.layout.headview_smartqa, null);
        View footView = inflater.inflate(R.layout.footview_smartqa, null);
        llFootview = footView.findViewById(R.id.ll_footview);
        llAnswer = footView.findViewById(R.id.ll_answer);
        tvAnswerTitleAnswer = footView.findViewById(R.id.tv_answer_title);
        tvAnswerContent = footView.findViewById(R.id.tv_answer_content);
        tvManualAnswering = footView.findViewById(R.id.tv_manual_answering);
        lvSmartqaData = contentView.findViewById(R.id.lv_smartqa_data);
        adapterQuestion = new QuestionAdapter(listQuestion, this);
        lvSmartqaData.setAdapter(adapterQuestion);
        etMinute = headView.findViewById(R.id.et_minute);
        etSecond = headView.findViewById(R.id.et_second);
//        etContent = headView.findViewById(R.id.ed_keyword);
        tvFindbypoint = headView.findViewById(R.id.tv_findbypoint);
        rcvTestquestion = headView.findViewById(R.id.rcv_testquestion);
        tvAnswerTitle = headView.findViewById(R.id.tv_answer_title);
        adapterTestQuestion = new TestQuestionAdapter(listTestQuestion, this);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rcvTestquestion.setLayoutManager(linearLayoutManager);
        rcvTestquestion.setAdapter(adapterTestQuestion);
        tvFindbytest = headView.findViewById(R.id.tv_findbytest);
        edKeyword = headView.findViewById(R.id.ed_keyword);
        tvFindbykeyword = headView.findViewById(R.id.tv_findbykeyword);
        popupWindowSmartQA = new PopupWindow(this);
        popupWindowSmartQA.setContentView(contentView);
        popupWindowSmartQA.setWidth(POPUPWINDOW_WIDTH);
        popupWindowSmartQA.setHeight(POPUPWINDOW_HEIGHT);
        popupWindowSmartQA.setFocusable(true);
        popupWindowSmartQA.setBackgroundDrawable(new PaintDrawable());
        lvSmartqaData.addHeaderView(headView);
        lvSmartqaData.addFooterView(footView);
        tvFindbypoint.setOnClickListener(smartQAClick);
        tvFindbytest.setOnClickListener(smartQAClick);
        tvFindbykeyword.setOnClickListener(smartQAClick);
        tvManualAnswering.setOnClickListener(smartQAClick);
        getTestQuestionListFromNet();
        lvSmartqaData.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                QuestionBean.ListBean itemAtPosition = (QuestionBean.ListBean) parent.getItemAtPosition(position);
                try {
                    getAnswerFromNet(((QuestionBean.ListBean) parent.getItemAtPosition(position)).getQuestionId(), position);
                } catch (NullPointerException e) {

                }
            }
        });
    }

    private void getAnswerFromNet(String questionId, final int position) {
        OkGoBuilder.getInstance().url(UrlConfig.GETANSWER).Builder((Activity) this).method(OkGoBuilder.PSOT).cls(AnswerBean.class).requestBody(HttpUtils.getRequestJson(initAnswerRequestBody(questionId))).callback(new OkGoUtil<AnswerBean>(AnswerBean.class) {
            @Override
            public void onSuccess(Response<AnswerBean> response) {


                if (response.body() != null && response.body() instanceof AnswerBean) {
                    AnswerBean body = response.body();
                    if (body != null) {
                        llAnswer.setVisibility(View.VISIBLE);
                        tvAnswerTitleAnswer.setText(body.getAnswerTitle());
                        tvAnswerContent.setText(body.getAnswerContent());
//                        QuestionBean.ListBean listBean = listQuestion.get(position - 1);
//                        listBean.setAnswer(body.getAnswerContent());
//                        listQuestion.set(position - 1, listBean);
//                        adapterQuestion.notifyDataSetChanged();
//                        listTestQuestion.addAll(body.getList());
//                        adapterTestQuestion.notifyDataSetChanged();
                    }
                }
            }

            @Override
            public void onError(Response<AnswerBean> response) {
                super.onError(response);
            }
        }).build();
    }

    private HashMap<String, String> initAnswerRequestBody(String questionId) {
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", SpUtil.getInstace().getString(Contants.USER_ID, null));
        map.put("questionId", questionId);
        return map;
    }

    class SmartQAClick implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.tv_findbypoint:
                    if (TextUtils.isEmpty(etMinute.getText().toString()) && TextUtils.isEmpty(etSecond.getText().toString())) {
                        ToastUtils.show(mContext, getString(R.string.please_input_video_point));
                        return;
                    }
                    getQuestionListFromNet(initQuestionRequestBody(etMinute.getText().toString(), etSecond.getText().toString()));
                    break;
                case R.id.tv_findbytest:
                    if (listTestQuestion.size() == 0) {
                        ToastUtils.show(mContext, getString(R.string.have_no_testquestion));
                        return;
                    }

                    for (int i = 0; i < listTestQuestion.size(); i++) {
                        if (listTestQuestion.get(i).isSelect()) {
                            testQuestionId = listTestQuestion.get(i).getTestQuestionId();
                        }
                    }
                    if (testQuestionId == null) {
                        ToastUtils.show(mContext, getString(R.string.please_select_testquestion));
                        return;
                    }
                    getQuestionListFromNet(initQuestionRequestBody());
                    break;
                case R.id.tv_findbykeyword:
                    if (TextUtils.isEmpty(edKeyword.getText().toString())) {
                        ToastUtils.show(mContext, getString(R.string.please_input_keywords));
                        return;
                    }
                    getQuestionListFromNet(initQuestionRequestBody(edKeyword.getText().toString()));
                    break;
                case R.id.tv_manual_answering:
                    popupWindowSmartQA.dismiss();
                    initPopupWindowForRTC();
                    getAuthAndJoinChannel();
                    popupWindowForRTC.showAtLocation(rlRoot, Gravity.TOP + Gravity.RIGHT, 0, 0);
                    break;
            }
        }
    }

    /**
     * 获取例题
     */
    private void getTestQuestionListFromNet() {
        OkGoBuilder.getInstance().url(UrlConfig.GETTESTQUESTIONLIST).Builder((Activity) mContext).method(OkGoBuilder.PSOT).cls(TestQuestionBean.class).requestBody(HttpUtils.getRequestJson(initTestQuestionRequestBody())).callback(new OkGoUtil<TestQuestionBean>(TestQuestionBean.class) {
            @Override
            public void onSuccess(Response<TestQuestionBean> response) {

                if (response.body() != null && response.body() instanceof TestQuestionBean) {
                    TestQuestionBean body = response.body();
                    if (body.getList() != null) {
                        listTestQuestion.addAll(body.getList());
                        adapterTestQuestion.notifyDataSetChanged();
                    }
                }
            }

            @Override
            public void onError(Response<TestQuestionBean> response) {
                super.onError(response);
            }
        }).build();
    }

    private HashMap<String, String> initTestQuestionRequestBody() {
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", SpUtil.getInstace().getString(Contants.USER_ID, null));
        map.put("videoId", videoId);
        return map;
    }

    /**
     * @param requestMap 根据条件获取可能的问题
     */
    private void getQuestionListFromNet(HashMap<String, String> requestMap) {
        OkGoBuilder.getInstance().url(UrlConfig.GETQUESTIONLIST).Builder((Activity) mContext).method(OkGoBuilder.PSOT).cls(QuestionBean.class).requestBody(HttpUtils.getRequestJson(requestMap)).callback(new OkGoUtil<QuestionBean>(QuestionBean.class) {
            @Override
            public void onSuccess(Response<QuestionBean> response) {
                if (response.body() != null && response.body() instanceof QuestionBean) {
                    listQuestion.clear();
                    QuestionBean body = response.body();
                    if (body.getList() != null) {
                        listQuestion.addAll(body.getList());
                    }
                    if (listQuestion.size() != 0) {
                        tvAnswerTitle.setVisibility(View.VISIBLE);
                    }
                    adapterQuestion.notifyDataSetChanged();
                    llFootview.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onError(Response<QuestionBean> response) {
                super.onError(response);
            }
        }).build();
    }

    /**
     * @param minute 分
     * @param second 秒
     * @return
     */
    private HashMap<String, String> initQuestionRequestBody(String minute, String second) {
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", SpUtil.getInstace().getString(Contants.USER_ID, null));
        map.put("videoId", videoId);
        map.put("pointMinute", TextUtils.isEmpty(minute) ? "0" : minute);
        map.put("pointSecond", TextUtils.isEmpty(second) ? "0" : second);
        return map;
    }

    /**
     * @return 例题
     */
    private HashMap<String, String> initQuestionRequestBody() {
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", SpUtil.getInstace().getString(Contants.USER_ID, null));
        map.put("videoId", videoId);
        map.put("testQuestionId", testQuestionId);
        return map;
    }

    /**
     * @param keyword 关键字
     * @return
     */
    private HashMap<String, String> initQuestionRequestBody(String keyword) {
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", SpUtil.getInstace().getString(Contants.USER_ID, null));
        map.put("videoId", videoId);
        map.put("keyWord", keyword);
        return map;
    }

    private void initPopupWindowForRTC() {
        View contentView = LayoutInflater.from(this).inflate(R.layout.activity_video_q_a, null);
//        Log.d(TAG, "initPopupWindowForRTC contentView " + contentView);
        // 初始化界面上的view
        initViewForPop(contentView);
        if (checkSelfPermission(REQUESTED_PERMISSIONS[0], PERMISSION_REQ_ID) &&
                checkSelfPermission(REQUESTED_PERMISSIONS[1], PERMISSION_REQ_ID) &&
                checkSelfPermission(REQUESTED_PERMISSIONS[2], PERMISSION_REQ_ID)) {
//            Log.d(TAG, "initPopupWindowForRTC initRTCEngineAndStartPreview ");
            // 初始化引擎以及打开预览界面
            initRTCEngineAndStartPreview();
        }
        tvTitleForRTC = contentView.findViewById(R.id.pop_video_chat_title);
        fl_data = contentView.findViewById(R.id.fl_data);
        popupWindowForRTC = new PopupWindow(this);
        popupWindowForRTC.setContentView(contentView);
        popupWindowForRTC.setWidth(POPUPWINDOW_WIDTH);
        popupWindowForRTC.setHeight(POPUPWINDOW_HEIGHT);
        popupWindowForRTC.setFocusable(false);
        popupWindowForRTC.setBackgroundDrawable(new PaintDrawable());
        tvTitleForRTC.setOnTouchListener(new View.OnTouchListener() {
            int orgX, orgY;
            int offsetX, offsetY;

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        orgX = (int) event.getX();
                        orgY = (int) event.getY();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        offsetX = (int) event.getRawX() - orgX;
                        offsetY = (int) event.getRawY() - orgY;
                        popupWindowForRTC.update(1080 - offsetX + 400 + orgX + tvTitleForRTC.getWidth(), offsetY, -1, -1, true);
                        break;
                    case MotionEvent.ACTION_UP:
                        break;
                }
                return true;
            }
        });
        contentView.findViewById(R.id.iv_destory).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Log.d(TAG, "mAliRtcEngine is null " + (mAliRtcEngine == null));
                if (mAliRtcEngine != null) {
                    //mAliRtcEngine.leaveChannel();
                    mAliRtcEngine.destroy();
                    mAliRtcEngine = null;
                }
                popupWindowForRTC.dismiss();
            }
        });
    }

    private void getRTCAuthToken() {
        OkGoBuilder.getInstance().url(UrlConfig.GET_RTC_AUTH_TOKEN).Builder((Activity) mContext)
                .method(OkGoBuilder.PSOT).cls(AliRtcAuthBean.class)
                .requestBody(HttpUtils.getRequestJson(getRequestBodyForAuthToken()))
                .callback(new OkGoUtil<AliRtcAuthBean>(AliRtcAuthBean.class) {
                    @Override
                    public void onSuccess(Response<AliRtcAuthBean> response) {
                        AliRtcAuthBean body = response.body();
                        if (body != null) {
                            //调用加入会议
                            joinChannel(body);
                        } else {
                            ToastUtils.show(mContext, R.string.neterror);
                        }
                    }

                    @Override
                    public void onError(Response<AliRtcAuthBean> response) {
                        super.onError(response);
                    }
                }).build();
    }

    private HashMap<String, String> getRequestBodyForAuthToken() {
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", SpUtil.getInstace().getString(Contants.USER_ID, null));
        map.put("videoId", videoId);
        map.put("keyWord", "");
        return map;
    }

    private void getRTCWattingInfo() {
        OkGoBuilder.getInstance().url(UrlConfig.GET_RTC_WATTING_INFO).Builder((Activity) mContext)
                .method(OkGoBuilder.PSOT).cls(AliRtcAuthBean.class)
                .requestBody(HttpUtils.getRequestJson(getRequestBodyForWatting()))
                .callback(new OkGoUtil<AliRtcAuthBean>(AliRtcAuthBean.class) {
                    @Override
                    public void onSuccess(Response<AliRtcAuthBean> response) {
                        AliRtcAuthBean body = response.body();
                        if (body != null) {
                            //更新UI进行显示
                        } else {
                            ToastUtils.show(mContext, R.string.neterror);
                        }
                    }

                    @Override
                    public void onError(Response<AliRtcAuthBean> response) {
                        super.onError(response);
                    }
                }).build();
    }

    private HashMap<String, String> getRequestBodyForWatting() {
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", SpUtil.getInstace().getString(Contants.USER_ID, null));
        map.put("videoId", videoId);
        return map;
    }

    public static final int CAMERA = 1001;
    public static final int SCREEN = 1002;
    public static final int CAMERA_FACE_BACK = 0;
    public static final int CAMERA_FACE_FRONT = 1;

    public static final String[] VIDEO_INFO_KEYS = {"Width", "Height", "FPS", "LossRate"};

    private static final int PERMISSION_REQ_ID = 0x0002;

    private static final String[] REQUESTED_PERMISSIONS = {
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.CAMERA,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };

    private PopupWindow popupWindowForRTC;
    private TextView tvTitleForRTC;
    //View rlRoot;
    Button showBtn;

    private SophonSurfaceView mRemoteView;
    /**
     * 本地流播放view
     */
    private SophonSurfaceView mLocalView;
    /**
     * SDK提供的对音视频通话处理的引擎类
     */
    private AliRtcEngine mAliRtcEngine;
    /**
     * 前台服务的Intent
     */
    private Intent mForeServiceIntent;

    /**
     * 承载远程User的Adapter
     */
//    private ChartUserAdapter mUserListAdapter;
    private boolean checkSelfPermission(String permission, int requestCode) {
        if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, REQUESTED_PERMISSIONS, requestCode);
            return false;
        }

        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions, @NonNull int[] grantResults) {

        if (requestCode == PERMISSION_REQ_ID) {
            if (grantResults[0] != PackageManager.PERMISSION_GRANTED ||
                    grantResults[1] != PackageManager.PERMISSION_GRANTED ||
                    grantResults[2] != PackageManager.PERMISSION_GRANTED) {
                showToast("Need permissions " + Manifest.permission.RECORD_AUDIO +
                        "/" + Manifest.permission.CAMERA + "/" + Manifest.permission.WRITE_EXTERNAL_STORAGE);
                finish();
                return;
            }
            initRTCEngineAndStartPreview();
        }
    }

    private void showToast(final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void initRTCEngineAndStartPreview() {

        //开启兼容H5
        AliRtcEngine.setH5CompatibleMode(1);
        // 防止初始化过多
        if (mAliRtcEngine == null) {
//            Log.d(TAG, "initRTCEngineAndStartPreview ");
            //实例化,必须在主线程进行。
            mAliRtcEngine = AliRtcEngine.getInstance(getApplicationContext());
            //设置事件的回调监听
            mAliRtcEngine.setRtcEngineEventListener(mEventListener);
            //设置接受通知事件的回调
            mAliRtcEngine.setRtcEngineNotify(mEngineNotify);
            // 初始化本地视图
            initLocalView();
            //开启预览
            startPreview();
            //加入频道
            //joinChannel();
        }
    }

    private void startPreview() {
        if (mAliRtcEngine == null) {
            return;
        }
        try {
            mAliRtcEngine.setPreCameraType(CAMERA_FACE_BACK);
            mAliRtcEngine.startPreview();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置本地的预览视图的view
     */
    private void initLocalView() {
//        mLocalView.getHolder().setFormat(PixelFormat.TRANSLUCENT);
        mLocalView.setZOrderOnTop(true);
        mLocalView.setZOrderMediaOverlay(true);
        AliRtcEngine.AliVideoCanvas aliVideoCanvas = new AliRtcEngine.AliVideoCanvas();
        aliVideoCanvas.view = mLocalView;
        aliVideoCanvas.renderMode = AliRtcRenderModeAuto;
        if (mAliRtcEngine != null) {
            mAliRtcEngine.setLocalViewConfig(aliVideoCanvas, AliRtcVideoTrackCamera);
        }
    }

    private void getAuthAndJoinChannel() {
        if (mAliRtcEngine == null) {
//            Log.e(TAG, "getAuthAndJoinChannel mAliRtcEngine is null");
            return;
        }
        getRTCAuthToken();
    }

    private void joinChannel(AliRtcAuthBean aliRtcAuthBean) {
        if (mAliRtcEngine == null) {
//            Log.e(TAG, "joinChannel mAliRtcEngine is null");
            return;
        }
        if (aliRtcAuthBean == null) {
//            Log.e(TAG, "joinChannel aliRtcAuthBean is null");
            return;
        }
//        Log.e(TAG, "joinChannel start");
        AliRtcAuthInfo userInfo = new AliRtcAuthInfo();

        userInfo.setAppid(aliRtcAuthBean.getAppId());
        userInfo.setNonce(aliRtcAuthBean.getNonce());
        //userInfo.setGslb(new String[]{aliRtcAuthBean.getGslb()});
        userInfo.setGslb(aliRtcAuthBean.getGslb());
        userInfo.setTimestamp(aliRtcAuthBean.getTimeStamp());
        userInfo.setToken(aliRtcAuthBean.getToken());
        userInfo.setConferenceId("" + aliRtcAuthBean.getConferenceId());
        //userInfo.setUserId(SpUtil.getInstace().getString(Contants.USER_ID, ""));
        userInfo.setUserId(aliRtcAuthBean.getUserid());
        /*
         *设置自动发布和订阅，只能在joinChannel之前设置
         *参数1    true表示自动发布；false表示手动发布
         *参数2    true表示自动订阅；false表示手动订阅
         */
        mAliRtcEngine.setAutoPublishSubscribe(true, true);
        // 加入频道，参数1:鉴权信息 参数2:用户名
        String userName = SpUtil.getInstace().getString(Contants.USER_NAME, "");
        mAliRtcEngine.joinChannel(userInfo, userName);
//        Log.e(TAG, "joinChannel end");

    }

    private void joinChannel() {
        if (mAliRtcEngine == null) {
            return;
        }
        //从控制台生成的鉴权信息，具体内容请查阅:https://help.aliyun.com/document_detail/146833.html
        AliRtcAuthInfo userInfo = new AliRtcAuthInfo();
        userInfo.setAppid("6n0dtm01");
//        userInfo.setNonce("AK-fb5d68fd-1882-4ee5-babe-ca021ff85959");
//        userInfo.setGslb(new String[]{"https://rgslb.rtc.aliyuncs.com"});
//        userInfo.setTimestamp(1596702987);
//        userInfo.setToken("f39214ac946cf8701cff832d52dca6f1ee68ab19933d00967035ecd63999f8fb");
//        userInfo.setConferenceId("edu_test");
//        userInfo.setUserId("testId");

//        box
        userInfo.setNonce("AK-9dc2363f-0c42-44a7-9740-251c173dbb21");
        userInfo.setGslb(new String[]{"https://rgslb.rtc.aliyuncs.com"});
        userInfo.setTimestamp(1596703675);
        userInfo.setToken("b70ce142a81ce19e99082057f5601c99383b5c1b2441f455c514c415102073a5");
        userInfo.setConferenceId("edu_test");
        userInfo.setUserId("testId1");
        /*
         *设置自动发布和订阅，只能在joinChannel之前设置
         *参数1    true表示自动发布；false表示手动发布
         *参数2    true表示自动订阅；false表示手动订阅
         */
        mAliRtcEngine.setAutoPublishSubscribe(true, true);
        // 加入频道，参数1:鉴权信息 参数2:用户名
        String userName = "testId1";
        mAliRtcEngine.joinChannel(userInfo, userName);

    }

    private void addRemoteUser(String uid) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //判断用户是否在线
                if (null == mAliRtcEngine) {
                    return;
                }
                AliRtcRemoteUserInfo remoteUserInfo = mAliRtcEngine.getUserInfo(uid);
                if (remoteUserInfo != null) {
                    if (convertRemoteUserToUserData(remoteUserInfo).mCameraSurface != null) {
                        fl_data.removeAllViews();
                        ViewParent parent = convertRemoteUserToUserData(remoteUserInfo).mCameraSurface.getParent();
                        if (parent != null) {
                            if (parent instanceof FrameLayout) {
                                ((FrameLayout) parent).removeAllViews();
                            }
                            fl_data.removeAllViews();
                        }
                        fl_data.addView(convertRemoteUserToUserData(remoteUserInfo).mCameraSurface,
                                new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
                    }
//                    mUserListAdapter.updateData(convertRemoteUserToUserData(remoteUserInfo), true);
                }
            }
        });
    }

    private void removeRemoteUser(String uid) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                fl_data.removeAllViews();
//                mUserListAdapter.removeData(uid, true);
            }
        });
    }

    private void updateRemoteDisplay(String uid, AliRtcEngine.AliRtcAudioTrack at, AliRtcEngine.AliRtcVideoTrack vt) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (null == mAliRtcEngine) {
                    return;
                }
                AliRtcRemoteUserInfo remoteUserInfo = mAliRtcEngine.getUserInfo(uid);
                // 如果没有，说明已经退出了或者不存在。则不需要添加，并且删除
                if (remoteUserInfo == null) {
                    // remote user exit room
//                    Log.e(TAG, "updateRemoteDisplay remoteUserInfo = null, uid = " + uid);
                    return;
                }
                //change
                AliRtcEngine.AliVideoCanvas cameraCanvas = remoteUserInfo.getCameraCanvas();
                AliRtcEngine.AliVideoCanvas screenCanvas = remoteUserInfo.getScreenCanvas();
                //视频情况
                if (vt == AliRtcVideoTrackNo) {
                    //没有视频流
                    cameraCanvas = null;
                    screenCanvas = null;
                } else if (vt == AliRtcVideoTrackCamera) {
                    //相机流
                    screenCanvas = null;
                    cameraCanvas = createCanvasIfNull(cameraCanvas);
                    //SDK内部提供进行播放的view
                    mAliRtcEngine.setRemoteViewConfig(cameraCanvas, uid, AliRtcVideoTrackCamera);
                } else if (vt == AliRtcVideoTrackScreen) {
                    //屏幕流
                    cameraCanvas = null;
                    screenCanvas = createCanvasIfNull(screenCanvas);
                    //SDK内部提供进行播放的view
                    mAliRtcEngine.setRemoteViewConfig(screenCanvas, uid, AliRtcVideoTrackScreen);
                } else if (vt == AliRtcVideoTrackBoth) {
                    //多流
                    cameraCanvas = createCanvasIfNull(cameraCanvas);
                    //SDK内部提供进行播放的view
                    mAliRtcEngine.setRemoteViewConfig(cameraCanvas, uid, AliRtcVideoTrackCamera);
                    screenCanvas = createCanvasIfNull(screenCanvas);
                    //SDK内部提供进行播放的view
                    mAliRtcEngine.setRemoteViewConfig(screenCanvas, uid, AliRtcVideoTrackScreen);
                } else {
                    return;
                }
                ChartUserBean chartUserBean = convertRemoteUserInfo(remoteUserInfo, cameraCanvas, screenCanvas);
                if (chartUserBean.mCameraSurface != null) {
                    fl_data.removeAllViews();
                    ViewParent parent = chartUserBean.mCameraSurface.getParent();
                    if (parent != null) {
                        if (parent instanceof FrameLayout) {
                            ((FrameLayout) parent).removeAllViews();
                        }
                        fl_data.removeAllViews();
                    }
                    fl_data.addView(chartUserBean.mCameraSurface,
                            new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
                }
//                mUserListAdapter.updateData(chartUserBean, true);

            }
        });
    }

    private ChartUserBean convertRemoteUserToUserData(AliRtcRemoteUserInfo remoteUserInfo) {
        String uid = remoteUserInfo.getUserID();
        ChartUserBean ret = new ChartUserBean();
        ret.mUserId = uid;
        ret.mUserName = remoteUserInfo.getDisplayName();
        ret.mIsCameraFlip = false;
        ret.mIsScreenFlip = false;
        return ret;
    }

    private AliRtcEngine.AliVideoCanvas createCanvasIfNull(AliRtcEngine.AliVideoCanvas canvas) {
        if (canvas == null || canvas.view == null) {
            //创建canvas，Canvas为SophonSurfaceView或者它的子类
            canvas = new AliRtcEngine.AliVideoCanvas();
            SophonSurfaceView surfaceView = new SophonSurfaceView(this);
            surfaceView.setZOrderOnTop(false);
            surfaceView.setZOrderMediaOverlay(false);
            canvas.view = surfaceView;
            //renderMode提供四种模式：Auto、Stretch、Fill、Crop，建议使用Auto模式。
            canvas.renderMode = AliRtcRenderModeAuto;
        }
        return canvas;
    }

    private ChartUserBean convertRemoteUserInfo(AliRtcRemoteUserInfo remoteUserInfo,
                                                AliRtcEngine.AliVideoCanvas cameraCanvas,
                                                AliRtcEngine.AliVideoCanvas screenCanvas) {
        String uid = remoteUserInfo.getUserID();
//        ChartUserBean ret = mUserListAdapter.createDataIfNull(uid);
        ChartUserBean ret = new ChartUserBean();
        ret.mUserId = remoteUserInfo.getUserID();

        ret.mUserName = remoteUserInfo.getDisplayName();

        ret.mCameraSurface = cameraCanvas != null ? cameraCanvas.view : null;
        ret.mIsCameraFlip = cameraCanvas != null && cameraCanvas.mirrorMode == AliRtcEngine.AliRtcRenderMirrorMode.AliRtcRenderMirrorModeAllEnabled;

        ret.mScreenSurface = screenCanvas != null ? screenCanvas.view : null;
        ret.mIsScreenFlip = screenCanvas != null && screenCanvas.mirrorMode == AliRtcEngine.AliRtcRenderMirrorMode.AliRtcRenderMirrorModeAllEnabled;

        return ret;
    }

    /**
     * 特殊错误码回调的处理方法
     *
     * @param error 错误码
     */
    private void processOccurError(int error) {
        switch (error) {
            case ERR_ICE_CONNECTION_HEARTBEAT_TIMEOUT:
            case ERR_SESSION_REMOVED:
                noSessionExit(error);
                break;
            default:
                break;
        }
    }

    /**
     * 错误处理
     *
     * @param error 错误码
     */
    private void noSessionExit(int error) {
        runOnUiThread(() -> new AlertDialog.Builder(mContext)
                .setTitle("ErrorCode : " + error)
                .setMessage("发生错误，请退出房间")
                .setPositiveButton("确定", (dialog, which) -> {
                    dialog.dismiss();
                    onBackPressed();
                })
                .create()
                .show());
    }

    /**
     * 用户操作回调监听(回调接口都在子线程)
     */
    private AliRtcEngineEventListener mEventListener = new AliRtcEngineEventListener() {

        /**
         * 加入房间的回调
         * @param result 结果码
         */
        @Override
        public void onJoinChannelResult(int result) {
            runOnUiThread(() -> {
                if (result == 0) {
                    showToast("加入频道成功");
                } else {
                    showToast("加入频道失败 错误码: " + result);
//                    Log.e(TAG, "onJoinChannelResult " + result);
                }
            });
        }

        /**
         * 订阅成功的回调
         * @param s userid
         * @param i 结果码
         * @param aliRtcVideoTrack 视频的track
         * @param aliRtcAudioTrack 音频的track
         */
        @Override
        public void onSubscribeResult(String s, int i, AliRtcEngine.AliRtcVideoTrack aliRtcVideoTrack,
                                      AliRtcEngine.AliRtcAudioTrack aliRtcAudioTrack) {
            if (i == 0) {
                updateRemoteDisplay(s, aliRtcAudioTrack, aliRtcVideoTrack);
            }
        }

        /**
         * 取消的回调
         * @param i 结果码
         * @param s userid
         */
        @Override
        public void onUnsubscribeResult(int i, String s) {
            updateRemoteDisplay(s, AliRtcAudioTrackNo, AliRtcVideoTrackNo);
        }

        /**
         * 出现错误的回调
         * @param error 错误码
         */
        @Override
        public void onOccurError(int error) {
            //错误处理
            processOccurError(error);
        }
    };

    /**
     * SDK事件通知(回调接口都在子线程)
     */
    private AliRtcEngineNotify mEngineNotify = new AliRtcEngineNotify() {
        /**
         * 远端用户停止发布通知，处于OB（observer）状态
         * @param aliRtcEngine 核心引擎对象
         * @param s userid
         */
        @Override
        public void onRemoteUserUnPublish(AliRtcEngine aliRtcEngine, String s) {
            updateRemoteDisplay(s, AliRtcAudioTrackNo, AliRtcVideoTrackNo);
        }

        /**
         * 远端用户上线通知
         * @param s userid
         */
        @Override
        public void onRemoteUserOnLineNotify(String s) {
            addRemoteUser(s);
        }

        /**
         * 远端用户下线通知
         * @param s userid
         */
        @Override
        public void onRemoteUserOffLineNotify(String s) {
            removeRemoteUser(s);
        }

        /**
         * 远端用户发布音视频流变化通知
         * @param s userid
         * @param aliRtcAudioTrack 音频流
         * @param aliRtcVideoTrack 相机流
         */
        @Override
        public void onRemoteTrackAvailableNotify(String s, AliRtcEngine.AliRtcAudioTrack aliRtcAudioTrack,
                                                 AliRtcEngine.AliRtcVideoTrack aliRtcVideoTrack) {
            updateRemoteDisplay(s, aliRtcAudioTrack, aliRtcVideoTrack);
        }
    };

//    private ChartUserAdapter.OnSubConfigChangeListener mOnSubConfigChangeListener = new ChartUserAdapter.OnSubConfigChangeListener() {
//        @Override
//        public void onFlipView(String uid, int flag, boolean flip) {
//            AliRtcRemoteUserInfo userInfo = mAliRtcEngine.getUserInfo(uid);
//            switch (flag) {
//                case CAMERA:
//                    if (userInfo != null) {
//                        AliRtcEngine.AliVideoCanvas cameraCanvas = userInfo.getCameraCanvas();
//                        if (cameraCanvas != null) {
//                            cameraCanvas.mirrorMode = flip ? AliRtcEngine.AliRtcRenderMirrorMode.AliRtcRenderMirrorModeAllEnabled : AliRtcEngine.AliRtcRenderMirrorMode.AliRtcRenderMirrorModeAllDisable;
//                            mAliRtcEngine.setRemoteViewConfig(cameraCanvas, uid, AliRtcVideoTrackCamera);
//                        }
//                    }
//                    break;
//                case SCREEN:
//                    if (userInfo != null) {
//                        AliRtcEngine.AliVideoCanvas screenCanvas = userInfo.getScreenCanvas();
//                        if (screenCanvas != null) {
//                            screenCanvas.mirrorMode = flip ? AliRtcEngine.AliRtcRenderMirrorMode.AliRtcRenderMirrorModeAllEnabled : AliRtcEngine.AliRtcRenderMirrorMode.AliRtcRenderMirrorModeAllDisable;
//                            mAliRtcEngine.setRemoteViewConfig(screenCanvas, uid, AliRtcVideoTrackScreen);
//                        }
//                    }
//                    break;
//            }
//        }
//
//        @Override
//        public void onShowVideoInfo(String uid, int flag) {
//            AliRtcEngine.AliRtcVideoTrack track = AliRtcVideoTrackNo;
//            switch (flag) {
//                case CAMERA:
//                    track = AliRtcVideoTrackCamera;
//                    break;
//                case SCREEN:
//                    track = AliRtcVideoTrackScreen;
//                    break;
//            }
//            if (mAliRtcEngine != null) {
//                String result = mAliRtcEngine.getMediaInfoWithUserId(uid, track, VIDEO_INFO_KEYS);
//
//                Toast.makeText(AlivcPlayerActivity.this, result, Toast.LENGTH_SHORT).show();
//            }
//        }
//    };

    private void initViewForPop(View contentView) {
        mLocalView = contentView.findViewById(R.id.pop_sf_local_view);
        //mRemoteView = contentView.findViewById(R.id.pop_remote_view);
        // 承载远程User的Adapter
//        mUserListAdapter = new ChartUserAdapter();
//        RecyclerView chartUserListView = contentView.findViewById(R.id.pop_chart_content_userlist);
//        LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
//        chartUserListView.setLayoutManager(layoutManager);
//        chartUserListView.addItemDecoration(new BaseRecyclerViewAdapter.DividerGridItemDecoration(
//                getResources().getDrawable(R.drawable.chart_content_userlist_item_divider)));
//        DefaultItemAnimator anim = new DefaultItemAnimator();
//        anim.setSupportsChangeAnimations(false);
//        chartUserListView.setItemAnimator(anim);
//        chartUserListView.setAdapter(mUserListAdapter);
//        mUserListAdapter.setOnSubConfigChangeListener(mOnSubConfigChangeListener);
    }
}
