package com.wasu.cs.ui;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
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.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.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.adapter.ChildrenDetailRecommendAdapter;
import com.wasu.cs.model.DemandProgram;
import com.wasu.cs.model.DemandRecommand;
import com.wasu.cs.model.DemandRecommand.RecommendItem;
import com.wasu.cs.module.ChildFavModule;
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.BitmapUtils;
import com.wasu.cs.widget.FocusGridLayoutManager;
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 java.util.ArrayList;
import java.util.List;

import basic.BuilderTypeManager.BuildType;
import cn.com.wasu.main.AppUtil;
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.R;

/**
 * @author jeepc
 */
public class ActivityChildrenDetail extends ActivityBase implements DetailView {
    private static final String TAG = "ActivityChildrenDetail";
    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;

    private DetailHorizontalScrollView mScrollView;
    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 ViewGroup adGroup;
    private FocusRecyclerView mRecommendGridView;// 推荐view
    public String traceid = "";
    DisplayMetrics dm;
    private boolean mScroll = false;
    private boolean mResetFocus; // 外部页面返回详情页时是否重置焦点到播放器
    private DetailPlayerOberserver mDetailOberserver; // 观察者实例

    /**
     * 弹出多个详情页容易导致oom，所以方式是最多只能弹出3层界面，后续记录ID，动态加载 上一个层级
     **/
    private static final int MAX_LAYER = 3;
    private static List<Activity> detailInstance = new ArrayList<Activity>();
    private DetailLogic detailLogic = new DetailLogic(this);
    /**
     * 增加返回键判断，区别用户按返回键和动态加载finish，避免重复处理
     */
    private boolean mBackPress = false;

    Bitmap bgBitmap = null;
    @Override
    protected void setDefaultBg(Drawable drawable) {
        bgBitmap = BitmapUtils.readBitMapByDecodeStream(this,R.drawable.children_detail_bg);
        getWindow().setBackgroundDrawable(new BitmapDrawable(getResources(),bgBitmap));
    }

