package com.wasu.cs.widget.mediacontrol;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.util.AttributeSet;
import android.util.Property;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.wasu.authsdk.AuthListener;
import com.wasu.authsdk.AuthSDK;
import com.wasu.authsdk.entity.OrderPlanList;
import com.wasu.comp.userlogin.DialogLogin;
import com.wasu.comp.videoview.IMediaControl;
import com.wasu.comp.videoview.IMediaListener;
import com.wasu.cs.model.DemandPlayinfo;
import com.wasu.cs.model.DemandProgram;
import com.wasu.cs.model.IAssetList;
import com.wasu.cs.model.VipStateModel;
import com.wasu.cs.ui.ActivityPlayer;
import com.wasu.cs.utils.JsonUtil;
import com.wasu.cs.utils.UserUtils;
import com.wasu.cs.widget.mediacontrol.adapter.PromptExitAsset;
import com.wasu.cs.widget.videoview.PlayerParams;
import com.wasu.cs.widget.videoview.WasuPlayerView;
import com.wasu.cs.widget.videoview.WasuPlayerViewPayUtil;
import com.wasu.module.http.RequestParams;
import com.wasu.module.log.WLog;
import com.wasu.util.NetUtils;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import basic.BuilderTypeManager.BuildType;
import cn.com.wasu.main.Common;

/**
 * 播控
 */
public class MediaController extends FrameLayout implements IMediaListener, IMediaController {

    private String TAG = "MediaController";

    // /////////////////////////////////////////////////////////////////////////////////////////

    public static final String SHARED_PREFERENCES_NAME = "player";
    public static final String SHARED_PREFERENCES_KEY_CURRENT_RATE = "1";

    public static final int NONE_EXCLUDE_OPTION = -1;//默认没有排除项

    public static final int DISPLAY_LEFTSIDEPANEL_CONTROLLER = 1 << 0;
    public static final int DISPLAY_BITRATE_CONTROLLER = 1 << 1;
    public static final int DISPLAY_PROMPT_FOOTER = 1 << 2;
    public static final int DISPLAY_PROMPT_BUFFER = 1 << 3;
    public static final int DISPLAY_PROMPT_EXIT_AD = 1 << 4;
    public static final int DISPLAY_PROMPT_PAUSE_AD = 1 << 5;
    public static final int DISPLAY_SEEKBAR_CONTROLLER = 1 << 6;
    public static final int DISPLAY_VOLUME_CONTROLLER = 1 << 7;
    public static final int DISPLAY_VOLUME_MUTE_CONTROLLER = 1 << 8;
    public static final int DISPLAY_CANT_OFF_SCREEN = 1 << 9;//不支持暂停息屏功能

    private static int ID_BASE = 500000000;

    public static int generateID() {
        return ++ID_BASE;
    }

    /**
     * 控件持续显示时间
     */
    private static final int DURATION_SHOW = 5000;
    /**
     * 动画持续时间
     */
    private static final int DURATION_ANIM = 500;
    /**
     * 缓冲超时时间
     */
    private static final int DURATION_BUFFERING_TIMEOUT = 8000;

    private static AccelerateInterpolator sAccelerator = new AccelerateInterpolator();
    private static DecelerateInterpolator sDecelerator = new DecelerateInterpolator();

    public enum AnimationDirection {
        LEFT, RIGHT, UP, DOWN, CENTER
    }


    /**
     * 默认显示选项
     */
    public int displayOption = DISPLAY_LEFTSIDEPANEL_CONTROLLER |
            DISPLAY_BITRATE_CONTROLLER |
            DISPLAY_PROMPT_FOOTER |
            DISPLAY_PROMPT_BUFFER |
            DISPLAY_PROMPT_EXIT_AD |
            DISPLAY_PROMPT_PAUSE_AD |
            DISPLAY_SEEKBAR_CONTROLLER |
            DISPLAY_VOLUME_CONTROLLER |
            DISPLAY_VOLUME_MUTE_CONTROLLER |
            DISPLAY_CANT_OFF_SCREEN;

    public void setDisplayOption(int displayOption) {
        this.displayOption = displayOption;
    }

    public boolean hasOption(int option) {
        return (displayOption & option) == option;
    }

    public void setExcludeOption(int option) {
        this.displayOption = displayOption & ~option;
    }

    // /////////////////////////////////////////////////////////////////////////////////////////

    /**
     * 播放器和数据是否已经准备好
     */
    private boolean isReady;
    /**
     * 当前是否在播放广告
     */
    private boolean isAdPlaying;

    public boolean isReady() {
        return isReady;
    }

    public void setReady(boolean isReady) {
        this.isReady = isReady;
        if (promptBuffer != null) {
            promptBuffer.handleReady(isReady);
        }
    }

    public boolean isAdPlaying() {
        return isAdPlaying;
    }

    public void setAdPlaying(boolean isAdPlaying) {
        this.isAdPlaying = isAdPlaying;
    }

    public boolean isPauseing() {
        if ((hasOption(DISPLAY_CANT_OFF_SCREEN) && promptPauseAD == null) || (!hasOption(DISPLAY_CANT_OFF_SCREEN) && promptPauseADOffScreen == null)) {
            return false;
        }
        if (hasOption(DISPLAY_CANT_OFF_SCREEN)) {//不能息屏
            return promptPauseAD.getVisibility() == VISIBLE;
        } else {
            return promptPauseADOffScreen.getVisibility() == VISIBLE;
        }

    }

    /**
     * 播放器
     */
    private IMediaControl player;
    private WasuPlayerView wasuPlayer;

    public IMediaControl getPlayer() {
        return player;
    }

    public void setPlayer(IMediaControl player) {
        this.player = player;
    }

    public void setPlayer(IMediaControl player, WasuPlayerView wasuplayer) {
        this.player = player;
        wasuPlayer = wasuplayer;
    }

