package com.wasu.cs.ui;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.wasu.authsdk.AuthSDK;
import com.wasu.authsdk.IAuthInterface;
import com.wasu.authsdk.entity.PriceInfo;
import com.wasu.comp.ad.AdView;
import com.wasu.comp.pay.DialogPay.PayStatusListener;
import com.wasu.comp.userlogin.DialogLogin;
import com.wasu.compfactory.WasuCompFactory;
import com.wasu.cs.model.DemandProgram;
import com.wasu.cs.model.DemandRecommand;
import com.wasu.cs.model.DemandRecommand.RecommendItem;
import com.wasu.cs.mvp.DetailPlayerOberserver;
import com.wasu.cs.mvp.IView.DetailView;
import com.wasu.cs.mvp.presenter.DetailLogic;
import com.wasu.cs.ui.DetailSeriesView.onSeriesListener;
import com.wasu.cs.utils.ActivityManager;
import com.wasu.cs.utils.UserUtils;
import com.wasu.cs.widget.DialogAssetExitApp;
import com.wasu.cs.widget.mediacontrol.DialogPlanBuy;
import com.wasu.cs.widget.mediacontrol.MediaController;
import com.wasu.cs.widget.videoview.ExtPlayer;
import com.wasu.cs.widget.videoview.PlayerParams;
import com.wasu.cs.widget.videoview.WasuPlayerView;
import com.wasu.cs.widget.videoview.WasuPlayerView.OnScreenChangedListener;
import com.wasu.module.log.WLog;
import com.wasu.statistics.WasuStatistics;
import com.wasu.widget.FocusLinearLayout;
import com.wasu.widget.FocusLinearLayout.OnChildViewSelectedListener;
import com.wasu.widgets.adapter.BaseFocusRecyclerViewAdapter;
import com.wasu.widgets.focuswidget.FocusRecyclerView;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.List;

import basic.BuilderTypeManager.BuildType;
import basic.app.TvAppLike;
import cn.com.wasu.main.AppUtil;
import cn.com.wasu.main.BuildConfig;
import cn.com.wasu.main.ChannelFlavor;
import cn.com.wasu.main.Common;
import cn.com.wasu.main.ErrorMap;
import cn.com.wasu.main.IntentConstant;
import cn.com.wasu.main.IntentMap;
import cn.com.wasu.main.LayoutCodeMap;
import cn.com.wasu.main.R;

import static com.wasu.widgets.adapter.BaseFocusRecyclerViewAdapter.TYPE_HEADER;

/**
 * @author zhenggang
 * @ClassName: ActivityDetail
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @date 2016年2月23日 下午5:07:38
 */
@SuppressLint("NewApi")
public class ActivityDetail extends ActivityBase implements DetailView {
    private static final String TAG = "ActivityDetail";
    private static final String PageViewType = "detail";
    public static String Detail_Action = "com.wasu.fullplay";
    DemandProgram mAsset;

    private final int RECOMMEND_MAXNUM = 10;
    /**
     * 指定当前播放的码率
     */
    public static final String ASSET_BITRATE = "bitrate";
    private String enter = "";//detail保存一份，防止推荐进入修改了本次播放的入口
    private DetailResTitle mResourceTitle;
    private DetailIndicatorLinearlayout mIndicatorLayout;

    public ViewGroup mPlayerGroup;
    private WasuPlayerView mVideoView;

    private TextView mCoupon;
    private TextView mDirectorTextView;
    private TextView mActorTextView;
    private TextView mDescriptTextView;

    private FocusLinearLayout mPlayBtnGroup;
    private TextView mPrice;
    private View mBtnMonth;
    private View mBtnPaySingle;
    private View mBtnFavorite;
    private View mBtnUserCenter;
    private View mBtnSerial;
    private View headView;
    private AdView mAdview; // 全局广告view保证不自己回收

    private ViewGroup adGroup;
    private FocusRecyclerView mRecommendGridView;// 推荐view
    public String traceid = "";
    DisplayMetrics dm;
    private boolean mScroll = false;
    private DetailPlayerOberserver mDetailOberserver; // 观察者实例
    private DetailRecommendAdapter mAdapter; // 推荐位adapter

    private static List<Activity> DetailInstance = new ArrayList<Activity>();
    private DetailLogic detailLogic = new DetailLogic(this);
    /**
     * 增加返回键判断，区别用户按返回键和动态加载finish，避免重复处理
     */
    private boolean mBackPress = false;
    private Context mContext;
    public long startTime;

    /**
     * 用于图文广告加载延时
     * */
    private Handler mHandler = new Handler();
    private Runnable mRunnable;
    /**记录用户进入详情页时的登陆状态*/
    private String mUserKeyBack;
    private boolean mResetFocus; // 外部页面返回详情页时是否重置焦点到播放器

    private int series = -1;
    private long currentPosition = 0;
    private boolean isFullPlay = false;

