package com.beanpodtech.allinone.activity;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.PaintDrawable;
import android.os.Build;
import android.os.Bundle;

import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
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.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
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 com.aliyun.player.IPlayer;
import com.aliyun.player.alivcplayerexpand.bean.LongVideoBean;
import com.aliyun.player.alivcplayerexpand.listener.OnScreenCostingSingleTagListener;
import com.aliyun.player.alivcplayerexpand.listener.QualityValue;
import com.aliyun.player.alivcplayerexpand.util.AliyunScreenMode;
import com.aliyun.player.alivcplayerexpand.util.ScreenUtils;
import com.aliyun.player.alivcplayerexpand.view.choice.AlivcShowMoreDialog;
import com.aliyun.player.alivcplayerexpand.view.control.ControlView;
import com.aliyun.player.alivcplayerexpand.view.dlna.callback.OnDeviceItemClickListener;
import com.aliyun.player.alivcplayerexpand.view.dot.AlivcDotMsgDialogFragment;
import com.aliyun.player.alivcplayerexpand.view.dot.DotView;
import com.aliyun.player.alivcplayerexpand.view.gesturedialog.BrightnessDialog;
import com.aliyun.player.alivcplayerexpand.view.more.AliyunShowMoreValue;
import com.aliyun.player.alivcplayerexpand.view.more.DanmakuSettingView;
import com.aliyun.player.alivcplayerexpand.view.more.ScreenCostView;
import com.aliyun.player.alivcplayerexpand.view.softinput.SoftInputDialogFragment;
//import com.aliyun.player.alivcplayerexpand.widget.AliyunVodPlayerView;
import com.aliyun.player.bean.InfoCode;
import com.aliyun.player.nativeclass.TrackInfo;
import com.aliyun.player.source.UrlSource;
import com.beanpodtech.allinone.BuildConfig;
import com.beanpodtech.allinone.adapter.QuestionPopupAdapter;
import com.beanpodtech.allinone.adapter.SmartQAAdapter;
import com.beanpodtech.allinone.adapter.TestQuestionAdapter;
import com.beanpodtech.allinone.adapter.VideoSceneAdapter;
import com.beanpodtech.allinone.bean.AliVideoBean;
import com.beanpodtech.allinone.bean.AnswerBean;
import com.beanpodtech.allinone.bean.BarrageBean;
import com.beanpodtech.allinone.bean.BaseRequestBean;
import com.beanpodtech.allinone.bean.KonwledgeBean;
import com.beanpodtech.allinone.bean.QaReqResponseBean;
import com.beanpodtech.allinone.bean.QaWaittingInfoBean;
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.service.TimeCounterService;
import com.beanpodtech.allinone.utils.BoxUtil;
import com.beanpodtech.allinone.utils.ChatUiHelper;
import com.beanpodtech.allinone.utils.Contants;
import com.beanpodtech.allinone.utils.EmojiUtils;
import com.beanpodtech.allinone.utils.FileUtil;
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.utils.TimeCounter;
import com.beanpodtech.allinone.widget.AliyunVodPlayerView;
import com.aliyun.player.bean.InfoBean;
import com.aliyun.player.nativeclass.MediaInfo;
import com.aliyun.player.source.VidSts;
//import com.aliyun.solution.longvideo.R;
import com.beanpodtech.allinone.R;
import com.aliyun.svideo.common.utils.ToastUtils;
//import com.aliyun.utils.VcPlayerLog;
import com.beanpodtech.allinone.widget.IndicatorView;
import com.beanpodtech.allinone.widget.ShowMoreView;
import com.beanpodtech.allinone.widget.StateButton;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.JsonObject;
import com.lzy.okgo.model.Response;

import org.jetbrains.annotations.NotNull;
import org.xwalk.core.XWalkResourceClient;
import org.xwalk.core.XWalkView;
import org.webrtc.sdk.SophonSurfaceView;
import org.xwalk.core.XWalkWebResourceRequest;
import org.xwalk.core.XWalkWebResourceResponse;

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 cn.eeo.classinsdk.ClassInSdkManager;
import cn.eeo.classinsdk.support.ScreenOrientation;
import okhttp3.RequestBody;

//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 AlivcPlayerActivity extends AppCompatActivity /*implements AliyunDownloadInfoListener*/ {
    /**
     * 课程Id
     */
    private static final String COURSEID = "courseId";
    /**
     * 视频Id
     */
    private static final String VIDEOID = "videoId";
    /**
     * 是否是试看
     */
    private static final String ISTRY = "isTry";
    /**
     * 需要跳转到的时间点
     */
    private static final String SEEKTOPOINT = "seekToPoint";
    /**
     * 试看时间2分钟
     */
    private static final int tryTime = 2 * 60 * 1000;
    private static final String ISNEEDTIMING = "isNeedTiming";
    private static final String TAG = "Edu_AlivcPlayerActivity";
    public static final String INTENT_PLAY_MEDIA = "intent_play_media";
    public static final String ISSPEED = "isSpeed";
    public static final String ISBackViewFree = "isBackViewFree"; // 是否开启回看不计费模式
    public Context mContext = this;
    private String courseId;
    private String videoId;
    private long seekToPoint = 0;
    private boolean isNeedTiming;
    private TextView tv_showinfo;
    private TextView tv_classinWaittingInfo;
    private LeftTimeReceiver receiver;
    /**
     * 最大缓存时间单位S
     */
    private static final int MAX_DURATION_CACHE = 600 * 60;
    /**
     * 最大缓存大小 单位MB
     */
    private static final int MAX_SIZE_CACHE = 15 * 1000;
    //    private static final String CACHE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/hongwen_video_cache";
    private static String CACHE_PATH;
    /**
     * 是否是试看视频
     */
    private boolean isTry;
    private AlertDialog dialogTry;
    private AlertDialog dialogLeftTime;
    private AlertDialog dialogLoginError;
    private RelativeLayout rlRoot;

    private long playingTime = 0; // total 播放时长(现实时间线中的时长，非所看视频时长) 包括重复播放、收费、不收费都算上
    // ======================== 倍速播放有效时长计算 =======================
    // 开启倍速之后 实际观看视频花费的时间(收费时长，有效时长)
    // 在 onInfo中 每过视频的60s 计算一次，在onStop中计算一次，在视频播放完成监听中计算一次
    private int validPlayTimeBySpeedMills = 0;
    // 用来记录 不同播放速度的 视频的每一秒（需要计费的秒）有多少个
    private int speed1SecondsSize = 0; //  使用1倍速观看视频 所花费的秒数
    private int speed125SecondsSize = 0;//  使用1.25倍速观看视频 所花费的秒数
    private int speed15SecondsSize = 0;//  使用1.5倍速观看视频 所花费的秒数
    private int speed2SecondsSize = 0;//  使用2倍速观看视频 所花费的秒数
    //================================弹幕相关=================================//
    private RelativeLayout rl_position1;
    private RelativeLayout rl_position2;
    private RelativeLayout rl_position3;
    private RelativeLayout rl_position4;
    private RelativeLayout rl_position5;
    private LinearLayout llBarrage;
    private TextView tvBarrage;
    private ImageView ivGif;
    private Animation animation;
    private FrameLayout fl_data;
    private List<BarrageBean.ListBean> listBarrage = new ArrayList<>();
    private int SEEKTOPOINT_MIN = 10 * 1000;
    private TextView tvTime;
    //    private ImageView ivAnswerContent;
    private long mCurrentPosition; // 视频当前播放位置
    private long mLessonId;

    private PopupWindow popVideoSecen; // 知识点 弹窗
    private TextView tvChooseKnowledge;
    private boolean isSpeed;
    final static String FROM_FREE = "fromfree"; // 来自免费体验区的
    final static String FREE_URL = "freeUrl"; // 来自免费体验区的
    boolean fromFree = false;  // 是否是免费体验课
    boolean isBackview = true;  // 默认回看免费
    private XWalkView webView;
    private int number;  // 排队人数


    /*
     *  免费体验课用的
     * */
    public static void startAlivcPlayerActivity(Context context, String url, boolean fromFree) {
        Intent intent = new Intent(context, AlivcPlayerActivity.class);
        intent.putExtra(FROM_FREE, fromFree);
        intent.putExtra(FREE_URL, url);
        context.startActivity(intent);
    }

    /*
     *  不计时  不是试看 （企业介绍视频等）
     * */
    public static void startAlivcPlayerActivity(Context context,
                                                AliVideoBean bean,
                                                String courseId,
                                                String videoId) {

        Intent intent = new Intent(context, AlivcPlayerActivity.class);
        intent.putExtra(INTENT_PLAY_MEDIA, bean);
        intent.putExtra(COURSEID, courseId);
        intent.putExtra(VIDEOID, videoId);

        intent.putExtra(ISTRY, false);//不是试看
        intent.putExtra(ISNEEDTIMING, false);//不计时

        context.startActivity(intent);
    }

    /**
     * @param context     上下文
     * @param bean        播放bean
     * @param courseId    课程Id
     * @param videoId     视频id
     * @param isTry       是否试看
     * @param seetToPoint 播放时间点
     */
    public static void startAlivcPlayerActivity(Context context,
                                                AliVideoBean bean,
                                                String courseId,
                                                String videoId,
                                                boolean isTry,
                                                long seetToPoint) {

        Intent intent = new Intent(context, AlivcPlayerActivity.class);
        intent.putExtra(INTENT_PLAY_MEDIA, bean);
        intent.putExtra(COURSEID, courseId);
        intent.putExtra(VIDEOID, videoId);
        intent.putExtra(ISTRY, isTry);
        intent.putExtra(SEEKTOPOINT, seetToPoint);

        intent.putExtra(ISNEEDTIMING, bean.isNeedTiming()); // 是否计时
        intent.putExtra(ISBackViewFree, bean.isBackView()); // 是否回看免费
        intent.putExtra(ISSPEED, bean.isSpeed()); // 是否显示倍速
        context.startActivity(intent);
    }


    /**
     * 播放视频的实体类
     */
    private AliVideoBean bean;

    /**
     * 播放器的View
     */
    private AliyunVodPlayerView mAliyunVodPlayerView;
    /**
     * Vid,TvId,视频标题,封面,剧集封面,sp默认清晰度
     */
    private String mVid, mTvId, mVideoTitle, mCoverUrl, mTvCoverUrl;

    /**
     * 判断是不是单集，系列，vip，本地视频，sp是否是vip，sp默认清晰度，sp是否开启硬解，sp 4g下载是否打开,sp是否运营商自动运行
     */
    private boolean mIsVip, mIsLocal,
            mSettingSpUtilsOperatorPlay;

    /**
     * 打点信息DialogFragment
     */
    private AlivcDotMsgDialogFragment mAlivcDotMsgDialogFragment;

    /**
     * 防止快速点击
     */

    private com.aliyun.player.source.VidAuth mAliyunPlayAuth;
    private long oldTime;

    /**
     * 全屏展示更多Dialog,弹幕设置Dialog
     */
    private AlivcShowMoreDialog showMoreDialog, danmakuShowMoreDialog;
    /**
     * 投屏选择Dialog
     */
    private AlivcShowMoreDialog screenShowMoreDialog;

    private ScreenCostView mScreenCostView;
    /**
     * 弹幕透明度、显示区域、速率progress
     */
    private int mAlphProgress = 0, mRegionProgress = 0, mSpeedProgress = 30;


    /**
     * 点击发送弹幕的画笔弹出的dialog
     */
    private SoftInputDialogFragment mSoftInputDialogFragment;
    /**
     * 猜你喜欢
     */
    private List<LongVideoBean> mSimilarVideoList;
    /**
     * VidSts
     */
    private VidSts mVidSts;
    /**
     * 猜你喜欢当前播放的position
     */
    private int mCurrentSimilarVideoPosition = 0;
    /**
     * loading进度
     */