    /**
     * 资产信息
     */
    private DemandProgram assetInfo;
    /**
     * 获取资产地址
     */
    private String assetUrl;
    /**
     * 播放类型
     */
    private int playType;
    /**
     * 联播list
     */
    private IAssetList assetList;
    /**
     * 列表index
     */
    private int playIndex;
    /**
     * 接收外部传进来的traceid，如果为空，则是非大数据推荐的影片
     */
    private String traceid;

    public DemandProgram getAssetInfo() {
        return assetInfo;
    }

    public void setAssetInfo(DemandProgram assetInfo) {
        this.assetInfo = assetInfo;
		/* 设置assetinfo，用于设置缓冲时的按键提示语*/
        if (promptBuffer != null){
            promptBuffer.setAssetInfo(assetInfo);
        }
    }

    public String getAssetUrl() {
        return assetUrl;
    }

    public void setAssetUrl(String assetUrl) {
        this.assetUrl = assetUrl;
    }

    public int getPlayType() {
        return playType;
    }

    public void setPlayType(int playType) {
        this.playType = playType;
    }

    public IAssetList getAssetList() {
        return assetList;
    }

    public void setAssetList(IAssetList assetList) {
        this.assetList = assetList;
    }

    public int getPlayIndex() {
        return playIndex;
    }

    public void setPlayIndex(int playIndex) {
        this.playIndex = playIndex;
    }

    public String getTraceid() {
        return traceid;
    }

    public void setTraceid(String traceid) {
        this.traceid = traceid;
    }

    /**
     * 播放信息
     */
    private PlayerParams playerParams;

    public PlayerParams getPlayerParams() {
        return playerParams;
    }

    public void setPlayerParams(PlayerParams playerParams) {
        this.playerParams = playerParams;
    }

    /**
     * 隐藏当前view
     */
    private Runnable hideCurrentViewTask = new Runnable() {

        @Override
        public void run() {
            hideCurrentView();
        }

    };