    @Override
    protected void doCreate(Bundle savedInstanceState) {
        startTime = System.currentTimeMillis();

        if (DetailInstance.size() >= TvAppLike.MAX_LAYER) {
            ActivityDetail thisActivity = (ActivityDetail)DetailInstance.get(0);
            thisActivity.SendPlayEndStatistics();
            thisActivity.finish();
            DetailInstance.remove(0);
        }
        DetailInstance.add(ActivityDetail.this);

        setContentView(R.layout.detail_layout);
        enter = AppUtil.playEnter;
        Intent intent = getIntent();
        if (intent == null) {
            showErrorExitDlg("启动方式错误");
            return;
        }
        mContext = this;

        String action = intent.getAction();
        String value = intent.getStringExtra("value");

        boolean isFullAction = !TextUtils.isEmpty(action) && action.equals(Detail_Action);
        if (isFullAction) {
            TvAppLike.MAX_LAYER = 1;
        }
        String programUrl = isFullAction ? fullPlay(value) : intent.getStringExtra(IntentConstant.DATAURI.value());
        traceid = intent.getStringExtra("traceid");
        initView();
        detailLogic.setTraceid(traceid);
        showLoading();
        detailLogic.loadAssetDetail(programUrl);
        //查询是否免广告
        detailLogic.adFreeQuery();
        //通过userKey的变化，检测用户是否有登入登出
        mUserKeyBack = AuthSDK.getInstance().getValue(IAuthInterface.KEY_USERKEY);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //pageView
        WasuStatistics.getInstance().pageViewStart(PageViewType);

        if (mVideoView != null) {
            mVideoView.StartTimer(); // 启动计时器
            mVideoView.onResume();

            //Add by Frewen.Wong 渡鸦科技
            if (isFullPlay || BuildConfig.FLAVOR.equalsIgnoreCase(ChannelFlavor.DUYA_TECH)) {
                if (!mVideoView.isFullScreen()) {
                    mVideoView.toggleFullScreen();
                }
            }

            String userkey = AuthSDK.getInstance().getValue(IAuthInterface.KEY_USERKEY);
            if (!mUserKeyBack.equals(userkey)){ // 登陆状态发生变化
                // 用户从vip随心看出去之后，登录状态变化则重置焦点到播放器，避免焦点丢失。mResetFocus防止用户从推荐位跳出后返回时焦点发生变化
                if (mResetFocus){
                    if (mPlayerGroup != null){
                        mPlayerGroup.requestFocus();
                    }
                    mUserKeyBack = userkey;
                    mResetFocus = false;
                }

                if (UserUtils.checkIsVipBoolen()){
                    // 用户去Vip随心看登陆之后，如果是VIP，返回时广告直接切断
                    mVideoView.skipCurrentAd();
                    // 播放正片时，进行码率检测。
                    // 会员默认码率逻辑 - 如果用户已经切换过码率,则保持码率不变。如果用户没有切换过码率，则修改默认码率
                    if (mVideoView.getDefaultPlayRate() == mVideoView.PLAY_RATE_NORMAL_L){
                        mVideoView.changeRate(mVideoView.PLAY_RATE_NORMAL_H);
                    }
                }else {
                    if (mVideoView.getDefaultPlayRate() == mVideoView.PLAY_RATE_NORMAL_H){
                        mVideoView.changeRate(mVideoView.PLAY_RATE_NORMAL_L);
                    }
                }
                mUserKeyBack = userkey; // 更新登陆状态
            }

            if (mDetailOberserver != null && mAsset != null){ // 从其他详情页返回时重置mark，便于发送关闭时的统计
                mDetailOberserver.MarkPlayInfo();
            }
        }
        detailLogic.queryPrice(false);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((isFullPlay || BuildConfig.FLAVOR.equalsIgnoreCase(ChannelFlavor.DUYA_TECH)) && keyCode == KeyEvent.KEYCODE_BACK) {
            exitDialogShow();
        }
        return super.onKeyDown(keyCode, event);
    }

    DialogAssetExitApp exitDialog;