//    private ProgressBar mLoadingProgressBar;
    /**
     * 是否需要刷新播放界面底部猜你喜欢视频列表,默认是需要刷新
     */
    private boolean mNeedToRefreshVideoLists = true;

    public int currentplayingTime = 0;  // 当前视频走的秒数  每大于60s 上传一次（每60s重置为0）
    public int counterForSaveNative = 0;

    //===================================RTC video Q&A========================
    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 LinearLayout ll_local;
    private ImageView iv_switch;
    //    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 MyHandler handler;

    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 final static int SMALL_SIZE = 0;
    private final static int MIDDLE_SIZE = 1;
    private final static int BIG_SIZE = 2;
    private final static int MIDDLE_WIDTH = 810;
    private final static int BIG_WIDTH = 1920;
    private final static int BIG_HEIGHT = 1080;
    private final static int offs = 555;
    /**
     * 视频尺寸 默认0 小窗  1中屏  2大屏
     */
    private int screenSize = SMALL_SIZE;

    private final static int NORMAL = 0;
    private final static int SWITCH = 1;
    private int isSwitchSmall = NORMAL;
    private int isSwitchMiddle = NORMAL;
    private int isSwitchBig = NORMAL;
    private int isSwitchAll = NORMAL;

    private void switchVideo(int screenSize) {
        RelativeLayout.LayoutParams params;
        switch (screenSize) {
            case SMALL_SIZE:
                if (isSwitchSmall == NORMAL) {
                    params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, (int) getResources().getDimension(R.dimen.y400));
                    params.addRule(RelativeLayout.BELOW, R.id.tv_bigscreen);
                    ll_local.setLayoutParams(params);
                    params = new RelativeLayout.LayoutParams((int) getResources().getDimension(R.dimen.x150), (int) getResources().getDimension(R.dimen.y150));
                    params.addRule(RelativeLayout.BELOW, R.id.tv_bigscreen);
                    params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                    fl_data.setLayoutParams(params);
                    SophonSurfaceView surfaceView = (SophonSurfaceView) fl_data.getChildAt(0);
                    if (surfaceView != null) {
                        surfaceView.setZOrderOnTop(true);
                        surfaceView.setZOrderMediaOverlay(true);
                    }
                    fl_data.bringToFront();
                    mLocalView.setZOrderOnTop(false);
                    mLocalView.setZOrderMediaOverlay(false);
                    isSwitchSmall = SWITCH;
                    isSwitchAll = SWITCH;
                } else {
                    params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, (int) getResources().getDimension(R.dimen.y400));
                    params.addRule(RelativeLayout.BELOW, R.id.tv_bigscreen);
                    fl_data.setLayoutParams(params);
                    params = new RelativeLayout.LayoutParams((int) getResources().getDimension(R.dimen.x150), (int) getResources().getDimension(R.dimen.y150));
                    params.addRule(RelativeLayout.BELOW, R.id.tv_bigscreen);
                    params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                    ll_local.setLayoutParams(params);
                    SophonSurfaceView surfaceView = (SophonSurfaceView) fl_data.getChildAt(0);
                    if (surfaceView != null) {
                        surfaceView.setZOrderOnTop(false);
                        surfaceView.setZOrderMediaOverlay(false);
                    }
                    ll_local.bringToFront();
                    mLocalView.setZOrderOnTop(true);
                    mLocalView.setZOrderMediaOverlay(true);
                    isSwitchSmall = NORMAL;
                    isSwitchAll = NORMAL;
                }
                break;
            case MIDDLE_SIZE:
                if (isSwitchMiddle == NORMAL) {
                    params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, (int) getResources().getDimension(R.dimen.y900));
                    params.addRule(RelativeLayout.BELOW, R.id.tv_bigscreen);
                    ll_local.setLayoutParams(params);
                    params = new RelativeLayout.LayoutParams((int) getResources().getDimension(R.dimen.x300), (int) getResources().getDimension(R.dimen.y300));
                    params.addRule(RelativeLayout.BELOW, R.id.tv_bigscreen);
                    params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                    fl_data.setLayoutParams(params);
                    SophonSurfaceView surfaceView = (SophonSurfaceView) fl_data.getChildAt(0);
                    if (surfaceView != null) {
                        surfaceView.setZOrderOnTop(true);
                        surfaceView.setZOrderMediaOverlay(true);
                    }
                    fl_data.bringToFront();
                    mLocalView.setZOrderOnTop(false);
                    mLocalView.setZOrderMediaOverlay(false);
                    isSwitchMiddle = SWITCH;
                    isSwitchAll = SWITCH;
                } else {
                    params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, (int) getResources().getDimension(R.dimen.y900));
                    params.addRule(RelativeLayout.BELOW, R.id.tv_bigscreen);
                    fl_data.setLayoutParams(params);
                    params = new RelativeLayout.LayoutParams((int) getResources().getDimension(R.dimen.x300), (int) getResources().getDimension(R.dimen.y300));
                    params.addRule(RelativeLayout.BELOW, R.id.tv_bigscreen);
                    params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                    ll_local.setLayoutParams(params);
                    SophonSurfaceView surfaceView = (SophonSurfaceView) fl_data.getChildAt(0);
                    if (surfaceView != null) {
                        surfaceView.setZOrderOnTop(false);
                        surfaceView.setZOrderMediaOverlay(false);
                    }
                    ll_local.bringToFront();
                    mLocalView.setZOrderOnTop(true);
                    mLocalView.setZOrderMediaOverlay(true);
                    isSwitchMiddle = NORMAL;
                    isSwitchAll = NORMAL;
                }
                break;
            case BIG_SIZE:
                if (isSwitchBig == NORMAL) {
                    params = new RelativeLayout.LayoutParams((int) getResources().getDimension(R.dimen.x1920) - 2 * (int) getResources().getDimension(R.dimen.x350), (int) getResources().getDimension(R.dimen.y900));
                    params.addRule(RelativeLayout.BELOW, R.id.tv_bigscreen);
                    params.addRule(RelativeLayout.CENTER_HORIZONTAL);
                    ll_local.setLayoutParams(params);
                    params = new RelativeLayout.LayoutParams((int) getResources().getDimension(R.dimen.x350), (int) getResources().getDimension(R.dimen.y350));
                    params.addRule(RelativeLayout.BELOW, R.id.tv_bigscreen);
                    params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                    fl_data.setLayoutParams(params);
                    SophonSurfaceView surfaceView = (SophonSurfaceView) fl_data.getChildAt(0);
                    if (surfaceView != null) {
                        surfaceView.setZOrderOnTop(true);
                        surfaceView.setZOrderMediaOverlay(true);
                    }
                    fl_data.bringToFront();
                    mLocalView.setZOrderOnTop(false);
                    mLocalView.setZOrderMediaOverlay(false);
                    isSwitchBig = SWITCH;
                    isSwitchAll = SWITCH;
                } else {
                    params = new RelativeLayout.LayoutParams((int) getResources().getDimension(R.dimen.x1920) - 2 * (int) getResources().getDimension(R.dimen.x350), (int) getResources().getDimension(R.dimen.y900));
                    params.addRule(RelativeLayout.BELOW, R.id.tv_bigscreen);
                    params.addRule(RelativeLayout.CENTER_HORIZONTAL);
                    fl_data.setLayoutParams(params);
                    params = new RelativeLayout.LayoutParams((int) getResources().getDimension(R.dimen.x350), (int) getResources().getDimension(R.dimen.y350));
                    params.addRule(RelativeLayout.BELOW, R.id.tv_bigscreen);
                    params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                    ll_local.setLayoutParams(params);
                    SophonSurfaceView surfaceView = (SophonSurfaceView) fl_data.getChildAt(0);
                    if (surfaceView != null) {
                        surfaceView.setZOrderOnTop(false);
                        surfaceView.setZOrderMediaOverlay(false);
                    }
                    ll_local.bringToFront();
                    mLocalView.setZOrderOnTop(true);
                    mLocalView.setZOrderMediaOverlay(true);
                    isSwitchBig = NORMAL;
                    isSwitchAll = NORMAL;
                }
                break;
        }
    }


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

    /*****************************classin start*********************************/
    //QaWaittingInfoBean qaWaittingInfoBean = new QaWaittingInfoBean();
    public long classinStartTime;
    public boolean classinWaittingFlag = false;
    public int remainingTime = 0;//second

    private void requestClassin(String knowledgeId) {
        OkGoBuilder.getInstance()
                .url(UrlConfig.REQUEST_MANUAL_ANSWERING)
                .Builder((Activity) mContext)
                .method(OkGoBuilder.PSOT)
                .cls(QaReqResponseBean.class)
                .requestBody(HttpUtils.getRequestJson(getRequestBodyForClassinReq(knowledgeId)))
                .callback(new OkGoUtil<QaReqResponseBean>(QaReqResponseBean.class) {
                    @Override
                    public void onSuccess(Response<QaReqResponseBean> response) {
                        QaReqResponseBean body = response.body();
                        if (body != null) {

                            if (body.getStatus() == -3) { // 答疑功能未开启
                                ToastUtils.show(mContext, "当前校区没有开通答疑功能");
                                return;

                            } else if (body.getStatus() == -4){ // 不在工作时间内
                                ToastUtils.show(mContext, "当前不在答疑的时间内");
                                return;

                            } else {
                                //call get waitting info
                                //joinChannel(body);
                                remainingTime = body.getRemainingTime();
                                //  202103  如果没有余额  不能转人工
                                if (remainingTime > 0) {
                                    classinWaittingFlag = true;
                                    // 排队人数
                                    number = body.getNumber();
                                    getClassinWattingInfo();
                                } else {
                                    classinWaittingFlag = false;
                                    ToastUtils.show(mContext, "您的剩余答疑时长不足，请充值");
                                }
                            }

                        } else {
                            classinWaittingFlag = false;
                            ToastUtils.show(mContext, R.string.neterror);
                        }
                    }

                    @Override
                    public void onError(Response<QaReqResponseBean> response) {
                        super.onError(response);
                        classinWaittingFlag = false;
                    }
                }).build();
    }

    private void getClassinWattingInfo() {
        OkGoBuilder.getInstance()
                .url(UrlConfig.GET_QA_WAITTING_INFO)
                .Builder((Activity) mContext)
                .method(OkGoBuilder.PSOT)
                .cls(QaWaittingInfoBean.class)
                .requestBody(HttpUtils.getRequestJson(getRequestBodyForClassinWatting()))
                .callback(new OkGoUtil<QaWaittingInfoBean>(QaWaittingInfoBean.class) {
                    @Override
                    public void onSuccess(Response<QaWaittingInfoBean> response) {
                        QaWaittingInfoBean body = response.body();
                        if (body != null) {
                            //返回排队信息
//                            Log.d("AAAAA", new Gson().toJson(response.body()) + "");
                            mLessonId = body.getLessonId();
                            getQueueInfoForClassin(body);
                        } else {
                            ToastUtils.show(mContext, R.string.neterror);
                        }
                    }

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

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

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

    private void getQueueInfoForClassin(QaWaittingInfoBean qaWaittingInfoBean) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (qaWaittingInfoBean.getState() != 1) {  // 不成功就继续发消息
                    keepSendingMsg(qaWaittingInfoBean.getCurrentPosition());

                } else {   //  =1  成功
                    number = 0;  // 排队人数重置为0
                    classinWaittingFlag = false;
                    mAliyunVodPlayerView.pause();

                    if (SpUtil.getInstace().getBoolean(Contants.IS_NEED_QUEUE, false)) {
                        AlivcPlayerActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                android.app.AlertDialog dialog = new android.app.AlertDialog.Builder(AlivcPlayerActivity.this)
                                        .setTitle("提示")
                                        .setMessage("老师已准备好，请确认接通")
                                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加"Yes"按钮
                                            @Override
                                            public void onClick(DialogInterface dialogInterface, int i) {
                                                finish();
                                            }
                                        }).create();
                                try {
                                    dialog.show();
                                } catch (Exception ignord) {

                                }
                            }
                        });
                    } else {
                        number = 0;
                        AlivcPlayerActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                AlertDialog alertDialog = new AlertDialog.Builder(AlivcPlayerActivity.this)
                                        .setTitle("提示")
                                        .setMessage("老师已准备好，请确认接通")
                                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加"Yes"按钮
                                            @Override
                                            public void onClick(DialogInterface dialogInterface, int i) {

                                                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 ");
                                                }
                                                String stuName = SpUtil.getInstace().getString(Contants.USER_NICKNAME, null);
                                                try {
                                                    ClassInSdkManager.setEnableEvalPage(true);
                                                    ClassInSdkManager.setEnableSoftDecoder(true);
                                                    ClassInSdkManager.setEnableUdp(false);
                                                    ClassInSdkManager.setDefaultScreenOrientation(ScreenOrientation.LANDSCAPE);
//                                                    Log.d(TAG, "sid " + qaWaittingInfoBean.getSchoolId() + " cid " + qaWaittingInfoBean.getCourseId() + " lid" + qaWaittingInfoBean.getLessonId());
                                                    ClassInSdkManager.openClassRoom((Activity) mContext,
                                                            qaWaittingInfoBean.getAccount(),
                                                            qaWaittingInfoBean.getSchoolId(),
                                                            qaWaittingInfoBean.getCourseId(),
                                                            qaWaittingInfoBean.getLessonId(),
                                                            stuName == null ? "学生" : stuName,
                                                            new ClassInSdkManager.OnEnterRoomStateListener() {

                                                                //ClassInSdkManager.openClassRoom((Activity) mContext, "17740028532", 101110l, 42451, 37449, "dd", new ClassInSdkManager.OnEnterRoomStateListener() {

                                                                @Override
                                                                public void onExitRoom(int i, @NotNull String s) {
                                                                    tv_classinWaittingInfo.setVisibility(View.GONE);
                                                                    long timeSpan = (System.currentTimeMillis() - classinStartTime) / 1000;
                                                                    String timeSpanStr = "";
                                                                    if (timeSpan < 60) {
                                                                        timeSpanStr = timeSpan + "秒";
                                                                    } else if (timeSpan < 3600) {
                                                                        timeSpanStr = (timeSpan / 60) + "分" + (timeSpan % 60) + "秒";
                                                                    } else if (timeSpan > 3600) {
                                                                        timeSpanStr = (timeSpan / (3600)) + "小时" + ((timeSpan / 60) % 60) + "分" + (timeSpan % 60) + "秒";
                                                                    }
                                                                    Toast.makeText(mContext, "Code:" + i + " | " + s + " 耗费时长：" + timeSpanStr, Toast.LENGTH_SHORT).show();
                                                                    overClassinQA(qaWaittingInfoBean.getLessonId(), (int) timeSpan);
                                                                }

                                                                @Override
                                                                public void onEnterSuccess() {
                                                                    tv_classinWaittingInfo.setVisibility(View.GONE);
                                                                    Toast.makeText(mContext, "进入成功", Toast.LENGTH_SHORT).show();
                                                                    classinStartTime = System.currentTimeMillis();
                                                                    entryClassinRoom(qaWaittingInfoBean.getLessonId());
                                                                }

                                                                @Override
                                                                public void onEnterFailed(@NotNull String s) {
                                                                    tv_classinWaittingInfo.setVisibility(View.GONE);
                                                                    Toast.makeText(mContext, s, Toast.LENGTH_SHORT).show();
                                                                }
                                                            });
                                                } catch (Exception e) {
                                                    tv_classinWaittingInfo.setVisibility(View.GONE);
                                                    Toast.makeText(mContext, e.getMessage(), Toast.LENGTH_LONG).show();
                                                }
                                                //changeVideoSize(screenSize);
                                            }
                                        }).create();

                                try {
                                    alertDialog.show();
                                } catch (Exception ignord) {

                                }
                            }
                        });
                    }
                    handler.removeMessages(0);

                    // 202103
               /* } else if (qaWaittingInfoBean.getState() == 6) {
                    handler.removeMessages(0);
                    classinWaittingFlag = false;

                    AlivcPlayerActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tv_classinWaittingInfo.setVisibility(View.GONE);

                            new AlertDialog.Builder(AlivcPlayerActivity.this)
                                    .setTitle("提示")
                                    .setMessage("发起失败，请重新发起")
                                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {

                                        }
                                    }).create().show();
                        }
                    });*/
                }
            }
        }).start();
    }

    // 轮询发起请求
    private void keepSendingMsg(int currPos) {
        Message message = Message.obtain();
        message.what = 0;
        message.arg1 = currPos;
        handler.sendMessageDelayed(message, 5000);
        if (!SpUtil.getInstace().getBoolean(Contants.IS_NEED_QUEUE, false)) {
            AlivcPlayerActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    tv_classinWaittingInfo.setVisibility(View.VISIBLE);
                    tv_classinWaittingInfo.setText(getString(R.string.exclusion_video)
                            + "\n前方有" + number + "人正排队等待,请稍后..。");
                }
            });
        }
    }

    private void cancelClassinReq() {
        OkGoBuilder.getInstance()
                .url(UrlConfig.CANCEL_ANSWER_REQUEST)
                .Builder((Activity) mContext)
                .method(OkGoBuilder.PSOT)
                .cls(BaseRequestBean.class)
                .requestBody(HttpUtils.getRequestJson(getReqBodyForCancelClassinReq()))
                .callback(new OkGoUtil<BaseRequestBean>(BaseRequestBean.class) {
                    @Override
                    public void onSuccess(Response<BaseRequestBean> response) {
                        BaseRequestBean body = response.body();
                        if (body != null) {
                        } else {
//                            ToastUtils.show(mContext, R.string.neterror);
                        }
                    }

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

    private HashMap<String, String> getReqBodyForCancelClassinReq() {
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", SpUtil.getInstace().getString(Contants.USER_ID, null));
        map.put("videoId", videoId);
        if (mLessonId != 0) {
            map.put("lessonId", mLessonId + "");
        }
        return map;
    }

    private void overClassinQA(long lessonId, int timeSpan) {
        OkGoBuilder.getInstance()
                .url(UrlConfig.OVER_MANUAL_ANSWERING)
                .Builder((Activity) mContext)
                .method(OkGoBuilder.PSOT)
                .cls(BaseRequestBean.class)
                .requestBody(HttpUtils.getRequestJson(getReqBodyForOverClassinQA(lessonId, timeSpan)))
                .callback(new OkGoUtil<BaseRequestBean>(BaseRequestBean.class) {
                    @Override
                    public void onSuccess(Response<BaseRequestBean> response) {
                        BaseRequestBean body = response.body();
                        if (body != null) {
                        } else {
                            ToastUtils.show(mContext, R.string.neterror);
                        }
                    }

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

    private HashMap<String, String> getReqBodyForOverClassinQA(long lessonId, int timeSpan) {
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", SpUtil.getInstace().getString(Contants.USER_ID, null));
        map.put("videoId", videoId);
        map.put("lessonId", "" + lessonId);
        map.put("timeSpan", "" + timeSpan);
        return map;
    }

    private void entryClassinRoom(long lessonId) {
        OkGoBuilder.getInstance()
                .url(UrlConfig.ENTRY_CLASSROOM)
                .Builder((Activity) mContext)
                .method(OkGoBuilder.PSOT)
                .cls(BaseRequestBean.class)
                .requestBody(HttpUtils.getRequestJson(getReqBodyForEntryClassinRoom(lessonId)))
                .callback(new OkGoUtil<BaseRequestBean>(BaseRequestBean.class) {
                    @Override
                    public void onSuccess(Response<BaseRequestBean> response) {
                        BaseRequestBean body = response.body();
                        if (body != null) {
                        } else {
                            ToastUtils.show(mContext, R.string.neterror);
                        }
                    }

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

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

    /*****************************classin end*********************************/

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

    //==============================================智能答疑弹窗相关========================================
    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 TextView tvManualAnswering;
    //    private RecyclerView rcvTestquestion;
//    private TextView tvFindbytest;
    private EditText edKeyword;
    private ImageView 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 QuestionPopupAdapter 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 PopupWindow popupWindowLearningFeedback;
    private Dialog dialogChoseMenu;
    private PopupWindow popupWindowTab;

    JsonObject jsonObject = new JsonObject();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        hideStatusBar();
        setContentView(R.layout.activity_alivc_player);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
//        AliPlayer aliyunVodPlayer;
//        aliyunVodPlayer = AliPlayerFactory.createAliPlayer(getApplicationContext());
//        UrlSource urlSource=new UrlSource();
//        urlSource.setUri();
//        aliyunVodPlayer.setDataSource();
        IntentFilter filter = new IntentFilter(Contants.ACTION_SENDLEFT);
        receiver = new LeftTimeReceiver();
        registerReceiver(receiver, filter);

        CACHE_PATH = FileUtil.getPathWithDirname(AlivcPlayerActivity.this, Environment.DIRECTORY_DOCUMENTS, "hongwen_video_cache");

//        mLongVideoBean = (LongVideoBean) getIntent().getSerializableExtra(INTENT_PLAY_MEDIA);
        fromFree = getIntent().getBooleanExtra(FROM_FREE, false);

        bean = (AliVideoBean) getIntent().getSerializableExtra(INTENT_PLAY_MEDIA);
        courseId = getIntent().getStringExtra(COURSEID);
        videoId = getIntent().getStringExtra(VIDEOID);
        isNeedTiming = getIntent().getBooleanExtra(ISNEEDTIMING, true);
        isTry = getIntent().getBooleanExtra(ISTRY, false);
        seekToPoint = getIntent().getLongExtra(SEEKTOPOINT, 0);

        isSpeed = getIntent().getBooleanExtra(ISSPEED, false); // 默认不开启倍速

        isBackview = getIntent().getBooleanExtra(ISBackViewFree, true); // 默认回看免费

//        mAliyunDownloadManager = AliyunDownloadManager.getInstance(getApplicationContext());
        handler = new MyHandler(this);

        jsonObject.addProperty("userId", SpUtil.getInstace().getString(Contants.USER_ID, null));


        initTryDialog();
        initLeftTimeDialog();
        initLoginErrorDialog();
//        initSetting();
//        initChoseDialog();
        initView();

//        if (SpUtil.getInstace().getBoolean(Contants.IS_SHOW_GARRAGE, true)) {
        if (!fromFree) {
            if (isHighEndChip()) {
                getBarrageFromNet();
            }
        }
//        }
//        initSeriseRecyclerView();
//        initSimlarRecyclerView();

        initListener();

        initData();

        if (!fromFree) { //  不是从免费体验课跳过来的才初始化
            initTabPopupWindow();
            initLearningFeedbackPopupwindow();
            initSmartQAPopupwindow();
            initVideoScenePop();
            getVideoScene(true);
        }
    }

    /*
     *  是不是高端芯片
     * */
    private boolean isHighEndChip() {
//        return true;
        Log.d(TAG, "MANUFACTURER:" + Build.MANUFACTURER);
        Log.d(TAG, "MODEL:" + Build.MODEL);
        Log.d(TAG, "PRODUCT:" + Build.PRODUCT);
        // 芯片判断
        if (Build.MANUFACTURER.contains("rockchip") || Build.MODEL.contains("rk3") || Build.PRODUCT.contains("rk3")
                || Build.MANUFACTURER.contains("AZW") || Build.MODEL.contains("GTKing") || Build.PRODUCT.contains("galilei")) {
            return true;
        } else {
            return false;
        }
    }

    private void getBarrageFromNet() {
        OkGoBuilder.getInstance()
                .url(UrlConfig.GET_BARRAGE_LIST)
                .Builder((Activity) mContext)
                .method(OkGoBuilder.PSOT)
                .cls(BarrageBean.class)
                .requestBody(HttpUtils.getRequestJson(initBarrageRequestBody()))
                .callback(new OkGoUtil<BarrageBean>(BarrageBean.class) {
                    @Override
                    public void onSuccess(Response<BarrageBean> response) {
                        if (response.body() != null) {
                            BarrageBean body = response.body();
                            if (body.getList() != null && body.getList().size() != 0) {
                                listBarrage.addAll(body.getList());
                            }
                        }

                    }

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

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

    int tag = -1;

    private void initBarrage(final int currentTime) {
        if (!SpUtil.getInstace().getBoolean(Contants.IS_SHOW_GARRAGE, true)) {
            return;
        }

        if (tag == currentTime) {
            return;
        } else {
            tag = currentTime;
        }
        BarrageBean.ListBean bean = null;
        for (int i = 0; i < listBarrage.size(); i++) {
            if (listBarrage.get(i).getTimePoint() == currentTime) {
                bean = listBarrage.get(i);
                break;
            }
        }
        if (bean == null) {
            return;
        }
        llBarrage = (LinearLayout) getLayoutInflater().inflate(R.layout.item_barrage, null);
        tvBarrage = llBarrage.findViewById(R.id.tv_barrage);
        ivGif = llBarrage.findViewById(R.id.iv_gif);
        if (isHighEndChip()) {
            Glide.with(this).asGif().load(bean.getAvaterUrl()).into(ivGif);
        }
        tvBarrage.setText(bean.getContent());
        RelativeLayout.LayoutParams lp = null;
        if (bean.getDirection() == 1) {
            animation = AnimationUtils.loadAnimation(this, R.anim.barrage_fromleft);
        }
        if (bean.getDirection() == 2) {
            animation = AnimationUtils.loadAnimation(this, R.anim.barrage_fromright);
        }
        animation.setDuration(bean.getSpeed() * 1000);
        tvBarrage.setTextColor(Color.parseColor(bean.getContentColor()));
        if (bean.getContentSize() == 1) {
            tvBarrage.setTextSize(TypedValue.COMPLEX_UNIT_SP, 22);
        }
        if (bean.getContentSize() == 2) {
            tvBarrage.setTextSize(TypedValue.COMPLEX_UNIT_SP, 26);
        }
        if (bean.getContentSize() == 3) {
            tvBarrage.setTextSize(TypedValue.COMPLEX_UNIT_SP, 30);
        }
        lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        lp.addRule(RelativeLayout.CENTER_VERTICAL);

        if (bean.getLocation() == 1) {
            rl_position1.removeAllViews();
            rl_position1.addView(llBarrage, lp);
        }
        if (bean.getLocation() == 2) {
            rl_position2.removeAllViews();
            rl_position2.addView(llBarrage, lp);
        }
        if (bean.getLocation() == 3) {
            rl_position3.removeAllViews();
            rl_position3.addView(llBarrage, lp);
        }
        if (bean.getLocation() == 4) {
            rl_position4.removeAllViews();
            rl_position4.addView(llBarrage, lp);
        }
        if (bean.getLocation() == 5) {
            rl_position5.removeAllViews();
            rl_position5.addView(llBarrage, lp);
        }
        if (bean.getLocation() == 0) {
            rl_position5.removeAllViews();
            rl_position5.addView(llBarrage, lp);
        }
//        rl_position5.addView(llBarrage, lp);
        llBarrage.startAnimation(animation);
        animation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animations) {
                rl_position1.removeAllViews();
                rl_position2.removeAllViews();
                rl_position3.removeAllViews();
                rl_position4.removeAllViews();
                rl_position5.removeAllViews();
                tvBarrage = null;
                animation = null;
                llBarrage = null;
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }


    private void getAnswerFromNet(String questionId, final int position) {
        OkGoBuilder.getInstance()
                .url(UrlConfig.GETANSWER)
                .Builder((Activity) mContext)
                .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) {
                                listQuestion.get(position).setAnswerBean(body);
                                adapterQuestion.notifyDataSetChanged();

                       /* llAnswer.setVisibility(View.VISIBLE);
//                        tvAnswerTitleAnswer.setText(body.getAnswerTitle());
                        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());
                        }
*/

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

                    // 隐藏软键盘
                    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
                    inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

                    getQuestionListFromNet(initQuestionRequestBody(edKeyword.getText().toString()));

                    break;
                case R.id.tv_manual_answering: // 转人工按钮

                    if (isFastClick()) return;
                    popupWindowSmartQA.dismiss();

                    if (listVideoScene.size() > 0) {
                        // 先 选择对应知识点
                        popVideoSecen.showAtLocation(rlRoot, Gravity.TOP + Gravity.RIGHT, 0, 0);
                        tvChooseKnowledge.setVisibility(View.VISIBLE);
                    } else {
                        startManualAnswering("");
                    }

                    break;
            }
        }
    }

    /*
     *  开始请求人工答疑
     * */
    private void startManualAnswering(String knowledgeId) {
        /*if (!BuildConfig.DEBUG) { // 正式版加时间判断
            // 202103  时间判断   周一到周六晚19-23.00，周六14-18 ； 周日不开放
            Calendar calendar = Calendar.getInstance();
            int i = calendar.get(Calendar.DAY_OF_WEEK);  // sunday 1   monday 2 ...  saturday 7
//            String msg = "工作时间为周一至周六19:00-23:00，及周六14:00-18:00 \n当前时间老师正在休整中... ";
            String msg = "抱歉，当前不在答疑时间内";

            if (i == 1) { // =============== 周日 ===============
                Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();
                return;
            } else if (i == 7) { // =============== 周六 =================
                int hour = calendar.get(Calendar.HOUR_OF_DAY);
//                int minute = calendar.get(Calendar.MINUTE);
                // 不工作的时间
                if (hour < 14
                        || hour == 18
//                        || (hour == 21 && minute > 29)
                        || hour > 22) { // 周六 其他时间
                    Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();
                    return;
                }
            } else { //  =============== 周一至周五  ================
                int hour = calendar.get(Calendar.HOUR_OF_DAY);
//                int minute = calendar.get(Calendar.MINUTE);
                // 不工作的时间
                if (hour < 19
//                        || (hour == 21 && minute > 29)
                        || hour > 22) {
                    Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();
                    return;
                }
            }
        }*/

        if (checkSelfPermission(REQUESTED_PERMISSIONS[0], PERMISSION_REQ_ID) &&
                checkSelfPermission(REQUESTED_PERMISSIONS[1], PERMISSION_REQ_ID) &&
                checkSelfPermission(REQUESTED_PERMISSIONS[2], PERMISSION_REQ_ID)) {
        }
        requestClassin(knowledgeId);
    }


    /**
     * @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();

                            // 202103 增加没有数据提示
                            if (body.getList() != null && body.getList().size() != 0) {
                                listQuestion.addAll(body.getList());
//                        llFootview.setVisibility(View.VISIBLE);
//                        llAnswer.setVisibility(View.GONE);
                            } else {
                                Toast.makeText(mContext, "抱歉未找到相关的问题，请选择人工答疑", Toast.LENGTH_SHORT).show();
//                        llFootview.setVisibility(View.GONE);
                            }
//                    if (listQuestion.size() != 0) {
//                        tvAnswerTitle.setVisibility(View.VISIBLE);
//                    }
                            adapterQuestion.notifyDataSetChanged();
                            lvSmartqaData.setSelection(0);
                        }
                    }

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


    /**
     * @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 HashMap<String, String> initSmartQARequestBody(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 initTryDialog() {
        dialogTry = new AlertDialog.Builder(this)
                .setTitle(R.string.tip)
                .setMessage(R.string.tip_trytimeover)
                .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {//添加"Yes"按钮
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        finish();
                    }
                })
                .create();
        dialogTry.setCancelable(false);
    }

    private void initLeftTimeDialog() {
        dialogLeftTime = new AlertDialog.Builder(this)
                .setTitle(R.string.tip)
                .setMessage(R.string.lefttime_less)
                .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {//添加"Yes"按钮
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        finish();
                    }
                })
                .create();
        dialogLeftTime.setCancelable(false);
    }

    private void initLoginErrorDialog() {
        dialogLoginError = new AlertDialog.Builder(this)
                .setTitle(R.string.login)
                .setMessage(R.string.login_error)
                .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {//添加"Yes"按钮
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        finish();
                    }
                })
                .create();
        dialogLoginError.setCancelable(false);
    }

    @Override
    protected void onResume() {
        super.onResume();
//        initSetting();
//        if (mAliyunDownloadManager != null) {
//            mAliyunDownloadManager.addDownloadInfoListener(this);
//        }

//        if (mAliyunVodPlayerView != null) {
//            mAliyunVodPlayerView.onResume();
//            mAliyunVodPlayerView.setOperatorPlay(mSettingSpUtilsOperatorPlay);
//        }
        BoxUtil.hideBottomUIMenu(this);

    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mAliyunVodPlayerView != null) {
            mAliyunVodPlayerView.pause();
            mCurrentPosition = mAliyunVodPlayerView.getCurrentPosition();
        }
    }

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

        if (mAliyunVodPlayerView != null) {
            mAliyunVodPlayerView.onStop();
        }

        if (!fromFree) {

            //sendPlayingTime(currentplayingTime);  原来的收费逻辑
//            TimeCounterService.startService(this, TimeCounterService.ACTION_CLOSED,
//                    videoId, courseId, currentplayingTime, null, isNeedTiming);  // === syncPlayingTimg ===
            currentplayingTime = 0;

            if (playingTime >= 5 * 1000) {
                sendPlayingTime(playingTime, (int) (mCurrentPosition / 1000));   //  === addUpPlayingTime ===
                playingTime = 0;
            }

            // =========================  倍速后 的 有效观看时长  ==========================
            if (isSpeed) {
//                validPlayTimeBySpeedMills =
//                        (new BigDecimal(speed1SecondsSize)
//                                .add(new BigDecimal(speed125SecondsSize).divide(new BigDecimal("1.25"), 0, RoundingMode.HALF_UP))
//                                .add(new BigDecimal(speed15SecondsSize).divide(new BigDecimal("1.5"), 0, RoundingMode.HALF_UP))
//                                .add(new BigDecimal(speed2SecondsSize).divide(new BigDecimal("2"), 0, RoundingMode.HALF_UP))
//                                .intValue());
                validPlayTimeBySpeedMills = (speed1SecondsSize * 1000)
                        + (speed125SecondsSize * 800)
                        + (speed15SecondsSize * 667)
                        + (speed2SecondsSize * 500);
            } else {
                validPlayTimeBySpeedMills = speed1SecondsSize * 1000;
            }


            //按有效观看时长的收费逻辑
            TimeCounterService.startService(this, TimeCounterService.ACTION_CLOSED,
                    videoId, courseId, validPlayTimeBySpeedMills, null, isNeedTiming);
//            Log.d("CCCCCCCCConstop", "seconds:" + validPlayTimeBySpeedSeconds + " videoId:" + videoId + " courseId:" + courseId + " needTiming:" + isNeedTiming);

            validPlayTimeBySpeedMills = 0;
        }


//        if (mAliyunDownloadManager != null) {
//            mAliyunDownloadManager.removeDownloadInfoListener(this);
//        }
    }

    @Override
    protected void onDestroy() {
        if (mAliyunVodPlayerView != null) {
            mAliyunVodPlayerView.onDestroy();
            mAliyunVodPlayerView = null;
        }
        if (mScreenCostView != null) {
            try {
                mScreenCostView.destroy();
            } catch (Exception e) {

            }
        }
        if (receiver != null) {
            unregisterReceiver(receiver);
        }
        //RTC video Q&A
      /*  if (mAliRtcEngine != null) {
            //mAliRtcEngine.leaveChannel();
            mAliRtcEngine.destroy();
            mAliRtcEngine = null;
        }*/
        if (handler != null) {
            handler.removeMessages(0);
            handler = null;
        }
        if (classinWaittingFlag) {
            cancelClassinReq();
        }
        SpUtil.getInstace().save(Contants.IS_NEED_QUEUE, false);
        if (webView != null) {
            webView.onDestroy();
        }
        super.onDestroy();
    }

    @Override
    public void onMultiWindowModeChanged(boolean isInMultiWindowMode) {
        super.onMultiWindowModeChanged(isInMultiWindowMode);
        if (mAliyunVodPlayerView != null) {
            mAliyunVodPlayerView.setMultiWindow(isInMultiWindowMode);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_VOLUME_UP:
                if (mAliyunVodPlayerView != null && mAliyunVodPlayerView.getIsCreenCosting()) {
                    int screenCostingVolume = mAliyunVodPlayerView.getScreenCostingVolume() + 5;
                    mAliyunVodPlayerView.setScreenCostingVolume(screenCostingVolume);
                    return true;
                }
                break;
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                if (mAliyunVodPlayerView != null && mAliyunVodPlayerView.getIsCreenCosting()) {
                    int screenCostingVolume = mAliyunVodPlayerView.getScreenCostingVolume() - 5;
                    mAliyunVodPlayerView.setScreenCostingVolume(screenCostingVolume);
                    return true;
                }
                break;
//            case KeyEvent.KEYCODE_BACK:
//                if (popupWindowForRTC != null && popupWindowForRTC.isShowing()) {
//                    if (mAliRtcEngine != null) {
//                        //mAliRtcEngine.leaveChannel();
//                        mAliRtcEngine.destroy();
//                        mAliRtcEngine = null;
//                    }
//                    popupWindowForRTC.dismiss();
//                    return true;
//                }
//                break;
            default:
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 初始化数据
     */
    private void initData() {
        String userId = SpUtil.getInstace().getString(Contants.USER_NAME, null);
        tv_showinfo.setText(/*"本视频禁止转载\n" + */EmojiUtils.getEmoji(userId)/* + "\n当前设备:" + BoxUtil.getDeviceSN()*/);

        if (fromFree) {
            UrlSource urlSource = new UrlSource();
            urlSource.setUri(getIntent().getStringExtra(FREE_URL));
            mAliyunVodPlayerView.setLocalSource(urlSource);
            mAliyunVodPlayerView.changeScreenMode(AliyunScreenMode.Full, false);

        } else {
            mCoverUrl = bean.getVideoMeta().getCoverURL();
            mAliyunPlayAuth = new com.aliyun.player.source.VidAuth();
            mAliyunPlayAuth.setPlayAuth(bean.getPlayAuth());
            mAliyunPlayAuth.setVid(bean.getVideoMeta().getVideoId());
            mAliyunVodPlayerView.setAuthInfo(mAliyunPlayAuth);

        }

        refreshView();
//        if (SpUtil.getInstace().getBoolean(Contants.IS_NEED_QUEUE, false)) {
//            getQueueInfo();
//        }
    }

    private void changeSpeed2Stand() {
        List<TrackInfo> trackInfos = mAliyunVodPlayerView.getTrackInfos();
        if (trackInfos == null) return;
        for (int i = 0; i < trackInfos.size(); i++) {
            // 设置为高清
            if (trackInfos.get(i).getVodDefinition().equals(QualityValue.QUALITY_STAND)) {
                mAliyunVodPlayerView.changeQuality(trackInfos.get(i));
                break;
            }
        }
    }

    private void refreshView() {
        mAliyunVodPlayerView.setCoverUri(mCoverUrl);
        mAliyunVodPlayerView.clearFrameWhenStop(true);
        //隐藏弹幕
        mAliyunVodPlayerView.hideDanmakuView();
        if (seekToPoint >= SEEKTOPOINT_MIN) {
            mAliyunVodPlayerView.seekTo(seekToPoint);
        }
//        mAliyunVodPlayerView.seekTo(12*1000);
//        mAliyunVodPlayerView.pause();

//        mAliyunVodPlayerView.start();
    }

//    /**
//     * 初始化设置界面的信息
//     */
//    private void initSetting() {
//        mSettingSpUtilsVideoQuantity = mSettingSpUtils.getVideoQuantity();
//    }

    private void initView() {
        rl_position1 = findViewById(R.id.rl_position1);
        rl_position2 = findViewById(R.id.rl_position2);
        rl_position3 = findViewById(R.id.rl_position3);
        rl_position4 = findViewById(R.id.rl_position4);
        rl_position5 = findViewById(R.id.rl_position5);
        tv_showinfo = findViewById(R.id.tv_showinfo);
        tv_classinWaittingInfo = findViewById(R.id.tv_qa_waittingnfo);
        rlRoot = findViewById(R.id.rl_root);
//        findViewById(R.id.btn).setOnHoverListener(new View.OnHoverListener() {
//            @Override
//            public boolean onHover(View v, MotionEvent event) {
//                int what = event.getAction();
//                switch (what) {
//                    case MotionEvent.ACTION_HOVER_ENTER:  //鼠标进入view
//                        //popupWindowSmartQA.showAtLocation(rlRoot, Gravity.TOP + Gravity.RIGHT, 0, 0);
//                        popupWindowForRTC.showAtLocation(rlRoot, Gravity.TOP + Gravity.RIGHT, 0, 0);
//                        System.out.println("bottom ACTION_HOVER_ENTER");
//                        break;
//                    case MotionEvent.ACTION_HOVER_MOVE:  //鼠标在view上
//                        System.out.println("bottom ACTION_HOVER_MOVE");
//                        break;
//                    case MotionEvent.ACTION_HOVER_EXIT:  //鼠标离开view
//                        System.out.println("bottom ACTION_HOVER_EXIT");
//                        break;
//                }
//                return false;
//            }
//        });
        // 202103  智能答疑外层的灰色按钮
        LinearLayout btnMenu = findViewById(R.id.btn);
        if (fromFree) { // 免费体验课
            btnMenu.setVisibility(View.GONE);
        } else {
//        if (SpUtil.getInstace().getBoolean(Contants.IS_NEED_QUEUE, false)) {
//            btnMenu.setVisibility(View.GONE);
//        } else {
//            btnMenu.setVisibility(View.VISIBLE);
//        }
            btnMenu.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                aaa
                    if (SpUtil.getInstace().getBoolean(Contants.IS_NEED_QUEUE, false)) {
//                    btnMenu.setVisibility(View.GONE);
                        finish();
                    } else {
                        popupWindowTab.showAtLocation(rlRoot, Gravity.TOP + Gravity.RIGHT, 0, 0);
//                    btnMenu.setVisibility(View.VISIBLE);
//                    popupWindowLearningFeedback.showAtLocation(rlRoot, Gravity.TOP + Gravity.RIGHT, 0, 0);
                    }
//                if (!isHighEndChip()) {
//                    mAliyunVodPlayerView.pause();
//                }
//                dialogChoseMenu.show();

                }
            });
        }
        //Adding by Eric start
        getSupportActionBar().hide();
        //Adding by Eric end
        mAliyunVodPlayerView = findViewById(R.id.video_view);

//        mAliyunVodPlayerView.setTitleBarCanShow(false);
        if (!fromFree) {
            mAliyunVodPlayerView.setNeedTiming(isNeedTiming);
        }
        //保持屏幕敞亮
        mAliyunVodPlayerView.setKeepScreenOn(true);
        //设置硬解码开关
        mAliyunVodPlayerView.setEnableHardwareDecoder(true);
//        aliyunVodPlayer.setPlayingCache(true, sdDir, 60 * 60 /*时长, s */, 300 /*大小，MB*/);
        mAliyunVodPlayerView.setPlayingCache(true, CACHE_PATH, MAX_DURATION_CACHE /*时长, s */, MAX_SIZE_CACHE /*大小，MB*/);
        initScreenView();
        initSoftDialogFragment();

        mAliyunVodPlayerView.setBtnSpeedVisible(isSpeed);
    }

    private void initSoftDialogFragment() {
        mSoftInputDialogFragment = SoftInputDialogFragment.newInstance();
        mSoftInputDialogFragment.setOnBarrageSendClickListener(new SoftInputDialogFragment.OnBarrageSendClickListener() {
            @Override
            public void onBarrageSendClick(String danmu) {
                if (mAliyunVodPlayerView != null) {
                    mAliyunVodPlayerView.setmDanmaku(danmu);
                    mSoftInputDialogFragment.dismiss();
                }
            }
        });
    }

    /**
     * 初始化投屏view
     */
    private void initScreenView() {
        mScreenCostView = new ScreenCostView(this);
        screenShowMoreDialog = new AlivcShowMoreDialog(this);
        screenShowMoreDialog.setContentView(mScreenCostView);
        mScreenCostView.setOnDeviceItemClickListener(new OnDeviceItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (mAliyunVodPlayerView != null) {
                    mAliyunVodPlayerView.screenCostPlay();
                }
                if (screenShowMoreDialog != null) {
                    screenShowMoreDialog.dismiss();
                }
            }
        });
    }

    private void initListener() {

        mAliyunVodPlayerView.setOnPreparedListener(new PlayerPreparedListener(this));
        mAliyunVodPlayerView.setOnCompletionListener(new PlayerCompletionListener(this));

        mAliyunVodPlayerView.setOnInfoListener(new PlayerInfoListener(this));

        mAliyunVodPlayerView.setOnDotViewClickListener(new PlayerDotViewClickListener(this));

        mAliyunVodPlayerView.setOnControlViewHideListener(new PlayerControlViewHideListener(this));
        mAliyunVodPlayerView.setOrientationChangeListener(new PlayerOrientationChangeListner(this));
//        mAliyunVodPlayerView.setOnTrailerViewClickListener(new AlivcPlayerActivity.PlayerTrailerViewClickListener(this));
        mAliyunVodPlayerView.setOnScreenBrightness(new PlayerControlViewScreenBrightnessListener(this));
        mAliyunVodPlayerView.setOnShowMoreClickListener(new PlayerControlViewShowMoreClickListener(this));
        mAliyunVodPlayerView.setOnScreenCostingSingleTagListener(new MyOnScreenCostingSingleTagListener(this));
        mAliyunVodPlayerView.setOnFinishListener(new PlayerControlViewFinishListener(this));
        mAliyunVodPlayerView.setSoftKeyHideListener(new MynewOnSoftKeyHideListener(this));
        mAliyunVodPlayerView.setOnScreenCostingVideoCompletionListener(new OnScreenCostingVideoCompletionListener(this));

        mAliyunVodPlayerView.setScreenBrightness(BrightnessDialog.getActivityBrightness(AlivcPlayerActivity.this));
        mAliyunVodPlayerView.setOnBackClickListener(new AliyunVodPlayerView.OnBackClickListener() {
            @Override
            public void onBackClicked() {
                onBackPressed();
            }
        });

        mAliyunVodPlayerView.setOnSpeedChangeListener(new AliyunVodPlayerView.OnSpeedChangeListener() {
            @Override
            public void onSpeedChange(float speed) {
                if (!isHighEndChip()) { // 一代盒子修改倍速 切换清晰度
                    if (speed != 1f || speed != 1.25f) {
                        // 获取当前清晰的   判断是不是超清 HD
                        String name = mAliyunVodPlayerView.getCurrentQualityName();
                        if (name != null && name.equals(QualityValue.QUALITY_HIGH)) {

                            changeSpeed2Stand();
                        }
                    }
                }
            }
        });
    }


    /**
     * 判断标题是否存在，阿里云演示字符串
     */
    private boolean isTitleContain() {
        if (TextUtils.isEmpty(mVideoTitle)) {
            return false;
        }
        int result = mVideoTitle.indexOf("阿里云演示");
        return result != -1;
    }

    /**
     * 判断标题是否存在，跑马灯并且含有阿里云演示字符串
     */
    private boolean isTitleContainMarquee() {
        if (TextUtils.isEmpty(mVideoTitle)) {
            return false;
        }
        int result = mVideoTitle.indexOf("阿里云演示");
        int result1 = mVideoTitle.indexOf("跑马灯");
        return result != -1 && result1 != -1;
    }

    /**
     * 判断标题是否存在，水印并且含有阿里云演示字符串
     */
    private boolean isTitleContainWaterMark() {
        if (TextUtils.isEmpty(mVideoTitle)) {
            return false;
        }
        int result = mVideoTitle.indexOf("阿里云演示");
        int result1 = mVideoTitle.indexOf("水印");
        return result != -1 && result1 != -1;
    }


    protected boolean isStrangePhone() {
        //隐藏状态栏时异常机型处理
        boolean strangePhone = "mx5".equalsIgnoreCase(Build.DEVICE)
                || "Redmi Note2".equalsIgnoreCase(Build.DEVICE)
                || "Z00A_1".equalsIgnoreCase(Build.DEVICE)
                || "hwH60-L02".equalsIgnoreCase(Build.DEVICE)
                || "hermes".equalsIgnoreCase(Build.DEVICE)
                || ("V4".equalsIgnoreCase(Build.DEVICE) && "Meitu".equalsIgnoreCase(Build.MANUFACTURER))
                || ("m1metal".equalsIgnoreCase(Build.DEVICE) && "Meizu".equalsIgnoreCase(Build.MANUFACTURER));

//        VcPlayerLog.e("lfj1115 ", " Build.Device = " + Build.DEVICE + " , isStrange = " + strangePhone);
        return strangePhone;
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        //旋转屏幕,需要隐藏打点的信息
        if (mAlivcDotMsgDialogFragment != null) {
            mAlivcDotMsgDialogFragment.dismiss();
        }
        if (mAliyunVodPlayerView != null) {
            int orientation = getResources().getConfiguration().orientation;
            if (orientation == Configuration.ORIENTATION_PORTRAIT) {
                //转为竖屏了。
                //显示状态栏
                this.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                mAliyunVodPlayerView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);

                //设置view的布局，宽高之类
                LinearLayout.LayoutParams aliVcVideoViewLayoutParams = (LinearLayout.LayoutParams) mAliyunVodPlayerView
                        .getLayoutParams();
                aliVcVideoViewLayoutParams.height = (int) (ScreenUtils.getWidth(this) * 9.0f / 16);
                aliVcVideoViewLayoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
            } else if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
                //转到横屏了。
                //隐藏状态栏
                if (!isStrangePhone()) {
                    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                            WindowManager.LayoutParams.FLAG_FULLSCREEN);
                    mAliyunVodPlayerView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
                }
                //设置view的布局，宽高
                RelativeLayout.LayoutParams aliVcVideoViewLayoutParams = (RelativeLayout.LayoutParams) mAliyunVodPlayerView
                        .getLayoutParams();
                aliVcVideoViewLayoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
                aliVcVideoViewLayoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
            }
        }
    }

    /**
     * 设置屏幕亮度
     */
    private void setWindowBrightness(int brightness) {
        Window window = getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.screenBrightness = brightness / 255.0f;
        window.setAttributes(lp);
    }


    /**
     * ------------------------------------------播放器View的相关回调 ------------------------------------------
     */
//播放准备完成的回调
    public static class PlayerPreparedListener implements IPlayer.OnPreparedListener {

        private WeakReference<AlivcPlayerActivity> mWeakReference;

        public PlayerPreparedListener(AlivcPlayerActivity alivcPlayerActivity) {
            mWeakReference = new WeakReference<>(alivcPlayerActivity);
        }

        @Override
        public void onPrepared() {
            AlivcPlayerActivity alivcPlayerActivity = mWeakReference.get();
            if (alivcPlayerActivity != null) {
                alivcPlayerActivity.onPlayerPrepared();
            }
        }
    }

    private void onPlayerPrepared() {

        // 一代盒子 默认高清（标准清晰度，非超清）
        if (!isHighEndChip()) {
            changeSpeed2Stand();
        }

        //获取当前播放视频的duration
        MediaInfo mediaInfo = mAliyunVodPlayerView.getMediaInfo();
        int duration = mediaInfo.getDuration();
//        mLongVideoBean.setDuration(duration + "");
        //如果是投屏中,播放结束后,自动播放下一级集数
        if (mAliyunVodPlayerView != null && mAliyunVodPlayerView.getIsCreenCosting()) {
            //先停止,再重新投屏
            mAliyunVodPlayerView.screenCostStop();
            mAliyunVodPlayerView.screenCostPlay();
        }
    }

    public static class PlayerInfoListener implements IPlayer.OnInfoListener {

        private WeakReference<AlivcPlayerActivity> mWeakReference;
        int currentPosSec = 0;  // 当前视频播放点的秒数
        int lastTimePosition = 0;

        public PlayerInfoListener(AlivcPlayerActivity alivcPlayerActivity) {
            mWeakReference = new WeakReference<>(alivcPlayerActivity);
        }

        final int z = 60;

        @Override
        public void onInfo(InfoBean infoBean) {

            AlivcPlayerActivity alivcPlayerActivity = mWeakReference.get();
            if (alivcPlayerActivity == null) {
                return;
            }

            if (infoBean.getCode().getValue() == InfoCode.CurrentPosition.getValue()) {
                //如果播放时间大于等于试看时间并且是试看视频 则弹窗提示不让看了
                if (infoBean.getExtraValue() >= alivcPlayerActivity.tryTime && alivcPlayerActivity.isTry) {
                    alivcPlayerActivity.mAliyunVodPlayerView.pause();
                    try {
                        alivcPlayerActivity.dialogTry.show();
                    } catch (Exception ignord) {

                    }
                }

                currentPosSec = (int) (infoBean.getExtraValue() / 1000);

                // 弹幕
                if (alivcPlayerActivity.isHighEndChip()) {
                    if (alivcPlayerActivity.listBarrage.size() != 0) {
                        alivcPlayerActivity.initBarrage(currentPosSec);
                    }
                }

                if (lastTimePosition != currentPosSec) {   // =========== 秒数有变化，过了一秒 ============

                    // 如果不是试看  且  需要计时  (计费)
                    if (!alivcPlayerActivity.isTry && alivcPlayerActivity.isNeedTiming) {

                        TimeCounter timeCounter = TimeCounter.getInstance(alivcPlayerActivity.getApplicationContext());

                        //=============  回看免费（原来的逻辑） ==================
                        if (alivcPlayerActivity.isBackview) {
                            //String fileName = timeCounter.getCurrentFileName();

                            //  如果 不存在 则创建 ？
                            if (!timeCounter.isBitmapExsitFlag()) {
                                //该操作放到service中进行
                                //get server bitmap
//                            if(timeCounter.getServerBitmapCheckState() == 1 && timeCounter.isServerBitmapExsitFlag()) {//本地和网络都不存在
//                                if (!timeCounter.isServerBitmapExsitFlag()) {
//                                    //bitmap or operation
//                                    timeCounter.setBitmapExsitFlag(true);
//                                } else {
//                                    //bitmap has aleardy exsit
//                                }
//                            }
//                                Log.d("lhs", "The bitmap does not exsit when the video playing, current seconds:" + currentPosition);
                                //create bitmap
                                long duration = alivcPlayerActivity.mAliyunVodPlayerView.getDuration(); // 整个视频时长
                                timeCounter.createtVideoSecondBitMap(duration / 1000);
                                timeCounter.setBitmapExsitFlag(true);
                            }

                            // 把当前视频时间折合成秒为单位  判断是否计费   true 需要计费
                            // (如果当前这一秒需要计费)
                            if (timeCounter.isNeedCountFlag((int) (infoBean.getExtraValue() / 1000))) { // infoBean.getExtraValue() / 1000  折合成秒为单位
                                alivcPlayerActivity.currentplayingTime += 1000;
                                alivcPlayerActivity.counterForSaveNative++;
                                // 下面这句话没用 因为并没有timeCounter.get....
//                                timeCounter.setCounterForSaveNative(alivcPlayerActivity.counterForSaveNative);

                                // counterForSaveNative 的作用也就是用来判断，每隔10 执行一下下面代码
                                //  每10s 执行一下 以下代码？？
                                if (alivcPlayerActivity.counterForSaveNative >= Contants.BITMAP_SAVE_INTERVAL) {
                                    alivcPlayerActivity.counterForSaveNative = 0;
                                    if (!timeCounter.isBitMapFileExist(timeCounter.getCurrentFileName())) {  // 文件名的设置在PlayVideoUtils里
                                        // 如果文件不存在  则创建
                                        timeCounter.createBitMapFile(timeCounter.getVideoSecondBitMap(), timeCounter.getCurrentFileName());
                                    } else {
                                        // 否则 保存
                                        timeCounter.saveBitMapToFile(timeCounter.getVideoSecondBitMap(), timeCounter.getCurrentFileName());
                                    }
                                }

                                if (alivcPlayerActivity.isSpeed) {
                                    // 获取当前这一秒的倍速播放速度
                                    float currentSpeed = alivcPlayerActivity.mAliyunVodPlayerView.getCurrentSpeed();
                                    if (currentSpeed == 1.0f) {
                                        alivcPlayerActivity.speed1SecondsSize++;
                                    } else if (currentSpeed == 1.25f) {
                                        alivcPlayerActivity.speed125SecondsSize++;
                                    } else if (currentSpeed == 1.5f) {
                                        alivcPlayerActivity.speed15SecondsSize++;
                                    } else if (currentSpeed == 2.0f) {
                                        alivcPlayerActivity.speed2SecondsSize++;
                                    }
                                } else {
                                    alivcPlayerActivity.speed1SecondsSize++;
                                }

//                                Log.d("AAAAAAAAAAA", currentSpeed + " "
//                                        + alivcPlayerActivity.speed1SecondsSize + " "
//                                        + alivcPlayerActivity.speed125SecondsSize + " "
//                                        + alivcPlayerActivity.speed15SecondsSize + " "
//                                        + alivcPlayerActivity.speed2SecondsSize);


                                // 大于60s 上传一次   currentplayingTime  0-60
                                if (alivcPlayerActivity.currentplayingTime >= Contants.TIME_UPLOAD_INTERVAL * 1000) {

//                                    int tempTime = alivcPlayerActivity.currentplayingTime;
                                    timeCounter.setCurrentplayingTime(alivcPlayerActivity.currentplayingTime);
                                    alivcPlayerActivity.currentplayingTime = 0;
                                    //alivcPlayerActivity.sendPlayingTime(tempTime);

                                    // === syncPlayingTimg ===   原来的收费逻辑
//                                    TimeCounterService.startService(alivcPlayerActivity, TimeCounterService.ACTION_TIME_UP,
//                                            alivcPlayerActivity.videoId, alivcPlayerActivity.courseId,
//                                            timeCounter.getCurrentplayingTime(), null, alivcPlayerActivity.isNeedTiming);
//                                    Log.d("BBBBBB" ,  timeCounter.getCurrentplayingTime() + "" ) ; //  0-60


                                    // =========================  倍速后 的 有效观看时长  ==========================
                                    if (alivcPlayerActivity.isSpeed) {
//                                        alivcPlayerActivity.validPlayTimeBySpeedMills =
//                                                (new BigDecimal(alivcPlayerActivity.speed1SecondsSize)
//                                                        .add(new BigDecimal(alivcPlayerActivity.speed125SecondsSize).divide(new BigDecimal("1.25"), 0, RoundingMode.HALF_UP))
//                                                        .add(new BigDecimal(alivcPlayerActivity.speed15SecondsSize).divide(new BigDecimal("1.5"), 0, RoundingMode.HALF_UP))
//                                                        .add(new BigDecimal(alivcPlayerActivity.speed2SecondsSize).divide(new BigDecimal("2"), 0, RoundingMode.HALF_UP))
//                                                        .intValue());
                                        alivcPlayerActivity.validPlayTimeBySpeedMills = (alivcPlayerActivity.speed1SecondsSize * 1000)
                                                + (alivcPlayerActivity.speed125SecondsSize * 800)
                                                + (alivcPlayerActivity.speed15SecondsSize * 667)
                                                + (alivcPlayerActivity.speed2SecondsSize * 500);
                                    } else {
                                        alivcPlayerActivity.validPlayTimeBySpeedMills = alivcPlayerActivity.speed1SecondsSize * 1000;
                                    }


                                    //按有效观看时长的收费逻辑
                                    TimeCounterService.startService(alivcPlayerActivity, TimeCounterService.ACTION_TIME_UP,
                                            alivcPlayerActivity.videoId, alivcPlayerActivity.courseId,
                                            alivcPlayerActivity.validPlayTimeBySpeedMills, null, alivcPlayerActivity.isNeedTiming);

//                                    Log.d("CCCCCCCCConinfo", "seconds:" + alivcPlayerActivity.validPlayTimeBySpeedSeconds
//                                            + " videoId:" + alivcPlayerActivity.videoId
//                                            + " courseId:" + alivcPlayerActivity.courseId +
//                                            " needTiming:" + alivcPlayerActivity.isNeedTiming);

                                    alivcPlayerActivity.speed1SecondsSize = 0;
                                    alivcPlayerActivity.speed125SecondsSize = 0;
                                    alivcPlayerActivity.speed15SecondsSize = 0;
                                    alivcPlayerActivity.speed2SecondsSize = 0;
                                    alivcPlayerActivity.validPlayTimeBySpeedMills = 0;
                                }
                            }

                        } else {
                            // =======================   回看也收费   ======================
                            alivcPlayerActivity.currentplayingTime += 1000;
                            alivcPlayerActivity.counterForSaveNative++;

                            if (alivcPlayerActivity.isSpeed) {
                                // 获取当前这一秒的倍速播放速度
                                float currentSpeed = alivcPlayerActivity.mAliyunVodPlayerView.getCurrentSpeed();
                                if (currentSpeed == 1.0f) {
                                    alivcPlayerActivity.speed1SecondsSize++;
                                } else if (currentSpeed == 1.25f) {
                                    alivcPlayerActivity.speed125SecondsSize++;
                                } else if (currentSpeed == 1.5f) {
                                    alivcPlayerActivity.speed15SecondsSize++;
                                } else if (currentSpeed == 2.0f) {
                                    alivcPlayerActivity.speed2SecondsSize++;
                                }
                            } else {
                                alivcPlayerActivity.speed1SecondsSize++;
                            }

                            // 大于60s 上传一次   currentplayingTime  0-60
                            if (alivcPlayerActivity.currentplayingTime >= Contants.TIME_UPLOAD_INTERVAL * 1000) {
                                timeCounter.setCurrentplayingTime(alivcPlayerActivity.currentplayingTime);
                                alivcPlayerActivity.currentplayingTime = 0;

                                // === syncPlayingTimg ===   原来的收费逻辑
//                                    TimeCounterService.startService(alivcPlayerActivity, TimeCounterService.ACTION_TIME_UP,
//                                            alivcPlayerActivity.videoId, alivcPlayerActivity.courseId,
//                                            timeCounter.getCurrentplayingTime(), null, alivcPlayerActivity.isNeedTiming);
//                                    Log.d("BBBBBB" ,  timeCounter.getCurrentplayingTime() + "" ) ; //  0-60


                                // =========================  倍速后 的 有效观看时长  ==========================
                                if (alivcPlayerActivity.isSpeed) {
//                                        alivcPlayerActivity.validPlayTimeBySpeedMills =
//                                                (new BigDecimal(alivcPlayerActivity.speed1SecondsSize)
//                                                        .add(new BigDecimal(alivcPlayerActivity.speed125SecondsSize).divide(new BigDecimal("1.25"), 0, RoundingMode.HALF_UP))
//                                                        .add(new BigDecimal(alivcPlayerActivity.speed15SecondsSize).divide(new BigDecimal("1.5"), 0, RoundingMode.HALF_UP))
//                                                        .add(new BigDecimal(alivcPlayerActivity.speed2SecondsSize).divide(new BigDecimal("2"), 0, RoundingMode.HALF_UP))
//                                                        .intValue());
                                    alivcPlayerActivity.validPlayTimeBySpeedMills = (alivcPlayerActivity.speed1SecondsSize * 1000)
                                            + (alivcPlayerActivity.speed125SecondsSize * 800)
                                            + (alivcPlayerActivity.speed15SecondsSize * 667)
                                            + (alivcPlayerActivity.speed2SecondsSize * 500);
                                } else {
                                    alivcPlayerActivity.validPlayTimeBySpeedMills = alivcPlayerActivity.speed1SecondsSize * 1000;
                                }


                                //按有效观看时长的收费逻辑
                                TimeCounterService.startService(alivcPlayerActivity, TimeCounterService.ACTION_TIME_UP,
                                        alivcPlayerActivity.videoId, alivcPlayerActivity.courseId,
                                        alivcPlayerActivity.validPlayTimeBySpeedMills, null, alivcPlayerActivity.isNeedTiming);

//                                    Log.d("CCCCCCCCConinfo", "seconds:" + alivcPlayerActivity.validPlayTimeBySpeedSeconds
//                                            + " videoId:" + alivcPlayerActivity.videoId
//                                            + " courseId:" + alivcPlayerActivity.courseId +
//                                            " needTiming:" + alivcPlayerActivity.isNeedTiming);

                                alivcPlayerActivity.speed1SecondsSize = 0;
                                alivcPlayerActivity.speed125SecondsSize = 0;
                                alivcPlayerActivity.speed15SecondsSize = 0;
                                alivcPlayerActivity.speed2SecondsSize = 0;
                                alivcPlayerActivity.validPlayTimeBySpeedMills = 0;
                            }
                        }
                    }


                    // 检查登录状态
                    long sec = alivcPlayerActivity.playingTime / 1000;
                    if (sec >= z && sec % z == 0) {
//                                Log.e("BBBBB", "sec = " + sec + "  " + sec % z + "");
                        alivcPlayerActivity.checkLogin();
                    }

                } else { // 不需要计时  因为变化的时间是一秒内，秒数没有变化
                }


                //统计播放时长使用
                int duration = currentPosSec - lastTimePosition;  // 两个播放点的间隔（比如手动点击进度条，最新的播放点距上一个播放点的间隔 s ）
                alivcPlayerActivity.playingTime += (duration > 600 && duration < 1200) ? duration : 500;
                alivcPlayerActivity.seekToPoint += 500;
                lastTimePosition = currentPosSec;

//              Log.d(TAG, "playingTime=" + alivcPlayerActivity.playingTime + " currentplayingTime:" + alivcPlayerActivity.currentplayingTime);
            }
        }

    }

    AlertDialog dialogLoginInvalid;

    /**
     * 检查登录状态
     */
    private void checkLogin() {

        RequestBody body = HttpUtils.getRequestJson(jsonObject);
        OkGoBuilder
                .getInstance()
                .url(UrlConfig.CHECK_LOGIN)
                .method(OkGoBuilder.PSOT)
                .cls(BaseRequestBean.class)
                .Builder(AlivcPlayerActivity.this)
                .requestBody(body)
                .callback(new OkGoUtil<BaseRequestBean>(BaseRequestBean.class) {
                    @Override
                    public void onSuccess(Response<BaseRequestBean> response) {

                        if (response.body().getStatus() == -1) {

                            mAliyunVodPlayerView.pause();

                            if (dialogLoginInvalid == null) {

                                dialogLoginInvalid = new AlertDialog.Builder(AlivcPlayerActivity.this)
                                        .setTitle(R.string.login)
                                        .setMessage(R.string.login_error)
                                        .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {//添加"Yes"按钮
                                            @Override
                                            public void onClick(DialogInterface dialogInterface, int i) {
                                                Intent intent = new Intent(AlivcPlayerActivity.this, LoginActivity.class);
                                                startActivity(intent);
                                                finish();
                                            }
                                        })
                                        .create();
                                dialogLoginInvalid.setCancelable(false);
                            }

                            if (dialogLoginInvalid != null && !dialogLoginInvalid.isShowing()) {
                                try {
                                    dialogLoginInvalid.show();
                                } catch (Exception ignord) {

                                }
                            }
                        }
                    }
                }).build();

    }


//    /**
//     * 更新当前播放进度
//     */
//    private void onPlayerCurrentPositionChanged(long currentPosition) {
//        //计算当前播放进度的百分比
//        double percent = 0;
//        String duration = mLongVideoBean.getDuration();
//        if (!TextUtils.isEmpty(duration)) {
//            percent = (currentPosition >= Double.valueOf(duration)) ? 100 : (currentPosition * 1.00 / Double.valueOf(duration) * 100.00);
//        }
//        //当百分比更新的时候,才更新数据库
//        if ((int) percent != mLongVideoBean.getWatchPercent()) {
////            mLongVideoBean.setWatchPercent((int) percent);
////            mLongVideoBean.setWatchDuration(currentPosition + "");
////            mLongVideoDatabaseManager.updateWatchHistory(mLongVideoBean);
//        }
//    }

    //播放完成的回调
    public static class PlayerCompletionListener implements IPlayer.OnCompletionListener {

        private WeakReference<AlivcPlayerActivity> mWeakReference;

        public PlayerCompletionListener(AlivcPlayerActivity alivcPlayerActivity) {
            mWeakReference = new WeakReference<>(alivcPlayerActivity);
        }

        @Override
        public void onCompletion() {
            AlivcPlayerActivity alivcPlayerActivity = mWeakReference.get();
            if (alivcPlayerActivity != null) {
                if (!alivcPlayerActivity.fromFree) {
                    //alivcPlayerActivity.sendPlayingTime(tempTime);
//                TimeCounter timeCounter = TimeCounter.getInstance(alivcPlayerActivity);
//                timeCounter.setCurrentplayingTime(alivcPlayerActivity.currentplayingTime);
                    // 原来的收费逻辑
//                    TimeCounterService.startService(alivcPlayerActivity, TimeCounterService.ACTION_COMPLETE,
//                            alivcPlayerActivity.videoId, alivcPlayerActivity.courseId, alivcPlayerActivity.currentplayingTime, null, alivcPlayerActivity.isNeedTiming); // === syncPlayingTimg ===
                    alivcPlayerActivity.currentplayingTime = 0;
//                Log.i("TAG", "======" + "播放完成");


                    // =========================  倍速后 的 有效观看时长  ==========================
                    if (alivcPlayerActivity.isSpeed) {
//                                        alivcPlayerActivity.validPlayTimeBySpeedMills =
//                                                (new BigDecimal(alivcPlayerActivity.speed1SecondsSize)
//                                                        .add(new BigDecimal(alivcPlayerActivity.speed125SecondsSize).divide(new BigDecimal("1.25"), 0, RoundingMode.HALF_UP))
//                                                        .add(new BigDecimal(alivcPlayerActivity.speed15SecondsSize).divide(new BigDecimal("1.5"), 0, RoundingMode.HALF_UP))
//                                                        .add(new BigDecimal(alivcPlayerActivity.speed2SecondsSize).divide(new BigDecimal("2"), 0, RoundingMode.HALF_UP))
//                                                        .intValue());
                        alivcPlayerActivity.validPlayTimeBySpeedMills = (alivcPlayerActivity.speed1SecondsSize * 1000)
                                + (alivcPlayerActivity.speed125SecondsSize * 800)
                                + (alivcPlayerActivity.speed15SecondsSize * 667)
                                + (alivcPlayerActivity.speed2SecondsSize * 500);
                    } else {
                        alivcPlayerActivity.validPlayTimeBySpeedMills = alivcPlayerActivity.speed1SecondsSize * 1000;
                    }

                    //按有效观看时长的收费逻辑
                    TimeCounterService.startService(alivcPlayerActivity, TimeCounterService.ACTION_COMPLETE,
                            alivcPlayerActivity.videoId, alivcPlayerActivity.courseId, alivcPlayerActivity.validPlayTimeBySpeedMills, null, alivcPlayerActivity.isNeedTiming);

//                    Log.d("CCCCCCCCConCompletion", "seconds:" + alivcPlayerActivity.validPlayTimeBySpeedSeconds
//                            + " videoId:" + alivcPlayerActivity.videoId
//                            + " courseId:" + alivcPlayerActivity.courseId +
//                            " needTiming:" + alivcPlayerActivity.isNeedTiming);

                    alivcPlayerActivity.validPlayTimeBySpeedMills = 0;
                }
            }
        }
    }

    private void sendPlayingTime(long time, int currentPos) {  // 202103
        OkGoBuilder.getInstance()
                .url(UrlConfig.ADDUPPLAYINGTIME)
                .Builder((Activity) mContext)
                .method(OkGoBuilder.PSOT)
                .cls(BaseRequestBean.class)
                .requestBody(HttpUtils.getRequestJson(getRequestBody(time, currentPos)))
                .callback(new OkGoUtil<BaseRequestBean>(BaseRequestBean.class) {
                    @Override
                    public void onSuccess(Response<BaseRequestBean> response) {
//                        if (response.body() != null && response.body() instanceof BaseRequestBean) {
//                            BaseRequestBean body = response.body();
//                        }
                    }
                }).build();
    }

    private HashMap<String, String> getRequestBody(long time, int currentPos) {
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", SpUtil.getInstace().getString(Contants.USER_ID, null));
        map.put("videoId", videoId);
        map.put("courseId", courseId);
        map.put("playingTime", time + "");
        map.put("start", currentPos + ""); // 秒  当前视频播放位置
        return map;
    }

    /**
     * 打点点击事件
     */
    public static class PlayerDotViewClickListener implements ControlView.OnDotViewClickListener {

        private WeakReference<AlivcPlayerActivity> weakReference;

        public PlayerDotViewClickListener(AlivcPlayerActivity alivcPlayerActivity) {
            weakReference = new WeakReference<>(alivcPlayerActivity);
        }

        @Override
        public void onDotViewClick(int x, int y, DotView dotView) {
            AlivcPlayerActivity alivcPlayerActivity = weakReference.get();
            if (alivcPlayerActivity != null) {
                alivcPlayerActivity.showDotViewMsgDialogFragment(x, y, dotView);
            }
        }
    }

    /**
     * 展示DialogFragment的内容信息
     */
    private void showDotViewMsgDialogFragment(int x, int y, DotView dotView) {
        mAlivcDotMsgDialogFragment = new AlivcDotMsgDialogFragment();
        mAlivcDotMsgDialogFragment.setX(x);
        mAlivcDotMsgDialogFragment.setY(y);
        mAlivcDotMsgDialogFragment.setDotView(dotView);
        mAlivcDotMsgDialogFragment.setOnDotViewMsgClickListener(new AlivcDotMsgDialogFragment.OnDotViewMsgClickListener() {
            @Override
            public void onDotViewMsgClick() {
                if (mAlivcDotMsgDialogFragment != null) {
                    mAlivcDotMsgDialogFragment.dismiss();
                    DotView mDotView = mAlivcDotMsgDialogFragment.getDotView();
                    if (mDotView != null && !TextUtils.isEmpty(mDotView.getDotTime())) {
                        mAliyunVodPlayerView.seekTo(Integer.valueOf(mDotView.getDotTime()) * 1000);
                    }
                }
            }
        });

        mAlivcDotMsgDialogFragment.show(getFragmentManager(), "AlivcDotMsgDialogFragment");
    }

    /**
     * 广告点击事件 退出页面
     */
    public static class PlayerControlViewFinishListener implements AliyunVodPlayerView.OnFinishListener {

        private WeakReference<AlivcPlayerActivity> weakReference;

        public PlayerControlViewFinishListener(AlivcPlayerActivity alivcPlayerActivity) {
            weakReference = new WeakReference<>(alivcPlayerActivity);
        }


        @Override
        public void onFinishClick() {
            AlivcPlayerActivity alivcPlayerActivity = weakReference.get();
            if (alivcPlayerActivity != null) {
                alivcPlayerActivity.finish();
            }
        }
    }

    /**
     * ControlView隐藏事件
     */
    public static class PlayerControlViewHideListener implements ControlView.OnControlViewHideListener {

        private WeakReference<AlivcPlayerActivity> weakReference;

        public PlayerControlViewHideListener(AlivcPlayerActivity alivcPlayerActivity) {
            weakReference = new WeakReference<>(alivcPlayerActivity);
        }

        @Override
        public void onControlViewHide() {
            AlivcPlayerActivity alivcPlayerActivity = weakReference.get();
            if (alivcPlayerActivity != null) {
                if (alivcPlayerActivity.mAlivcDotMsgDialogFragment != null) {
                    alivcPlayerActivity.mAlivcDotMsgDialogFragment.dismiss();
                }
            }
        }
    }

    /**
     * ControlView 横屏展示更多
     */
    public static class PlayerControlViewShowMoreClickListener implements ControlView.OnShowMoreClickListener {

        private WeakReference<AlivcPlayerActivity> weakReference;

        public PlayerControlViewShowMoreClickListener(AlivcPlayerActivity alivcPlayerActivity) {
            weakReference = new WeakReference<>(alivcPlayerActivity);
        }

        @Override
        public void showMore() {
            AlivcPlayerActivity alivcPlayerActivity = weakReference.get();
            if (alivcPlayerActivity != null) {
                long currentClickTime = System.currentTimeMillis();
                // 防止快速点击
                if (currentClickTime - alivcPlayerActivity.oldTime <= 1000) {
                    return;
                }
                alivcPlayerActivity.oldTime = currentClickTime;
                alivcPlayerActivity.showMore(alivcPlayerActivity);
            }
        }
    }


    //  ... 的点击事件   三个点的点击事件
    private void showMore(AlivcPlayerActivity activity) {

        showMoreDialog = new AlivcShowMoreDialog(activity);
        AliyunShowMoreValue moreValue = new AliyunShowMoreValue();
        moreValue.setSpeed(mAliyunVodPlayerView.getCurrentSpeed());
        moreValue.setVolume((int) mAliyunVodPlayerView.getCurrentVolume());

        ShowMoreView showMoreView = new ShowMoreView(activity, moreValue);

        if (isHighEndChip()) {
            showMoreView.setDMVisibile(View.VISIBLE);
        } else {
            showMoreView.setDMVisibile(View.GONE);
        }

        showMoreDialog.setContentView(showMoreView);
        try {
            showMoreDialog.show();
        } catch (Exception ignord) {

        }
        showMoreView.setOnDownloadButtonClickListener(new ShowMoreView.OnDownloadButtonClickListener() {
            @Override
            public void onDownloadClick() {

            }
        });


        /**
         * 初始化亮度
         */
        if (mAliyunVodPlayerView != null) {
            showMoreView.setBrightness(mAliyunVodPlayerView.getScreenBrightness());
        }
        // 亮度seek
        showMoreView.setOnLightSeekChangeListener(new ShowMoreView.OnLightSeekChangeListener() {
            @Override
            public void onStart(SeekBar seekBar) {

            }

            @Override
            public void onProgress(SeekBar seekBar, int progress, boolean fromUser) {
                setWindowBrightness(progress);
                if (mAliyunVodPlayerView != null) {
                    mAliyunVodPlayerView.setScreenBrightness(progress);
                }
            }

            @Override
            public void onStop(SeekBar seekBar) {

            }
        });

        /**
         * 初始化音量
         */
        if (mAliyunVodPlayerView != null) {
            showMoreView.setVoiceVolume(mAliyunVodPlayerView.getCurrentVolume());
        }
        showMoreView.setOnVoiceSeekChangeListener(new ShowMoreView.OnVoiceSeekChangeListener() {
            @Override
            public void onStart(SeekBar seekBar) {

            }

            @Override
            public void onProgress(SeekBar seekBar, int progress, boolean fromUser) {
                mAliyunVodPlayerView.setCurrentVolume(progress / 100.00f);
            }

            @Override
            public void onStop(SeekBar seekBar) {

            }
        });

        showMoreView.setOnBarrageButtonClickListener(new ShowMoreView.OnBarrageButtonClickListener() {
            @Override
            public void onBarrageClick() {
                if (showMoreDialog != null && showMoreDialog.isShowing()) {
                    showMoreDialog.dismiss();
                }
                showDanmakuSettingView();
            }
        });

        showMoreView.setOnScreenCastButtonClickListener(new ShowMoreView.OnScreenCastButtonClickListener() {
            @Override
            public void onScreenCastClick() {
                //如果是本地视频,则不支持投屏
                if (mIsLocal) {
                    ToastUtils.show(AlivcPlayerActivity.this, getString(R.string.alivc_player_local_not_support_screencost));
                    return;
                }
                if (showMoreDialog != null && showMoreDialog.isShowing()) {
                    showMoreDialog.dismiss();
                }
                showScreenCastView();
            }
        });
    }

    /**
     * 显示投屏对话框
     */
    private void showScreenCastView() {
        try {
            screenShowMoreDialog.show();
        } catch (Exception ignord) {

        }
    }

    /**
     * 显示弹幕设置对话框
     */
    private void showDanmakuSettingView() {
        danmakuShowMoreDialog = new AlivcShowMoreDialog(this);
        DanmakuSettingView mDanmakuSettingView = new DanmakuSettingView(this);
        mDanmakuSettingView.setAlphaProgress(mAlphProgress);
        mDanmakuSettingView.setSpeedProgress(mSpeedProgress);
        mDanmakuSettingView.setRegionProgress(mRegionProgress);
        danmakuShowMoreDialog.setContentView(mDanmakuSettingView);
        try {
            danmakuShowMoreDialog.show();
        } catch (Exception ignord) {

        }

        //透明度
        mDanmakuSettingView.setOnAlphaSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                mAlphProgress = progress;
                if (mAliyunVodPlayerView != null) {
                    mAliyunVodPlayerView.setDanmakuAlpha(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        //显示区域
        mDanmakuSettingView.setOnRegionSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                mRegionProgress = progress;
                if (mAliyunVodPlayerView != null) {
                    mAliyunVodPlayerView.setDanmakuRegion(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        //速率
        mDanmakuSettingView.setOnSpeedSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                mSpeedProgress = progress;
                if (mAliyunVodPlayerView != null) {
                    mAliyunVodPlayerView.setDanmakuSpeed(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        //恢复默认
        mDanmakuSettingView.setOnDefaultListener(new DanmakuSettingView.OnDefaultClickListener() {
            @Override
            public void onDefaultClick() {
                if (mAliyunVodPlayerView != null) {
                    mAliyunVodPlayerView.setDanmakuDefault();
                }
            }
        });

    }


    /**
     * 发送弹幕
     */
    private class MynewOnSoftKeyHideListener implements AliyunVodPlayerView.OnSoftKeyHideListener {

        private WeakReference<AlivcPlayerActivity> weakReference;

        private MynewOnSoftKeyHideListener(AlivcPlayerActivity aliyunPlayerSkinActivity) {
            weakReference = new WeakReference<>(aliyunPlayerSkinActivity);
        }

        @Override
        public void softKeyHide() {

        }

        @Override
        public void onClickPaint() {
            AlivcPlayerActivity aliyunPlayerActivity = weakReference.get();
            if (aliyunPlayerActivity != null) {
                aliyunPlayerActivity.mSoftInputDialogFragment.show(getFragmentManager(), "SoftInputDialogFragment");

            }

        }
    }

    private static class MyOnScreenCostingSingleTagListener implements OnScreenCostingSingleTagListener {

        private WeakReference<AlivcPlayerActivity> weakReference;

        private MyOnScreenCostingSingleTagListener(AlivcPlayerActivity aliyunPlayerSkinActivity) {
            weakReference = new WeakReference<>(aliyunPlayerSkinActivity);
        }

        @Override
        public void onScreenCostingSingleTag() {
            AlivcPlayerActivity aliyunPlayerSkinActivity = weakReference.get();
            if (aliyunPlayerSkinActivity != null) {
                aliyunPlayerSkinActivity.screenCostingSingleTag();
            }
        }
    }

    private void screenCostingSingleTag() {
        if (screenShowMoreDialog != null && screenShowMoreDialog.isShowing()) {
            screenShowMoreDialog.dismiss();
        }
    }

    /**
     * 投屏时,视频播放完成回调
     */
    private static class OnScreenCostingVideoCompletionListener implements AliyunVodPlayerView.OnScreenCostingVideoCompletionListener {

        private WeakReference<AlivcPlayerActivity> weakReference;

        public OnScreenCostingVideoCompletionListener(AlivcPlayerActivity alivcPlayerActivity) {
            weakReference = new WeakReference<>(alivcPlayerActivity);
        }

        @Override
        public void onScreenCostingVideoCompletion() {
            AlivcPlayerActivity alivcPlayerActivity = weakReference.get();
            if (alivcPlayerActivity != null) {
//                alivcPlayerActivity.screenCostingVideoCompletion();
            }
        }
    }


    /**
     * 横竖屏切换监听
     */
    public class PlayerOrientationChangeListner implements AliyunVodPlayerView.OnOrientationChangeListener {

        private WeakReference<AlivcPlayerActivity> weakReference;

        public PlayerOrientationChangeListner(AlivcPlayerActivity alivcPlayerActivity) {
            weakReference = new WeakReference<>(alivcPlayerActivity);
        }

        @Override
        public void orientationChange(boolean from, AliyunScreenMode currentMode) {
            AlivcPlayerActivity alivcPlayerActivity = weakReference.get();
            if (alivcPlayerActivity != null) {
                if (alivcPlayerActivity.mIsLocal && currentMode == AliyunScreenMode.Small) {
                    finish();
                } else {
                    alivcPlayerActivity.hideShowMoreDialog(from, currentMode);
                    alivcPlayerActivity.hideDanmakuSettingDialog(from, currentMode);
                    alivcPlayerActivity.hideScreenSostDialog(from, currentMode);
//                alivcPlayerActivity.currentScreenMode = currentMode;
                }
            }
        }
    }

    private void hideShowMoreDialog(boolean from, AliyunScreenMode currentMode) {
        if (showMoreDialog != null) {
            if (currentMode == AliyunScreenMode.Small) {
                showMoreDialog.dismiss();
            }
        }
    }

    private void hideDanmakuSettingDialog(boolean fromUser, AliyunScreenMode currentMode) {
        if (danmakuShowMoreDialog != null) {
            if (currentMode == AliyunScreenMode.Small) {
                danmakuShowMoreDialog.dismiss();
            }
        }
    }

    private void hideScreenSostDialog(boolean fromUser, AliyunScreenMode currentMode) {
        if (screenShowMoreDialog != null) {
            if (currentMode == AliyunScreenMode.Small) {
                screenShowMoreDialog.dismiss();
            }
        }
    }

    /**
     * 屏幕亮度改变监听
     */
    public static class PlayerControlViewScreenBrightnessListener implements AliyunVodPlayerView.OnScreenBrightnessListener {

        private WeakReference<AlivcPlayerActivity> weakReference;

        public PlayerControlViewScreenBrightnessListener(AlivcPlayerActivity alivcPlayerActivity) {
            weakReference = new WeakReference<>(alivcPlayerActivity);
        }

        @Override
        public void onScreenBrightness(int brightness) {
            AlivcPlayerActivity alivcPlayerActivity = weakReference.get();
            if (alivcPlayerActivity != null) {
                alivcPlayerActivity.onScreenBrightness(brightness);
            }
        }
    }

    private void onScreenBrightness(int brightness) {
        if (mAliyunVodPlayerView != null) {
            mAliyunVodPlayerView.setScreenBrightness(brightness);
            setWindowBrightness(brightness);
        }

    }

    class LeftTimeReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Contants.ACTION_SENDLEFT)) {
                int leftTime = intent.getIntExtra(Contants.LEFT_TIME, -1);
                if (leftTime == -1) {
                    mAliyunVodPlayerView.pause();
                    try {
                        dialogLoginError.show();
                    } catch (Exception ignord) {

                    }
                    return;
                }
                if (leftTime <= 60) {
                    mAliyunVodPlayerView.pause();
                    try {
                        dialogLeftTime.show();
                    } catch (Exception ignord) {

                    }
                } else {
                    ToastUtils.show(AlivcPlayerActivity.this, getString(R.string.lefttime_less));
                }
            }
        }
    }

    //全屏并且隐藏状态栏
    private void hideStatusBar() {
        WindowManager.LayoutParams attrs = getWindow().getAttributes();
        attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
        getWindow().setAttributes(attrs);
    }


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

                }
            }
        }
    }


    /*
     *  取消人工答疑排队弹窗
     * */
    private void showCancelQueueDialog() {

        AlertDialog alertDialog = new AlertDialog.Builder(AlivcPlayerActivity.this)
                .setTitle(R.string.tip)
                .setMessage(R.string.cancel_queue)
                .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                })
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                .create();
        try {
            alertDialog.show();
        } catch (Exception ignord) {

        }
    }

    private static final int MIN_CLICK_DELAY_TIME = 1500;
    private static long lastClickTime;

    // 使用 if (isFastClick()) return;
    public static boolean isFastClick() {

        long curClickTime = System.currentTimeMillis();

        if ((curClickTime - lastClickTime) < MIN_CLICK_DELAY_TIME) {
            return true;
        }
        lastClickTime = curClickTime;

        return false;

    }

    @Override
    public void onBackPressed() {
        if (classinWaittingFlag) {
            showCancelQueueDialog();
        } else {
            super.onBackPressed();
        }
    }

    // ==================================================================================================

    private void showFeedBack() {
        if (popVideoSecen.isShowing()) {
            popVideoSecen.dismiss();
        }
        if (popupWindowSmartQA.isShowing()) {
            popupWindowSmartQA.dismiss();
        }
        popupWindowLearningFeedback.showAtLocation(rlRoot, Gravity.TOP + Gravity.RIGHT, 0, 0);
        if (webView != null) {
            try {
                webView.resumeTimers();
                webView.onShow();
            } catch (Exception ignord) {

            }
        }
    }


    private void showSmartQA() {
        if (popupWindowLearningFeedback.isShowing()) {
            popupWindowLearningFeedback.dismiss();
            if (webView != null) {
                webView.pauseTimers();
                webView.onHide();
            }
        }
        if (popVideoSecen.isShowing()) {
            popVideoSecen.dismiss();
        }
//                if (isHighEndChip()) {
        popupWindowSmartQA.showAtLocation(rlRoot, Gravity.TOP + Gravity.RIGHT, 0, 0);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
        Date date = new Date(System.currentTimeMillis());
        tvTime.setText(simpleDateFormat.format(date));
//                } else {
//                    QAFullScreenActivity.startActivity(mContext, videoId, courseId, seekToPoint);
//                    finish();
//                }
    }

    private void showKnowledge() {
        if (popupWindowLearningFeedback.isShowing()) {
            popupWindowLearningFeedback.dismiss();
            if (webView != null) {
                webView.pauseTimers();
                webView.onHide();
            }
        }
        if (popupWindowSmartQA.isShowing()) {
            popupWindowSmartQA.dismiss();
        }
        popVideoSecen.showAtLocation(rlRoot, Gravity.TOP + Gravity.RIGHT, 0, 0);
        tvChooseKnowledge.setVisibility(View.GONE);
    }

    // ==================================================================================================


    private void setTouchEvent(View view, View contentView) {
        view.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;
                        popupWindowLearningFeedback.update(1080 - offsetX + contentView.getWidth() + 40, offsetY, -1, -1, true);
                        break;
                    case MotionEvent.ACTION_UP:
                        break;
                    default:
                        break;
                }
                return true;
            }
        });
    }

    // ==================================================================================================

    /*
     *  初始化 右上角按钮 pop
     * */
    private void initTabPopupWindow() {
        View contentView = LayoutInflater.from(this).inflate(R.layout.popupwindow_tab, null); // 202103 智能答疑按钮所在布局
        popupWindowTab = new PopupWindow(this);
        popupWindowTab.setContentView(contentView);
        popupWindowTab.setWidth(POPUPWINDOW_WIDTH);
        popupWindowTab.setFocusable(true);
        popupWindowTab.setBackgroundDrawable(new PaintDrawable());
        contentView.findViewById(R.id.common_toolbar_title).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showFeedBack();
                popupWindowTab.dismiss();
            }
        });
        // 202103 智能答疑按钮
        contentView.findViewById(R.id.common_toolbar_title_qa).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showSmartQA();
                popupWindowTab.dismiss();
            }
        });

        // 知识点
        contentView.findViewById(R.id.tv_knowledge).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showKnowledge();
                popupWindowTab.dismiss();
            }
        });
    }


    /*
     *  初始化 智能答疑pop
     * */
    private void initSmartQAPopupwindow() {
        SmartQAClick smartQAClick = new SmartQAClick();
        LayoutInflater inflater = LayoutInflater.from(this);
        View contentView = inflater.inflate(R.layout.popupwindow_smart_q_a, null);
        tvManualAnswering = contentView.findViewById(R.id.tv_manual_answering);
        lvSmartqaData = contentView.findViewById(R.id.lv_smartqa_data);
        tvTime = contentView.findViewById(R.id.tv_time);
        adapterQuestion = new QuestionPopupAdapter(listQuestion, mContext);
        lvSmartqaData.setAdapter(adapterQuestion);
        adapterTestQuestion = new TestQuestionAdapter(listTestQuestion, this);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        edKeyword = contentView.findViewById(R.id.ed_keyword);
        tvFindbykeyword = contentView.findViewById(R.id.tv_findbykeyword);
        TextView common_toolbar_title = contentView.findViewById(R.id.common_toolbar_title);
        popupWindowSmartQA = new PopupWindow(this);
        popupWindowSmartQA.setContentView(contentView);
        popupWindowSmartQA.setWidth(POPUPWINDOW_WIDTH);
        popupWindowSmartQA.setHeight(POPUPWINDOW_HEIGHT);
        popupWindowSmartQA.setFocusable(true);
        popupWindowSmartQA.setBackgroundDrawable(new PaintDrawable());
        tvFindbykeyword.setOnClickListener(smartQAClick);
        tvManualAnswering.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) {

                }
            }
        });
        adapterQuestion.setOnPicClickListener(new QuestionPopupAdapter.OnPicClickListener() {
            @Override
            public void onPicAnswerClicked(int pos) {
                Intent intent = new Intent(AlivcPlayerActivity.this, PicActivity.class);
                intent.putExtra("url", listQuestion.get(pos).getAnswerBean().getAnswerContent());
                startActivity(intent);
            }
        });

        TextView view = contentView.findViewById(R.id.common_toolbar_title_qa);
        setTouchEvent(view, contentView);

        common_toolbar_title.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showFeedBack();
            }
        });

        // 知识点
        contentView.findViewById(R.id.tv_knowledge).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showKnowledge();
            }
        });

    }


    /*
     *  初始化 学情反馈pop
     * */
    private void initLearningFeedbackPopupwindow() {
        View contentView = LayoutInflater.from(this).inflate(R.layout.popupwindow_learning_feedback, null);
        webView = contentView.findViewById(R.id.wv_data);
        String url = UrlConfig.BASE + "Home/Xiti/index?userId=" + SpUtil.getInstace().getString(Contants.USER_ID, null) + "&videoId=" + videoId;
        webView.setResourceClient(new MyResourceClient(webView));
        webView.loadUrl(url);
        popupWindowLearningFeedback = new PopupWindow(this);
        popupWindowLearningFeedback.setContentView(contentView);
        popupWindowLearningFeedback.setWidth(POPUPWINDOW_WIDTH);
        popupWindowLearningFeedback.setHeight(POPUPWINDOW_HEIGHT);
        popupWindowLearningFeedback.setFocusable(true);
        popupWindowLearningFeedback.setBackgroundDrawable(new PaintDrawable());

        contentView.findViewById(R.id.common_toolbar_title_qa).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showSmartQA();
            }
        });
        // 知识点
        contentView.findViewById(R.id.tv_knowledge).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showKnowledge();
            }
        });

        TextView view = contentView.findViewById(R.id.common_toolbar_title);
        setTouchEvent(view, contentView);
    }

    class MyResourceClient extends XWalkResourceClient {
        MyResourceClient(XWalkView view) {
            super(view);
        }

        @Override
        public boolean shouldOverrideUrlLoading(XWalkView view, String url) {
            if (url.startsWith(UrlConfig.BASE)) {
                return false;
            } else {
                return true;
            }
        }

        @Override
        public XWalkWebResourceResponse shouldInterceptLoadRequest(XWalkView view, XWalkWebResourceRequest request) {
            String url = request.getUrl().toString();
            if (url.startsWith(UrlConfig.BASE)) {
                return super.shouldInterceptLoadRequest(view, request);
            } else {
                return createXWalkWebResourceResponse("text/html", "UTF-8", null);
            }
        }
    }

    //  知识点切片
    List<KonwledgeBean.ListBean> listVideoScene = new ArrayList<>();
    VideoSceneAdapter adapterVideoScene;

    /*
     *  初始化 知识点pop
     * */
    private void initVideoScenePop() {

        popVideoSecen = new PopupWindow();
        View contentView = LayoutInflater.from(AlivcPlayerActivity.this).inflate(R.layout.layout_pop_video_scene, null);
        popVideoSecen.setContentView(contentView);
        popVideoSecen.setContentView(contentView);
        popVideoSecen.setWidth(POPUPWINDOW_WIDTH);
        popVideoSecen.setHeight(POPUPWINDOW_HEIGHT);
        popVideoSecen.setFocusable(true);
        popVideoSecen.setBackgroundDrawable(new PaintDrawable());
        popVideoSecen.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                try {
                    tvChooseKnowledge.setVisibility(View.GONE);
                } catch (Exception ignored) {
                }
            }
        });
        tvChooseKnowledge = contentView.findViewById(R.id.tv_choose_knowledge);
        RecyclerView recyclerView = contentView.findViewById(R.id.recy);
        recyclerView.setLayoutManager(new LinearLayoutManager(AlivcPlayerActivity.this, RecyclerView.VERTICAL, false));
        adapterVideoScene = new VideoSceneAdapter(AlivcPlayerActivity.this, listVideoScene);
        adapterVideoScene.setOnItemClick(new VideoSceneAdapter.OnItemClick() {
            @Override
            public void onItemClick(int pos) {
                popVideoSecen.dismiss();
                long l;
                try {
                    String secondes = listVideoScene.get(pos).getKnowledgeTime();  // 单位 秒
                    l = Long.parseLong(secondes);
                } catch (Exception e) {
                    return;
                }

                final int visibile = tvChooseKnowledge.getVisibility();

                if (visibile == View.VISIBLE) {
                    startManualAnswering(listVideoScene.get(pos).getKnowledgeId());
                } else if (visibile == View.GONE) {
                    mAliyunVodPlayerView.seekTo(l * 1000);
                }

            }
        });
        recyclerView.setAdapter(adapterVideoScene);

        contentView.findViewById(R.id.common_toolbar_title).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showFeedBack();
            }
        });

        contentView.findViewById(R.id.common_toolbar_title_qa).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showSmartQA();
            }
        });


        TextView view = contentView.findViewById(R.id.tv_knowledge);
        setTouchEvent(view, contentView);
    }


    //  知识点切片
    private void getVideoScene(boolean first) {

        OkGoBuilder.getInstance()
                .url(UrlConfig.GET_VIDEO_KONWLEDGE)
                .Builder((Activity) mContext)
                .method(OkGoBuilder.PSOT)
                .cls(KonwledgeBean.class)
                .requestBody(HttpUtils.getRequestJson(getKnowParam()))
                .callback(new OkGoUtil<KonwledgeBean>(KonwledgeBean.class) {
                    @Override
                    public void onSuccess(Response<KonwledgeBean> response) {

                        KonwledgeBean body = response.body();
                        listVideoScene.clear();
                        if (body != null) {
                            List<KonwledgeBean.ListBean> list = body.getList();
                            if (list != null && list.size() > 0) {
                                listVideoScene.addAll(list);
                            }
                        } else {
                            if (!first) {
                                ToastUtils.show(mContext, R.string.neterror);
                            }
                        }
                        adapterVideoScene.notifyDataSetChanged();
                    }

                    @Override
                    public void onError(Response<KonwledgeBean> response) {
                        super.onError(response);
                        listVideoScene.clear();
                        adapterVideoScene.notifyDataSetChanged();
                    }
                }).build();
    }

    private JsonObject getKnowParam() {

        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("userId", SpUtil.getInstace().getString(Contants.USER_ID, null));
        jsonObject.addProperty("videoId", videoId);

        return jsonObject;
    }


    // ------------------------------------------------------------------

    /**
     * 获取例题
     */