    /**
     * 切换更低的码率task
     */
    private Runnable changeRateTask = new Runnable() {

        /**
         * 1.如果用户摁过菜单键，则提示用户自己选择较低码率
         * 2.否则自动切换到较低码率，并提示用户可以通过菜单键重新选择
         * 3.默认超时时间8秒
         */

        @Override
        public void run() {
            if (!NetUtils.isNetConnected(getContext())) {
                return;
            }

            if (!hasOption(MediaController.DISPLAY_BITRATE_CONTROLLER) || assetInfo == null) {
                return;
            }

            long fitRate = getContext().getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE).getLong(SHARED_PREFERENCES_KEY_CURRENT_RATE, WasuPlayerView.DEFAULT_PLAY_RATE);

            long lowFitRate = fitRate;
            long absRate = Long.MAX_VALUE;
            Set<Entry<Long, DemandPlayinfo>> entrySet = assetInfo.getPlayinfoList().entrySet();
            for (Entry<Long, DemandPlayinfo> entry : entrySet) {
                long tmpRate = entry.getKey();

                if (tmpRate >= fitRate) {
                    continue;
                }

                if (Math.abs(fitRate - tmpRate) <= absRate) {
                    lowFitRate = tmpRate;
                    absRate = Math.abs(fitRate - tmpRate);
                }
            }

            if (bitrateController.isShowed() && fitRate != lowFitRate) {
                Toast.makeText(getContext(), "当前网络较差,您可以通过菜单键选择较低码率", Toast.LENGTH_SHORT).show();
            } else {
                if (fitRate != lowFitRate) {
                    Toast.makeText(getContext(), "当前网络较差,已为您切换到较低码率,您可以通过菜单键重新选择", Toast.LENGTH_SHORT).show();

                    player.stopPlayback();
                    ((WasuPlayerView) player).ignoreHeadAd();

                    if (getContext() instanceof ActivityPlayer) {
                        Intent intent = new Intent(ActivityPlayer.ACTION);
                        intent.putExtra(ActivityPlayer.ASSET_INFO, assetInfo);
                        intent.putExtra(ActivityPlayer.ASSET_URL, assetUrl);
                        intent.putExtra(ActivityPlayer.PLAY_TYPE, playType);
                        intent.putExtra(ActivityPlayer.PLAY_INDEX, playIndex);
                        intent.putExtra(ActivityPlayer.ASSET_LIST, (Serializable) assetList);
                        intent.putExtra(ActivityPlayer.TRACEID, traceid);
                        intent.putExtra(ActivityPlayer.ASSET_BITRATE, lowFitRate);
                        getContext().startActivity(intent);
                    } else {
                        playerParams.setBitrate(lowFitRate);
                        ((WasuPlayerView) player).play(playerParams);
                    }
                } else {
                    if (!player.isPlaying()) {
                        Toast.makeText(getContext(), "当前网络较差,正在努力加载中,请耐心等待", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }

    };

    // /////////////////////////////////////////////////////////////////////////////////////////

    /**
     * 当前显示的子view
     */
    private IMediaControllerChildView currentView;

    private PromptHeader promptHeader;// 顶部提示
    private PromptFooter promptFooter;// 底部提示
    private VolumeController volumeController;// 音量控制
    private VolumeMuteController volumeMuteController;// 静音控制
    private SeekbarController seekbarController;// seek控制
    private LeftSidePanelController leftSidePanelController;// 左边控制
    private PromptBuffer promptBuffer;// 缓冲提示
    private PromptImageAD promptImageAD;// 贴片广告提示
    private PromptADCountdown promptADCountdown;// 广告倒计时
    private PromptPauseAD promptPauseAD;// 暂停提示
    private PromptPauseADOffScreen promptPauseADOffScreen;// 少儿暂停提示
    private PromptExitAsset promptExitAD; // 新退出提示
    private BitrateController bitrateController;// 码率控制

    public MediaController(Context context) {
        super(context);
        init(context);
    }

    /**
     * @param context
     * @param excludeOption 要排除的选项
     */
    public MediaController(Context context, int excludeOption) {
        super(context);
        if (excludeOption != NONE_EXCLUDE_OPTION) {
            setExcludeOption(excludeOption);
        }
        init(context);
    }

    public MediaController(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public MediaController(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    private void init(Context context) {
        setFocusable(false);
        setFocusableInTouchMode(false);

        promptHeader = new PromptHeader(context);
        promptFooter = new PromptFooter(context);
        volumeController = new VolumeController(context);
        volumeMuteController = new VolumeMuteController(context);
        seekbarController = new SeekbarController(context);
        leftSidePanelController = new LeftSidePanelController(context);
        promptBuffer = new PromptBuffer(context);
        promptImageAD = new PromptImageAD(context);
        promptADCountdown = new PromptADCountdown(context);
        if (hasOption(DISPLAY_CANT_OFF_SCREEN)) {//不能息屏
            promptPauseAD = new PromptPauseAD(context);
            promptPauseAD.setVisibility(View.GONE);
            addViewWithAnimInfo(promptPauseAD, Gravity.CENTER, AnimationDirection.CENTER);
        } else {
            promptPauseADOffScreen = new PromptPauseADOffScreen(context);
            promptPauseADOffScreen.setVisibility(View.GONE);
            addViewWithAnimInfo(promptPauseADOffScreen, Gravity.CENTER, AnimationDirection.CENTER);
        }
        if (hasOption(DISPLAY_PROMPT_EXIT_AD)) {//有退出推荐
            promptExitAD = new PromptExitAsset(context);
            promptExitAD.setVisibility(View.GONE);
            addViewWithAnimInfo(promptExitAD, Gravity.CENTER, AnimationDirection.CENTER);
        }
        bitrateController = new BitrateController(context);

        promptHeader.setVisibility(View.GONE);
        promptFooter.setVisibility(View.GONE);
        volumeController.setVisibility(View.GONE);
        volumeMuteController.setVisibility(View.GONE);
        seekbarController.setVisibility(View.GONE);
        leftSidePanelController.setVisibility(View.GONE);
        promptBuffer = new PromptBuffer(context);
        promptImageAD.setVisibility(View.GONE);
        promptADCountdown.setVisibility(View.GONE);
        bitrateController.setVisibility(View.GONE);


        addViewWithAnimInfo(promptHeader, Gravity.TOP, AnimationDirection.DOWN);
        addViewWithAnimInfo(promptFooter, Gravity.BOTTOM, AnimationDirection.UP);
        addViewWithAnimInfo(volumeController, Gravity.CENTER, AnimationDirection.CENTER);
        addViewWithAnimInfo(volumeMuteController, Gravity.CENTER, AnimationDirection.CENTER);
        addViewWithAnimInfo(seekbarController, Gravity.BOTTOM, AnimationDirection.UP);
        addViewWithAnimInfo(leftSidePanelController, Gravity.LEFT, AnimationDirection.RIGHT);
        addViewWithAnimInfo(promptBuffer, Gravity.CENTER, AnimationDirection.CENTER);
        addViewWithAnimInfo(bitrateController, Gravity.RIGHT, AnimationDirection.LEFT);
    }

    public void clear() {
        removeCallbacks(hideCurrentViewTask);
        removeCallbacks(changeRateTask);

        promptHeader.clear();
        promptFooter.clear();
        volumeController.clear();
        volumeMuteController.clear();
        seekbarController.clear();
        leftSidePanelController.clear();
        promptBuffer.clear();
        promptImageAD.clear();
        promptADCountdown.clear();
        if (promptPauseAD != null) {
            promptPauseAD.clear();
        }
        if (promptPauseADOffScreen != null) {
            promptPauseADOffScreen.clear();
        }
        if (promptExitAD != null) {
            promptExitAD.clear();
        }
        bitrateController.clear();

        isAdPlaying = false;
        isReady = false;
    }

    public void destory(){
        clear();
        if(promptBuffer != null){
            promptBuffer.destory();
        }
    }

    /**
     * 隐藏当前view
     */
    public void hideCurrentView() {
        if (currentView == null || !currentView.isAutoHide()) {
            return;
        }

        /*******************如果当前view及其relative view正在显示过程中,直接返回********************/
        AnimInfo info = (AnimInfo) ((View) currentView).getTag();
        if (info != null && info.animIn != null && info.animIn.isRunning()) {
            return;
        }

        List<IMediaControllerChildView> relativeViews = currentView.getRelativeViews();
        if (relativeViews != null) {
            for (IMediaControllerChildView v : relativeViews) {
                AnimInfo i = (AnimInfo) ((View) v).getTag();
                if (i != null && i.animIn != null && i.animIn.isRunning()) {
                    return;
                }
            }
        }
        /**************************************************************************************/

        if (relativeViews != null) {
            for (IMediaControllerChildView v : relativeViews) {
                setVisibility(false, true, v.getId());
            }

            currentView.getRelativeViews().clear();
        }

        setVisibility(false, currentView.getId());
    }

    public void handleFullScreen(boolean isFullScreen) {
        promptBuffer.handleFullScreen(isFullScreen);
        volumeController.handleFullScreen(isFullScreen);
        promptFooter.handleFullScreen(isFullScreen);
    }

    public boolean addViewWithAnimInfo(View view, int gravity, AnimationDirection direction) {
        return addViewWithAnimInfo(view, gravity, direction, -1);
    }

    public boolean addViewWithAnimInfo(View view, int gravity, AnimationDirection direction, int index) {
        if (NO_ID == view.getId()) {
            return false;
        }

        View existing = findViewById(view.getId());
        if (null != existing) {
            return false;
        }

        AnimInfo info = new AnimInfo();
        info.direction = direction;
        info.gravity = gravity;
        view.setTag(info);

        if ((gravity & Gravity.TOP) == Gravity.TOP || (gravity & Gravity.BOTTOM) == Gravity.BOTTOM) {
            LayoutParams lp = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, gravity);
            addView(view, index, lp);
        } else if ((gravity & Gravity.LEFT) == Gravity.LEFT || (gravity & Gravity.RIGHT) == Gravity.RIGHT) {
            LayoutParams lp = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, gravity);
            addView(view, index, lp);
        } else if ((gravity & Gravity.CENTER) == Gravity.CENTER) {
            LayoutParams lp = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, gravity);
            addView(view, index, lp);
        } else {
            LayoutParams lp = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, gravity);
            addView(view, index, lp);
        }

        prepareViewAnimation(view);

        return true;
    }

    public void prepareViewAnimation(View view) {
        AnimInfo info = (AnimInfo) view.getTag();

        if (null == info) {
            return;
        }

        if (null != info.animIn && null != info.animOut) {
            return;
        }

        switch (info.direction) {
            case CENTER:
                setupViewAnimationCenter(view);
                break;
            case LEFT:
                setupViewAnimationLeft(view);
                break;
            case RIGHT:
                setupViewAnimationRight(view);
                break;
            case DOWN:
                setupViewAnimationDown(view);
                break;
            case UP:
                setupViewAnimationUp(view);
                break;
        }
    }

    @SuppressLint("NewApi")
    private void setupViewAnimationCenter(View view) {
        AnimInfo info = (AnimInfo) view.getTag();

        if (null == info) {
            return;
        }

        view.setAlpha(0f);
        setViewAnimationIn(view, View.ALPHA, 1f, 0l);
        setViewAnimationOut(view, View.ALPHA, 0f, 0l);
    }

    @SuppressLint("NewApi")
    private void setupViewAnimationLeft(View view) {
        AnimInfo info = (AnimInfo) view.getTag();

        if (null == info) {
            return;
        }

        FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) view.getLayoutParams();

        if ((info.gravity & Gravity.LEFT) == Gravity.LEFT) {

            lp.leftMargin = getMeasuredWidth();
            updateViewLayout(view, lp);
            setViewAnimationIn(view, View.TRANSLATION_X, -getMeasuredWidth());
            setViewAnimationOut(view, View.TRANSLATION_X, 0);

        } else if ((info.gravity & Gravity.RIGHT) == Gravity.RIGHT) {

            lp.rightMargin = -view.getMeasuredWidth();
            updateViewLayout(view, lp);
            setViewAnimationIn(view, View.TRANSLATION_X, -view.getMeasuredWidth());
            setViewAnimationOut(view, View.TRANSLATION_X, 0);

        }
    }