    @Override
    protected void doCreate(Bundle savedInstanceState) {
        WLog.i(TAG,"doCreate()");

        if (detailInstance.size() >= MAX_LAYER) {
            ActivityChildrenDetail thisActivity = (ActivityChildrenDetail) detailInstance.get(0);
            thisActivity.SendPlayEndStatistics();
            thisActivity.finish();
            detailInstance.remove(0);
        }
        detailInstance.add(ActivityChildrenDetail.this);

        setContentView(R.layout.activity_children_detail_layout);
        enter = AppUtil.playEnter;
        Intent intent = getIntent();
        if (intent == null) {
            showErrorExitDlg("启动方式错误");
            return;
        }
        String programUrl = intent.getStringExtra(IntentConstant.DATAURI.value());
        traceid = intent.getStringExtra("traceid");
        initView();
        detailLogic.setTraceid(traceid);
        showLoading();
        detailLogic.loadAssetDetail(programUrl);
        //查询是否免广告
        detailLogic.adFreeQuery();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mVideoView != null) {
            mVideoView.onResume();
            if (mResetFocus) {
                mPlayerGroup.requestFocus();
                mResetFocus = false;
            }
            if (mDetailOberserver != null && mAsset != null) { // 从其他详情页返回时重置mark，便于发送关闭时的统计
                mDetailOberserver.MarkPlayInfo();
            }
            if(mVideoView.isFullScreen()){
                //跳到屏保焦点改变 需重设
                mVideoView.requestFocus();
            }
        }
        detailLogic.queryPrice(false);
    }

    @Override
    public void onBackPressed() {
        mBackPress = true;
        if (mVideoView != null) {
//            WasuStatistics.getInstance().use(mAsset.getId(), mVideoView.getCurrentPosition()+"");
            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:
                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();

        mScrollView = (DetailHorizontalScrollView) findViewById(R.id.detail_scroll);
        mScrollView.setSmoothScrollingEnabled(true);
        // 播放器和资产
        mPlayerGroup = (ViewGroup) findViewById(R.id.detail_player);
        mPlayerGroup.setOnFocusChangeListener(mIndicatorChange);
        mCoupon = (TextView) findViewById(R.id.detail_coupon);
        mPrice = (TextView) findViewById(R.id.detail_pay_price);
        mVideoView = new WasuPlayerView(this, BuildType.payTypeUrl,MediaController.DISPLAY_PROMPT_EXIT_AD|MediaController.DISPLAY_CANT_OFF_SCREEN);
        mVideoView.setAnchorView(mPlayerGroup, this);

        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 mScrollView = (ScrollView) findViewById(R.id.detail_description_scroll);
        mScrollView.setOnFocusChangeListener(new OnFocusChangeListener() {

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

            }
        });
        mScrollView.setNextFocusRightId(R.id.detail_playBtnGroup);
        // 播放按钮group
        mPlayBtnGroup = (FocusLinearLayout) 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);
            }
        });
        mPlayBtnGroup.setNextFocusRightId(R.id.detail_ad);
        mPlayBtnGroup.setOnFocusChangeListener(mIndicatorChange);

        mBtnPaySingle = findViewById(R.id.detail_pay_single); // 单点
        mBtnMonth = findViewById(R.id.detail_pay);
        mBtnFavorite = findViewById(R.id.detail_favorite);
        mBtnUserCenter = findViewById(R.id.detail_usercenter);
        mBtnSerial = 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) findViewById(R.id.detail_ad_parent);
        adGroup = (ViewGroup) findViewById(R.id.detail_ad);
        adGroup.setNextFocusRightId(R.id.detail_recommendRrid);
        adParent.setOnFocusChangeListener(mIndicatorChange);
        //推荐位
        mRecommendGridView = (FocusRecyclerView) findViewById(R.id.detail_recommendRrid);
        mRecommendGridView.setOnFocusChangeListener(mIndicatorChange);
    }

    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_children_detail_favorited);
        } else {
            mBtnFavorite.setBackgroundResource(R.drawable.selector_children_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);
    }

    private void play() {
        WLog.i(TAG, "play()");
        if (mVideoView != null) {
            if (mVideoView.isPlaying()) {
                mVideoView.stopPlayback();
            }
            PlayerParams params = new PlayerParams();
            params.setAssetInfo(mAsset);
            params.setDomain(BuildType.HTTP_DOMAIN);
            mVideoView.play(params);
        }
    }

    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();
                mResetFocus = true;
            } else if (id == R.id.detail_pay_single) {// 单价购买
                mResetFocus = true;
                WasuStatistics.getInstance().BigDataconsume(mAsset.getId(), mAsset.getPriceInfo().getPrice() + "");
                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(ActivityChildrenDetail.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();
                detailLogic.doWasuChildFavorite();
            } else if (id == R.id.detail_usercenter) {
                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(ActivityChildrenDetail.this, "用户登录失败", Toast.LENGTH_SHORT).show();
                    }
                }
            });
            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);
        }

        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);
        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(ActivityChildrenDetail.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(ActivityChildrenDetail.this, "支付失败", Toast.LENGTH_SHORT).show();
                }
            }
        });
        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;
        //更新收藏ui
        if(mAsset!=null){
            updateFavoriteUi(ChildFavModule.getInstance().hasFavorite(mAsset.getId()));
        }
        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(ActivityChildrenDetail.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);
            //免费
            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_children_detail_usercenter_sxk);
        } else {
            if (priceInfo.getRestTime() > 0) {
                mBtnUserCenter.setBackgroundResource(R.drawable.selector_children_detail_usercenter_xdyyh);
            } else {
                mBtnUserCenter.setBackgroundResource(R.drawable.selector_children_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) {

        ChildrenDetailRecommendAdapter mAdapter = new ChildrenDetailRecommendAdapter(mRecommendGridView, this);
        mRecommendGridView.setAdapter(mAdapter);
        mRecommendGridView.setNextFocusDownId(mRecommendGridView.getId());
        mRecommendGridView.setClipChildren(true);
        mRecommendGridView.setClipToPadding(false);
        mRecommendGridView.setFocusShadowDrawable(getResources().getDrawable(R.drawable.shape_focus_corner));
        FocusGridLayoutManager gridLayoutManager = new FocusGridLayoutManager(ActivityChildrenDetail.this, 5);
        gridLayoutManager.setOrientation(GridLayoutManager.VERTICAL);
        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(R.dimen.d_7dp);
                outRect.top = getResources().getDimensionPixelSize(R.dimen.d_7dp);
                outRect.right = getResources().getDimensionPixelSize(R.dimen.d_7dp);
                outRect.bottom = getResources().getDimensionPixelSize(R.dimen.d_7dp);

            }
        });

        mAdapter.setOnItemListener(new BaseFocusRecyclerViewAdapter.OnItemListener() {
            @Override
            public void onItemClick(int 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);
                if (recommenditem.getLayout().equals("Detail_Series") || recommenditem.getLayout().equals("Detail_Movie")) {
                    Intent intent = new Intent();
                    IntentMap.startIntent(ActivityChildrenDetail.this, intent,null, recommenditem.getJsonUrl(), ActivityChildrenDetail.class);
                } else {
                    Intent intent = new Intent();
                    IntentMap.startIntent(ActivityChildrenDetail.this, intent, recommenditem.getLayout(), recommenditem.getJsonUrl(), null);
                }
            }

            @Override
            public void onItemLongClick(int position) {

            }

            @Override
            public void onItemFocusChange(View itemView, int position, boolean hasFocus) {
                mIndicatorLayout.setIndicatorFocus(1);
                mScroll = true;
            }
        });
        List<ChildrenDetailRecommendAdapter.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 ChildrenDetailRecommendAdapter.listEntey(r.getPicUrl(), r.getTitle()));
            }
        }

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