//    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 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;
//    }

//    private void initChoseDialog() {
//        dialogChoseMenu = new AlertDialog.Builder(this).setMessage("请选择智能答疑或学情反馈").setPositiveButton("学情反馈", new DialogInterface.OnClickListener() {
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//                dialogChoseMenu.dismiss();
//                popupWindowLearningFeedback.showAtLocation(rlRoot, Gravity.TOP + Gravity.RIGHT, 0, 0);
//            }
//        }).setNegativeButton("智能答疑", new DialogInterface.OnClickListener() {
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//
//            }
//        }).create();
//    }


     /* private void currentVideoBigOrSmall() {
        if (isSwitchAll == NORMAL) {
            SophonSurfaceView surfaceView = (SophonSurfaceView) fl_data.getChildAt(0);
            if (surfaceView != null) {
                surfaceView.setZOrderOnTop(false);
                surfaceView.setZOrderMediaOverlay(false);
            }
            ll_local.bringToFront();
            mLocalView.setZOrderOnTop(true);
            mLocalView.setZOrderMediaOverlay(true);
            isSwitchSmall = NORMAL;
            isSwitchMiddle = NORMAL;
            isSwitchBig = NORMAL;
        } else {
            SophonSurfaceView surfaceView = (SophonSurfaceView) fl_data.getChildAt(0);
            if (surfaceView != null) {
                surfaceView.setZOrderOnTop(true);
                surfaceView.setZOrderMediaOverlay(true);
            }
            fl_data.bringToFront();
            mLocalView.setZOrderOnTop(false);
            mLocalView.setZOrderMediaOverlay(false);
            isSwitchSmall = SWITCH;
            isSwitchMiddle = SWITCH;
            isSwitchBig = SWITCH;
        }

    }*/

    /**
     * 改变视窗大小
     *
     * @param screenSize 选定的大小
     */
   /* private void changeVideoSize(int screenSize) {
        RelativeLayout.LayoutParams params;
        switch (screenSize) {
            case SMALL_SIZE:
                popupWindowForRTC.update(-1, -1, POPUPWINDOW_WIDTH, POPUPWINDOW_HEIGHT, true);
                params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, (int) getResources().getDimension(R.dimen.y400));
                params.addRule(RelativeLayout.BELOW, R.id.tv_bigscreen);
                if (isSwitchAll == NORMAL) {
                    fl_data.setLayoutParams(params);
                } else {
                    ll_local.setLayoutParams(params);
                }
                params = new RelativeLayout.LayoutParams((int) getResources().getDimension(R.dimen.x150), (int) getResources().getDimension(R.dimen.y150));
                params.addRule(RelativeLayout.BELOW, R.id.tv_bigscreen);
                params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                if (isSwitchAll == NORMAL) {
                    ll_local.setLayoutParams(params);
                } else {
                    fl_data.setLayoutParams(params);
                }
                this.screenSize = SMALL_SIZE;
                break;
            case MIDDLE_SIZE:
                popupWindowForRTC.update(offs, -1, MIDDLE_WIDTH, BIG_HEIGHT, true);
                params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, (int) getResources().getDimension(R.dimen.y900));
                params.addRule(RelativeLayout.BELOW, R.id.tv_bigscreen);
                if (isSwitchAll == NORMAL) {
                    fl_data.setLayoutParams(params);
                } else {
                    ll_local.setLayoutParams(params);
                }
                params = new RelativeLayout.LayoutParams((int) getResources().getDimension(R.dimen.x300), (int) getResources().getDimension(R.dimen.y300));
                params.addRule(RelativeLayout.BELOW, R.id.tv_bigscreen);
                params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                if (isSwitchAll == NORMAL) {
                    ll_local.setLayoutParams(params);
                } else {
                    fl_data.setLayoutParams(params);
                }
                this.screenSize = MIDDLE_SIZE;
                break;
            case BIG_SIZE:
                popupWindowForRTC.update(-1, -1, BIG_WIDTH, BIG_HEIGHT, true);
                params = new RelativeLayout.LayoutParams((int) getResources().getDimension(R.dimen.x1920) - 2 * (int) getResources().getDimension(R.dimen.x350), (int) getResources().getDimension(R.dimen.y900));
                params.addRule(RelativeLayout.BELOW, R.id.tv_bigscreen);
                params.addRule(RelativeLayout.CENTER_HORIZONTAL);
                if (isSwitchAll == NORMAL) {
                    fl_data.setLayoutParams(params);
                } else {
                    ll_local.setLayoutParams(params);
                }
                params = new RelativeLayout.LayoutParams((int) getResources().getDimension(R.dimen.x350), (int) getResources().getDimension(R.dimen.y350));
                params.addRule(RelativeLayout.BELOW, R.id.tv_bigscreen);
                params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                if (isSwitchAll == NORMAL) {
                    ll_local.setLayoutParams(params);
                } else {
                    fl_data.setLayoutParams(params);
                }
                this.screenSize = BIG_SIZE;

                break;
        }
        currentVideoBigOrSmall();
    }*/

   /* 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 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 void initSmartQAPopupwindow() {
//        requestOptions = new RequestOptions()
//                .error(R.drawable.ic_head_default_right)
//                .circleCrop();
//        View contentView = LayoutInflater.from(this).inflate(R.layout.activity_smart_q_a, null);
//        rvChatList = contentView.findViewById(R.id.rv_chat_list);
//        iv_head = contentView.findViewById(R.id.iv_head);
//        LinearLayoutManager mLinearLayout = new LinearLayoutManager(this);
//        rvChatList.setLayoutManager(mLinearLayout);
//        smartQAAdapter = new SmartQAAdapter(this, listSmartQA);
//        rvChatList.setAdapter(smartQAAdapter);
//        etContent = contentView.findViewById(R.id.et_content);
//        ivEmoji = contentView.findViewById(R.id.iv_emoji);
//        btnSend = contentView.findViewById(R.id.btn_send);
//        bottomLayout = contentView.findViewById(R.id.bottom_layout);
//        rlEmotion = contentView.findViewById(R.id.rlEmotion);
//        llContent = contentView.findViewById(R.id.llContent);
//        tv_title = contentView.findViewById(R.id.common_toolbar_title);
//        homeEmoji = contentView.findViewById(R.id.home_emoji);
//        vpEmoji = contentView.findViewById(R.id.vp_emoji);
//        indEmoji = contentView.findViewById(R.id.ind_emoji);
//        popupWindowSmartQA = new PopupWindow(this);
//        popupWindowSmartQA.setContentView(contentView);
//        popupWindowSmartQA.setWidth(POPUPWINDOW_WIDTH);
//        popupWindowSmartQA.setHeight(POPUPWINDOW_HEIGHT);
//        popupWindowSmartQA.setFocusable(true);
//        popupWindowSmartQA.setBackgroundDrawable(new PaintDrawable());
//        tv_title.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;
//
//
////                       offs etX = (int) event.getRawX() - orgX;
////                        offsetY = (int) event.getRawY() - orgY;
//                        popupWindowSmartQA.update(1080 - offsetX + 400 + orgX + tv_title.getWidth(), offsetY, -1, -1, true);
//                        break;
//                    case MotionEvent.ACTION_UP:
//                        break;
//                }
//                return true;
//            }
//        });
//        contentView.findViewById(R.id.bottom_drag_view).setOnTouchListener(new View.OnTouchListener() {
//
//            int orgY, orgHeight, offsetY;
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                switch (event.getAction()) {
//                    case MotionEvent.ACTION_DOWN:
//                        orgY = (int) event.getRawY();
//                        orgHeight = popupWindowSmartQA.getHeight();
//                        break;
//                    case MotionEvent.ACTION_MOVE:
//                        offsetY = (int)event.getRawY() - orgY;
//                        popupWindowSmartQA.update(-1, (orgHeight + offsetY > POPUPWINDOW_MIN_HEIGHT) ? orgHeight + offsetY : -1);
//                        break;
//                    case MotionEvent.ACTION_UP:
//                        break;
//                }
//                return true;
//            }
//        });
//        contentView.findViewById(R.id.bottom_drag_view).setOnHoverListener(new View.OnHoverListener() {
//
//            PointerIcon mOrgPI;
//            //@SuppressLint({"SetTextI18n", "ResourceType"})
//            @RequiresApi(api = Build.VERSION_CODES.N)
//            @Override
//            public boolean onHover(View v, MotionEvent event) {
//                int what = event.getAction();
//                switch(what){
//                    case MotionEvent.ACTION_HOVER_ENTER:  //鼠标进入view
//                        mOrgPI = getWindow().getDecorView().getPointerIcon();
//                        Log.i("lhsdrag", "bottom ACTION_HOVER_ENTER...mOrgPI ");
//                        getWindow().getDecorView().setPointerIcon(PointerIcon.getSystemIcon(AlivcPlayerActivity.this, PointerIcon.TYPE_GRAB));
//                        break;
//                    case MotionEvent.ACTION_HOVER_MOVE:  //鼠标在view上
//                        Log.i(TAG, "bottom ACTION_HOVER_MOVE...");
//                        break;
//                    case MotionEvent.ACTION_HOVER_EXIT:  //鼠标离开view
//                        Log.i("lhsdrag", "bottom ACTION_HOVER_EXIT...");
//                        getWindow().getDecorView().setPointerIcon(mOrgPI);
//                        break;
//                }
//                return false;
//            }
//        });
//        contentView.findViewById(R.id.tv_manual_answering).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                popupWindowSmartQA.dismiss();
//                initPopupWindowForRTC();
//                getAuthAndJoinChannel();
//                popupWindowForRTC.showAtLocation(rlRoot, Gravity.TOP + Gravity.RIGHT, 0, 0);
//            }
//        });
//        contentView.findViewById(R.id.tv_learning_feedback).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                popupWindowSmartQA.dismiss();
//                popupWindowLearningFeedback.showAtLocation(rlRoot, Gravity.TOP + Gravity.RIGHT, 0, 0);
//            }
//        });
//        sendSmartQA("", true);
//        initChatUi();
//    }


  /*  private void initChatUi() {
        //mBtnAudio
        mUiHelper = ChatUiHelper.with(this);
        mUiHelper.bindContentLayout(llContent)
                .bindttToSendButton(btnSend)
                .bindEditText(etContent)
                .bindBottomLayout(bottomLayout)
                .bindEmojiLayout(rlEmotion)
                .bindToEmojiButton(ivEmoji)
                .bindEmojiData(homeEmoji, vpEmoji, indEmoji);
        //底部布局弹出,聊天列表上滑
        rvChatList.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                if (bottom < oldBottom) {
                    rvChatList.post(new Runnable() {
                        @Override
                        public void run() {
                            if (smartQAAdapter.getItemCount() > 0) {
                                rvChatList.smoothScrollToPosition(smartQAAdapter.getItemCount() - 1);
                            }
                        }
                    });
                }
            }
        });
//        //点击空白区域关闭键盘
        rvChatList.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                mUiHelper.hideBottomLayout(false);
                mUiHelper.hideSoftInput();
                etContent.clearFocus();
                ivEmoji.setImageResource(R.drawable.ic_emoji);
                return false;
            }
        });
        btnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (etContent.getText().toString() != null && !TextUtils.isEmpty(etContent.getText().toString())) {
                    sendSmartQA(etContent.getText().toString(), false);
                } else {
                    ToastUtils.show(mContext, getString(R.string.please_desqa));
                }
            }
        });
    }*/

   /* private void sendSmartQA(final String question, final boolean isInit) {
        OkGoBuilder.getInstance().url(UrlConfig.SMARTQA).Builder((Activity) mContext).method(OkGoBuilder.PSOT).cls(SmartQABean.class).requestBody(HttpUtils.getRequestJson(initSmartQARequestBody(question))).callback(new OkGoUtil<SmartQABean>(SmartQABean.class) {
            @Override
            public void onSuccess(Response<SmartQABean> response) {
                if (response.body() != null && response.body() instanceof SmartQABean) {
                    mUiHelper.hideBottomLayout(false);
                    mUiHelper.hideSoftInput();
                    etContent.clearFocus();
                    ivEmoji.setImageResource(R.drawable.ic_emoji);
                    etContent.getText().clear();
                    if (!isInit) {
                        sendBean = new SmartQABean.ListBean();
                        sendBean.setContent(question);
                        sendBean.setSendType(1);
                        sendBean.setSendTime(DateUtils.format(System.currentTimeMillis(), "HH:mm:ss"));
                        listSmartQA.add(sendBean);
                    }
                    SmartQABean smartQABean = response.body();
                    if (isInit) {
                        Glide.with(AlivcPlayerActivity.this)
                                .load(smartQABean.getAvaterUrl())
                                .apply(requestOptions)
                                .into(iv_head);
                    }
                    List<SmartQABean.ListBean> list = smartQABean.getList();
                    if (list != null && list.size() != 0) {
                        listSmartQA.addAll(list);
                    }
                    smartQAAdapter.notifyDataSetChanged();
                    if (smartQAAdapter.getItemCount() != 0) {
                        rvChatList.smoothScrollToPosition(smartQAAdapter.getItemCount() - 1);
                    }
                }
            }

            @Override
            public void onError(Response<SmartQABean> response) {
//                loadingView.dismiss();
                super.onError(response);
            }
        }).build();
    }*/


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

