package com.beanpodtech.allinone.activity;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.PaintDrawable;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
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.bean.AliRtcAuthBean;
import com.beanpodtech.allinone.bean.AnswerBean;
import com.beanpodtech.allinone.bean.ChartUserBean;
import com.beanpodtech.allinone.bean.QuestionBean;
import com.beanpodtech.allinone.http.UrlConfig;
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.PlayVideoUtils;
import com.beanpodtech.allinone.utils.SpUtil;
import com.bumptech.glide.Glide;
import com.lzy.okgo.model.Response;

import org.webrtc.sdk.SophonSurfaceView;

import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
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 QAFullScreenActivity extends BaseActivity {
    /**
     * 视频Id
     */
    private static final String VIDEOID = "videoId";
    /**
     * 课程Id
     */
    private static final String COURSEID = "courseId";
    /**
     * 跳转时间点
     */
    private static final String SEEKTOPOINT = "seekToPoint";
    private ListView lvSmartqaData;
    //    private EditText etMinute;
//    private EditText etSecond;
//    private TextView tvFindbypoint;
    private View llFootview;
    //    private RecyclerView rcvTestquestion;
//    private TextView tvFindbytest;
    private EditText edKeyword;
    private ImageView tvFindbykeyword;
    private LinearLayout llAnswer;
    private TextView tvAnswerContent;
    private String testQuestionId;
    private QuestionAdapter adapterQuestion;
    private List<QuestionBean.ListBean> listQuestion = new ArrayList<>();
    private String videoId;
    private Button btnExit;
    private Button btnReturn;
    private String courseId;
    private long seekToPoint;
    private TextView tvAnswerTitleAnswer;
    private ImageView tvManualAnswering;
    private View footView;
    //    private TextView tv_answer_title;
    private MyHandler handler;
    private Button btn_return_popup;
    /**
     * 是否在1对1聊天
     */
    private boolean isVideoing = false;
    private ImageView ivAnswerContent;

    public static void startActivity(Context context, String videoId, String courseId, long seekToPoint) {
        Intent intent = new Intent(context, QAFullScreenActivity.class);
        intent.putExtra(VIDEOID, videoId);
        intent.putExtra(COURSEID, courseId);
        intent.putExtra(SEEKTOPOINT, seekToPoint);
        context.startActivity(intent);
    }


    @Override
    public void widgetClick(View v) {
        switch (v.getId()) {
            case R.id.btn_exit:
                finish();
                break;
            case R.id.btn_return:
                PlayVideoUtils.getInstance().setVideoId(videoId).setContext(mContext).setSeekToPoint(seekToPoint).setCourseId(courseId).setType(PlayVideoUtils.NORMAL_VIDEO).setIsNeedRecord(true).build();
                finish();
                break;
            case R.id.btn_return_popup:
                if (isVideoing) {
                    new AlertDialog.Builder(QAFullScreenActivity.this)
                            .setTitle("提示")
                            .setMessage("确定断开视频答疑？")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加"Yes"按钮
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    if (mAliRtcEngine != null) {
                                        //mAliRtcEngine.leaveChannel();
                                        mAliRtcEngine.destroy();
                                        mAliRtcEngine = null;
                                    }
                                    popupWindowForRTC.dismiss();
                                    PlayVideoUtils.getInstance().setVideoId(videoId).setContext(mContext).setSeekToPoint(seekToPoint).setCourseId(courseId).setType(PlayVideoUtils.NORMAL_VIDEO).setIsNeedRecord(true).build();
                                    finish();
                                }
                            }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    }).create().show();
                } else {
                    SpUtil.getInstace().save(Contants.IS_NEED_QUEUE, true);
                    popupWindowForRTC.dismiss();
                    PlayVideoUtils.getInstance().setVideoId(videoId).setContext(mContext).setSeekToPoint(seekToPoint).setCourseId(courseId).setType(PlayVideoUtils.NORMAL_VIDEO).setIsNeedRecord(true).build();
                }
                break;
            default:
                break;
        }
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_q_a_full_screen;
    }

    @Override
    public void initView(View view) {
        initFootView();
        SmartQAClick smartQAClick = new SmartQAClick();
//        llFootview = findViewById(R.id.ll_footview);
//        llAnswer = findViewById(R.id.ll_answer);
//        tv_answer_title = findViewById(R.id.tv_answer_title);
//        tvAnswerContent = findViewById(R.id.tv_answer_content);
        lvSmartqaData = findViewById(R.id.lv_smartqa_data);
        adapterQuestion = new QuestionAdapter(listQuestion, this);
        lvSmartqaData.setAdapter(adapterQuestion);
//        etMinute = findViewById(R.id.et_minute);
//        etSecond = findViewById(R.id.et_second);
//        tvFindbypoint = findViewById(R.id.tv_findbypoint);
//        rcvTestquestion = findViewById(R.id.rcv_testquestion);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
//        rcvTestquestion.setLayoutManager(linearLayoutManager);
//        rcvTestquestion.setAdapter(adapterTestQuestion);
//        tvFindbytest = findViewById(R.id.tv_findbytest);
        edKeyword = findViewById(R.id.ed_keyword);
        tvFindbykeyword = findViewById(R.id.tv_findbykeyword);
//        tvFindbypoint.setOnClickListener(smartQAClick);
//        tvFindbytest.setOnClickListener(smartQAClick);
        tvFindbykeyword.setOnClickListener(smartQAClick);
        btnExit = findViewById(R.id.btn_exit);
        btnReturn = findViewById(R.id.btn_return);
        TextView tvTime = findViewById(R.id.tv_time);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
        Date date = new Date(System.currentTimeMillis());
        tvTime.setText(simpleDateFormat.format(date));
        rlRoot = findViewById(R.id.ll_root);
        findViewById(R.id.tv_manual_answering).setOnClickListener(smartQAClick);
        lvSmartqaData.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                try {
                    getAnswerFromNet(((QuestionBean.ListBean) parent.getItemAtPosition(position)).getQuestionId(), position);
                } catch (NullPointerException e) {

                }
            }
        });
        lvSmartqaData.addFooterView(footView);
        initPopupWindowForRTC();
    }

    private void initFootView() {
        footView = getLayoutInflater().inflate(R.layout.footview_smartqa, null);
//        llAnswer = footView.findViewById(R.id.ll_answer);
        llFootview = footView.findViewById(R.id.ll_footview);
        llAnswer = footView.findViewById(R.id.ll_answer);
        ivAnswerContent = footView.findViewById(R.id.iv_answer_content);
        tvAnswerTitleAnswer = footView.findViewById(R.id.tv_answer_title);
        tvAnswerContent = footView.findViewById(R.id.tv_answer_content);
        tvManualAnswering = footView.findViewById(R.id.tv_manual_answering);
    }

    @Override
    public void initListener() {
        btnExit.setOnClickListener(this);
        btnReturn.setOnClickListener(this);
    }

    @Override
    public void initData(Context mContext) {
        handler = new MyHandler(this);
        videoId = getIntent().getStringExtra(VIDEOID);
        courseId = getIntent().getStringExtra(COURSEID);
        seekToPoint = getIntent().getLongExtra(SEEKTOPOINT, 0);
    }

    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);
                        lvSmartqaData.setSelection(adapterQuestion.getCount() - 1);
                        if (body.getAnswerType() == 1) {
                            ivAnswerContent.setVisibility(View.VISIBLE);
                            tvAnswerContent.setVisibility(View.GONE);
                            Glide.with(mContext).load(body.getAnswerContent()).into(ivAnswerContent);
                        } else {
                            ivAnswerContent.setVisibility(View.GONE);
                            tvAnswerContent.setVisibility(View.VISIBLE);
                            tvAnswerContent.setText(body.getAnswerContent());
                        }
                    }
                }
            }

            @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:

                    getAuthAndJoinChannel();
                    popupWindowForRTC.showAtLocation(rlRoot, Gravity.TOP, 0, 0);