//        mRecommendGridView.setAdapter(new RecommendAdapter(this, recommend));
//        mRecommendGridView.setFocusHightlightDrawable(R.drawable.tv_select_focus);
//        mRecommendGridView.postAnimation(50, null);
//        mRecommendGridView.setNextFocusDownId(mRecommendGridView.getId());
//        mRecommendGridView.setFocusShadowDrawable(R.drawable.focus_shadow);
//        mRecommendGridView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//            @Override
//            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//	            WLog.i(TAG, "position=" + position);
//
//                mIndicatorLayout.setIndicatorFocus(1);
//
//	            int maxScorllAmount = mScrollView.getMaxScrollAmount();
//                if (position == 2 || position == 3 || position == 7 || position == 8) {
//                    mScrollView.smoothScrollTo(maxScorllAmount, 0);
//	            }else if (mScroll && (position == 0 || position == 5)) {
//		            mScrollView.smoothScrollTo(-maxScorllAmount, 0);
//                }else if(position == 4 || position == 9){
//                    mScrollView.smoothScrollBy(maxScorllAmount, 0);
//                }
//
//                mScroll = true;
//            }
//
//            @Override
//            public void onNothingSelected(AdapterView<?> parent) {
//
//            }
//        });
//        mRecommendGridView.setOnItemClickListener(new OnItemClickListener() {
//
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                WLog.e(TAG, "onItemClick = " + position);
//                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 loadRecommendFailed(int ret, String extra) {

    }

    @Override
    public void loadAdSuccess(AdView view) {
        LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        adGroup.addView(view, params);
    }

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

    @Override
    public void adFreeQuerySuccess(int free) {

    }

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

    }

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

        if(detailInstance.size()<=0){
           BitmapUtils.recycleBitmap(bgBitmap);
        }

        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 (mPlayBtnGroup != null) {
            mPlayBtnGroup.removeAllViews();
            mPlayBtnGroup = null;
        }
        if (mIndicatorLayout != null) {
            mIndicatorLayout.removeAllViews();
            mIndicatorLayout.clear();
            mIndicatorLayout = null;
        }
        if (mResourceTitle != null) {
            mResourceTitle.removeAllViews();
            mResourceTitle = null;
        }
        mScrollView = null;

        mDirectorTextView = null;
        mActorTextView = null;
        mDescriptTextView = null;
        mPlayBtnGroup = null;
        mBtnMonth = null;
        mBtnFavorite = null;
        mBtnUserCenter = null;
        mBtnSerial = null;
        mRecommendGridView = null;
        dm = null;
    }
}
