package com.bokecc.dwlivedemo.activity;

import static android.view.View.VISIBLE;
import static com.bokecc.dwlivedemo.utils.NotificationUtil.ACTION_DESTROY;
import static com.bokecc.dwlivedemo.utils.NotificationUtil.ACTION_PLAY_PAUSE;
import static com.bokecc.livemodule.utils.AppPhoneStateListener.ACTION_PAUSE;
import static com.bokecc.livemodule.utils.AppPhoneStateListener.ACTION_RESUME;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.bokecc.chatroom.impl.ChatRoomManagerImpl;
import com.bokecc.chatroom.pojo.bean.CCInteractionViewBean;
import com.bokecc.chatroom.pojo.bean.ChatConfig;
import com.bokecc.chatroom.pojo.bean.RoleConstrant;
import com.bokecc.chatroom.ui.CCChatView;
import com.bokecc.chatroom.ui.listener.IChatRoomListener;
import com.bokecc.chatroom.ui.listener.IEmojiLayoutListener;
import com.bokecc.commerce.CommerceUiListener;
import com.bokecc.commerce.pojo.CCGoodsModel;
import com.bokecc.commerce.view.CCGoodsListView;
import com.bokecc.commerce.view.CCRecommendGoodsView;
import com.bokecc.common.utils.Tools;
import com.bokecc.dwlivedemo.Constants;
import com.bokecc.dwlivedemo.DWApplication;
import com.bokecc.dwlivedemo.R;
import com.bokecc.dwlivedemo.base.BaseActivity;
import com.bokecc.dwlivedemo.component.RTCComponent;
import com.bokecc.dwlivedemo.popup.ExitPopupWindow;
import com.bokecc.dwlivedemo.utils.NotificationUtil;
import com.bokecc.gift.pojo.GiftInfo;
import com.bokecc.gson.Gson;
import com.bokecc.invitationcard.IBaseCallBack;
import com.bokecc.invitationcard.pojo.InvitationCardRankBean;
import com.bokecc.invitationcard.ui.InvitationCardBaseLayout;
import com.bokecc.invitationcard.ui.InvitationCardMainLayout;
import com.bokecc.invitationcard.ui.InvitationCardRankList;
import com.bokecc.invitationcard.ui.utils.ImageUtils;
import com.bokecc.livemodule.base.BaseDocComponent;
import com.bokecc.livemodule.live.DWLiveCoreHandler;
import com.bokecc.livemodule.live.DWLiveRedPacketListener;
import com.bokecc.livemodule.live.chat.KeyboardHeightObserver;
import com.bokecc.livemodule.live.chat.KeyboardHeightProvider;
import com.bokecc.livemodule.live.courseware.CoursewareComponent;
import com.bokecc.livemodule.live.doc.LiveDocComponent;
import com.bokecc.livemodule.live.doc.LiveDocComponentOld;
import com.bokecc.livemodule.live.function.FunctionCallBack;
import com.bokecc.livemodule.live.function.FunctionHandler;
import com.bokecc.livemodule.live.intro.LiveIntroComponent;
import com.bokecc.livemodule.live.morefunction.MoreFunctionLayout;
import com.bokecc.livemodule.live.morefunction.rtc.RTCVideoLayout;
import com.bokecc.livemodule.live.multirtc.MultiRTCControlLayout;
import com.bokecc.livemodule.live.multirtc.MultiRTCVideoLayout;
import com.bokecc.livemodule.live.qa.LiveQAComponent;
import com.bokecc.livemodule.live.qa.qainputlayout.QaInputLayout;
import com.bokecc.livemodule.live.room.LiveRoomLayout;
import com.bokecc.livemodule.live.video.LiveVideoView;
import com.bokecc.livemodule.popup.FloatingPopupWindow;
import com.bokecc.livemodule.utils.ChatImageUtils;
import com.bokecc.livemodule.utils.KeyboardUtils;
import com.bokecc.livemodule.utils.SPUtil;
import com.bokecc.livemodule.view.CustomToast;
import com.bokecc.livemodule.view.gift.GiftListView;
import com.bokecc.livemodule.view.gift.GiftView;
import com.bokecc.livemodule.view.gift.interfaces.OnClickBottomStatusListener;
import com.bokecc.livemodule.view.like.HintLikeView;
import com.bokecc.livemodule.view.redpacket.RedPacketStateListener;
import com.bokecc.livemodule.view.redpacket.RedPacketViewHelper;
import com.bokecc.questionnaire.ui.IQuestionnaireMainListener;
import com.bokecc.questionnaire.ui.QuestionnaireBaseLayout;
import com.bokecc.questionnaire.ui.QuestionnaireMainLayout;
import com.bokecc.redpacket.ui.RedPacketBaseHelper;
import com.bokecc.redpacket.ui.RedPacketHelper;
import com.bokecc.sdk.mobile.live.BaseCallback;
import com.bokecc.sdk.mobile.live.DWLive;
import com.bokecc.sdk.mobile.live.common.log.ELog;
import com.bokecc.sdk.mobile.live.pojo.ChatMessage;
import com.bokecc.sdk.mobile.live.pojo.InteractionConfigure;
import com.bokecc.sdk.mobile.live.pojo.InteractionOngoing;
import com.bokecc.sdk.mobile.live.pojo.LiveDigestBean;
import com.bokecc.sdk.mobile.live.pojo.RedPacketInfo;
import com.bokecc.vote.ui.IVoteMainListener;
import com.bokecc.vote.ui.VoteBaseLayout;
import com.bokecc.vote.ui.VoteMainLayout;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 直播播放页（默认视频大屏，文档小屏，可手动切换）
 */
public class LivePlayActivity extends BaseActivity implements DWLiveRedPacketListener, KeyboardHeightObserver {

    private static final String TAG = "LivePlayActivity";

    View mRoot;
    private GiftView giftView;

    private HintLikeView hint_like_view;
    // 顶部布局
    RelativeLayout mLiveTopLayout;
    // 底部布局
    RelativeLayout mLiveMsgLayout;
    // 大屏:视频 连麦 文档
    RelativeLayout rl_video_container;
    // 直播间状态布局
    LiveRoomLayout mLiveRoomLayout;
    // 小屏:悬浮弹窗（用于展示文档和视频 连麦）
    FloatingPopupWindow mLiveFloatingView;
    // 直播功能处理机制（签到、答题卡/投票、问卷、抽奖）
    FunctionHandler mFunctionHandler;
    // 更多功能控件（私聊、连麦、公告）
    MoreFunctionLayout mMoreFunctionLayout;
    //多人连麦控制组件
    MultiRTCControlLayout mMultiRTCControlLayout;
    //多人连麦视频组件
    MultiRTCVideoLayout mMultiRTCVideoLayout;
    //多人连麦，横屏模式下展示的视频右侧功能区：包含连麦视频窗口布局与连麦控制器布局
    private LinearLayout mVideoRightPanel;
    private RelativeLayout mVideoRightRTCCon;
    private RelativeLayout mVideoRightControlCon;
    private GiftListView giftListView;

    private RelativeLayout mCideoBottomPanel;

    // 软键盘控制
    private KeyboardHeightProvider keyboardHeightProvider;

    // 随堂测和答题收起功能小图标
    private TextView mLandVote;
    private TextView mPortraitVote;
    // 广播接收者
    private BroadcastReceiver broadcastReceiver;

    // intent 是否是默认视频大屏
    private boolean isVideoMain;
    private RedPacketViewHelper redPacketViewHelper;

    private QaInputLayout qaInputLayout;

    private boolean isCoursewareShow = false;
    private Gson gson;



    private RedPacketStateListener redPacketStateListener = new RedPacketStateListener() {
        @Override
        public void onStart() {

        }

        @Override
        public void openRedPacket(String redPacketId, String liveId) {
            DWLive.getInstance().grabRedPacket(liveId, redPacketId, null);
        }

        @Override
        public void onEnd(String redPacketId) {
            mFunctionHandler.onRedPacketEnd(redPacketId);
        }
    };

    private RTCComponent mRTCComponent;
    private RedPacketBaseHelper redPacketHelper;

    private InvitationCardMainLayout invitationCard;

    private boolean isInvitationCardInit = false;
    private Button btnInteractInvitationEnter;
    private Button btnInteractLiveCommerceEnter;
    private CCRecommendGoodsView recommerceGoodsView;
    private RelativeLayout rlInteractPanel;
    private CCGoodsListView recommerceGoodslistView;
    private VoteMainLayout voteMain;
    private InvitationCardRankList invitationRankList;
    private QuestionnaireMainLayout questionnaireLayout;
    private boolean isChatEmojiShow;
    private RelativeLayout llInteractPanel;
    private View livePortraitMsgTips;

