package com.bokecc.dwlivedemo.activity;

import android.app.Activity;
import android.app.AppOpsManager;
import android.app.PictureInPictureParams;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.util.Rational;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bokecc.dwlivedemo.BuildConfig;
import com.bokecc.dwlivedemo.DWApplication;
import com.bokecc.dwlivedemo.R;
import com.bokecc.dwlivedemo.base.BaseActivity;
import com.bokecc.dwlivedemo.popup.ExitPopupWindow;
import com.bokecc.dwlivedemo.popup.FloatingPopupWindow;
import com.bokecc.dwlivedemo.utils.NetUtils;
import com.bokecc.dwlivedemo.utils.NotificationUtil;
import com.bokecc.livemodule.base.BaseReplayRoomLayout;
import com.bokecc.livemodule.live.chat.OnChatComponentClickListener;
import com.bokecc.livemodule.popup.DLNAPopupWindow;
import com.bokecc.livemodule.replay.DWReplayCoreHandler;
import com.bokecc.livemodule.replay.chat.ReplayChatComponent;
import com.bokecc.livemodule.replay.doc.ReplayDocComponent;
import com.bokecc.livemodule.replay.intro.ReplayIntroComponent;
import com.bokecc.livemodule.replay.qa.ReplayQAComponent;
import com.bokecc.livemodule.replay.room.ReplayRoomLayout;
import com.bokecc.livemodule.replay.summary.ReplaySummaryComponent;
import com.bokecc.livemodule.replay.summary.adapter.SummaryItemBean;
import com.bokecc.livemodule.replay.video.ReplayVideoView;
import com.bokecc.livemodule.utils.PhoneStateConstant;
import com.bokecc.sdk.mobile.live.BaseCallback;
import com.bokecc.sdk.mobile.live.logging.ELog;
import com.bokecc.sdk.mobile.live.pojo.PlayUrlInfoBean;
import com.bokecc.sdk.mobile.live.pojo.ReplaySummaryInfo;
import com.bokecc.sdk.mobile.live.replay.DWLiveReplay;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import static android.view.View.VISIBLE;
import static com.bokecc.livemodule.live.chat.adapter.LivePublicChatAdapter.CONTENT_IMAGE_COMPONENT;
import static com.bokecc.livemodule.live.chat.adapter.LivePublicChatAdapter.CONTENT_ULR_COMPONET;

/**
 * 回放播放页（默认文档大屏，视频小屏，可手动切换）
 */
public class ReplayPlayActivity extends BaseActivity {
    private static final String TAG = "ReplayPlayActivity";

    // <editor-fold defaultstate="collapsed" desc="实例变量">
    private View mRoot;
    private LinearLayout mReplayMsgLayout;
    private RelativeLayout mReplayVideoContainer;
    private ReplayVideoView mReplayVideoView;
    private FloatingPopupWindow mReplayFloatingView;
    private ReplayRoomLayout mReplayRoomLayout;
    private BroadcastReceiver broadcastReceiver;
    private boolean isVideoMain;
    private boolean isDestroyed = false;
    private ReplaySummaryComponent summaryComponent;

    private PictureInPictureParams.Builder mPictureInPictureParamsBuilder;

    private ReplayIntroComponent mIntroComponent;
    private ReplayQAComponent mQaLayout;
    private ReplayChatComponent mChatLayout;
    private ReplayDocComponent mDocLayout;


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

    private ViewPager mViewPager;

    private RadioGroup mRadioGroup;
    private RadioButton mIntroTag;
    private RadioButton mSummaryTag;
    private RadioButton mQaTag;
    private RadioButton mChatTag;
    private TextView replay_room_error_tip;

    private ExitPopupWindow mExitPopupWindow;
    private boolean isExitPicInPicMode = false;
    private DLNAPopupWindow dlnaPopupWindow;


    // </editor-fold>


    // <editor-fold defaultstate="collapsed" desc="对外方法">