/*    private void initPopupWindowForRTC() {
        View contentView = LayoutInflater.from(this).inflate(R.layout.activity_video_q_a, null);
        TextView tvSmallscreen = contentView.findViewById(R.id.tv_smallscreen);
        TextView tvMiddlescreen = contentView.findViewById(R.id.tv_middlescreen);
        TextView tvBigscreen = contentView.findViewById(R.id.tv_bigscreen);

        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);
        ll_local = contentView.findViewById(R.id.ll_local);
        iv_switch = contentView.findViewById(R.id.iv_switch);
//        TextView tv_changescreen = contentView.findViewById(R.id.tv_changescreen);
        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) {
                if (screenSize == 0) {
                    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 + orgX + 40 + contentView.getWidth() - orgX, offsetY, -1, -1, true);
                            break;
                        case MotionEvent.ACTION_UP:
                            break;
                    }
                    return true;
                }
                return false;
            }
        });
        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();
                handler.removeMessages(0);
            }
        });
        tvSmallscreen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (screenSize == SMALL_SIZE) {
                    return;
                }
                changeVideoSize(SMALL_SIZE);
            }
        });
        tvMiddlescreen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (screenSize == MIDDLE_SIZE) {
                    return;
                }
                changeVideoSize(MIDDLE_SIZE);
            }
        });
        tvBigscreen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (screenSize == BIG_SIZE) {
                    return;
                }
                changeVideoSize(BIG_SIZE);
            }
        });
        iv_switch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switchVideo(screenSize);
            }
        });
    }*/



    /*    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, 5000);
                    queue--;
                    if (!SpUtil.getInstace().getBoolean(Contants.IS_NEED_QUEUE, false)) {
                        AlivcPlayerActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                tvTitleForRTC.setText(getString(R.string.exclusion_video) + "\n前方有" + queue + "人正排队等待,预计" + queue + "分钟后内应答,请稍后.");
                            }
                        });
                    }

                } else {
                    AlivcPlayerActivity.this.mAliyunVodPlayerView.pause();
                    if (SpUtil.getInstace().getBoolean(Contants.IS_NEED_QUEUE, false)) {
                        AlivcPlayerActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                new android.app.AlertDialog.Builder(AlivcPlayerActivity.this)
                                        .setTitle("提示")
                                        .setMessage("老师已准备好，请确认接通")
                                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加"Yes"按钮
                                            @Override
                                            public void onClick(DialogInterface dialogInterface, int i) {
                                                finish();
                                            }
                                        }).create().show();
                            }
                        });

                    } else {
                        AlivcPlayerActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                new AlertDialog.Builder(AlivcPlayerActivity.this)
                                        .setTitle("提示")
                                        .setMessage("老师已准备好，请确认接通")
                                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加"Yes"按钮
                                            @Override
                                            public void onClick(DialogInterface dialogInterface, int i) {
                                                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();
                                                }
                                                //popupWindowForRTC.showAtLocation(rlRoot, Gravity.TOP + Gravity.RIGHT, 0, 0);

                                                try {
                                                    ClassInSdkManager.setEnableEvalPage(true);
                                                    ClassInSdkManager.setEnableSoftDecoder(false);
                                                    ClassInSdkManager.setEnableUdp(false);
                                                    ClassInSdkManager.openClassRoom((Activity) mContext, "15909832215", 101110l, 42451, 37353, "dd", new ClassInSdkManager.OnEnterRoomStateListener() {

                                                        @Override
                                                        public void onExitRoom(int i, @NotNull String s) {
                                                            Toast.makeText(mContext, "Code:" + i + " | " + s, Toast.LENGTH_SHORT).show();
                                                        }

                                                        @Override
                                                        public void onEnterSuccess() {
                                                            Toast.makeText(mContext, "进入成功", Toast.LENGTH_SHORT).show();
                                                        }

                                                        @Override
                                                        public void onEnterFailed(@NotNull String s) {
                                                            Toast.makeText(mContext, s, Toast.LENGTH_SHORT).show();
                                                        }
                                                    });
                                                } catch (Exception e) {
                                                    Toast.makeText(mContext, e.getMessage(), Toast.LENGTH_LONG).show();
                                                }
                                                //changeVideoSize(screenSize);
                                            }
                                        }).create().show();
                            }
                        });
                    }
                    handler.removeMessages(0);
                }
            }
        }).start();
    }*/

   /* 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(AlivcPlayerActivity.this)
                .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 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");
        getQueueInfo();
    }*/

  /*  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);
                }
                handler.removeMessages(0);
//                tvTitleForRTC.setText(R.string.rtc_with_teacher);
            }

        });

    }*/

   /* 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);

            }
        });
    }*/


//    /**
//     * 试看点击事件
//     */
//    public static class PlayerTrailerViewClickListener implements TrailersView.OnTrailerViewClickListener {
//
//        private WeakReference<AlivcPlayerActivity> weakReference;
//
//        public PlayerTrailerViewClickListener(AlivcPlayerActivity alivcPlayerActivity) {
//            weakReference = new WeakReference<>(alivcPlayerActivity);
//        }
//
//        @Override
//        public void onTrailerPlayAgainClick() {
//            AlivcPlayerActivity alivcPlayerActivity = weakReference.get();
//            if (alivcPlayerActivity != null) {
////                alivcPlayerActivity.requestSts(false);
//            }
//        }
//
//        @Override
//        public void onOpenVipClick() {
//            AlivcPlayerActivity alivcPlayerActivity = weakReference.get();
//            if (alivcPlayerActivity != null) {
//                alivcPlayerActivity.onOpenVipClick();
//            }
//        }
//    }


//    private void onOpenVipClick() {
//        Intent intent = new Intent(this, AlivcSettingActivity.class);
//        startActivity(intent);
//    }

    //    private void screenCostingVideoCompletion() {
//        onPlayerCompletion();
//    }


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

}