    /**
     * 启动直播界面
     *
     * @param activity    activity
     * @param isVideoMain 是否是以大屏为主
     * @param userId      客户id，互动组件需要
     */
    public static void openActivity(Activity activity, boolean isVideoMain, String userId, String nickName, String roomId, boolean isDisAllowScreenShot) {
        Intent intent = new Intent(activity, LivePlayActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("isVideoMain", isVideoMain);
        intent.putExtra("userId", userId);
        intent.putExtra("nickName", nickName);
        intent.putExtra("roomId", roomId);
        intent.putExtra("isDisAllowScreenShot", isDisAllowScreenShot);
        activity.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        Log.i("LivePlayActivityLife", "onCreate?savedInstanceState=" + savedInstanceState);
        // 请求全屏
//        requestFullScreenFeature();
        // 请求状态栏黑色
        requestStatusBarBlack(this);
        // 屏幕常亮
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_live_play);

        if (savedInstanceState != null) {
            //activity重建，需要退出重进
            Toast.makeText(getApplicationContext(), "监测到系统设置改变，请重新登录", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        isVideoMain = getIntent().getBooleanExtra("isVideoMain", true);

        initViews();
        initViewPager();
        initRoomStatusListener();
        mFunctionHandler = new FunctionHandler();
        mFunctionHandler.initFunctionHandler(this, functionCallBack);
        keyboardHeightProvider = new KeyboardHeightProvider(this);
        mRoot.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                try {
                    if (!isFinishing()) {
                        keyboardHeightProvider.start();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        // 初始化广播接收器
        initReceiver();
        //设置红包雨回调
        DWLiveCoreHandler.getInstance().setDwLiveRedPacketListener(this);

        // 开始播放
        mLiveVideoView.start();

        //Release模式下，启用防录屏
        boolean isDisAllowScreenShot = getIntent().getBooleanExtra("isDisAllowScreenShot", false);
        if (isDisAllowScreenShot) {
            mLiveVideoView.setAntiRecordScreen(this);
        }

        //注册连麦组件
        mRTCComponent = new RTCComponent();
        mRTCComponent.register(
                this,
                mRoot,
                mLiveTopLayout,
                mLiveRtcView,
                mLiveRoomLayout,
                rl_video_container,
                mLiveFloatingView,
                mLiveVideoView,
                mMoreFunctionLayout.getRTCControlLayout(),
                mMultiRTCControlLayout,
                mLiveMsgLayout,
                mMultiRTCVideoLayout,
                mVideoRightPanel,
                mVideoRightRTCCon,
                mVideoRightControlCon,
                mCideoBottomPanel
        );
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Log.i("LivePlayActivityLife", "onSaveInstanceState");
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.i("LivePlayActivityLife", "onStart");
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (ccChatView != null) {
            ccChatView.onResume();
        }
        Log.i("LivePlayActivityLife", "onResume");
        keyboardHeightProvider.addKeyboardHeightObserver(this);
        keyboardHeightProvider.addKeyboardHeightObserver(mLiveRoomLayout);
        keyboardHeightProvider.addKeyboardHeightObserver(mQaLayout);
        keyboardHeightProvider.addKeyboardHeightObserver(mMoreFunctionLayout);
        keyboardHeightProvider.addKeyboardHeightObserver(giftListView);
        keyboardHeightProvider.addKeyboardHeightObserver(mFunctionHandler);
        mFunctionHandler.setRootView(mRoot);
        // 开启弹幕
        mLiveRoomLayout.openLiveBarrage();
        // 取消通知
        NotificationUtil.cancelNotification(this);

    }

    @Override
    protected void onPause() {
        super.onPause();
        if (ccChatView != null) {
            ccChatView.onPause();
        }
        Log.i("LivePlayActivityLife", "onPause");
        keyboardHeightProvider.clearObserver();
        mFunctionHandler.removeRootView();
        // 停止弹幕
        mLiveRoomLayout.closeLiveBarrage();
        //隐藏软键盘
        KeyboardUtils.hideKeyboard(this);
        onKeyboardHeightChanged(0, Configuration.ORIENTATION_PORTRAIT);
        if (isFinishing()) {
            selfDestroy();
        }
    }

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

        Log.i("LivePlayActivityLife", "onStop");
        if (!isFinishing()) {
            NotificationUtil.sendLiveNotification(this);
        }
    }

    //为防止 onDestroy 延后执行，将销毁逻辑

    @Override
    protected void onDestroy() {
        Log.i("LivePlayActivityLife", "onDestroy");
        super.onDestroy();
        selfDestroy();
    }

    private boolean isDestroyed = false;

    private void selfDestroy() {
        if (isDestroyed) {
            return;
        }
        Log.i("LivePlayActivityLife", "selfDestroy");
        // 回收资源
        isDestroyed = true;
        if (ccChatView != null) {
            ccChatView.onDestroy();
        }
        if (giftView != null) {
            giftView.destroy();
        }
        if (hint_like_view != null) {
            hint_like_view.destroy();
        }
        if (keyboardHeightProvider != null) {
            keyboardHeightProvider.close();
        }
        if (mLiveFloatingView != null) {
            mLiveFloatingView.dismiss();
        }
        if (mFunctionHandler != null) {
            mFunctionHandler.onDestroy(this);
        }
        if (mLiveVideoView != null) {
            mLiveVideoView.stop();
        }
        if (mLiveRoomLayout != null) {
            mLiveRoomLayout.destroy();
        }
        if (mLiveRtcView != null) {
            mLiveRtcView.destroy();
        }
        if (mLiveVideoView != null) {
            mLiveVideoView.destroy();
        }
        if (redPacketViewHelper != null) {
            redPacketViewHelper.endGiftRain(false);
            redPacketViewHelper = null;
        }
        //注销互动组件红包雨,防止内存泄漏
        if (redPacketHelper != null) {
            redPacketHelper.release();
        }
        //注销互动组件投票和问卷,防止内存泄漏
        if (voteMain != null) {
            voteMain.release();
        }
        if (questionnaireLayout != null) {
            questionnaireLayout.release();
        }
        //注销互动组件邀请卡
        if (invitationCard != null) {
            invitationCard.release();
        }
        //注销互动组件直播带货浮窗
        if (recommerceGoodsView != null) {
            recommerceGoodsView.release();
        }
        //注销互动组件直播带货列表
        if (recommerceGoodslistView != null) {
            recommerceGoodslistView.release();
        }
        if (mRTCComponent != null) {
            mRTCComponent.release();
            mRTCComponent = null;
        }
        if (coursewareComponent!=null){
            coursewareComponent.destroy();
        }
        // 取消通知显示
        NotificationUtil.cancelNotification(this);
        if (broadcastReceiver != null) {
            unregisterReceiver(broadcastReceiver);
        }
    }

    @Override
    public void onBackPressed() {
        if (!isPortrait()) {
            if (!mLiveRoomLayout.onBackPressed()) {
                quitFullScreen();
            }
            return;
        } else {
            if (ccChatView != null) {
                ccChatView.onBackPressed();
            }
        }
        // 弹出退出提示
        showExitTips();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (mFunctionHandler != null) {
            mFunctionHandler.onConfigurationChanged(newConfig);
        }
        if (giftView != null) {
            giftView.setOnConfigurationChanged(newConfig);
        }
        // 横屏隐藏状态栏
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().getDecorView().setSystemUiVisibility(getSystemUiVisibility(true));
            //如果随堂测 答题卡的缩小按钮存在
            if (mPortraitVote.getVisibility() == VISIBLE) {
                mPortraitVote.setVisibility(View.GONE);
                mLandVote.setVisibility(VISIBLE);
            }
            //隐藏互动展示层
            llInteractPanel.setVisibility(View.GONE);
        } else {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().getDecorView().setSystemUiVisibility(getSystemUiVisibility(false));
            if (mLandVote.getVisibility() == VISIBLE) {
                mLandVote.setVisibility(View.GONE);
                mPortraitVote.setVisibility(VISIBLE);
            }
            //显示互动展示层
            llInteractPanel.setVisibility(VISIBLE);
        }
        if (mRTCComponent != null) {
            mRTCComponent.onConfigurationChanged(newConfig);
        }
        // 调整窗口的位置
        if (mLiveFloatingView != null) {
            mLiveFloatingView.onConfigurationChanged(newConfig.orientation);
        }
        // 开启或者关闭弹幕
        mLiveRoomLayout.openLiveBarrage();
    }

    @TargetApi(19)
    private static int getSystemUiVisibility(boolean isFull) {
        if (isFull) {
            int flags = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                flags |= View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
            }
            return flags;
        } else {
            return View.SYSTEM_UI_FLAG_VISIBLE;
        }
    }

    private void initViews() {
        mRoot = getWindow().getDecorView().findViewById(android.R.id.content);
        mLiveTopLayout = findViewById(R.id.rl_pc_live_top_layout);

        rl_video_container = findViewById(R.id.rl_video_container);
        mLiveRoomLayout = findViewById(R.id.live_room_layout);
        mLiveRoomLayout.setActivity(this);
        mMultiRTCVideoLayout = findViewById(R.id.live_multi_rtc_video_layout);
        mMultiRTCControlLayout = findViewById(R.id.live_multi_rtc_control_layout);
        mVideoRightPanel = findViewById(R.id.ll_video_right_panel);
        mVideoRightRTCCon = findViewById(R.id.rl_video_right_panel_rtcvideo_con);
        mVideoRightControlCon = findViewById(R.id.rl_video_right_panel_control_con);
        mCideoBottomPanel = findViewById(R.id.rl_live_multi_rtc_video_layout_con);
        // 视频下方界面
        mLiveMsgLayout = findViewById(R.id.ll_pc_live_msg_layout);
        livePortraitMsgTips = findViewById(R.id.live_portrait_msg_tips);
        mViewPager = findViewById(R.id.live_portrait_container_viewpager);
        mRadioGroup = findViewById(R.id.rg_infos_tag);
        mIntroTag = findViewById(R.id.live_portrait_info_intro);
        mFileTag = findViewById(R.id.live_portrait_info_file);
        mQaTag = findViewById(R.id.live_portrait_info_qa);
        mChatTag = findViewById(R.id.live_portrait_info_chat);
        mDocTag = findViewById(R.id.live_portrait_info_document);
        mMoreFunctionLayout = findViewById(R.id.more_function_layout);
        //互动展示层，旋转消失
        llInteractPanel = findViewById(R.id.rl_interact_panel);
        //公告弹出框

        //随堂测 答题卡缩小的按钮
        mLandVote = findViewById(R.id.tv_land_vote);
        mLandVote.setOnClickListener(voteClickListener);
        mPortraitVote = findViewById(R.id.tv_portrait_vote);
        mPortraitVote.setOnClickListener(voteClickListener);

        //问答输入框
        qaInputLayout = findViewById(R.id.qa_input_layout);


        // 弹出框界面
        mExitPopupWindow = new ExitPopupWindow(this);
        mLiveFloatingView = new FloatingPopupWindow(LivePlayActivity.this);
        mLiveFloatingView.setFloatDismissListener(new FloatingPopupWindow.FloatDismissListener() {
            @Override
            public void dismiss() {
                if (mLiveRoomLayout != null) {
                    mLiveRoomLayout.setSwitchText(true);
                }

            }
        });

        // 初始化控制布局，需登录成功之后调用
        mLiveRoomLayout.init(isVideoMain);


        initInteractView();

        //初始化互动组件入口菜单
        initInteractMenu();

        //初始化互动组价-礼物
        initGiftModel();
        //初始化互动组件-打赏
        initLikeModel();
        //初始化投票
        initVoteModel();
        //初始化邀请卡
        initInvitationCardModel();

        questionnaireSendMode = new AtomicInteger(-1);
        //初始化问卷
        initQuestionnaireModel();
        //初始化互动组件-红包雨
        initRedpacketModel();
        //初始化互动组件邀请卡
        initInvitationCard();
        //初始化直播带货
        initLiveCommerce();

    }


    private void initReceiver() {
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (NotificationUtil.ACTION_PLAY_PAUSE.equals(action)) {
                    NotificationUtil.sendLiveNotification(LivePlayActivity.this);
                } else if (NotificationUtil.ACTION_DESTROY.equals(action)) {
                    exit();
                } else if (ACTION_PAUSE.equals(action)) {
                    // 取消连麦申请
                    DWLiveCoreHandler.getInstance().disConnectSpeak();
                    //暂停视频播放
                    DWLiveCoreHandler.getInstance().stop();
                } else if (ACTION_RESUME.equals(action)) {
                    //恢复视频播放
                    DWLiveCoreHandler.getInstance().start(LivePlayActivity.this);
                }
            }
        };
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ACTION_PLAY_PAUSE);
        intentFilter.addAction(ACTION_DESTROY);
        intentFilter.addAction(ACTION_PAUSE);
        intentFilter.addAction(ACTION_RESUME);
        registerReceiver(broadcastReceiver, intentFilter);
    }


    //*************************************** 直播间状态监听 ***************************************/
    LiveRoomLayout.LiveRoomStatusListener roomStatusListener = new LiveRoomLayout.LiveRoomStatusListener() {
        @Override
        public void switchVideoDoc(boolean isVideoMain) {
            switchView(isVideoMain);  // 切换视频
        }

        @Override
        public void openVideoDoc() {
            if (mLiveFloatingView == null) {
                return;
            }
            if (mLiveRoomLayout.isVideoMain()) {
                mLiveFloatingView.show(mRoot);
                if (mDocLayout.getParent() != null) {
                    ((ViewGroup) mDocLayout.getParent()).removeView(mDocLayout);
                }
                mLiveFloatingView.addView(mDocLayout);
            } else {
                Log.d("demo_bokecc", "[demo_bokecc.LivePlayActivity.openVideoDoc]  multi=" + DWLiveCoreHandler.getInstance().isMultiStreamMode() + "");

                mLiveFloatingView.show(mRoot);
                if (DWLiveCoreHandler.getInstance().isMultiStreamMode()) {
                    //分流模式直接显示rtcvideo
                    if (mLiveRtcView.getParent() != null) {
                        ((ViewGroup) mLiveRtcView.getParent()).removeView(mLiveRtcView);
                    }
                    mLiveFloatingView.addView(mLiveRtcView);
                } else {
                    if (mLiveVideoView.getParent() != null) {
                        ((ViewGroup) mLiveVideoView.getParent()).removeView(mLiveVideoView);
                    }
                    mLiveFloatingView.addView(mLiveVideoView);
                }

            }
        }

        // 退出直播间
        @Override
        public void closeRoom() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // 如果当前状态是竖屏，则弹出退出确认框，否则切换为竖屏
                    if (isPortrait()) {
                        showExitTips();
                    } else {
                        quitFullScreen();
                    }
                }
            });
        }

        // 全屏
        @Override
        public void fullScreen() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                    mLiveMsgLayout.setVisibility(View.GONE);
                    if (qaInputLayout != null) {
                        qaInputLayout.setVisibility(View.GONE);
                    }
                }
            });
        }

        // 踢出直播间
        @Override
        public void kickOut() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    CustomToast.showToast(LivePlayActivity.this, "您已经被踢出直播间", Toast.LENGTH_SHORT);
                    finish();
                }
            });
        }

        @Override
        public void onClickDocScaleType(int scaleType) {
            if (mDocLayout != null) {
                mDocLayout.setScaleType(scaleType);
            }
        }

        @Override
        public void onStreamEnd() {
            //初始化视频界面并隐藏悬浮框
            if (mLiveFloatingView != null) {
                mLiveFloatingView.dismiss();
            }
            //问卷需要在直播结束是检查是否需要显示
            onInteractStreamEnd();
        }

        @Override
        public void onStreamStart() {
            if (!mLiveFloatingView.isShowing()) {
                //显示小窗
                showFloatingLayout();
                switchView(mLiveRoomLayout.isVideoMain());  // 开课回调
            }

            //尝试获取一下当前正在进行的随堂测，需要考虑用户重新登录及Home桌面的问题
            DWLive.getInstance().getPracticeInformation();

            //问卷需要在直播开始时检查是否需要显示
            onInteractStreamStart();

        }
    };

    // 初始化房间状态监听
    private void initRoomStatusListener() {
        if (mLiveRoomLayout == null) {
            return;
        }
        mLiveRoomLayout.setLiveRoomStatusListener(roomStatusListener);
    }

    // 退出全屏
    private void quitFullScreen() {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        mLiveMsgLayout.setVisibility(VISIBLE);
        checkMoreFunctionBtnShow();
    }

    // 切换大小屏
    private void switchView(boolean isVideoMain) {
        if (mLiveVideoView.getParent() != null) {
            ((ViewGroup) (mLiveVideoView.getParent())).removeView(mLiveVideoView);
        }
        if (mDocLayout == null) {
            //实际代码可直接使用docsdk
            boolean isUseDocSdk = SPUtil.getInstance().getBoolean(Constants.SP_DOC_COMPONENT_KEY, true);
            if (isUseDocSdk) {
                mDocLayout = new LiveDocComponent(this);
            } else {
                mDocLayout = new LiveDocComponentOld(this);
            }
        }
        if (DWLiveCoreHandler.getInstance().hasPdfView()) {
            if (mDocLayout.getParent() != null) {
                ((ViewGroup) (mDocLayout.getParent())).removeView(mDocLayout);
            }
        }

        if (DWLiveCoreHandler.getInstance().isRtcing() && DWLiveCoreHandler.getInstance().isVideoRtc()) {
            //----------------------------------------------连麦中切换窗口
            if (mLiveRtcView.getParent() != null) {
                ((ViewGroup) (mLiveRtcView.getParent())).removeView(mLiveRtcView);
            }
            if (isVideoMain) {
                if (DWLiveCoreHandler.getInstance().hasPdfView()) {
                    mLiveFloatingView.addView(mDocLayout);
                    mDocLayout.setDocScrollable(false);
                }
                rl_video_container.addView(mLiveRtcView);
            } else {
                if (DWLiveCoreHandler.getInstance().hasPdfView()) {
                    rl_video_container.addView(mDocLayout, 0);
                    mDocLayout.setDocScrollable(true);
                }
                mLiveFloatingView.addView(mLiveRtcView);
            }
        } else {
            //---------------------------------------------player拉流切换窗口
            if (isVideoMain) {
                if (DWLiveCoreHandler.getInstance().hasPdfView()) {
                    mLiveFloatingView.addView(mDocLayout);
                    mDocLayout.setDocScrollable(false);
                }
                // 处理连麦
                if (mLiveRtcView.getParent() != null) {
                    ((ViewGroup) (mLiveRtcView.getParent())).removeView(mLiveRtcView);
                }
                rl_video_container.addView(mLiveRtcView);
                rl_video_container.addView(mLiveVideoView);


            } else {
                // 处理连麦
                if (mLiveRtcView.getParent() != null) {
                    ((ViewGroup) (mLiveRtcView.getParent())).removeView(mLiveRtcView);
                }
                mLiveFloatingView.addView(mLiveRtcView);
                mLiveFloatingView.addView(mLiveVideoView);
                if (DWLiveCoreHandler.getInstance().hasPdfView()) {
                    rl_video_container.addView(mDocLayout, 0);
                    mDocLayout.setDocScrollable(true);
                }

            }
        }
    }


    //*************************************** 下方布局 ***************************************/

    List<View> mLiveInfoList = new ArrayList<>();
    List<Integer> mIdList = new ArrayList<>();
    List<RadioButton> mTagList = new ArrayList<>();

    ViewPager mViewPager;

    RadioGroup mRadioGroup;
    RadioButton mIntroTag;
    RadioButton mQaTag;
    RadioButton mChatTag;
    RadioButton mDocTag;
    RadioButton mFileTag;

    /**
     * 初始化ViewPager
     */
    private void initViewPager() {
        initComponents();
        PagerAdapter adapter = new PagerAdapter() {
            @Override
            public int getCount() {
                return mLiveInfoList.size();
            }

            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                container.addView(mLiveInfoList.get(position));
                return mLiveInfoList.get(position);
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                container.removeView(mLiveInfoList.get(position));
            }

            @Override
            public boolean isViewFromObject(View view, Object object) {
                return view == object;
            }
        };
        mViewPager.setAdapter(adapter);
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                mTagList.get(position).setChecked(true);
                hideKeyboard();
                checkMoreFunctionBtnShow();
                hideChatInputAndEmoji();
                if (mIdList.get(position)==R.id.live_portrait_info_file){
                    livePortraitMsgTips.setVisibility(View.GONE);
                    isCoursewareShow = true;
                }else {
                    isCoursewareShow = false;

                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });


        mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                mViewPager.setCurrentItem(mIdList.indexOf(i), true);
            }
        });
        if (mTagList != null && mTagList.size() > 0) {
            mTagList.get(0).performClick();
        }
    }

    /**
     * 隐藏右侧悬浮按钮
     */
    private void hideRightFloatButtons() {
        if (mMoreFunctionLayout != null) {
            mMoreFunctionLayout.setVisibility(View.GONE);
            //点赞按钮隐藏
        }
        showLikeIcon(false);
    }

    private void showRightFloatButtons() {
        if (mMoreFunctionLayout != null) {
            mMoreFunctionLayout.setVisibility(VISIBLE);
            //点赞按钮隐藏
        }
        showLikeIcon(true);
    }

    private void hideChatInputAndEmoji() {
        if (ccChatView != null) {
            ccChatView.hideChatView();
        }
}


    private void checkMoreFunctionBtnShow() {
        try {
            if (qaInputLayout != null) {
                qaInputLayout.setVisibility(View.GONE);
            }
            View view = mLiveInfoList.get(mViewPager.getCurrentItem());
            if (view instanceof LiveQAComponent && qaInputLayout != null) {
                qaInputLayout.setVisibility(VISIBLE);
                //当前是问答页
                if (qaInputLayout.getIsImgListShow()) {
                    if (mMoreFunctionLayout != null) {
                        mMoreFunctionLayout.setVisibility(View.GONE);
                        //点赞按钮隐藏
                    }
                    showLikeIcon(false);

                } else {
                    //判断问答图片布局是否显示
                    if (mMoreFunctionLayout != null) {
                        mMoreFunctionLayout.setVisibility(VISIBLE);
                        //点赞按钮隐藏
                    }
                    showLikeIcon(true);
                }
            } else if (view instanceof CCChatView) {
                if (isChatEmojiShow) {
                    hideRightFloatButtons();
                } else {
                    showRightFloatButtons();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //********************************* 直播 问答、聊天、文档、简介 组件相关 ******************/

    // 简介组件
    LiveIntroComponent mIntroComponent;
    CoursewareComponent coursewareComponent;
    // 问答组件
    LiveQAComponent mQaLayout;
    // 聊天组件
    CCChatView ccChatView;
    // 文档组件
    BaseDocComponent mDocLayout;
    // 视频组件
    LiveVideoView mLiveVideoView;
    // 连麦组件
    RTCVideoLayout mLiveRtcView;

    //根据直播间模版初始化相关组件
    private void initComponents() {
        DWLiveCoreHandler dwLiveCoreHandler = DWLiveCoreHandler.getInstance();
        if (dwLiveCoreHandler == null) {
            return;
        }
        // 显示文档
        if (dwLiveCoreHandler.hasPdfView()) {
            initDocLayout();
        }
        //初始化连麦
        initRtcLayout();
        // 显示视频
        initVideoLayout();
        // 显示悬浮窗
        showFloatingLayout();

        // 显示聊天
        if (dwLiveCoreHandler.hasChatView()) {
            initChatLayout();
        }
        // 显示文档
        if (dwLiveCoreHandler.hasQaView()) {
            initQaLayout();
        } else {
            //隐藏 qa 输入框
            qaInputLayout.setVisibility(View.GONE);
        }
        // 直播间简介
        initIntroLayout();
        //课件下载
        if (dwLiveCoreHandler.hasCoursewareView()){
            initCoursewareLayout();
        }
        // 判断当前直播间模版是否是仅视频大屏模式，如果是，隐藏更多功能
//        if (dwLiveCoreHandler.isOnlyVideoTemplate()) {
//            mMoreFunctionLayout.setVisibility(View.GONE);
//        }

    }



    // 初始化简介布局区域
    private void initIntroLayout() {
        mIdList.add(R.id.live_portrait_info_intro);
        mTagList.add(mIntroTag);
        mIntroTag.setVisibility(VISIBLE);
        mIntroComponent = new LiveIntroComponent(this);
        mIntroComponent.setOnClickBottomStatusListener(onClickBottomStatusListener);
        mLiveInfoList.add(mIntroComponent);
    }

    // 初始化课件下载
    private void initCoursewareLayout() {
        mIdList.add(R.id.live_portrait_info_file);
        mTagList.add(mFileTag);
        mFileTag.setVisibility(VISIBLE);

        coursewareComponent = new CoursewareComponent(this, true);
        coursewareComponent.setOnCoursewareMessageListener(new CoursewareComponent.OnCoursewareMessageListener() {
            @Override
            public void onMessage(int status) {
                if (status==1&&!isCoursewareShow){
                    livePortraitMsgTips.setVisibility(VISIBLE);
                }
            }
        });
        mLiveInfoList.add(coursewareComponent);
    }

    // 初始化问答布局区域
    private void initQaLayout() {
        mIdList.add(R.id.live_portrait_info_qa);
        mTagList.add(mQaTag);
        mQaTag.setVisibility(VISIBLE);
        mQaLayout = new LiveQAComponent(this);
        mQaLayout.setOnClickBottomStatusListener(onClickBottomStatusListener);
        mLiveInfoList.add(mQaLayout);
        //显示图片布局时，隐藏互动按钮
        if (qaInputLayout != null) {
            qaInputLayout.setQaImagePanelListener(new QaInputLayout.QaImagePanelListener() {
                @Override
                public void onImagePanelShow() {
                    checkMoreFunctionBtnShow();
                }

                @Override
                public void onImagePanelHide() {
                    checkMoreFunctionBtnShow();
                }
            });

            qaInputLayout.setQaSendListener(new QaInputLayout.QaSendListener() {
                @Override
                public void onLookStateChanged(boolean isSelf) {
                    toastOnUiThread(isSelf ? "只看我的问答" : "显示所有问答");
                    mQaLayout.setOnlyShowSelf(isSelf);
                }
            });
        }

    }

    // 初始化聊天布局区域
    private void initChatLayout() {
        mIdList.add(R.id.live_portrait_info_chat);
        mTagList.add(mChatTag);
        mChatTag.setVisibility(VISIBLE);
        ccChatView = new CCChatView(this);
        mLiveInfoList.add(ccChatView);

        String accountId = "";
        String userId = "";
        String roomId = "";
        String nickName = "";
        String avatar = "";
        String sessionId = "";
        try {
            //从登录信息中获取（上个界面传入）
            accountId = getIntent().getStringExtra("userId");
            userId = DWLiveCoreHandler.getInstance().getViewer().getId();
            roomId = getIntent().getStringExtra("roomId");
            nickName = DWLiveCoreHandler.getInstance().getViewer().getName();
            avatar = DWLiveCoreHandler.getInstance().getViewer().getAvatar();
            sessionId = DWLiveCoreHandler.getInstance().getViewer().getKey();
        } catch (Exception e) {
            e.printStackTrace();
        }

        //云直播大班课模板默认 2001，云直播研讨课模板 3001
        String business = "2001";
        if (DWLiveCoreHandler.getInstance().getLiveSceneMode() == LiveDigestBean.SCENE_SEMINAR) {
            business = "3001";
        }

        int isSeminar = DWLiveCoreHandler.getInstance().getLiveSceneMode();

        ccChatView.initialize(new ChatConfig()
                .setAccountId(accountId)
                .setRoomId(roomId)
                .setUserId(userId)
                .setBusinessLine(business)
                .setRole(RoleConstrant.student)
                .setNickName(nickName)
                .setAvatar(avatar)
                .setSessionId(sessionId)
                .setIsSeminar(isSeminar)
                .setChatClient(DWLive.getInstance())
        );
        //添加礼物图标到聊天室组件上
        int giftSwitch = DWLiveCoreHandler.getInstance().getInteractSwitch(DWLiveCoreHandler.INTERACT_GIFT);
        if (giftSwitch > 0) {
            List<CCInteractionViewBean> ccInteractionViewBeanList = new ArrayList<>();
            CCInteractionViewBean ccInteractionViewBean = new CCInteractionViewBean("", R.drawable.cc_chat_icon_gift, R.drawable.cc_chat_icon_gift, false);
            ccInteractionViewBean.setOnClickListener(new CCInteractionViewBean.OnClickListener() {
                @Override
                public void onClick(CCInteractionViewBean ccInteractionViewBean) {
                    if (giftListView != null) {
                        giftListView.setVisibility(VISIBLE);
                    }
                }
            });
            ccInteractionViewBeanList.add(ccInteractionViewBean);
            ccChatView.addInteractionView(ccInteractionViewBeanList);
        }
        List<CCInteractionViewBean> moreViewList = new ArrayList<>();

        //添加图标到聊天室更多按钮: 礼物、红包记录、投票记录、问卷
        if (giftSwitch > 0) {
            CCInteractionViewBean ccInteractionViewBean = new CCInteractionViewBean(" 礼物", R.drawable.icon_interact_gift_enter, R.drawable.icon_interact_gift_enter, false);
            ccInteractionViewBean.setOnClickListener(new CCInteractionViewBean.OnClickListener() {
                @Override
                public void onClick(CCInteractionViewBean ccInteractionViewBean) {
                    if (giftListView != null) {
                        giftListView.setVisibility(VISIBLE);
                    }
                }
            });
            moreViewList.add(ccInteractionViewBean);
        }
        if (DWLiveCoreHandler.getInstance().getInteractSwitch(DWLiveCoreHandler.INTERACT_RED_PACKET) > 0) {
            CCInteractionViewBean ccInteractionViewBean = new CCInteractionViewBean("红包记录", R.drawable.icon_interact_red_enter, R.drawable.icon_interact_red_enter, false);
            ccInteractionViewBean.setOnClickListener(new CCInteractionViewBean.OnClickListener() {
                @Override
                public void onClick(CCInteractionViewBean ccInteractionViewBean) {
                    showRed();
                }
            });
            moreViewList.add(ccInteractionViewBean);
        }
        if (DWLiveCoreHandler.getInstance().getInteractSwitch(DWLiveCoreHandler.INTERACT_VOTE) > 0) {
            CCInteractionViewBean ccInteractionViewBean = new CCInteractionViewBean("投票记录", R.drawable.icon_interact_vote_enter, R.drawable.icon_interact_vote_enter, false);
            ccInteractionViewBean.setOnClickListener(new CCInteractionViewBean.OnClickListener() {
                @Override
                public void onClick(CCInteractionViewBean ccInteractionViewBean) {
                    showVote();
                }
            });
            moreViewList.add(ccInteractionViewBean);
        }
        if (DWLiveCoreHandler.getInstance().getInteractSwitch(DWLiveCoreHandler.INTERACT_QUESTIONNAIRE) > 0) {
            CCInteractionViewBean ccInteractionViewBean = new CCInteractionViewBean("问卷", R.drawable.icon_interact_questionnaire_enter, R.drawable.icon_interact_questionnaire_enter, false);
            ccInteractionViewBean.setOnClickListener(new CCInteractionViewBean.OnClickListener() {
                @Override
                public void onClick(CCInteractionViewBean ccInteractionViewBean) {
                    showQuestionnaire(false);
                }
            });
            moreViewList.add(ccInteractionViewBean);
        }
        ccChatView.setInteractionDialogData(moreViewList);

        ccChatView.setEmojiClickListener(new IEmojiLayoutListener() {
            @Override
            public void change(boolean b) {
                isChatEmojiShow = b;
                if (b) {
                    hideRightFloatButtons();
                } else {
                    showRightFloatButtons();
                }
            }

        });
        ChatRoomManagerImpl.getInstance().setListener(new IChatRoomListener() {
            @Override
            public void onMessage(String event, String message) {
                //横屏显示弹幕
                //公聊事件为chat_message
                if (!event.equals("chat_message")||getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE){
                    return;
                }
                try{
                    boolean flag = false;
                    JSONObject jsonObject = new JSONObject(message);
                    ChatMessage msg = new ChatMessage(jsonObject,true);
                    if (ChatImageUtils.isImgChatMessage(msg.getMessage())) {
                        return;
                    }
                    if (DWLive.getInstance()!=null
                            &&DWLive.getInstance().getViewer()!=null
                            &&!TextUtils.isEmpty(DWLive.getInstance().getViewer().getId())
                            &&!TextUtils.isEmpty(msg.getUserId())
                            &&DWLive.getInstance().getViewer().getId().equals(msg.getUserId())){
                        flag = true;
                    }

                    if (flag||"0".equals(msg.getStatus())) {
                        mLiveRoomLayout.addDanmaku(msg.getMessage(),msg.getUserRole());
                    }
                }catch (Exception e){
                     e.printStackTrace();
                }
            }

            @Override
            public void onInitSuccess() {

            }

            @Override
            public void onConnectFailure() {

            }

            @Override
            public void onConnect() {

            }
        });

    }

    // 初始化文档布局区域
    private void initDocLayout() {
        boolean isUseDocSdk = SPUtil.getInstance().getBoolean(Constants.SP_DOC_COMPONENT_KEY, true);
        if (isUseDocSdk) {
            mDocLayout = new LiveDocComponent(this);
        } else {
            mDocLayout = new LiveDocComponentOld(this);
        }
        if (isVideoMain) {
            mLiveFloatingView.removeNowView();
            mLiveFloatingView.addView(mDocLayout);
        } else {
            rl_video_container.addView(mDocLayout);
            mDocLayout.setDocScrollable(true);
        }

    }

    //初始化连麦布局区域
    private void initRtcLayout() {
        mLiveRtcView = new RTCVideoLayout(this);
        if (mLiveRtcView.getParent() != null) {
            ((ViewGroup) mLiveRtcView.getParent()).removeView(mLiveRtcView);
        }
        if (isVideoMain) {
            rl_video_container.addView(mLiveRtcView);
        } else {
            DWLiveCoreHandler dwLiveCoreHandler = DWLiveCoreHandler.getInstance();
            if (dwLiveCoreHandler != null && dwLiveCoreHandler.hasPdfView()) {
                mLiveFloatingView.addView(mLiveRtcView);
            } else {
                rl_video_container.addView(mLiveRtcView);
            }
        }
    }

    // 初始化视频布局区域
    private void initVideoLayout() {
        mLiveVideoView = new LiveVideoView(this);
        if (mLiveVideoView.getParent() != null) {
            ((ViewGroup) mLiveVideoView.getParent()).removeView(mLiveVideoView);
        }
        if (isVideoMain) {
            rl_video_container.addView(mLiveVideoView);
        } else {
            DWLiveCoreHandler dwLiveCoreHandler = DWLiveCoreHandler.getInstance();
            if (dwLiveCoreHandler != null && dwLiveCoreHandler.hasPdfView()) {
                mLiveFloatingView.addView(mLiveVideoView);
            } else {
                rl_video_container.addView(mLiveVideoView);
            }

        }
    }


    // 展示文档悬浮窗布局
    private void showFloatingLayout() {
        DWLiveCoreHandler dwLiveCoreHandler = DWLiveCoreHandler.getInstance();
        if (dwLiveCoreHandler == null) {
            return;
        }
        // 判断当前直播间模版是否有"文档"功能，如果没文档，则小窗功能也不应该有
        if (dwLiveCoreHandler.hasPdfView()) {
            mLiveFloatingView.show(mRoot);
        }
    }


    //********************************** 工具方法 *******************************************/

    // 隐藏输入法
    private void hideKeyboard() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(mLiveTopLayout.getWindowToken(), 0);
        }
    }


    //*********************************  退出相关逻辑 ***************************************/
    private ExitPopupWindow mExitPopupWindow;

    // 弹出退出提示
    private void showExitTips() {
        if (mExitPopupWindow != null) {
            mExitPopupWindow.setConfirmExitRoomListener(new ExitPopupWindow.ConfirmExitRoomListener() {
                @Override
                public void onConfirmExitRoom() {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            exit();
                        }
                    });
                }
            });
            mExitPopupWindow.show(mRoot);
        }
    }

    // 退出房间
    private void exit() {
        mExitPopupWindow.dismiss();
        finish();
    }


    //*********************************  答题卡和随堂测收起功能*********************************/
    private boolean isVote;
    //添加答题卡收起监听
    private final FunctionCallBack functionCallBack = new FunctionCallBack() {
        @Override
        public void onMinimize(boolean isVote) {
            super.onMinimize(isVote);
            LivePlayActivity.this.isVote = isVote;
            if (isVote) {
                mPortraitVote.setBackgroundResource(R.drawable.float_answer2);
                mLandVote.setBackgroundResource(R.drawable.float_answer2);
            } else {
                mPortraitVote.setBackgroundResource(R.drawable.float_answer);
                mLandVote.setBackgroundResource(R.drawable.float_answer);
            }
            //显示按钮
            if (isPortrait()) {
                mPortraitVote.setVisibility(VISIBLE);
                mLandVote.setVisibility(View.GONE);
            } else {
                mLandVote.setVisibility(VISIBLE);
                mPortraitVote.setVisibility(View.GONE);
            }
        }

        @Override
        public void onClose() {
            super.onClose();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    //隐藏按钮
                    mPortraitVote.setVisibility(View.GONE);
                    mLandVote.setVisibility(View.GONE);
                }
            });
        }
    };
    //随堂测 答题卡缩小按钮的点击时间
    View.OnClickListener voteClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mFunctionHandler != null) {
                if (isVote) {
                    mFunctionHandler.onVoteStart();
                } else {
                    mFunctionHandler.onPractice();
                }
            }
            mPortraitVote.setVisibility(View.GONE);
            mLandVote.setVisibility(View.GONE);
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (mRTCComponent!=null){
//            return mRTCComponent.performKeyDown(keyCode, event) || super.onKeyDown(keyCode, event);
//        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onRedPacketStart(RedPacketInfo redPacketInfo) {
        if (redPacketInfo == null) {
            return;
        }
        if (redPacketViewHelper != null && redPacketViewHelper.isRuning()) {
            redPacketViewHelper.endGiftRain(false);
            redPacketViewHelper = null;
        }
        if (redPacketInfo != null) {
            mFunctionHandler.onRedPacketStart(redPacketInfo);
        }
        redPacketViewHelper = new RedPacketViewHelper();
        redPacketViewHelper.setGiftRainListener(redPacketStateListener);
        redPacketViewHelper.startRedPacket(redPacketInfo, this);
    }

    @Override
    public void onRedPacketEnd(final String redPacketId) {
        if (redPacketViewHelper != null && redPacketViewHelper.isRuning()) {
            redPacketViewHelper.endGiftRain(false);
            redPacketViewHelper = null;
        }
        mFunctionHandler.onRedPacketEnd(redPacketId);

    }

    //*********************************   测试代码 *********************************/
    private OnClickBottomStatusListener onClickBottomStatusListener = new OnClickBottomStatusListener() {
        @Override
        public void onClickGift() {
            if (giftListView != null) {
                giftListView.setVisibility(VISIBLE);
            }
        }
    };


    // <editor-fold defaultstate="collapsed" desc="互动组件相关">

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (qaInputLayout != null) {
            qaInputLayout.onActivityResult(requestCode, resultCode, data);
        }
        //问卷包含选择图片提交功能，需要Activity传递结果
        if (questionnaireLayout != null) {
            questionnaireLayout.onActivityResult(requestCode, resultCode, data);
        }
    }


    private void initInvitationCard() {
        invitationCard = findViewById(R.id.invitation_card);

        if (DWLiveCoreHandler.getInstance().getInteractionConfigure() != null && DWLiveCoreHandler.getInstance().getInteractionConfigure().getInviteSwitch() > 0) {

            String userId = "";
            try {
                //从登录信息中获取（上个界面传入）
                userId = getIntent().getStringExtra("userId");
            } catch (Exception e) {
                e.printStackTrace();
            }
            String nickName = "";
            try {
                //从登录信息中获取（上个界面传入）,这里面计算一个长度的字符串
                nickName = getIntent().getStringExtra("nickName");
                if (nickName != null) {
                    Paint paint = new Paint();
                    paint.setTextSize(20);
                    float width = paint.measureText(nickName);
                    if (width > 100f) {
                        int sub = (int) (100 * nickName.length() / width);
                        if (sub < nickName.length() && sub > 0) {
                            nickName = nickName.substring(0, sub) + "..";
                        }
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            String roomId = "";
            try {
                roomId = getIntent().getStringExtra("roomId");
            } catch (Exception e) {
                e.printStackTrace();
            }

            String viewerId = "";
            try {
                viewerId = DWLiveCoreHandler.getInstance().getViewer().getId();
            } catch (Exception e) {
                e.printStackTrace();
            }

            String roomTitle = "";
            try {
                roomTitle = DWLiveCoreHandler.getInstance().getRoomInfo().getName();
            } catch (Exception e) {
                e.printStackTrace();
            }
            String roomDesc = "";
            try {
                roomDesc = DWLiveCoreHandler.getInstance().getRoomInfo().getDesc();
                //限制30个字符
                if (roomDesc != null && roomDesc.length() > 30) {
                    roomDesc = roomDesc.substring(0, 30);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            String startTime = "";
            try {
                startTime = DWLiveCoreHandler.getInstance().getRoomInfo().getEstimateStartTime();
                //时间格式做一下转换
                if (startTime.endsWith(".0")) {
                    startTime = startTime.substring(0, startTime.length() - 2);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            final String finalViewerId = viewerId;
            final String finalRoomId = roomId;
            final String finalRoomTitle = roomTitle;
            final String finalRoomDesc = roomDesc;
            final String finalStartTime = startTime;
            final String finalNickName = nickName;

            final String liveLinkUrl = "https://view.csslcloud.net/api/view/index?roomid=" + roomId + "&userid=" + userId;
            //获取组件token
            DWLive.getInstance().getInteractiveToken(new BaseCallback<String>() {
                @Override
                public void onError(String error) {
                    Toast.makeText(LivePlayActivity.this, "获取组件token失败", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onSuccess(final String token) {
                    invitationCard.setListener(new InvitationCardMainLayout.IInvitationCardListener() {
                        @Override
                        public void onCardLongClick(View view) {
                            //当前view生成Bitmap，保存的逻辑可以自定义实现
                            int width = view.getWidth();
                            int height = view.getHeight();
                            Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
                            Canvas canvas = new Canvas(bitmap);
                            view.draw(canvas);
                            File file = ImageUtils.save2Album(LivePlayActivity.this, bitmap, Bitmap.CompressFormat.JPEG);
                            Toast.makeText(LivePlayActivity.this, "已保存至相册", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onClose() {
                            invitationCard.setVisibility(View.GONE);
                        }

                        @Override
                        public void onInitSuccess() {
                            isInvitationCardInit = true;
                            invitationCard.getRankList(new IBaseCallBack<List<InvitationCardRankBean>>() {
                                @Override
                                public void onSuccess(List<InvitationCardRankBean> invitationCardRankBeans) {
                                    //设置排行榜数据
                                    setInvitationRankData(invitationCardRankBeans, false);
                                }

                                @Override
                                public void onFailed(int code, String msg) {

                                }
                            });
                        }


                    });

                    invitationCard.initialize(
                            new InvitationCardBaseLayout
                                    .InvitationCardConfig()
                                    .setInteractToken(token)
                                    .setUserId(finalViewerId)
                                    .setRoomId(finalRoomId)
                                    .setOngoingId("")
                                    .setOngoing(false)
                                    //邀请卡内容相关
                                    .setCardLiveTitle(finalRoomTitle)
                                    .setCardLiveTime(finalStartTime)
                                    .setCardLiveDesc(finalRoomDesc)
                                    .setCardNickname(finalNickName)
                                    .setCardQrCodeUrl(liveLinkUrl)
                                    .setCardAvatarUrl("")
                    );
                }
            });


        }


    }

    private void initInteractView() {

        //互动组件邀请卡按钮
        btnInteractInvitationEnter = findViewById(R.id.btn_interact_invitation_enter);
        //互动组件问卷按钮
        //互动组件直播带货购物车按钮
        btnInteractLiveCommerceEnter = findViewById(R.id.btn_interact_live_commerce_enter);
        //互动组件直播带货商品悬浮窗
        recommerceGoodsView = findViewById(R.id.recommerce_goods_view);
        //互动组件面板-展示直播带货列表、投票等互动组件界面
        rlInteractPanel = findViewById(R.id.rl_live_interact_con);
        rlInteractPanel.setVisibility(View.GONE);

        //互动组件直播带货商品列表
        recommerceGoodslistView = findViewById(R.id.recommerce_goodslist_view);
        //互动组件投票列表
        voteMain = findViewById(R.id.vote_main);
        //互动组件邀请卡排行榜
        invitationRankList = findViewById(R.id.invitation_rank_list);
        //互动组件问卷列表
        questionnaireLayout = findViewById(R.id.questionnaire_layout);

    }

    private void initInteractMenu() {
        //初始化互动组件功能菜单
        //直播带货入口显示
        btnInteractLiveCommerceEnter.setVisibility(View.GONE);

        DWLiveCoreHandler dwLiveCoreHandler = DWLiveCoreHandler.getInstance();


        if (dwLiveCoreHandler != null && dwLiveCoreHandler.getInteractionConfigure() != null && dwLiveCoreHandler.getInteractionConfigure().getInviteSwitch() > 0) {
            btnInteractInvitationEnter.setVisibility(VISIBLE);
        } else {
            btnInteractInvitationEnter.setVisibility(View.GONE);
        }

        if (dwLiveCoreHandler != null && dwLiveCoreHandler.getInteractionConfigure() != null && dwLiveCoreHandler.getInteractionConfigure().getLiveCommerce() > 0) {
            btnInteractLiveCommerceEnter.setVisibility(VISIBLE);
        } else {
            btnInteractLiveCommerceEnter.setVisibility(View.GONE);
        }


        btnInteractLiveCommerceEnter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showInteractPanel(INTERACT_GOODS_LIST);
                recommerceGoodslistView.flushList();
            }
        });

        rlInteractPanel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rlInteractPanel.setVisibility(View.GONE);
            }
        });

        //显示邀请榜
        btnInteractInvitationEnter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //判断是否显示排行榜
                if (invitationCard.getIsShowRankList()) {
                    showInvitationRankList();
                } else {
                    //直接显示邀请卡
                    invitationCard.setVisibility(VISIBLE);
                    invitationCard.post(new Runnable() {
                        @Override
                        public void run() {
                            if (isInvitationCardInit) {
                                invitationCard.getCardList();
                            }
                        }
                    });
                }

            }
        });

    }

    private void initLikeModel() {
        hint_like_view = findViewById(R.id.hint_like_view);
        if (DWLiveCoreHandler.getInstance().getInteractionConfigure() != null && DWLiveCoreHandler.getInstance().getInteractionConfigure().getLikeSwitch() > 0) {
            hint_like_view.initConfig();
        } else {
            hint_like_view.setVisibility(View.GONE);
        }
    }

    private void showLikeIcon(boolean show) {
        if (hint_like_view == null) {
            return;
        }
        if (show && DWLiveCoreHandler.getInstance().getInteractionConfigure() != null && DWLiveCoreHandler.getInstance().getInteractionConfigure().getLikeSwitch() > 0) {
            hint_like_view.setVisibility(VISIBLE);
        } else {
            hint_like_view.setVisibility(View.GONE);
        }
    }

    private void initGiftModel() {
        giftView = findViewById(R.id.gifView);
        if (DWLiveCoreHandler.getInstance().getInteractionConfigure() != null && DWLiveCoreHandler.getInstance().getInteractionConfigure().getGiftConfigure() != null) {
            ELog.e("LivePlayActivity", "init gift model " + DWLiveCoreHandler.getInstance().getInteractionConfigure().toString());
            if (DWLiveCoreHandler.getInstance().getInteractionConfigure().getGiftConfigure().getGiftSwitch() == 0) {
                return;
            } else {
                giftListView = findViewById(R.id.git_list_view);
                giftView.setGiftListListener(new GiftView.GiftListListener() {
                    @Override
                    public void onGiftList(List<GiftInfo> list) {
                        giftListView.setGiftListData(list);
                    }
                });
                InteractionConfigure.GiftConfigure giftConfigure = DWLiveCoreHandler.getInstance().getInteractionConfigure().getGiftConfigure();
                giftView.init(giftConfigure);

                giftListView.setOnClickGiftListListener(new GiftListView.OnClickGiftListListener() {

                    @Override
                    public void onClickSendGift(String sumGiftPerice, GiftInfo giftInfo, int num) {
                        giftListView.setVisibility(View.GONE);
                        giftView.sendGIft(giftInfo, num);
                    }
                });
            }
        } else {
            giftView.setVisibility(View.GONE);
        }
    }

    private void initRedpacketModel() {
        if (DWLiveCoreHandler.getInstance().getInteractionConfigure() != null && DWLiveCoreHandler.getInstance().getInteractionConfigure().getRedEnvelopesSwitch() > 0) {
            //开关打开，执行初始化操作
            redPacketHelper = new RedPacketHelper(this);
            initRedPacketComponent();

        }
    }

    private void initRedPacketComponent() {
        if (redPacketHelper == null) {
            return;
        }
        String viewerId = "";
        try {
            viewerId = DWLiveCoreHandler.getInstance().getViewer().getId();
        } catch (Exception e) {
            e.printStackTrace();
        }
        String roomId = "";
        try {
            roomId = DWLiveCoreHandler.getInstance().getRoomInfo().getEncryptId();
        } catch (Exception e) {
            e.printStackTrace();
        }
        final String finalViewerId = viewerId;
        final String finalRoomId = roomId;
        //获取组件token
        DWLive.getInstance().getInteractiveToken(new BaseCallback<String>() {
            @Override
            public void onError(String error) {
                Toast.makeText(LivePlayActivity.this, "获取组件token失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onSuccess(final String token) {
                //获取正在进行的活动
                DWLive.getInstance().getInteractiveOngoing(new BaseCallback<List<InteractionOngoing>>() {
                    @Override
                    public void onError(String error) {
                        initRedPacketHelper(finalViewerId, finalRoomId, token, false, "");
                    }

                    @Override
                    public void onSuccess(List<InteractionOngoing> ongoingList) {
                        //是否正在进行
                        boolean isOngoing = false;
                        String ongoingId = "";
                        if (ongoingList != null) {
                            for (int i = 0; i < ongoingList.size(); i++) {
                                if (ongoingList.get(i).getType() == InteractionOngoing.TYPE_INTERACT_RED_PACKET) {
                                    isOngoing = true;
                                    ongoingId = ongoingList.get(i).getId();
                                    break;
                                }
                            }
                        }
                        initRedPacketHelper(finalViewerId, finalRoomId, token, isOngoing, ongoingId);

                    }
                });
            }
        });
    }

    /**
     * 初始化红包 helper
     *
     * @param userId    viewerId
     * @param roomId    房间id
     * @param token     组件token
     * @param ongoing   是否正在进行
     * @param ongoingId 正在进行的活动id
     */
    private void initRedPacketHelper(String userId, String roomId, String token, boolean ongoing, String ongoingId) {
        redPacketHelper.initialize(new RedPacketBaseHelper.RedPacketConfig()
                .setUserId(userId)
                .setRoomId(roomId)
                .setInteractToken(token)
                .setOngoing(ongoing)
                .setOngoingId(ongoingId));
    }


    private void initLiveCommerce() {

        if (DWLiveCoreHandler.getInstance().getInteractionConfigure() != null && DWLiveCoreHandler.getInstance().getInteractionConfigure().getLiveCommerce() > 0) {
            //获取token
            DWLiveCoreHandler.getInstance().getInteractionToken(new BaseCallback<String>() {
                @Override
                public void onError(String error) {

                }

                @Override
                public void onSuccess(final String token) {
                    //初始化商品列表
                    Intent intent = getIntent();
                    if (intent != null) {
                        String userId = "";
                        try {
                            //从登录信息中获取（上个界面传入）
                            userId = intent.getStringExtra("userId");
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        String roomId = "";
                        try {
                            roomId = intent.getStringExtra("roomId");
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        String viewerId = "";
                        try {
                            viewerId = DWLiveCoreHandler.getInstance().getViewer().getId();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        String nickName = "";
                        try {
                            //从登录信息中获取（上个界面传入）
                            nickName = getIntent().getStringExtra("nickName");
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if (!TextUtils.isEmpty(userId) && !TextUtils.isEmpty(roomId)) {
                            recommerceGoodslistView.initialize(token, userId, roomId, viewerId, nickName, new CommerceUiListener() {
                                @Override
                                public void onClose() {
                                    recommerceGoodslistView.setVisibility(View.GONE);
                                    rlInteractPanel.setVisibility(View.GONE);
                                }

                                @Override
                                public void onCommercePush(String s) {

                                }

                                @Override
                                public void onProductLink(String s) {
                                    if (DWApplication.getInstance().getChannelMessageListener()==null){
                                        Tools.openSystemBrowser(LivePlayActivity.this, s);
                                    }
                                }

                                @Override
                                public void onGoodsInfo(CCGoodsModel ccGoodsModel) {
                                    if (ccGoodsModel==null){
                                        return;
                                    }
                                    if (gson==null){
                                        gson = new Gson();
                                    }
                                    DWApplication.getInstance().onMessage(gson.toJson(ccGoodsModel));
                                }
                            });
                        }


                    }


                    //初始化悬浮窗
                    DWLive.getInstance().getInteractiveOngoing(new BaseCallback<List<InteractionOngoing>>() {
                        @Override
                        public void onError(String error) {

                        }

                        @Override
                        public void onSuccess(List<InteractionOngoing> ongoingList) {
                            //是否正在进行
                            boolean isOngoing = false;
                            String ongoingId = "";
                            if (ongoingList != null) {
                                for (int i = 0; i < ongoingList.size(); i++) {
                                    if (ongoingList.get(i).getType() == InteractionOngoing.TYPE_INTERACT_LIVE_COMMERCE) {
                                        isOngoing = true;
                                        ongoingId = ongoingList.get(i).getId();
                                        break;
                                    }
                                }
                            }
                            String userId = getIntent().getStringExtra("userId");
                            String roomId = getIntent().getStringExtra("roomId");

                            String viewerId = "";
                            try {
                                viewerId = DWLiveCoreHandler.getInstance().getViewer().getId();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                            String nickName = "";
                            try {
                                //从登录信息中获取（上个界面传入）
                                nickName = getIntent().getStringExtra("nickName");
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                            recommerceGoodsView.initialize(token, userId, roomId, viewerId, nickName, new CommerceUiListener() {
                                @Override
                                public void onClose() {
                                    recommerceGoodsView.setVisibility(View.GONE);
                                }

                                @Override
                                public void onCommercePush(String s) {
                                    recommerceGoodsView.setVisibility(VISIBLE);
                                    recommerceGoodsView.show(s);
                                }

                                @Override
                                public void onProductLink(String s) {
                                    if (DWApplication.getInstance().getChannelMessageListener()==null){
                                        Tools.openSystemBrowser(LivePlayActivity.this, s);
                                    }
                                }

                                @Override
                                public void onGoodsInfo(CCGoodsModel ccGoodsModel) {
                                    if (ccGoodsModel==null){
                                        return;
                                    }
                                    if (gson==null){
                                        gson = new Gson();
                                    }
                                    DWApplication.getInstance().onMessage(gson.toJson(ccGoodsModel));
                                }
                            });
                            if (isOngoing) {
                                if (ongoingId != null && ongoingId.length() > 0) {
                                    recommerceGoodsView.show(ongoingId);
                                }
                                recommerceGoodsView.setVisibility(VISIBLE);
                            } else {
                                recommerceGoodsView.setVisibility(View.GONE);
                            }
                        }
                    });

                }
            });


        }
    }

    /**
     * 直播带货商品列表
     */
    private final static int INTERACT_GOODS_LIST = 0;
    /**
     * 投票列表
     */
    private final static int INTERACT_VOTE_MAIN = 1;
    /**
     * 邀请卡排行榜
     */
    private final static int INTERACT_CARD_RANK = 2;
    /**
     * 问卷列表
     */
    private final static int INTERACT_FORM_MAIN = 3;


    private AtomicInteger questionnaireSendMode;

    private boolean isLiveStarted = false;


    /**
     * 隐藏互动组件面板
     */
    private void hideInteractPanel() {
        rlInteractPanel.setVisibility(View.GONE);
        recommerceGoodslistView.setVisibility(View.GONE);
        voteMain.setVisibility(View.GONE);
        invitationRankList.setVisibility(View.GONE);
        questionnaireLayout.setVisibility(View.GONE);
    }

    private void hideInteractPanel(int type) {
        switch (type) {
            case INTERACT_GOODS_LIST:
                if (recommerceGoodslistView.getVisibility() == VISIBLE) {
                    recommerceGoodslistView.setVisibility(View.GONE);
                    rlInteractPanel.setVisibility(View.GONE);
                }
                break;
            case INTERACT_VOTE_MAIN:
                voteMain.setVisibility(View.GONE);
                rlInteractPanel.setVisibility(View.GONE);
                break;
            case INTERACT_CARD_RANK:
                if (invitationRankList.getVisibility() == VISIBLE) {
                    invitationRankList.setVisibility(View.GONE);
                    rlInteractPanel.setVisibility(View.GONE);
                }
                break;
            case INTERACT_FORM_MAIN:
                if (questionnaireLayout.getVisibility() == VISIBLE) {
                    questionnaireLayout.setVisibility(View.GONE);
                    rlInteractPanel.setVisibility(View.GONE);
                }
                break;

            default:
        }
    }

    private void showInteractPanel(int type) {
        //横屏状态不处理
        if (isLandScape()) {
            hideInteractPanel();
            return;
        }
        hideInteractPanel();
        rlInteractPanel.setVisibility(VISIBLE);
        switch (type) {
            case INTERACT_GOODS_LIST:
                recommerceGoodslistView.setVisibility(VISIBLE);
                break;
            case INTERACT_VOTE_MAIN:
                voteMain.setVisibility(VISIBLE);
                break;
            case INTERACT_CARD_RANK:
                invitationRankList.setVisibility(VISIBLE);
                break;
            case INTERACT_FORM_MAIN:
                questionnaireLayout.setVisibility(VISIBLE);
                break;

            default:
        }
    }

    private void initQuestionnaireModel() {
        if (DWLiveCoreHandler.getInstance().getInteractionConfigure() != null) {
            InteractionConfigure interactionConfigure = DWLiveCoreHandler.getInstance().getInteractionConfigure();
            if (interactionConfigure.getQuestionnaire() != null) {
                InteractionConfigure.Questionnaire questionnaire = interactionConfigure.getQuestionnaire();
                if (questionnaire.getSwitch() > 0) {
                    //推送方式：0:手动推送 1:进入直播时 2：结束直播时
                    final int sendMode = questionnaire.getSendMode();
                    if (questionnaireSendMode != null) {
                        questionnaireSendMode.set(questionnaire.getSendMode());
                    }
                    //活动编码
                    final String activityCode = questionnaire.getActivityCode();
                    //表单编码
                    final String formCode = questionnaire.getFormCode();

                    String viewerId = "";
                    try {
                        viewerId = DWLiveCoreHandler.getInstance().getViewer().getId();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    String roomId = "";
                    try {
                        roomId = DWLiveCoreHandler.getInstance().getRoomInfo().getEncryptId();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    final String finalViewerId = viewerId;
                    final String finalRoomId = roomId;
                    DWLive.getInstance().getInteractiveToken(new BaseCallback<String>() {
                        @Override
                        public void onError(String s) {
                            Toast.makeText(LivePlayActivity.this, "获取组件token失败:" + s, Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onSuccess(final String token) {
                            questionnaireLayout.setQuestionnaireMainListener(new IQuestionnaireMainListener() {
                                @Override
                                public void onQuestionnairePush() {
                                    //收到问卷推送 显示问卷布局
                                    showQuestionnaire(true);
                                }

                                @Override
                                public void onCloseClick() {
                                    hideInteractPanel(INTERACT_FORM_MAIN);
                                }
                            });
                            String authority = getPackageName() + ".interact.fileprovider";
                            questionnaireLayout.initialize(
                                    new QuestionnaireBaseLayout.QuestionnaireConfig()
                                            .setInteractToken(token)
                                            .setUserId(finalViewerId)
                                            .setRoomId(finalRoomId)
                                            .setFormCode(formCode)
                                            .setActivityId(activityCode)
                                            .setSendMode(sendMode)
                                            .setCaptureAuthority(authority)

                            );
//                            if (sendMode==1){
//                                showQuestionnaire();
//                            }else if (sendMode==2){
//                                //设置直播结束后展示问卷列表
//                            }
                        }
                    });
                }

            }
        }
    }

    private void initInvitationCardModel() {
        if (DWLiveCoreHandler.getInstance().getInteractionConfigure() != null && DWLiveCoreHandler.getInstance().getInteractionConfigure().getInviteSwitch() > 0) {
            invitationRankList.setListener(new InvitationCardRankList.IInvitationCardRankListListener() {
                @Override
                public void onCloseClick() {
                    invitationRankList.setVisibility(View.GONE);
                }

                @Override
                public void onInviteClick() {
                    invitationRankList.setVisibility(View.GONE);
                    if (invitationCard != null) {
                        //直接显示邀请卡
                        invitationCard.setVisibility(VISIBLE);
                        invitationCard.post(new Runnable() {
                            @Override
                            public void run() {
                                if (invitationCard.getIsBusinessInit()) {
                                    invitationCard.getCardList();
                                }
                            }
                        });
                    }
                }
            });
        }
    }

    private void initVoteModel() {
        if (DWLiveCoreHandler.getInstance().getInteractionConfigure() != null && DWLiveCoreHandler.getInstance().getInteractionConfigure().getVoteSwitch() > 0) {
            String viewerId = "";
            try {
                viewerId = DWLiveCoreHandler.getInstance().getViewer().getId();
            } catch (Exception e) {
                e.printStackTrace();
            }
            String roomId = "";
            try {
                roomId = DWLiveCoreHandler.getInstance().getRoomInfo().getEncryptId();
            } catch (Exception e) {
                e.printStackTrace();
            }
            final String finalViewerId = viewerId;
            final String finalRoomId = roomId;
            DWLive.getInstance().getInteractiveToken(new BaseCallback<String>() {
                @Override
                public void onError(String s) {
                    Toast.makeText(LivePlayActivity.this, "获取组件token失败:" + s, Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onSuccess(final String token) {
                    //获取正在进行的活动
                    DWLive.getInstance().getInteractiveOngoing(new BaseCallback<List<InteractionOngoing>>() {
                        @Override
                        public void onError(String error) {
                            initVoteHelper(finalViewerId, finalRoomId, token, false, "");
                        }

                        @Override
                        public void onSuccess(List<InteractionOngoing> ongoingList) {
                            //是否正在进行
                            boolean isOngoing = false;
                            String ongoingId = "";
                            if (ongoingList != null) {
                                for (int i = 0; i < ongoingList.size(); i++) {
                                    if (ongoingList.get(i).getType() == InteractionOngoing.TYPE_INTERACT_VOTE) {
                                        isOngoing = true;
                                        ongoingId = ongoingList.get(i).getId();
                                        break;
                                    }
                                }
                            }
                            initVoteHelper(finalViewerId, finalRoomId, token, isOngoing, ongoingId);

                        }
                    });


                }
            });
        }
    }

    private void initVoteHelper(String userId, String roomId, String token, boolean ongoing, String ongoingId) {
        voteMain.initialize(new VoteBaseLayout.VoteConfig()
                .setInteractToken(token)
                .setUserId(userId)
                .setRoomId(roomId)
                .setOngoing(ongoing)
                .setOngoingId(ongoingId));
        voteMain.setVoteMainListener(new IVoteMainListener() {
            @Override
            public void onVoteStart() {
                showInteractPanel(INTERACT_VOTE_MAIN);
            }

            @Override
            public void onVoteEnd() {
                hideInteractPanel(INTERACT_VOTE_MAIN);
            }

            @Override
            public void onCloseClick() {
                hideInteractPanel(INTERACT_VOTE_MAIN);
            }
        });
    }

    public void showQuestionnaire(boolean directOpenDetailPanel) {
        if (questionnaireLayout.getVisibility() == VISIBLE && !directOpenDetailPanel) {
            hideInteractPanel(INTERACT_FORM_MAIN);
            questionnaireLayout.hidePanel();
        } else {
            if (directOpenDetailPanel) {
                questionnaireLayout.showDetailPanel();
            } else {
                questionnaireLayout.showListPanel();
            }
            showInteractPanel(INTERACT_FORM_MAIN);
        }
    }


    public void showVote() {
        showInteractPanel(INTERACT_VOTE_MAIN);
    }


    public void showRed() {
        //回调点击
        if (redPacketHelper != null) {
            redPacketHelper.getUserRecord();
        }
    }

    public void setInvitationRankData(List<InvitationCardRankBean> invitationCardRankBeans, boolean show) {
        if (invitationRankList != null) {
            invitationRankList.setData(invitationCardRankBeans);
            if (show) {
                showInteractPanel(INTERACT_CARD_RANK);
            }
        }
    }


    private boolean isInvitationRankRequesting = false;

    public void showInvitationRankList() {
        if (invitationCard == null) {
            return;
        }
        if (!isInvitationRankRequesting) {
            isInvitationRankRequesting = true;
            invitationCard.getRankList(new IBaseCallBack<List<InvitationCardRankBean>>() {
                @Override
                public void onSuccess(List<InvitationCardRankBean> invitationCardRankBeans) {
                    isInvitationRankRequesting = false;
                    setInvitationRankData(invitationCardRankBeans, true);
                }

                @Override
                public void onFailed(int i, String s) {

                }
            });
        }
    }


    private boolean isLandScape() {
        return getResources().getConfiguration().orientation != Configuration.ORIENTATION_PORTRAIT;
    }

    @Override
    public void onKeyboardHeightChanged(int height, int orientation) {
        if (questionnaireLayout != null) {
            questionnaireLayout.setPadding(0, 0, 0, height);
        }
        if (qaInputLayout != null) {
            qaInputLayout.onKeyboardHeightChanged(height, orientation);
        }
        if (ccChatView != null) {
            ccChatView.onKeyboardHeightChanged(height, orientation);
        }
    }

    public void onInteractStreamEnd() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (questionnaireLayout != null && questionnaireSendMode != null && questionnaireSendMode.get() == 2 && isLiveStarted) {
                    isLiveStarted = false;
                    questionnaireLayout.showRelationQuestionnaire();
                }
            }
        });

    }

    public void onInteractStreamStart() {
        isLiveStarted = true;
    }

    // </editor-fold>
}