    @SuppressLint("NewApi")
    private void setupViewAnimationRight(View view) {
        AnimInfo info = (AnimInfo) view.getTag();

        if (null == info) {
            return;
        }

        FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) view.getLayoutParams();

        if ((info.gravity & Gravity.LEFT) == Gravity.LEFT) {

            lp.leftMargin = -view.getMeasuredWidth();
            updateViewLayout(view, lp);
            setViewAnimationIn(view, View.TRANSLATION_X, view.getMeasuredWidth());
            setViewAnimationOut(view, View.TRANSLATION_X, 0);

        } else if ((info.gravity & Gravity.RIGHT) == Gravity.RIGHT) {

            lp.rightMargin = getMeasuredWidth();
            updateViewLayout(view, lp);
            setViewAnimationIn(view, View.TRANSLATION_X, getMeasuredWidth());
            setViewAnimationOut(view, View.TRANSLATION_X, 0);

        }
    }

    @SuppressLint("NewApi")
    private void setupViewAnimationUp(View view) {
        AnimInfo info = (AnimInfo) view.getTag();

        if (null == info) {
            return;
        }

        FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) view.getLayoutParams();

        if ((info.gravity & Gravity.TOP) == Gravity.TOP) {

            lp.topMargin = getMeasuredHeight();
            updateViewLayout(view, lp);
            setViewAnimationIn(view, View.TRANSLATION_Y, -getMeasuredHeight());
            setViewAnimationOut(view, View.TRANSLATION_Y, 0);

        } else if ((info.gravity & Gravity.BOTTOM) == Gravity.BOTTOM) {

            lp.bottomMargin = -view.getMeasuredHeight();
            updateViewLayout(view, lp);
            setViewAnimationIn(view, View.TRANSLATION_Y, -view.getMeasuredHeight());
            setViewAnimationOut(view, View.TRANSLATION_Y, 0);

        }

    }

    @SuppressLint("NewApi")
    private void setupViewAnimationDown(View view) {
        AnimInfo info = (AnimInfo) view.getTag();

        if (null == info) {
            return;
        }

        FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) view.getLayoutParams();

        if ((info.gravity & Gravity.TOP) == Gravity.TOP) {

            lp.topMargin = -view.getMeasuredHeight();
            updateViewLayout(view, lp);
            setViewAnimationIn(view, View.TRANSLATION_Y, view.getMeasuredHeight());
            setViewAnimationOut(view, View.TRANSLATION_Y, 0);

        } else if ((info.gravity & Gravity.BOTTOM) == Gravity.BOTTOM) {

            lp.bottomMargin = getMeasuredHeight();
            updateViewLayout(view, lp);
            setViewAnimationIn(view, View.TRANSLATION_Y, getMeasuredHeight());
            setViewAnimationOut(view, View.TRANSLATION_Y, 0);

        }
    }

    @SuppressLint("NewApi")
    private void setViewAnimationIn(final View view, Property<?, Float> property, float value) {
        setViewAnimationIn(view, property, value, DURATION_ANIM);
    }

    @SuppressLint("NewApi")
    private void setViewAnimationIn(final View view, Property<?, Float> property, float value, long duration) {
        AnimInfo info = (AnimInfo) view.getTag();

        if (null == info) {
            return;
        }

        PropertyValuesHolder pvh = PropertyValuesHolder.ofFloat(property, value);
        info.animIn = ObjectAnimator.ofPropertyValuesHolder(view, pvh);
        info.animIn.setDuration(duration);
        info.animIn.setInterpolator(sDecelerator);
        info.animIn.addListener(new AnimatorListenerAdapter() {

            @Override
            public void onAnimationStart(Animator animation) {
                view.setVisibility(View.VISIBLE);
                if (view instanceof IMediaControllerChildView) {
                    IMediaControllerChildView child = (IMediaControllerChildView) view;
                    child.onShow(MediaController.this);
                }
            }

        });

//        //seek bar先显示进度条
//        if (view instanceof IMediaControllerChildView && view instanceof SeekbarController) {
//            IMediaControllerChildView child = (IMediaControllerChildView) view;
//            child.onShow(MediaController.this);
//        }
    }

    @SuppressLint("NewApi")
    private void setViewAnimationOut(final View view, Property<?, Float> property, float value) {
        setViewAnimationOut(view, property, value, DURATION_ANIM);
    }

    @SuppressLint("NewApi")
    private void setViewAnimationOut(final View view, Property<?, Float> property, float value, long duration) {
        AnimInfo info = (AnimInfo) view.getTag();

        if (null == info) {
            return;
        }

        PropertyValuesHolder pvh = PropertyValuesHolder.ofFloat(property, value);
        info.animOut = ObjectAnimator.ofPropertyValuesHolder(view, pvh);
        info.animOut.setDuration(DURATION_ANIM);
        info.animOut.setInterpolator(sAccelerator);
        info.animOut.addListener(new AnimatorListenerAdapter() {

            @Override
            public void onAnimationStart(Animator animation) {
                if (view instanceof IMediaControllerChildView) {
                    IMediaControllerChildView child = (IMediaControllerChildView) view;
                    child.onHide(MediaController.this);
                }
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                view.setVisibility(View.GONE);
            }
        });
    }

    public void setVisibility(boolean show, int viewId) {
        setVisibility(show, false, viewId);
    }

    public void notifyVolumeChanged(int volume) {
        volumeMuteController.volumeChanged(volume);
    }

    /**
     * 显示或隐藏view
     *
     * @param show
     *            是否显示
     * @param isUnattached
     *            是否是独立的view，不与其他view互斥
     * @param viewId
     */
    public void setVisibility(boolean show, final boolean isUnattached, final int viewId) {
        if (show) {
            post(new Runnable() {
                @Override
                public void run() {
                    showView(viewId, isUnattached);
                }
            });
        } else {
            post(new Runnable() {
                @Override
                public void run() {
                    hideView(viewId, isUnattached);
                }
            });
        }
    }

    private void showView(int viewId, final boolean isUnattached) {
        final View view = findViewById(viewId);
        if (null != view) {
            AnimInfo info = (AnimInfo) view.getTag();
            if (null != info) {
                if (info.animIn.isRunning()) {
                    return;
                }

                if (info.animOut.isRunning()) {
                    if (!isUnattached) {
                        return;
                    }

                    info.animOut.end();
                }

                info.animIn.start();
            }

            player.addObserver((IMediaControllerChildView) view);
            if (!isUnattached) {
                currentView = (IMediaControllerChildView) view;
                removeCallbacks(hideCurrentViewTask);
                postDelayed(hideCurrentViewTask, DURATION_SHOW);
            }
        } else {
            WLog.e("AdPlayerView", "showView null");
        }
    }

    private void hideView(int viewId, final boolean isUnattached) {
        final View view = findViewById(viewId);
        if (null != view) {
            AnimInfo info = (AnimInfo) view.getTag();
            if (null != info) {
                if (info.animOut.isRunning()) {
                    WLog.e("AdPlayerView", "hideView anim out running");
                    return;
                }

                if (info.animIn.isRunning()) {
                    if (!isUnattached) {
                        WLog.e("AdPlayerView", "hideView anim in running");
                        return;
                    }

                    info.animIn.end();
                }
                info.animOut.start();
            }

            player.removeObserver((IMediaControllerChildView) view);
            if (!isUnattached) {
                currentView = null;
            }
        } else {
            WLog.e("AdPlayerView", "hideView null");
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        boolean ret = false;
        if (event.getAction() == KeyEvent.ACTION_DOWN) {

            switch (event.getKeyCode()) {
                case KeyEvent.KEYCODE_BACK:
                    ret = handleKeyBack(event);
                    break;
                case KeyEvent.KEYCODE_MENU:
                    handleKeyMenu(event);
                    ret = true;
                    break;
                case KeyEvent.KEYCODE_DPAD_UP:
                    handleKeyUp(event);
                    ret = true;
                    break;
                case KeyEvent.KEYCODE_DPAD_DOWN:
                    handleKeyDown(event);
                    ret = true;
                    break;
                case KeyEvent.KEYCODE_DPAD_LEFT:
                    handleKeyLeft(event);
                    ret = true;
                    break;
                case KeyEvent.KEYCODE_DPAD_RIGHT:
                    handleKeyRight(event);
                    ret = true;
                    break;
                case KeyEvent.KEYCODE_DPAD_CENTER:
                case KeyEvent.KEYCODE_ENTER:
                    handleKeyEnter(event);
                    ret = true;
                    break;
                case KeyEvent.KEYCODE_VOLUME_UP:
                    handleKeyVolumeUp(event);
                    ret = true;
                    break;
                case KeyEvent.KEYCODE_VOLUME_DOWN:
                    handleKeyVolumeDown(event);
                    ret = true;
                    break;
                case KeyEvent.KEYCODE_VOLUME_MUTE:
                    handleKeyVolumeMute(event);
                    ret = true;
                    break;
            }
        }
        return ret;
    }

    /**
     * 处理返回键
     *
     * @param event
     */
    private boolean handleKeyBack(KeyEvent event) {
        if (currentView != null) {
            if (!currentView.onShield(event)) {
                removeCallbacks(hideCurrentViewTask);
                hideCurrentView();
            } else {
                removeCallbacks(hideCurrentViewTask);
                postDelayed(hideCurrentViewTask, DURATION_SHOW);
            }
        } else {
            if (hasOption(DISPLAY_PROMPT_EXIT_AD)) {
                setVisibility(true, promptExitAD.getId());
            } else {
                return false;
            }
        }

        return true;
    }

    /**
     * 处理确定键
     *
     * @param event
     */
    private void handleKeyEnter(KeyEvent event) {
        if (isAdPlaying) { // 按确认键跳出华数包月
            if (currentView != null && currentView instanceof PromptExitAsset) { // 隐藏当前view
                if (currentView.onShield(event)) {
                    removeCallbacks(hideCurrentViewTask);
                    hideCurrentView();
                }
            }
            if (wasuPlayer.mDialogPay != null && wasuPlayer.mDialogPay.isShowing() || currentView instanceof PromptExitAsset) {
            } else {
                loadWasuPay();
            }
            return;
        }

        if (!isReady) {
            if (currentView != null && currentView instanceof PromptExitAsset) {
                if (currentView.onShield(event)) {
                    removeCallbacks(hideCurrentViewTask);
                    hideCurrentView();
                }
            }
            return;
        }

        if ((currentView != null && !currentView.onShield(event)) || (currentView == null)) {
            if (currentView instanceof PromptExitAsset
                    || (hasOption(DISPLAY_CANT_OFF_SCREEN) && currentView instanceof PromptPauseAD)
                    || (!hasOption(DISPLAY_CANT_OFF_SCREEN) && currentView instanceof PromptPauseADOffScreen)) {
                removeCallbacks(hideCurrentViewTask);
                hideCurrentView();
            } else {

                removeCallbacks(hideCurrentViewTask);

                if (!(currentView instanceof SeekbarController)) {
                    hideCurrentView();
                } else {
                    if (currentView.getRelativeViews() != null) {
                        currentView.getRelativeViews().clear();
                    }
                }

                if (hasOption(DISPLAY_PROMPT_PAUSE_AD)) {
                    if (hasOption(DISPLAY_CANT_OFF_SCREEN)) {
                        seekbarController.resetSeekIndicatorToPause();
                        promptPauseAD.setRelativeViews(seekbarController, promptHeader);

                        setVisibility(true, promptPauseAD.getId());
                    } else {
                        seekbarController.resetSeekIndicatorToPause();
                        promptPauseADOffScreen.setRelativeViews(seekbarController, promptHeader);
                        setVisibility(true, promptPauseADOffScreen.getId());
                    }
                    setVisibility(true, true, seekbarController.getId());
                    setVisibility(true, true, promptHeader.getId());
                    promptHeader.assetName.setSelected(true);
                }
            }


        } else {
            removeCallbacks(hideCurrentViewTask);
            postDelayed(hideCurrentViewTask, DURATION_SHOW);
        }
    }

    /**
     * 处理菜单键
     *
     * @param event
     */
    private void handleKeyMenu(KeyEvent event) {
        if (!isReady || isAdPlaying) {
            return;
        }

        if ((currentView != null && !currentView.onShield(event)) || (currentView == null)) {
            removeCallbacks(hideCurrentViewTask);
            hideCurrentView();

            if (hasOption(DISPLAY_BITRATE_CONTROLLER) && assetInfo != null) {
                setVisibility(true, bitrateController.getId());
            }
        } else {
            removeCallbacks(hideCurrentViewTask);
            postDelayed(hideCurrentViewTask, DURATION_SHOW);
        }
    }

    /**
     * 处理方向上键
     *
     * @param event
     */
    private void handleKeyUp(KeyEvent event) {
        if (!isReady || isAdPlaying) {

            // 将事件传递给PromptExitAsset
            if (currentView != null && currentView instanceof PromptExitAsset) {
                if (!currentView.onShield(event)) {
                    removeCallbacks(hideCurrentViewTask);
                    hideCurrentView();
                }
            }
            return;
        }

        if ((currentView != null && !currentView.onShield(event)) || (currentView == null)) {
            removeCallbacks(hideCurrentViewTask);
            if (currentView instanceof SeekbarController) {
                if (currentView.getRelativeViews() != null) {
                    currentView.getRelativeViews().clear();
                }
            }
            hideCurrentView();

            if (hasOption(DISPLAY_PROMPT_FOOTER)) {
                setVisibility(false, seekbarController.getId());
                setVisibility(false, true, promptHeader.getId());

                promptFooter.setRelativeViews(promptHeader);

                setVisibility(true, promptFooter.getId());
                setVisibility(true, true, promptHeader.getId());
            }
        } else {
            removeCallbacks(hideCurrentViewTask);
            postDelayed(hideCurrentViewTask, DURATION_SHOW);
        }
    }

    /**
     * 处理方向下键
     *
     * @param event
     */
    private void handleKeyDown(KeyEvent event) {
        if (!isReady || isAdPlaying) {

            // 将事件传递给PromptExitAsset
            if (currentView != null && currentView instanceof PromptExitAsset) {
                if (!currentView.onShield(event)) {
                    removeCallbacks(hideCurrentViewTask);
                    hideCurrentView();
                }
            }
            return;
        }


        if ((currentView != null && !currentView.onShield(event)) || (currentView == null)) {
            removeCallbacks(hideCurrentViewTask);
            if (currentView instanceof SeekbarController) {
                if (currentView.getRelativeViews() != null) {
                    currentView.getRelativeViews().clear();
                }
            }
            hideCurrentView();

            if (hasOption(DISPLAY_PROMPT_FOOTER)) {
                setVisibility(false, seekbarController.getId());
                setVisibility(false, true, promptHeader.getId());

                promptFooter.setRelativeViews(promptHeader);

                setVisibility(true, promptFooter.getId());
                setVisibility(true, true, promptHeader.getId());
            }
        } else {
            removeCallbacks(hideCurrentViewTask);
            postDelayed(hideCurrentViewTask, DURATION_SHOW);
        }
    }

    /**
     * 处理方向左键
     *
     * @param event
     */
    private void handleKeyLeft(KeyEvent event) {
        if (!isReady || isAdPlaying) {
            if (currentView != null && currentView instanceof PromptExitAsset) {
                if (!currentView.onShield(event)) {
                    removeCallbacks(hideCurrentViewTask);
                    hideCurrentView();
                }
            }
            return;
        }

        if ((currentView != null && !currentView.onShield(event)) || (currentView == null)) {
            removeCallbacks(hideCurrentViewTask);
            hideCurrentView();

            if (hasOption(DISPLAY_SEEKBAR_CONTROLLER)) {
                seekbarController.setRelativeViews(promptHeader);

                setVisibility(true, seekbarController.getId());
                setVisibility(true, true, promptHeader.getId());
            }
        } else {
            removeCallbacks(hideCurrentViewTask);
            postDelayed(hideCurrentViewTask, DURATION_SHOW);
        }
    }

    /**
     * 处理方向右键
     *
     * @param event
     */
    private void handleKeyRight(KeyEvent event) {
        if (!isReady || isAdPlaying) {
            if (currentView != null && currentView instanceof PromptExitAsset) {
                if (!currentView.onShield(event)) {
                    removeCallbacks(hideCurrentViewTask);
                    hideCurrentView();
                }
            }
            return;
        }

        if (isAdPlaying) {
            return;
        }

        if ((currentView != null && !currentView.onShield(event)) || (currentView == null)) {
            removeCallbacks(hideCurrentViewTask);
            hideCurrentView();

            if (hasOption(DISPLAY_SEEKBAR_CONTROLLER)) {
                seekbarController.setRelativeViews(promptHeader);

                setVisibility(true, seekbarController.getId());
                setVisibility(true, true, promptHeader.getId());
            }
        } else {
            removeCallbacks(hideCurrentViewTask);
            postDelayed(hideCurrentViewTask, DURATION_SHOW);
        }
    }

    /**
     * 处理音量加键
     *
     * @param event
     */
    private void handleKeyVolumeUp(KeyEvent event) {
        if ((currentView != null && !currentView.onShield(event)) || (currentView == null)) {
            removeCallbacks(hideCurrentViewTask);
            hideCurrentView();

            if (hasOption(DISPLAY_VOLUME_CONTROLLER)) {
                setVisibility(true, volumeController.getId());
            }
        } else {
            removeCallbacks(hideCurrentViewTask);
            postDelayed(hideCurrentViewTask, DURATION_SHOW);
        }
    }

    /**
     * 处理音量减键
     *
     * @param event
     */
    private void handleKeyVolumeDown(KeyEvent event) {
        if ((currentView != null && !currentView.onShield(event)) || (currentView == null)) {
            removeCallbacks(hideCurrentViewTask);
            hideCurrentView();

            if (hasOption(DISPLAY_VOLUME_CONTROLLER)) {
                setVisibility(true, volumeController.getId());
            }
        } else {
            removeCallbacks(hideCurrentViewTask);
            postDelayed(hideCurrentViewTask, DURATION_SHOW);
        }
    }

    /**
     * 处理静音键
     *
     * @param event
     */
    private void handleKeyVolumeMute(KeyEvent event) {
        if ((currentView != null && !currentView.onShield(event)) || (currentView == null)) {
            removeCallbacks(hideCurrentViewTask);
            hideCurrentView();

            if (hasOption(DISPLAY_VOLUME_MUTE_CONTROLLER)) {
                setVisibility(true, volumeMuteController.getId());
            }
        } else {
            removeCallbacks(hideCurrentViewTask);
            postDelayed(hideCurrentViewTask, DURATION_SHOW);
        }
    }

    public void showBufferView() {
        if (hasOption(DISPLAY_PROMPT_BUFFER)) {
            setVisibility(true, true, promptBuffer.getId());
        }
    }

    public void hideBufferView() {
        setVisibility(false, true, promptBuffer.getId());
    }

    @Override
    public void onAdStatusChanged(int arg0, int arg1) {
        switch (arg0) {
            case IMediaListener.AD_START:
                isAdPlaying = true;
                hideCurrentView();
                showBufferView();
                break;
            case IMediaListener.AD_PLAY:
                hideBufferView();
                break;
            case IMediaListener.AD_END:
                isAdPlaying = false;
                showBufferView();
                break;
        }
    }

    /**
     * 调起华数订包
     */
    private void loadWasuPay() {
        if (WasuPlayerViewPayUtil.getInstance().checkLogin()) {
            BookWasuPackage();
        } else {
            WasuPlayerViewPayUtil.getInstance().ShowLoginUI(getContext(), BuildType.loginurl, new DialogLogin.LoginStatusListener() {
                @Override
                public void onLogStatus(boolean b) {
                    if (b) { // 登陆成功
                        /**
                         * 登陆后刷新会员状态
                         * */
                        UserUtils.updateWasuVip(new RequestParams.RequestListener() {
                            @Override
                            public boolean onResponse(int i, String s, int i1, Object o) {
                                VipStateModel vipStateModel = JsonUtil.fromJson(s, VipStateModel.class);
                                if (vipStateModel != null) {
                                    for (VipStateModel.UpmInfoEntity.PlanAndCategoryBOsEntity data : vipStateModel.getUpmInfo().getPlanAndCategoryBOs()) {
                                        if (data != null && Common.WASU_PACKAGE_ID.equalsIgnoreCase(data.getObjectBizId())) {
                                            WLog.d("cm", data.getObjectName() + data.getObjectBizId() + data.getExpireTime() + data.getType());
                                            //说明订购的是华数VIP包
                                            AuthSDK.getInstance().saveValue("vipState", data.getAdFree() + "");
                                            AuthSDK.getInstance().saveValue("vipExpireTime", data.getExpireTime() + "");
                                        }
                                    }

                                    /**回调完成后再查询vip状态**/
                                    if (checkIsVip().equals("0")) { // 不是会员再让别人买包
                                        BookWasuPackage();
                                    } else { // vip用户对该影片重新询价
                                        if (wasuPlayer != null && wasuPlayer.mDetailLogic != null) {
                                            wasuPlayer.mDetailLogic.queryPrice(false);
                                        }
                                        /**广告时强制中断**/
                                        if (wasuPlayer != null && wasuPlayer.getVideoView() != null && isAdPlaying()) {
                                            wasuPlayer.getVideoView().skipCurrentAd();
                                        }
                                    }
                                } else {
                                    WLog.e("danxx", "getUserVipState return String--->null");
                                }
                                return false;
                            }
                        });


                    } else {
                        Toast.makeText(getContext(), "用户登录失败", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
    }

    private void BookWasuPackage() {
        final String planBizId = "40414189714680000002551";

        Map<String, Object> categoryBizId = new HashMap<>();
        categoryBizId.put("categoryBizId", "40814315811460000001283");
        AuthSDK.getInstance().queryOrderPlanByCategoryBizId(categoryBizId, new AuthListener() {
            @Override
            public void result(int i, String s, Object o) {
                if (i == 0) {
                    List<OrderPlanList.OrderPlan> list = ((OrderPlanList) o).getList();
                    if (list == null || list.size() <= 0) {
                        return;
                    }
                    double price = 0;
                    String name = "";
                    for (int j = 0; j < list.size(); j++) {
                        if (list.get(j).planBizId.equals(planBizId)) {//默认续订月包
                            price = list.get(j).price;
                            name = list.get(j).name;
                            break;
                        }
                    }
                    if (price == 0) return;
                    Map<String, Object> params = new HashMap<>();
                    params.put("planBizId", planBizId);
                    params.put("resourceName", name);
                    params.put("price", price);

                    DialogCommonPlanBuy paydialog = new DialogCommonPlanBuy(getContext(), BuildType.payTypeUrl, params, new DialogCommonPlanBuy.PayStatusListener() {
                        @Override
                        public void onPay(int status, int code) {
                            if (status == 0) {
                                if (wasuPlayer.mDetailLogic != null) { // 订购成功对影片重新询价
                                    wasuPlayer.mDetailLogic.queryPrice(false);
                                }
                                /**广告时强制中断**/
                                if (wasuPlayer != null && wasuPlayer.getVideoView() != null && isAdPlaying()) {
                                    wasuPlayer.getVideoView().skipCurrentAd();
                                }
                                Toast.makeText(getContext(), "订购成功!", Toast.LENGTH_LONG).show();
                            } else {
                                if (code == 12) {
                                    Toast.makeText(getContext(), "支付失败，请重新登录后再支付！", Toast.LENGTH_LONG).show();
                                } else {
                                    Toast.makeText(getContext(), "支付失败!", Toast.LENGTH_LONG).show();
                                }
                            }
                        }
                    });
                    if (!paydialog.isShowing()) {
                        paydialog.show();
                    }
                }
            }
        });
    }

    // 获取vip信息
    private String checkIsVip() {
        String isvip = AuthSDK.getInstance().getValue("vipState");
        return isvip.isEmpty() ? "0" : isvip;
    }


    @Override
    public void onCompletion(MediaPlayer arg0) {
        this.assetInfo = null;
        setVisibility(false, seekbarController.getId());

        hideBufferView();
    }

    @Override
    public void onError(MediaPlayer arg0, int arg1, int arg2) {
        hideBufferView();
    }

    @Override
    public void onInfo(MediaPlayer arg0, int arg1, int arg2) {
        switch (arg1) {
            case MediaPlayer.MEDIA_INFO_BUFFERING_START:
                showBufferView();
                break;
            case MediaPlayer.MEDIA_INFO_BUFFERING_END:
                hideBufferView();
                break;
        }
    }

    @Override
    public void onPause(MediaPlayer arg0) {

    }

    @Override
    public void onPrepareComplete(MediaPlayer arg0) {
        hideBufferView();
    }

    @Override
    public void onPreparing(MediaPlayer arg0) {

    }

    @Override
    public void onProgress(int arg0, int arg1, int arg2) {

    }

    @Override
    public void onResume(MediaPlayer arg0) {

    }

    @Override
    public void onSeekComplete(MediaPlayer arg0) {
        hideBufferView();
    }

    @Override
    public void onSeeking(MediaPlayer arg0) {
        showBufferView();
    }

    @Override
    public void onStart(MediaPlayer arg0) {

    }

    @Override
    public void onStatusChanged(MediaPlayer arg0, int arg1) {
        removeCallbacks(changeRateTask);
        if (arg1 == IMediaListener.STATE_PREPARING || arg1 == IMediaListener.STATE_BUFFERING) {
            showBufferView();
            if (arg1 == IMediaListener.STATE_PREPARING || arg1 == IMediaListener.STATE_BUFFERING) {
                postDelayed(changeRateTask, DURATION_BUFFERING_TIMEOUT);
            }
        } else {
            if (player != null && player.isInPlaybackState()) {
                hideBufferView();
            }
        }
    }

    @Override
    public void onStop(MediaPlayer arg0) {

    }

    @Override
    public void onWasuError(int arg0, String arg1) {

    }

    @Override
    public void onWasuPlayLimit(int arg0, String arg1) {
        if (arg0 == IMediaListener.WASU_PLAY_IN_PREVIEW) {
            seekbarController.setLimitTime(Integer.valueOf(arg1) * 60000);
        } else if (arg0 == IMediaListener.WASU_PLAY_FREE) {
            seekbarController.setLimitTime(Integer.MAX_VALUE);
        }
    }

    public class AnimInfo {
        public int gravity;
        public AnimationDirection direction;
        public ObjectAnimator animIn;
        public ObjectAnimator animOut;
    }

    /***/
    public IMediaControllerChildView getCurrentView() {
        return currentView;
    }

}