    /**
     * 启动回放界面
     *
     * @param activity    activity
     * @param isVideoMain 是否是以大屏为主
     * @param recordId    回放id，用于记忆播放
     */
    public static void openActivity(Activity activity, boolean isVideoMain, String recordId) {
        Intent intent = new Intent(activity, ReplayPlayActivity.class);
        intent.putExtra("isVideoMain", isVideoMain);
        intent.putExtra("recordId", recordId);
//        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        activity.startActivity(intent);
    }

    // </editor-fold>


    // <editor-fold defaultstate="collapsed" desc="生命周期及重写方法">

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

        // 回放id
        String recordId = getIntent().getStringExtra("recordId");

        Log.i(TAG,"recordId:"+recordId);



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

        initViews();
        initViewPager();
        initReceiver();


        // 设置进度记忆唯一标识
        DWReplayCoreHandler replayCoreHandler = DWReplayCoreHandler.getInstance();
        if (replayCoreHandler != null) {
            replayCoreHandler.setRecordTag(recordId);
        }

//        DWLiveReplay.getInstance().setLastPosition(5 * 60 * 1000);
        // 开始播放
        mReplayVideoView.start();

        // 设置防录屏
//        mReplayVideoView.setAntiRecordScreen(this);

    }


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

    @Override
    protected void onPause() {
        Log.i(TAG, "onPause");
        super.onPause();
        if (isFinishing()) {
            destroy();
        }
    }


    @Override
    protected void onResume() {
        Log.i(TAG, "onResume");
        super.onResume();
        if (isExitPicInPicMode){
            isExitPicInPicMode = false;
            DWApplication.getInstance().setInPictureInPictureMode(false);
            if (!isFinishing()) {
                Log.i(TAG, "onPictureInPictureModeChanged 2");
                //显示其他元素
                mReplayMsgLayout.setVisibility(VISIBLE);
                if (DWReplayCoreHandler.getInstance().hasDocView()) {
                    mReplayFloatingView.show(mRoot);
                    mReplayRoomLayout.setSwitchText(false);
                }
            }
        }
        // 取消通知
        NotificationUtil.cancelNotification(this);

    }

    @Override
    protected void onStop() {
        Log.i(TAG, "onStop");
        super.onStop();
        // 开启通知
        if (!isFinishing()) {
            NotificationUtil.sendReplayNotification(this);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //如果activity创建时检测到已经存在画中画模式，则不关闭画中画
            if (DWApplication.getInstance().isInPictureInPictureMode()) {
                DWApplication.getInstance().setInPictureInPictureMode(false);
                Log.i(TAG, "isInPictureInPictureMode, finish");
                finish();
//                finishAffinity();
            }
        }
    }

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


    @Override
    public void onBackPressed() {
        ELog.d(TAG, "onBackPressed()");
        if (!isPortrait()) {
            quitFullScreen();
            return;
        }
        if (mExitPopupWindow != null) {
            mExitPopupWindow.setConfirmExitRoomListener(confirmExitRoomListener);
            mExitPopupWindow.show(mRoot);
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        Log.i(TAG, "onConfigurationChanged");
        super.onConfigurationChanged(newConfig);
        // 横屏隐藏状态栏
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            getWindow().getDecorView().setSystemUiVisibility(getSystemUiVisibility(true));
        } else {
            getWindow().getDecorView().setSystemUiVisibility(getSystemUiVisibility(false));
        }
        //调整窗口的位置
        if (mReplayFloatingView != null) {
            mReplayFloatingView.onConfigurationChanged(newConfig.orientation);
        }
    }

    @Override
    public void onPictureInPictureModeChanged(boolean isInPictureInPictureMode, Configuration newConfig) {
        Log.i(TAG, "onPictureInPictureModeChanged:" + isInPictureInPictureMode);
        if (isInPictureInPictureMode) {
            DWApplication.getInstance().setInPictureInPictureMode(true);
            //隐藏其他元素，只保留视频元素
        } else {
            //到onResume在判断是否退出画中画
            isExitPicInPicMode = true;
        }

    }

    @Override
    public void onUserLeaveHint() {
        Log.i(TAG, "onUserLeaveHint:");

    }

    @Override
    protected void onNewIntent(Intent intent) {
        Log.i(TAG, "onNewIntent:");
        super.onNewIntent(intent);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode==KeyEvent.KEYCODE_VOLUME_UP){
            // 音量增大按键被按下
            if (dlnaPopupWindow!=null&&dlnaPopupWindow.onVolumeChange(true)){
                return true;
            }
        }else if (keyCode==KeyEvent.KEYCODE_VOLUME_DOWN){
            // 音量增大按键被按下
            if (dlnaPopupWindow!=null&&dlnaPopupWindow.onVolumeChange(false)){
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    // </editor-fold>


    // <editor-fold defaultstate="collapsed" desc="回调变量">
    private final ExitPopupWindow.ConfirmExitRoomListener confirmExitRoomListener = new ExitPopupWindow.ConfirmExitRoomListener() {
        @Override
        public void onConfirmExitRoom() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    exit();
                }
            });
        }
    };


    private final ReplayRoomLayout.ReplayRoomStatusListener roomStatusListener =
            new ReplayRoomLayout.ReplayRoomStatusListener() {

                @Override
                public void switchVideoDoc(boolean isVideoMain) {
                    switchView(isVideoMain);
                }

                @Override
                public void openVideoDoc() {
                    if (mReplayRoomLayout.isVideoMain()) {
                        ReplayPlayActivity.this.isVideoMain = true;
                        mReplayFloatingView.show(mRoot);
                        if (mDocLayout.getParent() != null) {
                            ((ViewGroup) mDocLayout.getParent()).removeView(mDocLayout);
                        }
                        mReplayFloatingView.addView(mDocLayout);
                    } else {
                        ReplayPlayActivity.this.isVideoMain = false;
                        mReplayFloatingView.show(mRoot);
                        if (mReplayVideoView.getParent() != null) {
                            ((ViewGroup) mReplayVideoView.getParent()).removeView(mReplayVideoView);
                        }
                        mReplayFloatingView.addView(mReplayVideoView);
                    }
                }

                @Override
                public void closeRoom() {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            // 如果当前状态是竖屏，则弹出退出确认框，否则切换为竖屏
                            if (isPortrait()) {
                                if (mExitPopupWindow != null) {
                                    mExitPopupWindow.setConfirmExitRoomListener(confirmExitRoomListener);
                                    mExitPopupWindow.show(mRoot);
                                }
                            } else {
                                quitFullScreen();
                            }
                        }
                    });
                }

                @Override
                public void fullScreen() {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                            mReplayMsgLayout.setVisibility(View.GONE);
                            getWindow().getDecorView().setSystemUiVisibility(getSystemUiVisibility(true));
                        }
                    });
                }

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

                @Override
                public void onChangePlayMode(DWLiveReplay.PlayMode playMode) {
                    mReplayVideoView.changeModeLayout(playMode);

                }


            };


    // </editor-fold>


    // <editor-fold defaultstate="collapsed" desc="私有方法">

    /**
     * 销毁
     */
    private void destroy() {
        if (isDestroyed) {
            return;
        }
        ELog.i(TAG, "activity onDestroy?");
        NotificationUtil.cancelNotification(this);
        try{
            unregisterReceiver(broadcastReceiver);
            mReplayFloatingView.dismiss();
            Log.i(TAG, "mReplayVideoView.destroy()");
            mReplayVideoView.destroy();
            isDestroyed = true;
            phoneStateListener = null;
            if (dlnaPopupWindow!=null){
                dlnaPopupWindow.release();
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }


    private static int getSystemUiVisibility(boolean isFull) {
        if (isFull) {
            int flags = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LOW_PROFILE;
            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);
        mReplayVideoContainer = findViewById(R.id.rl_video_container);
        mReplayRoomLayout = findViewById(R.id.replay_room_layout);
        mReplayMsgLayout = findViewById(R.id.ll_pc_replay_msg_layout);
        mViewPager = findViewById(R.id.live_portrait_container_viewpager);
        mRadioGroup = findViewById(R.id.rg_infos_tag);
        mIntroTag = findViewById(R.id.live_portrait_info_intro);
        mSummaryTag = findViewById(R.id.live_portrait_summary_intro);
        mQaTag = findViewById(R.id.live_portrait_info_qa);
        mChatTag = findViewById(R.id.live_portrait_info_chat);
        replay_room_error_tip = findViewById(R.id.replay_room_error_tip);
        replay_room_error_tip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                replay_room_error_tip.setVisibility(View.GONE);
                mDocLayout.reloadDocView();
            }
        });

        // 弹出框界面
        mExitPopupWindow = new ExitPopupWindow(this);
        mReplayFloatingView = new FloatingPopupWindow(this);
        mReplayFloatingView.setFloatDismissListener(floatDismissListener);
        mReplayRoomLayout.setReplayRoomStatusListener(roomStatusListener);
        mReplayRoomLayout.setPlayerTimerListener(new BaseReplayRoomLayout.OnPlayerTimerListener() {
            @Override
            public void onPlayerTimer(long time) {
                if (summaryComponent != null) {
                    summaryComponent.updateTime(time);
                }
            }
        });

        mReplayRoomLayout.setOnPicInPicListener(new BaseReplayRoomLayout.OnPicInPicListener() {
            @Override
            public void onPicInPicClick() {
                //如果当前是横屏状态，强制切换竖屏，然后进入画中画模式
                if (getResources().getConfiguration().orientation != Configuration.ORIENTATION_PORTRAIT) {
                    quitFullScreen();
                    mReplayRoomLayout.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            checkAndEnterPicInPicMode();
                        }
                    }, 1000);
                } else {
                    checkAndEnterPicInPicMode();
                }


            }
        });
        mReplayRoomLayout.setOnDlnaListener(new BaseReplayRoomLayout.OnDlnaListener() {
            @Override
            public void onDlnaClick(PlayUrlInfoBean infoBean) {
                //如果当前是横屏状态，强制切换竖屏，然后进入投屏模式
                if (getResources().getConfiguration().orientation != Configuration.ORIENTATION_PORTRAIT) {
                    quitFullScreen();
                }
                //如果视频播放完成，先自动重播
                if (mReplayVideoView.isPlayComplete()){
                    DWReplayCoreHandler.getInstance().retryReplay(0,false);
                }
                if (dlnaPopupWindow==null){
                    dlnaPopupWindow = new DLNAPopupWindow(ReplayPlayActivity.this);
                    dlnaPopupWindow.setOnExitListener(new DLNAPopupWindow.OnExitListener() {
                        @Override
                        public void onExit() {
                            if (mReplayVideoView!=null){
                                mReplayVideoView.start();
                            }

                        }
                    });
                }

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
                    if (infoBean!=null&&infoBean.getVideos()!=null&& !infoBean.getVideos().isEmpty() &&infoBean.getVideos().get(0)!=null&&infoBean.getVideos().get(0).getVideoStream()!=null&& !infoBean.getVideos().get(0).getVideoStream().isEmpty()){
                        String url = infoBean.getVideos().get(0).getVideoStream().get(0);
                        Log.i(TAG,"投屏url："+url);
                        //如果为加密视频，需要将返回的url中的127.0.0.1的ip转换为手机局域网ip，由于涉及到网络ACCESS_NETWORK_STATE权限，所以不在sdk中处理
                        String playUrl = url;
                        if (url.contains(".pcm")){
                            //加密视频，进行转换
                            String encode = URLEncoder.encode(url);
                            String localIp = NetUtils.getLocalIpAddress(ReplayPlayActivity.this);

                            int drmPort = mReplayVideoView.getDrmPort();
                            if (drmPort==0){
                                toastOnUiThread("请等待drm初始化成功");
                            }
                            playUrl = "http://"+localIp+":" + drmPort + "/?url=" + encode;
                        }

                        String title = "";
                        if (DWReplayCoreHandler.getInstance().getBaseRecordInfo()!=null){
                            title = DWReplayCoreHandler.getInstance().getBaseRecordInfo().getTitle();
                        }

                        dlnaPopupWindow.setVideoName(title);
                        long position = mReplayVideoView.getCurrentPosition();
                        dlnaPopupWindow.setCurrentPosition(position);
                        dlnaPopupWindow.show(playUrl,ReplayPlayActivity.this,mRoot, Gravity.CENTER,0,0);
                        if (mReplayVideoView!=null){
                            mReplayVideoView.pause();
                        }
                    }
                }
            }
        });

        String recordId = getIntent().getStringExtra("recordId");
        // 初始化房间信息
        mReplayRoomLayout.init(isVideoMain, recordId);
        mReplayRoomLayout.setActivity(this);
    }

    private void checkAndEnterPicInPicMode() {
        if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE)) {
            //进入画中画模式
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                AppOpsManager appOpsManager = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE);
                if (AppOpsManager.MODE_ALLOWED == appOpsManager.checkOpNoThrow(AppOpsManager.OPSTR_PICTURE_IN_PICTURE,
                        getApplicationInfo().uid, getPackageName())) {

                    //画中画开关开启
                    if (mPictureInPictureParamsBuilder == null) {
                        mPictureInPictureParamsBuilder = new PictureInPictureParams.Builder();
                    }
                    //如果是文档大屏模式，需要切换一下
                    if (DWReplayCoreHandler.getInstance().hasDocView() && !isVideoMain) {
                        switchView(true);
                        mReplayRoomLayout.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                minimize();
                            }
                        }, 1000);
                    } else {
                        minimize();
                    }
                } else {
                    //画中画开关关闭
                    toastOnUiThread("请前往设置手动打开画中画开关！");

                }


            } else {
                toastOnUiThread("版本不支持画中画功能！");
            }
        } else {
            toastOnUiThread("设备不支持画中画功能！");
        }
    }

    /**
     * 进入画中画模式
     */
    private void minimize() {
        double as = mReplayVideoView.getWidth()*1.0/mReplayVideoView.getHeight();

        //must be between 0.418410 and 2.390000
        if (as>2.39||as<0.42){
            toastOnUiThread("此屏幕比例暂不支持画中画");
            return;
        }
        //1. 隐藏下方布局
        mReplayMsgLayout.setVisibility(View.GONE);
        //2. 隐藏浮窗
        if (DWReplayCoreHandler.getInstance().hasDocView()) {
            mReplayFloatingView.dismiss();
        }
        //3. 隐藏记忆播放提示
        mReplayRoomLayout.hideMemoryPlayTip();
        //4. 隐藏视频控制条
        mReplayRoomLayout.hideController();


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Rational aspectRatio = new Rational(mReplayVideoView.getWidth(), mReplayVideoView.getHeight());

            mPictureInPictureParamsBuilder.setAspectRatio(aspectRatio).build();
            enterPictureInPictureMode(mPictureInPictureParamsBuilder.build());
        }
    }


    /**
     * 根据直播间模版初始化相关组件
     */
    private void initComponents() {
        DWReplayCoreHandler dwReplayCoreHandler = DWReplayCoreHandler.getInstance();
        if (dwReplayCoreHandler == null) {
            return;
        }

        // 初始化视频控件
        initVideoLayout();

        // 判断当前直播间模版是否有"文档"功能
        if (dwReplayCoreHandler.hasDocView()) {
            initDocLayout();
        }
        // 判断当前直播间模版是否有"聊天"功能
        if (dwReplayCoreHandler.hasChatView()) {
            initChatLayout();
            ELog.d(TAG, "initChatLayout");
        }
        // 判断当前直播间模版是否有"问答"功能
        if (dwReplayCoreHandler.hasQaView()) {
            initQaLayout();
            ELog.d(TAG, "initQaLayout");
        }
        // 直播间简介
        initIntroLayout();
        initSummaryLayout();


    }


    /**
     * 注册广播接收者
     */
    private void initReceiver() {
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (action.equals(PhoneStateConstant.PHONE_STATE)) {
                    final String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
                    phoneStateListener.state(state);
                }

            }
        };
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(PhoneStateConstant.PHONE_STATE);
        registerReceiver(broadcastReceiver, intentFilter);
        setPhoneStateListener(new PhoneStateListener() {
            @Override
            public void state(String action) {
                /* Incoming call */
                if (TelephonyManager.EXTRA_STATE_RINGING.equals(action)) {
                    Log.i(TAG, "current state is EXTRA_STATE_RINGING.");
                    PhoneStateConstant.isPhoneInCall = true;
                } else if (TelephonyManager.EXTRA_STATE_OFFHOOK.equals(action)) {/* Outgoing call */
                    Log.i(TAG, "current state is OFFHOOK.");
                    PhoneStateConstant.isPhoneInCall = true;
                    DWLiveReplay.getInstance().pause();
                } else if (TelephonyManager.EXTRA_STATE_IDLE.equals(action)) { /* Call ended */
                    Log.i(TAG, "current state is IDLE.");
                    PhoneStateConstant.isPhoneInCall = false;
                    DWLiveReplay.getInstance().resume();
                } else if (NotificationUtil.ACTION_PLAY_PAUSE.equals(action)) {
                    if (mReplayRoomLayout != null) {
                        mReplayRoomLayout.changePlayerStatus();
                    }
                    NotificationUtil.sendReplayNotification(ReplayPlayActivity.this);
                }
            }
        });
    }


    /**
     * 初始化聊天布局区域
     */
    private void initChatLayout() {
        mIdList.add(R.id.live_portrait_info_chat);
        mTagList.add(mChatTag);
        mChatTag.setVisibility(VISIBLE);
        mChatLayout = new ReplayChatComponent(this);
        mChatLayout.setOnChatComponentClickListener(new OnChatComponentClickListener() {
            @Override
            public void onClickChatComponent(Bundle bundle) {
                if (bundle == null) {
                    return;
                }
                String type = bundle.getString("type");
                if (CONTENT_IMAGE_COMPONENT.equals(type)) {
                    Intent intent = new Intent(ReplayPlayActivity.this, ImageDetailsActivity.class);
                    intent.putExtra("imageUrl", bundle.getString("url"));
                    startActivity(intent);
                } else if (CONTENT_ULR_COMPONET.equals(type)) {
                    Uri uri = Uri.parse(bundle.getString("url"));
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    startActivity(intent);
                }
            }
        });
        mLiveInfoList.add(mChatLayout);
        if (mChatLayout != null) {
            mReplayRoomLayout.setSeekListener(mChatLayout);
        }
    }

    /**
     * 初始化问答布局区域
     */
    private void initQaLayout() {
        mIdList.add(R.id.live_portrait_info_qa);
        mTagList.add(mQaTag);
        mQaTag.setVisibility(VISIBLE);
        mQaLayout = new ReplayQAComponent(this);
        mLiveInfoList.add(mQaLayout);
    }

    /**
     * 初始化简介布局区域
     */
    private void initIntroLayout() {
        ELog.d(TAG, "initIntroLayout");
        mIdList.add(R.id.live_portrait_info_intro);
        mTagList.add(mIntroTag);
        mIntroTag.setVisibility(VISIBLE);
        mIntroComponent = new ReplayIntroComponent(this);
        mLiveInfoList.add(mIntroComponent);
    }

    /**
     * 初始化大纲
     */
    private void initSummaryLayout() {
        if (!DWReplayCoreHandler.getInstance().hasSummary()) {
            return;
        }
        mIdList.add(R.id.live_portrait_summary_intro);
        mTagList.add(mSummaryTag);
        mSummaryTag.setVisibility(VISIBLE);

        summaryComponent = new ReplaySummaryComponent(this);
        mLiveInfoList.add(summaryComponent);

        summaryComponent.setOnSelectSummaryChange(new ReplaySummaryComponent.OnSelectSummaryChange() {
            @Override
            public void onSelectSummaryChange(SummaryItemBean summaryItemBean) {
                long time = summaryItemBean.getTime();
                mReplayRoomLayout.seekTo((int) time);
            }
        });

        DWReplayCoreHandler.getInstance().getSummaryInfo(new BaseCallback<ReplaySummaryInfo>() {
            @Override
            public void onSuccess(ReplaySummaryInfo msg) {
                if (msg != null) {
                    summaryComponent.setData(msg);
                }
            }

            @Override
            public void onError(String error) {
                //暂无总结数据
            }
        });

    }

    /**
     * 初始化文档布局区域
     */
    private void initDocLayout() {
        mDocLayout = new ReplayDocComponent(this);
        mDocLayout.setDocListener(new ReplayDocComponent.DocListener() {
            @Override
            public void docFail() {
                replay_room_error_tip.setVisibility(VISIBLE);

            }
        });
        if (isVideoMain) {
            mReplayFloatingView.addView(mDocLayout);
        } else {
            if (DWReplayCoreHandler.getInstance().hasDocView()) {
                mReplayVideoContainer.addView(mDocLayout);
                mDocLayout.setDocScrollable(true);
            }
        }
        // 显示小窗
        showFloatingDocLayout();
    }

    /**
     * 初始化视频布局区域
     */
    private void initVideoLayout() {
        mReplayVideoView = new ReplayVideoView(this);
        if (isVideoMain) {
            mReplayVideoContainer.addView(mReplayVideoView);
        } else {
            if (DWReplayCoreHandler.getInstance().hasDocView()) {
                mReplayFloatingView.addView(mReplayVideoView);
            } else {
                mReplayVideoContainer.addView(mReplayVideoView);
            }
        }

    }

    /**
     * 展示文档悬浮窗布局
     */
    private void showFloatingDocLayout() {
        // 判断当前直播间模版是否有"文档"功能，如果没文档，则小窗功能也不应该有
        if (DWReplayCoreHandler.getInstance().hasDocView()) {
            mReplayFloatingView.show(mRoot);
        }
    }


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

            @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 final FloatingPopupWindow.FloatDismissListener floatDismissListener = new FloatingPopupWindow.FloatDismissListener() {
        @Override
        public void dismiss() {
            mReplayRoomLayout.setSwitchText(true);
        }
    };


    /**
     * 切换文档-视频大小窗
     *
     * @param isVideoMain 是否是视频为主
     */
    private void switchView(boolean isVideoMain) {
        if (mReplayVideoView.getParent() != null) {
            ((ViewGroup) mReplayVideoView.getParent()).removeView(mReplayVideoView);
        }
        if (mDocLayout.getParent() != null) {
            ((ViewGroup) mDocLayout.getParent()).removeView(mDocLayout);
        }
        if (isVideoMain) {
            this.isVideoMain = true;
            // 缓存视频的切换前的画面
            mReplayFloatingView.addView(mDocLayout);
            mReplayVideoContainer.addView(mReplayVideoView);
            mDocLayout.setDocScrollable(false);//webview不可滑动
        } else {
            this.isVideoMain = false;
            // 缓存视频的切换前的画面
            mReplayFloatingView.addView(mReplayVideoView);
            mReplayVideoContainer.addView(mDocLayout);
            mDocLayout.setDocScrollable(true);//webview可滑动
        }
    }

    /**
     * 退出全屏
     */
    private void quitFullScreen() {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        mReplayMsgLayout.setVisibility(VISIBLE);

        getWindow().getDecorView().setSystemUiVisibility(getSystemUiVisibility(false));
    }

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

    // </editor-fold>

}