//                    getQueueInfo();
                    break;
            }
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        popupWindowForRTC.showAtLocation(rlRoot, Gravity.TOP, 0, 0);
    }

    int queue = 10;

    private void getQueueInfo() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (queue > 0) {
                    Message message = Message.obtain();
                    message.what = 0;
                    message.arg1 = queue;
                    handler.sendMessageDelayed(message, 2000);
                    queue--;
                    QAFullScreenActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tvExclusion.setText(getString(R.string.exclusion) + "\n您的前面还有" + queue + "人");
                        }
                    });


                } else {
                    handler.removeMessages(0);
                }
            }
        }).start();
    }

//    /**
//     * 获取例题
//     */
//    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());
//                    }
//                    adapterQuestion.notifyDataSetChanged();
//                }


                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) {
//                        tv_answer_title.setVisibility(View.VISIBLE);
//                    }
                    adapterQuestion.notifyDataSetChanged();
                    footView.setVisibility(View.VISIBLE);
                    lvSmartqaData.setSelection(0);
                }
            }

            @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 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 LinearLayout rlRoot;
    private FrameLayout fl_data;
    private TextView tvExclusion;

    private void initPopupWindowForRTC() {
        View contentView = LayoutInflater.from(this).inflate(R.layout.popupwindow_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);
        tvExclusion = contentView.findViewById(R.id.tv_exclusion);
        fl_data = contentView.findViewById(R.id.fl_data);
        btn_return_popup = contentView.findViewById(R.id.btn_return_popup);
        popupWindowForRTC = new PopupWindow(this);
        popupWindowForRTC.setContentView(contentView);
        popupWindowForRTC.setWidth(RelativeLayout.LayoutParams.MATCH_PARENT);
        popupWindowForRTC.setHeight(RelativeLayout.LayoutParams.MATCH_PARENT);
        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();
            }
        });
        btn_return_popup.setOnClickListener(this);
    }

    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();
        }
    }

    public 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");
//            Log.d(TAG, "initRTCEngineAndStartPreview ");
            //实例化,必须在主线程进行。
            mAliRtcEngine = AliRtcEngine.getInstance(getApplicationContext());
            //设置事件的回调监听
            mAliRtcEngine.setRtcEngineEventListener(mEventListener);
            //设置接受通知事件的回调
            mAliRtcEngine.setRtcEngineNotify(mEngineNotify);
            // 初始化本地视图
            initLocalView();
            //开启预览
            startPreview();
            //加入频道
            //joinChannel();
        }
        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);
        getQueueInfo();
//        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);
                }
                tvExclusion.setText(R.string.rtc_with_teacher);
                isVideoing = true;
            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isVideoing = false;
    }

    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);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (popupWindowForRTC != null && popupWindowForRTC.isShowing()) {
                if (mAliRtcEngine != null) {
                    //mAliRtcEngine.leaveChannel();
                    mAliRtcEngine.destroy();
                    mAliRtcEngine = null;
                }
                popupWindowForRTC.dismiss();
            } else {
                finish();
            }
        }
        return false;
//        return super.onKeyDown(keyCode, event);
    }

    class MyHandler extends Handler {
        WeakReference<Activity> mActivityReference;

        MyHandler(Activity activity) {
            mActivityReference = new WeakReference<Activity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            final Activity activity = mActivityReference.get();
            if (activity != null) {
                switch (msg.what) {
                    case 0:
                        Log.i("TAG", "=====queue=" + msg.arg1);
                        getQueueInfo();
                        break;
                }
            }
        }
    }


}