    /**
     * 显示退出应用对话框
     */
    private void exitDialogShow() {
        if (mVideoView.isAdPlaying() || mVideoView.isPlaying()) {
            mVideoView.pause();
        }

        if (mContext == null) {
            return;
        }
        if (exitDialog != null && exitDialog.isShowing()) {
            return;
        }
        exitDialog = new DialogAssetExitApp(mContext);
        exitDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                exitDialog.DestoryDialog();
                exitDialog.dismiss();
                mVideoView.start();
            }
        });
        exitDialog.setStartTime(startTime);
        exitDialog.show();
    }

    /**
     * 需要退出App
     */
    public void exitApp() {
        ActivityManager.getInstance().exitApp();
    }

    @Override
    public void onBackPressed() {
        mBackPress = true;
//        ImageFetcherModule.getInstance().stopAllTask();
        if (mVideoView != null) {
            mVideoView.stopPlayback();
            try {
                mVideoView.removeAllViews();
                mVideoView.finalize();
            } catch (Throwable e) {
                e.printStackTrace();
            }
            mVideoView = null;
        }
        super.onBackPressed();
    }


    private OnFocusChangeListener mIndicatorChange = new OnFocusChangeListener() {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            //WLog.i(TAG, "mIndicatorChange v.getid()="+v.getId()+"hasFocus="+hasFocus);
            switch (v.getId()) {
                case R.id.detail_player:
                    if (mRecommendGridView.getX() > 0) {
                        mRecommendGridView.scrollToPosition(0);
                    }
                case R.id.detail_playBtnGroup:
                    if (hasFocus == true) {
                        mIndicatorLayout.setIndicatorFocus(0);
                    }
                    break;
                case R.id.detail_ad_parent:
                    if (hasFocus == true) {
                        mScroll = false;
                        mIndicatorLayout.setIndicatorFocus(1);
                    }
                    break;
                case R.id.detail_recommendRrid:
                    if (hasFocus == true) {
                        mIndicatorLayout.setIndicatorFocus(1);
                    }
                    break;
                case R.id.detail_commentlist:
                    if (hasFocus == true) {
                    }
                    break;
                case R.id.detail_pics:
                    if (hasFocus == true) {
                    }
                    break;
                default:
                    break;
            }

        }
    };

    private void initView() {
        //初始化资产标题
        mResourceTitle = (DetailResTitle) findViewById(R.id.detail_title);
        //初始化分类标签
        initIndicator();

        // recycleview 的haedview。包含广告和按钮两部分
        headView = LayoutInflater.from(this).inflate(R.layout.activity_detail_headview, null);


        // 播放器和资产
        mPlayerGroup = (ViewGroup) findViewById(R.id.detail_player);
        mPlayerGroup.setOnFocusChangeListener(mIndicatorChange);
        mCoupon = (TextView) findViewById(R.id.detail_coupon);
        mPrice = (TextView) headView.findViewById(R.id.detail_pay_price);

        //use this as context will cause memory leak ,after test found use softref deals fine (WebCore)
        SoftReference<ActivityDetail> softActivity = new SoftReference<ActivityDetail>(this);
        mVideoView = new WasuPlayerView(softActivity.get(), detailLogic, BuildType.payTypeUrl,MediaController.DISPLAY_PROMPT_EXIT_AD);
        mVideoView.setFullPlay(isFullPlay);

        mVideoView.setAnchorView(mPlayerGroup, this);

        if (isFullPlay || BuildConfig.FLAVOR.equalsIgnoreCase(ChannelFlavor.DUYA_TECH)) {
            if (!mVideoView.isFullScreen()) {
                mVideoView.toggleFullScreen();
            }
        }

        mPlayerGroup.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mVideoView != null) {
                    if (mVideoView.isHasStart() || mVideoView.isPlaying() || mVideoView.isAdPlaying()) {
                        mVideoView.toggleFullScreen();
                    } else {
                        play();
                        mVideoView.toggleFullScreen();
                    }
                }
            }
        });
        mPlayerGroup.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    return v.performClick();
                }
                return false;
            }
        });
        mPlayerGroup.setNextFocusRightId(R.id.detail_playBtnGroup);

        mDirectorTextView = (TextView) findViewById(R.id.detail_player_director);
        mActorTextView = (TextView) findViewById(R.id.detail_player_actor);
        mDescriptTextView = (TextView) findViewById(R.id.detail_player_description);
        final ScrollView detailScrollView = (ScrollView) findViewById(R.id.detail_description_scroll);
        detailScrollView.setOnFocusChangeListener(new OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    detailScrollView.setBackgroundResource(R.drawable.tv_select_focus);
                } else {
                    detailScrollView.setBackgroundResource(R.drawable.transparent);
                }

            }
        });
        detailScrollView.setNextFocusRightId(R.id.detail_playBtnGroup);
        // 播放按钮group
        mPlayBtnGroup = (FocusLinearLayout) headView.findViewById(R.id.detail_playBtnGroup);
        mPlayBtnGroup.setVisibility(View.GONE);
        mPlayBtnGroup.setOnChildViewSelectedListener(new OnChildViewSelectedListener() {

            @Override
            public void OnChildViewSelected(View view, boolean selected) {
                if (view == null) return;//单点支付完成后会设置为GONE
                view.setSelected(selected);
                if (view.getId() == mBtnPaySingle.getId() && mPlayBtnGroup.hasFocus() && selected == true) {
                    mPrice.setTextColor(getResources().getColor(R.color.yellow));
                } else {
                    mPrice.setTextColor(getResources().getColor(R.color.white));
                }
            }
        });
        mPlayBtnGroup.setNextFocusRightId(R.id.detail_ad);
        mPlayBtnGroup.setOnFocusChangeListener(mIndicatorChange);
        mPlayBtnGroup.setFocusScale(1.2f, 1.2f);

        mBtnPaySingle = headView.findViewById(R.id.detail_pay_single); // 单点购买
        mBtnMonth = headView.findViewById(R.id.detail_pay); // 飞狐vip
        mBtnFavorite = headView.findViewById(R.id.detail_favorite); // 收藏
        mBtnUserCenter = headView.findViewById(R.id.detail_usercenter);// VIP随心看
        mBtnSerial = headView.findViewById(R.id.detail_serial);//选集
        mBtnPaySingle.setOnClickListener(onBtnListener);
        mBtnPaySingle.setOnTouchListener(touchListener);
        mBtnMonth.setOnClickListener(onBtnListener);
        mBtnMonth.setOnTouchListener(touchListener);
        mBtnFavorite.setOnClickListener(onBtnListener);
        mBtnFavorite.setOnTouchListener(touchListener);
        mBtnUserCenter.setOnClickListener(onBtnListener);
        mBtnUserCenter.setOnTouchListener(touchListener);
        mBtnSerial.setOnClickListener(onBtnListener);
        mBtnSerial.setOnTouchListener(touchListener);

        //广告
        ViewGroup adParent = (ViewGroup) headView.findViewById(R.id.detail_ad_parent);
        adParent.setOnFocusChangeListener(mIndicatorChange);
        //推荐位
        mRecommendGridView = (FocusRecyclerView) findViewById(R.id.detail_recommendRrid);
        mRecommendGridView.setOnFocusChangeListener(mIndicatorChange);
        mRecommendGridView.setItemViewFocusSearchListener(new FocusRecyclerView.ItemViewFocusSearchListener() {
            @Override
            public boolean onItemViewFocusSearch(FocusRecyclerView parent, View itemView, int itemCount, int position, KeyEvent event) {
                mRecommendGridView.postInvalidate();
                return false;
            }
        });

        // 推荐位adapter init
        mAdapter = new DetailRecommendAdapter(mRecommendGridView, this);
        mRecommendGridView.setExtraMove(0.9); // 修改移动距离
        mRecommendGridView.setAdapter(mAdapter);
        mRecommendGridView.setNextFocusDownId(mRecommendGridView.getId());
        mRecommendGridView.setClipChildren(true);
        mRecommendGridView.setClipToPadding(false);
        final GridLayoutManager gridLayoutManager = new GridLayoutManager(ActivityDetail.this, 2);
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup(){

            @Override
            public int getSpanSize(int position) {
                return  mAdapter.getItemViewType(position) == TYPE_HEADER
                        ? gridLayoutManager.getSpanCount() : 1;
            }
        });
        gridLayoutManager.setOrientation(GridLayoutManager.HORIZONTAL);
        mAdapter.setHeaderView(headView);
        View footerView = LayoutInflater.from(this).inflate(R.layout.activity_detail_blankfooterview, null);
        if (footerView != null) {
            mAdapter.setFooterView(footerView);
        }
        mRecommendGridView.setLayoutManager(gridLayoutManager);
        mRecommendGridView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.left = getResources().getDimensionPixelSize(cn.com.wasu.main.R.dimen.d_7dp);
                outRect.top = getResources().getDimensionPixelSize(cn.com.wasu.main.R.dimen.d_7dp);
                outRect.right = getResources().getDimensionPixelSize(cn.com.wasu.main.R.dimen.d_7dp);
                outRect.bottom = getResources().getDimensionPixelSize(cn.com.wasu.main.R.dimen.d_7dp);

            }
        });
    }

    private void initIndicator() {
        mIndicatorLayout = (DetailIndicatorLinearlayout) findViewById(R.id.detail_indicator);
        TextView textView;
        textView = (TextView) LayoutInflater.from(this).inflate(R.layout.layout_detail_indicator_text, null);
        textView.setText("详情");
        mIndicatorLayout.addView(textView);
        textView = (TextView) LayoutInflater.from(this).inflate(R.layout.layout_detail_indicator_text, null);
        textView.setText("推荐");
        mIndicatorLayout.addView(textView);
        mIndicatorLayout.setIndicatorFocus(0);
    }

    @Override
    public void updateFavoriteUi(boolean hasFavorite) {
        if (hasFavorite == true) {
            mBtnFavorite.setBackgroundResource(R.drawable.selector_detail_favorited);
        } else {
            mBtnFavorite.setBackgroundResource(R.drawable.selector_detail_favorite);
        }
    }

    private OnTouchListener touchListener = new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                return v.performClick();
            }
            return false;
        }
    };

    private void fillDetailView() {
        /**资产信息**/
        mResourceTitle.setData(mAsset);
        //导演
        if (String.format(getString(R.string.detail_director), mAsset.getDirector()).trim().equals("")) {
            mDirectorTextView.setText("导演：无");
        } else {
            mDirectorTextView.setText(mAsset.getDirector());
        }
        //主演
        if (String.format(getString(R.string.detail_star), mAsset.getActor()).trim().equals("")) {
            mActorTextView.setText("主演：无");
        } else {
            mActorTextView.setText(mAsset.getActor());
        }
        //介绍
        if (mAsset.getDescription().trim().equals("")) {
            mDescriptTextView.setText("无节目介绍");
        } else {
            mDescriptTextView.setText(mAsset.getDescription());
        }
        //播控按钮
        if (mAsset.getPrice() == 0) {//是否显示购买播放
            mBtnMonth.setVisibility(View.GONE);
        } else {
            mBtnMonth.setVisibility(View.VISIBLE);
        }
        if (BuildType.HIDE_USERCENTER) {//是否显示用户中心
            mBtnUserCenter.setVisibility(View.GONE);
        } else {
            mBtnUserCenter.setVisibility(View.VISIBLE);
        }
        if (mAsset.getAssetType() == DemandProgram.SHOWTYPE_TV_SERIES) {//是否显示选集
            mBtnSerial.setVisibility(View.VISIBLE);
        } else {
            mBtnSerial.setVisibility(View.GONE);
        }
        mPlayBtnGroup.setVisibility(View.VISIBLE);
    }

    public void play() {
        WLog.i(TAG, "play()");
        if (mVideoView != null) {
            if (mVideoView.isPlaying()) {
                mVideoView.stopPlayback();
            }
            PlayerParams params = new PlayerParams();
            if(isFullPlay && series >= 0) {
                mAsset.setCurPlayIndex(series);
            }
            if(isFullPlay) {
                mVideoView.setPosition((int) currentPosition * 1000);
            }
            params.setAssetInfo(mAsset);
            params.setDomain(BuildType.HTTP_DOMAIN);
            mVideoView.play(params);
            //Add By Frewen.Wong 渡鸦科技全屏播放
            if (isFullPlay || BuildConfig.FLAVOR.equalsIgnoreCase(ChannelFlavor.DUYA_TECH)) {
                if (!mVideoView.isFullScreen()) {
                    mVideoView.toggleFullScreen();
                }
            }
        }
    }

    private void doPlayWithSeriesChoice() {
        if (mAsset.getDetailSeriesSet() == null || mAsset.getDetailSeriesSet().getSize() == 0) {
            Toast.makeText(this, "没有可以播放的剧集", Toast.LENGTH_SHORT).show();
            detailLogic.loadSeriesSet(mAsset.getOnlineEpisodesUrl());
            return;
        }
        int curEpisode = mAsset.getCurPlayIndex();
        if (curEpisode < 0) {
            return;
        }
        WLog.i(TAG, "curEpisode=" + curEpisode);
        final Dialog dialog = new Dialog(this, R.style.seriesdialog);
        DetailSeriesView popuview = new DetailSeriesView(this, mAsset.getDetailSeriesSet().getSize(), mAsset, curEpisode, new onSeriesListener() {

            @Override
            public void onChoice(int series) {
                WLog.i(TAG, "onChoice series=" + series);
                dialog.dismiss();
                if (series == mAsset.getCurPlayIndex()) {//如果是点击当前播放的集数，则直接放大
                    if (mVideoView != null) {
                        mVideoView.toggleFullScreen();
                    }
                } else {//如果不是当前小窗口播放的视频则设置当前的集数，并重新播放
                    if (mVideoView != null) {
                        mVideoView.stopPlayback();
                    }
                    mAsset.setCurPlayIndex(series);
                    play();
                    mPlayerGroup.requestFocus();
                }
            }
        });
        dialog.setContentView(popuview);
        Window dialogWindow = dialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.BOTTOM);

        if (dm == null) {
            dm = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(dm);
        }
        lp.width = LayoutParams.MATCH_PARENT;
        lp.height = (int) getResources().getDimension(R.dimen.d_389dp);
        dialogWindow.setAttributes(lp);
        popuview.setDialog(dialog);
        dialog.show();
    }

    private OnClickListener onBtnListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            int id = v.getId();
            if (id == R.id.detail_pay) {// 包月购买
                WasuStatistics.getInstance().detailClick(mAsset.getTitle(), mAsset.getId(), mAsset.getPpv(), "包月_1_1");
                dealVipPay();
                //Add By Frewen.Wong 解决从乐视盒子上从个人中心页面回来，焦点丢失的Bug。
                if (!BuildConfig.FLAVOR.equalsIgnoreCase(ChannelFlavor.LETV_MARKET)) {
                    mResetFocus = true;
                }
            } else if (id == R.id.detail_pay_single) {// 单价购买

                if (!BuildConfig.FLAVOR.equalsIgnoreCase(ChannelFlavor.LETV_MARKET)) {
                    mResetFocus = true;
                }
                WasuStatistics.getInstance().detailClick(mAsset.getTitle(), mAsset.getId(), mAsset.getPpv(), "单点_1_1");
                if (mVideoView != null) {
                    mVideoView.showPayDialog(true, mAsset.getTitle(), mAsset.getId(), mAsset.getPriceInfo().mPrice, new PayStatusListener() {
                        @Override
                        public void onPay(int arg0, int arg1) {
                            if (arg0 == 0) {
                                detailLogic.queryPrice(false);
                                //支付成功后播放器获得焦点
                                mPlayerGroup.requestFocus();
                            } else {
                                Toast.makeText(ActivityDetail.this, "支付失败", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                }
            } else if (id == R.id.detail_favorite) {
                WasuStatistics.getInstance().detailClick(mAsset.getTitle(), mAsset.getId(), mAsset.getPpv(), "收藏_1_1");
                detailLogic.doFavorite();
            } else if (id == R.id.detail_usercenter) {

                if (!BuildConfig.FLAVOR.equalsIgnoreCase(ChannelFlavor.LETV_MARKET)) {
                    mResetFocus = true;
                }
                WasuStatistics.getInstance().detailClick(mAsset.getTitle(), mAsset.getId(), mAsset.getPpv(), "营业厅_1_1");
                openUserCenter(Common.UserCenterUrl);
            } else if (id == R.id.detail_serial) {
                WasuStatistics.getInstance().detailClick(mAsset.getTitle(), mAsset.getId(), mAsset.getPpv(), "选集_1_1");
                if (mAsset.getAssetType() == DemandProgram.SHOWTYPE_TV_SERIES) {
                    doPlayWithSeriesChoice();
                }
            }
        }
    };

    private void addRecommendClick(RecommendItem recommend, DemandRecommand demandRecommand) {
        int index = 0;
        int len = demandRecommand.getRecommendItems().size();
        if (len > RECOMMEND_MAXNUM)
            len = RECOMMEND_MAXNUM;
        String[] ids = new String[len];
        String[] traceids = new String[len];
        for (int i = 0; i < len; i++) {
            ids[i] = demandRecommand.getRecommendItems().get(i).getId();
            if (ids[i] == recommend.getId()) {
                index = i + 1;
            }
            traceids[i] = demandRecommand.getRecommendItems().get(i)
                    .getTraceid();
        }
        if (TextUtils.isEmpty(recommend.getTraceid())) {// 非大数据推荐的推荐位
            /**
             * 非推荐位项目点击
             * 首页+详情页 非推荐
             * */
            WasuStatistics.getInstance().click(recommend.getId());
        } else {
            /**
             * 推荐项目点击
             * 首页点击+详情页大数据推荐点击
             * */
            WasuStatistics.getInstance().click(mAsset.getId());
        }
        AppUtil.playEnter = "关联推荐_" + index;
    }

    /**
     * 搜狐资产是否是用户登录和支付
     **/
    protected void dealVipPay() {
        String userKey = AuthSDK.getInstance().getValue(AuthSDK.KEY_USERKEY);
        if (TextUtils.isEmpty(userKey)) {//用户未登录，引导登录
            DialogLogin dialogLogin = new WasuCompFactory().createUniLogin(this, BuildType.loginurl);
            dialogLogin.setLoginStatusListener(new DialogLogin.LoginStatusListener() {
                @Override
                public void onLogStatus(boolean b) {
                    if (b) {//登录成功，二次询价,需要引导用户订包
                        detailLogic.queryPrice(true);
                        mPlayerGroup.requestFocus();
                    } else {//登录失败
                        Toast.makeText(ActivityDetail.this, "用户登录失败", Toast.LENGTH_SHORT).show();
                    }
                }
            });
            mVideoView.closeBKBMDialog();
            dialogLogin.show();
        } else {//已经登录，弹出支付
            showMonthPayDialog();
        }
    }

    /**
     * @param
     * @return void
     * @throws
     * @Title: initVideoView
     * @Description: 用于加载不同的视频流
     */
    private void initVideoView() {
        // sohu资产和华数资产启用不同的播放器
        if (mAsset != null && mAsset.getAssetFrom() == 91/** sohu资产 **/) {
            mVideoView.switchPlayer(ExtPlayer.Sohu);
        } else {
            mVideoView.switchPlayer(ExtPlayer.Default);
        }

        mVideoView.setExcludeOption(MediaController.DISPLAY_PROMPT_EXIT_AD);
        mDetailOberserver = new DetailPlayerOberserver(this, mAsset, detailLogic, mVideoView);
        mVideoView.addObserver(mDetailOberserver);
        mVideoView.addOnScreenChangedListener(new OnScreenChangedListener() {

            @Override
            public void onScreenChanged(boolean isFullScreen) {
                if (isFullScreen == false && !mPlayBtnGroup.hasFocus()) {// 适配其他盒子中播放器无法获得焦点的个别情况
                    mPlayerGroup.requestFocus();
                }
            }
        });
    }

    @Override
    public boolean uiIsFinishing() {
        return isFinishing();
    }


    @Override
    public void fatalError(String msg) {
        showErrorExitDlg(msg);
    }


    public void notifyPlayerPriceChanged(int ret, String extra, Object retData) {
        if (mVideoView != null) {
            mVideoView.priceChanged(ret, extra, retData);
        }
    }

    @Override
    public String getEnter() {
        return enter;
    }

    @Override
    public void toastMsg(String msg) {
        postMessage(msg);
    }

    /**
     * 显示免费的UI
     **/
    private void showFreeUI() {
        if (mBtnPaySingle.getVisibility() == View.VISIBLE) {
            mBtnPaySingle.setVisibility(View.GONE);
            fixFocusLose();
        }
        if (mBtnMonth.getVisibility() == View.VISIBLE) {
            mBtnMonth.setVisibility(View.GONE);
            fixFocusLose();
        }
        mBtnUserCenter.setVisibility(View.VISIBLE);
        mCoupon.setVisibility(View.GONE);//隐藏观影卷
    }

    /**
     * 处理隐藏了view之后，焦点丢失的问题
     */
    private void fixFocusLose() {
        if (mPlayBtnGroup.hasFocus()) {
            if (mPlayBtnGroup.getFocusedChild() != null) {
                mPlayBtnGroup.getFocusedChild().requestFocus();
            } else {
                mPlayBtnGroup.getChildAt(0).requestFocus();
            }
        } else {
            mPlayBtnGroup.setSelectedViewIndex(-1);
        }
    }

    /**
     * 显示单点情况的UI
     **/
    private void showSinglePayUI() {
        mBtnPaySingle.setVisibility(View.VISIBLE);
        mBtnMonth.setVisibility(View.GONE);
        mCoupon.setVisibility(View.VISIBLE);
        mBtnUserCenter.setVisibility(View.VISIBLE);
        mBtnUserCenter.setBackgroundResource(R.drawable.selector_detail_usercenter_sxk);
        mPrice.setText(mAsset.getPriceInfo().mPrice + "元");
    }

    /**
     * 显示包月情况的UI
     **/
    private void showMonthPayUI() {
        mBtnMonth.setVisibility(View.VISIBLE);
        mBtnPaySingle.setVisibility(View.GONE);
        //搜狐资产，中途退出营业厅，询价需要隐藏播放器
        if (mAsset != null && mAsset.getAssetFrom() == 91) {
            mBtnUserCenter.setVisibility(View.GONE);//搜狐资产收费时隐藏用户中心按钮
        }
        fixFocusLose();
    }

    /**
     * 包月支付dialog
     **/
    protected void showMonthPayDialog() {
        DialogPlanBuy dialogPlanBuy = new DialogPlanBuy(ActivityDetail.this, Common.OtherOrderUrl, mAsset.getAssetFromLabel(), new DialogPlanBuy.PayStatusListener() {
            @Override
            public void onPay(int status, int code) {
                if (status == 0) {
                    //支付成功后播放器获得焦点
                    mPlayerGroup.requestFocus();
                    detailLogic.queryPrice(false);//重新刷UI
                    play();
                } else {
                    Toast.makeText(ActivityDetail.this, "支付失败", Toast.LENGTH_SHORT).show();
                }
            }
        });
        mVideoView.closeBKBMDialog();
        dialogPlanBuy.show();
    }

    private long preTimeMills;

    public void openUserCenter(String pageUrl) {
        try {
            long currTimeMills = System.currentTimeMillis();
            if (preTimeMills == 0 || currTimeMills - preTimeMills > 1000) {
                preTimeMills = currTimeMills;
                Intent intent = new Intent();
                String jsonUrl = pageUrl + "vcType=" + Common.vcType
                        + "&deviceType=" + Common.deviceType;
                IntentMap.startIntent(this, intent, "Wasu_UserCenter", jsonUrl,
                        null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 手工发送playend统计（用于超出3层后关闭activity的统计）
     * */
    public void SendPlayEndStatistics(){
        if (mVideoView != null) {
            mDetailOberserver.SendPlayEnd(mVideoView.getCurrentPosition(), mVideoView.getDuration());
            WLog.e("Alistatistic","发送关闭后的统计");
        }
    }


    @Override
    public void loadAssetDetailSuccess(DemandProgram asset) {
        hideLoading();
        this.mAsset = asset;
        fillDetailView();
        initVideoView();
        play();
        detailLogic.queryPrice(false);
        detailLogic.loadRecommend(asset.getRecommendUrl()/*+"&appId="+Common.appKey+"&userId="+userid+"&bizCode=apkdata&scenarioCode=DetailPG"*/);
        detailLogic.loadAdData();
    }

    @Override
    public void loadAssetDetailFailed(int errno, String msg) {
        hideLoading();
        showErrorExitDlg(ErrorMap.mapError(ActivityDetail.this,
                errno, msg));
    }

    @Override
    public void queryPriceSuccess(PriceInfo priceInfo, boolean guidtobuy) {
        //价格有变动，需要刷新UI，开始默认所有资产都免费
        if (priceInfo.mPrice != mAsset.getPriceInfo().mPrice || priceInfo.mOriginalPrice != mAsset.getPriceInfo().mOriginalPrice) {
            mAsset.setPriceInfo(priceInfo);
            mAsset.setPrice(priceInfo.getPrice()); // 设置价格
            //免费
            if (mAsset.isFree()) {
                showFreeUI();
                return;
            }
            //单点
            if (mAsset.isSinglePay()) {
                showSinglePayUI();
                return;
            }
            //包月
            if (mAsset.isMonthPay()) {
                showMonthPayUI();
                return;
            }
        }
        //会员引导续订
        if (AuthSDK.getInstance().getValue(IAuthInterface.KEY_USERKEY).isEmpty()) {
            mBtnUserCenter.setBackgroundResource(R.drawable.selector_detail_usercenter_sxk);
        } else {
            if (priceInfo.getRestTime() > 0) {
                /**单点付费显示免费的UI**/
                if (priceInfo.mOriginalPrice>0&&priceInfo.mOriginalPrice!=99999&&priceInfo.mPrice<=0 && "0".equals(UserUtils.checkIsVip())){
                    mBtnUserCenter.setBackgroundResource(R.drawable.selector_detail_usercenter_sxk);
                }else {
                    mBtnUserCenter.setBackgroundResource(R.drawable.selector_detail_usercenter_xdyyh);
                }
            } else {
                mBtnUserCenter.setBackgroundResource(R.drawable.selector_detail_usercenter_sxk);
            }
        }
        if (guidtobuy == true) {
            //引导用户订购
            showMonthPayDialog();
        }
    }

    @Override
    public void queryPriceFailed(int ret, String extra) {
        if (mAsset != null && mAsset.getIsFree() == 0) {// 不是免费的给用户提示，退出页面
            mBtnMonth.setVisibility(View.VISIBLE);
            showErrorExitDlg("询价失败");
            return;
        } else {
            showFreeUI();
        }
    }

    @Override
    public void loadRecommendSuccess(final DemandRecommand recommend) {
        mAdapter.setOnItemListener(new BaseFocusRecyclerViewAdapter.OnItemListener() {
            @Override
            public void onItemClick(int position) {
                position -=1; // 自减防止增加头部导致的position错误
                mResetFocus = false; // 不重置焦点
                if (position <= 4) {
                    WasuStatistics.getInstance().detailClick(mAsset.getTitle(), mAsset.getId(), mAsset.getPpv(), "关联推荐_1_" + (position + 1));
                } else {
                    WasuStatistics.getInstance().detailClick(mAsset.getTitle(), mAsset.getId(), mAsset.getPpv(), "关联推荐_2_" + (position - 4));
                }
                RecommendItem recommenditem = recommend.getRecommendItems().get(position);
                //推荐位统计
                addRecommendClick(recommenditem, recommend);
                Intent intent = new Intent();
                IntentMap.startIntent(ActivityDetail.this, intent, recommenditem.getLayout(), recommenditem.getJsonUrl(), null);
            }

            @Override
            public void onItemLongClick(int position) {
            }

            @Override
            public void onItemFocusChange(View itemView, int position, boolean hasFocus) {
                if (hasFocus && (position == 2 || position ==1)){
                    if (mRecommendGridView.getX() > 0) {
                        mRecommendGridView.scrollToPosition(0);
                    }
                }
                mIndicatorLayout.setIndicatorFocus(1);
                mScroll = true;
            }
        });
        List<DetailRecommendAdapter.listEntey> list = new ArrayList<>();
        int size = recommend.getRecommendItems().size() <10 ? recommend.getRecommendItems().size() : 10;
        for (int i = 0; i<size; i++){
            RecommendItem r = recommend.getRecommendItems().get(i);
            if (r.getPicUrl() != null && r.getTitle() != null){
                list.add(new DetailRecommendAdapter.listEntey(r.getPicUrl(), r.getTitle()));
            }
        }

        mAdapter.setData(list);
        mAdapter.notifyDataSetChanged();

        adGroup = (ViewGroup) headView.findViewById(R.id.detail_ad);
        adGroup.setNextFocusRightId(R.id.detail_recommendRrid);
    }

    @Override
    public void loadRecommendFailed(int ret, String extra) {
        adGroup = (ViewGroup) headView.findViewById(R.id.detail_ad);
        adGroup.setNextFocusRightId(R.id.detail_recommendRrid);
    }

    @Override
    public void loadAdSuccess(final AdView view) {
        mAdview = view;
        if (adGroup == null){
           mHandler = new Handler();

            if (mRunnable == null) {
                mRunnable = new Runnable() {
                    @Override
                    public void run() {
                        loadAdSuccess(view);
                    }
                };
            }
            mHandler.postDelayed(mRunnable, 1000);
            return;
        }
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        adGroup.addView(view, params);
    }

    @Override
    public void loadAdFailed() {
        ImageView view = new ImageView(this);
        view.setImageResource(R.drawable.default_wasu_bg);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        adGroup.addView(view, params);
    }

    @Override
    public void adFreeQuerySuccess(int free) {

    }

    @Override
    public void adFreeQueryFailed(int ret, String extra) {

    }

    @Override
    protected void onPause() {
        super.onPause();
        // pageViewEnd
        WasuStatistics.getInstance().pageViewEnd(PageViewType, mAsset!=null?mAsset.getPpv():"", mAsset!=null?mAsset.getTitle():"");

        if (mVideoView != null){
            mVideoView.StopTimer();
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (DetailInstance.size() > 0 && mBackPress) {
            DetailInstance.remove(DetailInstance.size() - 1);
        }

        if (mVideoView != null) {
            mVideoView.stopPlayback();
            try {
                mVideoView.removeAllViews();
                mVideoView.finalize();
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
        mVideoView = null;
        if (detailLogic != null) {
            detailLogic.detachView();
            detailLogic = null;
        }
        if (adGroup != null) {
            adGroup.removeAllViews();
            adGroup = null;
        }

        if (mHandler != null && mRunnable != null){
            mHandler.removeCallbacks(mRunnable);
        }

        if (mPlayBtnGroup != null) {
            mPlayBtnGroup.removeAllViews();
            mPlayBtnGroup = null;
        }
        if (mIndicatorLayout != null) {
            mIndicatorLayout.removeAllViews();
            mIndicatorLayout.clear();
            mIndicatorLayout = null;
        }
        if (mResourceTitle != null) {
            mResourceTitle.removeAllViews();
            mResourceTitle = null;
        }

        if (mAdview != null){
            mAdview.destroyAd();
        }
        mAdview = null;
        mDirectorTextView = null;
        mActorTextView = null;
        mDescriptTextView = null;
        mPlayBtnGroup = null;
        mBtnMonth = null;
        mBtnFavorite = null;
        mBtnUserCenter = null;
        mBtnSerial = null;
        mRecommendGridView = null;
        dm = null;
    }

    /**
     *
     * @param outState
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
//        super.onSaveInstanceState(outState);
    }

    private String fullPlay(String value) {
        if(TextUtils.isEmpty(value)) {
            return "";
        }
        String layoutCode = "";
        String catId = "";
        String assetId = "";
        int Type = 0;

        try {
            JSONObject json = new JSONObject(value);
            Type = json.optInt("Type");
            catId = json.optString("Categoryid");
            assetId = json.optString("Id");
            series = json.optInt("Series");
            currentPosition = json.optLong("CurrentPosition");
            isFullPlay = json.optBoolean("IsFullPlay");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        switch (Type) {
            case 3:
                layoutCode = LayoutCodeMap.DETAIL_NEWS;
                break;
        }

        if (!TextUtils.isEmpty(catId)) {
            StringBuilder url = new StringBuilder(BuildType.HTTP_DOMAIN + "?s=" + BuildType.SITE_ID);
            url.append("&p=" + (TextUtils.isEmpty(assetId) ? "sntCat" : "sntAssetDetail"));
            url.append("&k=" + Common.URL_KEY);
            url.append("&v=" + Common.URL_V);
            url.append("&catId=" + catId);
            if (!TextUtils.isEmpty(assetId)) {
                url.append("&assetId=" + assetId);
            }

            Intent intent = new Intent();
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtra(IntentConstant.BACK_MAIN.value(), false);
            intent.putExtra(IntentConstant.LAST_PLAY_TIME.value(), currentPosition);
            intent.putExtra(IntentConstant.LAST_SERIES.value(), series);
            intent.putExtra(IntentConstant.Full_Play.value(), isFullPlay);

            if (!TextUtils.isEmpty(layoutCode)) {
                IntentMap.startIntent(this, intent, layoutCode, url.toString(), null);
                finish();
            }
            return url.toString();
        }
        return "";
    }
}
