package com.wasu.cs.widget.videoview;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Rect;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.ViewTreeObserver.OnScrollChangedListener;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;

import com.wasu.authsdk.AuthSDK;
import com.wasu.common.WError;
import com.wasu.comp.videoview.IMediaControl;
import com.wasu.comp.videoview.IMediaInterceptListener;
import com.wasu.comp.videoview.IMediaListener;
import com.wasu.comp.videoview.UrlProperty;
import com.wasu.comp.videoview.VideoView;
import com.wasu.cs.model.ILiveAssets;
import com.wasu.cs.model.LiveDemandProgram;
import com.wasu.cs.model.LivePlayInfo;
import com.wasu.cs.module.ScreenSaverModule;
import com.wasu.cs.widget.mediacontrol.LiveMediaController;
import com.wasu.module.datafetch.DataFetchException;
import com.wasu.module.datafetch.DataFetchListener.ObjectListener;
import com.wasu.module.datafetch.DataFetchModule;
import com.wasu.module.datafetch.ObjectBase;
import com.wasu.module.log.WLog;
import com.wasu.statistics.PlayInfo;
import com.wasu.statistics.WasuStatistics;
import com.wasu.util.NetUtils;

import java.util.ArrayList;
import java.util.List;

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

/**
 * 直播/轮播播放器
 *
 * @author zhangrm
 */
public final class WasuLivePlayerView extends RelativeLayout implements IMediaControl, IMediaListener, AppUtil.OnNetStateListener {

    private static final String TAG = "WasuLivePlayerView";

    public static final String CONFIG_FILE = "main_page_video_live";
    public static final String CHANNEL_KEY = "channel_id";
    private boolean StartStatisticsTag = false; //避免播放器恢复没有触发播放而多发统计

    /**
     * 播放器状态监听器
     */
    private List<IMediaListener> mediaListeners;

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

    private static final int STATUS_INIT = 0;
    private static final int STATUS_PARSE_INTENT = 1;
    private static final int STATUS_FETCH_ASSET_INFO = 2;
    private static final int STATUS_PLAY_AUTH = 3;
    private static final int STATUS_DONE = 4;

    /**
     * 当前状态
     */
    private int currentStatus;

    /**
     * 下一个流程
     */
    private static final int PROCESS_NEXT = 0;
    /**
     * 上一个流程
     */
    private static final int PROCESS_PREVIOUS = 1;

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

    public static final int TYPE_MAIN_PAGE = 0;//首页直播/轮播类型
    public static final int TYPE_SUBJECT = 1;//专题直播类型

    /**
     * 直播类型
     */
    private int type = TYPE_MAIN_PAGE;
    /**
     * 首页直播数据
     */
    private ILiveAssets liveInfo;
    /**
     * 获取数据地址
     */
    private String liveJsonUrl;
    /**
     * 当前直播json数据
     */
    private String jsonData;
    /**
     * 当前频道id
     */
    private String channelId;

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


    private Handler processHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {

            if (msg.what == PROCESS_NEXT) {
                switch (currentStatus) {

                    case STATUS_INIT:
                        if (mediaController != null) {
                            mediaController.showBufferView();
                            mediaController.setReady(false);
                        }
                        checkParameters();
                        break;
                    case STATUS_PARSE_INTENT:
                        if (mediaController != null) {
                            mediaController.showBufferView();
                            mediaController.setReady(false);
                        }
                        fetchAssetInfo();
                        break;
                    case STATUS_FETCH_ASSET_INFO:
                        if (mediaController != null) {
                            mediaController.showBufferView();
                            mediaController.setReady(false);
                        }
                        playAuth();
                        break;
                    case STATUS_PLAY_AUTH:
                        if (mediaController != null) {
                            mediaController.showBufferView();
                            mediaController.setReady(false);
                        }
                        play();
                        break;
                    case STATUS_DONE:
                        if (mediaController != null) {
                            mediaController.showBufferView();
                            mediaController.setLiveInfo(liveInfo);
                            mediaController.setReady(true);
                        }

                        if (playerMask != null) {
                            playerMask.setAssetInfo(liveInfo);
                        }
                        break;

                }
            } else if (msg.what == PROCESS_PREVIOUS) {
                // TODO
            }

        }

    };

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

    /**
     * 播放器
     */
    private VideoView videoView;
    /**
     * 播放器蒙版
     */
    private LivePlayerMask playerMask;
    /**
     * 播控
     */
    private LiveMediaController mediaController;

    public LiveMediaController getMediaController() {
        return mediaController;
    }

    /**
     * 锚
     */
    private View anchorView;
    /**
     * 当前宿主activity
     */
    private Activity activity;
    /**
     * 当前是否全屏
     */
    private boolean isFullScreen;

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

    public WasuLivePlayerView(Context context) {
        super(context);
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
        this.setLayoutParams(layoutParams);

        this.setPadding(0, 0, 0, 0);
        this.setBackgroundColor(Color.BLACK);

        init();
    }


    /**
     * 设置锚
     *
     * @param anchor
     * @param activity
     */
    public void setAnchorView(View anchor, Activity activity) {
        if (anchor == null || activity == null) {
            return;
        }

        if (this.anchorView != null) {
            ViewTreeObserver observerTmp = anchorView.getViewTreeObserver();
            try {
                observerTmp.removeGlobalOnLayoutListener(mOnGlobalLayoutListener);
                observerTmp.removeOnScrollChangedListener(mOnScrollChangedListener);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        this.anchorView = anchor;
        this.activity = activity;

        final ViewTreeObserver observer = anchorView.getViewTreeObserver();
        try {
            observer.addOnScrollChangedListener(mOnScrollChangedListener);
            observer.addOnGlobalLayoutListener(mOnGlobalLayoutListener);
        } catch (Exception e) {
            e.printStackTrace();
        }

        Activity act = this.activity;
        if (act != null) {
            FrameLayout content = (FrameLayout) act.findViewById(android.R.id.content);
            if (content.getTag() != null) {
                return;
            }

            FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(anchorView.getMeasuredWidth(), anchorView.getMeasuredHeight());
            int[] location = new int[2];
            anchorView.getLocationInWindow(location);
            lp.leftMargin = location[0];
            lp.topMargin = location[1];

            content.addView(this, content.getChildCount(), lp);
            content.setTag(true);
        }

    }

    /**
     * 监听anchorView的Scroll变化
     */
    private OnScrollChangedListener mOnScrollChangedListener = new OnScrollChangedListener() {

        @Override
        public void onScrollChanged() {
            updateLayout();
        }
    };

    /**
     * 监听anchorView的layout的变化
     */
    private OnGlobalLayoutListener mOnGlobalLayoutListener = new OnGlobalLayoutListener() {

        @Override
        public void onGlobalLayout() {
            updateLayout();
        }
    };

    /**
     * 根据anchorView的layout更新视频显示区域
     *
     * @return
     */
    private boolean updateLayout() {
        if (getParent() == null) {
            return false;
        }

        if (isFullScreen) {
            return false;
        }

        FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) getLayoutParams();
        Rect lastRect = new Rect(lp.leftMargin, lp.topMargin, lp.leftMargin + lp.width, lp.topMargin + lp.height);

        int[] location = new int[2];
        anchorView.getLocationInWindow(location);
        lp.leftMargin = location[0] + anchorView.getPaddingLeft();
        lp.topMargin = location[1] + anchorView.getPaddingTop();
        lp.width = anchorView.getMeasuredWidth() - anchorView.getPaddingLeft() - anchorView.getPaddingRight();
        lp.height = anchorView.getMeasuredHeight() - anchorView.getPaddingTop() - anchorView.getPaddingBottom();

        Rect newRect = new Rect(lp.leftMargin, lp.topMargin, lp.leftMargin + lp.width, lp.topMargin + lp.height);
        if (newRect.equals(lastRect)) {
            return false;
        }

        setLayoutParams(lp);
        return false;
    }

    /**
     * 设置显示选项
     *
     * @param displayOption
     */
    public void setDisplayOption(int displayOption) {
        if (mediaController == null) {
            return;
        }

        mediaController.setDisplayOption(displayOption);
    }

    /**
     * 设置不显示的控件
     *
     * @param option
     */
    public void setExcludeOption(int option) {
        if (mediaController == null) {
            return;
        }

        mediaController.setExcludeOption(option);
    }

    @Override
    protected void onAttachedToWindow() {
        ScreenSaverModule.getInstance().updateUserActionTime();

        AppUtil.addOnNetStateListener(this);

        super.onAttachedToWindow();
    }

    @Override
    protected void onDetachedFromWindow() {

        AppUtil.removeOnNetStateListener(this);

        if (videoView != null) {
            try {
                videoView.finalize();
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
        }

        if (mediaListeners != null) {
            mediaListeners.clear();
        }

        if (mediaController != null) {
            mediaController.removeAllViews();
        }

        super.onDetachedFromWindow();
    }

    /**
     * 切换全屏
     *
     * @return 切换后当前是否全屏状态
     */
    public boolean toggleFullScreen() {
        if (this.anchorView == null) {
            return false;
        }

        FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) getLayoutParams();
        if (!isFullScreen) {
            lp.leftMargin = 0;
            lp.topMargin = 0;
            lp.width = FrameLayout.LayoutParams.MATCH_PARENT;
            lp.height = FrameLayout.LayoutParams.MATCH_PARENT;
            isFullScreen = true;
        } else {
            int[] location = new int[2];
            anchorView.getLocationInWindow(location);
            lp.leftMargin = location[0];
            lp.topMargin = location[1];
            lp.width = anchorView.getMeasuredWidth();
            lp.height = anchorView.getMeasuredHeight();
            isFullScreen = false;
        }
        setLayoutParams(lp);

        if (isFullScreen) {
            requestFocus();
        } else {
            anchorView.requestFocus();
        }

        if (mediaController != null) {
            mediaController.handleFullScreen(isFullScreen);
        }

        if (playerMask != null) {
            playerMask.handleFullScreen(isFullScreen);
        }

        return isFullScreen;
    }

    /**
     * 设置播放器是否为全屏播放器，全屏播放器在显示播控的时候会显示loading圈和文字信息
     * 非全屏状态只会显示loading圈，不会显示文字
     * @param isFullScreen
     */
    public void handleFullScreen(boolean isFullScreen) {

        if (mediaController != null) {
            mediaController.handleFullScreen(isFullScreen);
        }

        if (playerMask != null) {
            playerMask.handleFullScreen(isFullScreen);
        }
    }

    public boolean isFullScreen() {
        return isFullScreen;
    }

    private void init() {
        setFocusable(true);
        setFocusableInTouchMode(true);
        mediaListeners = new ArrayList<IMediaListener>();

        videoView = new VideoView(this.getContext());
        videoView.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        addView(videoView);

        playerMask = new LivePlayerMask(getContext());
        playerMask.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        playerMask.setPlayer(this);
        addView(playerMask);

        mediaController = new LiveMediaController(this.getContext());
        mediaController.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        mediaController.setPlayer(this);
        addView(mediaController);

        videoView.addObserver(this);
        videoView.addObserver(playerMask);
        videoView.addObserver(mediaController);
    }

    public void setLoadingViewBackground(String url) {
        if(null != playerMask) {
            playerMask.setBackgroundUrl(url);
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_UP) {
            return false;
        }

        if (anchorView != null && !isFullScreen) {
            return false;
        }

        if (!mediaController.dispatchKeyEvent(event) && event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            if (anchorView == null) {
                return super.dispatchKeyEvent(event);
            } else {
                toggleFullScreen();
                return true;
            }
        }else{
            return true;
        }

//        return super.dispatchKeyEvent(event);
    }

    /**
     * 解析传入数据
     *
     * @return
     */
    private void checkParameters() {
        currentStatus = STATUS_PARSE_INTENT;

        if (TextUtils.isEmpty(liveJsonUrl) && TextUtils.isEmpty(jsonData) && liveInfo == null) {
            WLog.e(TAG, "传入数据为空");
            return;
        }

        processHandler.sendEmptyMessage(PROCESS_NEXT);
    }

    /**
     * 根据assetUrl获取assetInfo
     */
    private void fetchAssetInfo() {
        currentStatus = STATUS_FETCH_ASSET_INFO;

        if (type == TYPE_MAIN_PAGE) {
            DataFetchModule.getInstance().fetchObjectGet(liveJsonUrl, LiveDemandProgram.class, new ObjectListener() {

                @Override
                public void onObjectGet(int arg0, String arg1, ObjectBase arg2) {
                    if (arg0 != WError.ERROR_NONE) {
                        WLog.e(TAG, "获取数据失败1");
                        return;
                    }

                    liveInfo = (LiveDemandProgram) arg2;
                    if (liveInfo == null) {
                        WLog.e(TAG, "获取数据失败2");
                        return;
                    }
                    /***
                     * 当数据解析出来后设置第一个直播源来播放
                     */
                    channelId = liveInfo.getChannelId(0);
                    processHandler.sendEmptyMessage(PROCESS_NEXT);
                }
            });
        } else if (type == TYPE_SUBJECT) {
            try {
                liveInfo = new LivePlayInfo(jsonData);
                if (liveInfo == null || liveInfo.getChannelSize() == 0) {
                    WLog.e(TAG, "获取数据失败3");
                    return;
                }

                processHandler.sendEmptyMessage(PROCESS_NEXT);
            } catch (DataFetchException e) {
                e.printStackTrace();
            }
        } else {
            //TODO otherwise
        }
    }

    /**
     * 播放鉴权
     */
    private void playAuth() {
        currentStatus = STATUS_PLAY_AUTH;

        String cId = getContext().getSharedPreferences(CONFIG_FILE, Context.MODE_PRIVATE).getString(CHANNEL_KEY, "");
        if (TextUtils.isEmpty(cId)) {
            if (TextUtils.isEmpty(channelId)) {
                channelId = liveInfo.getChannelId(0);
            }
        } else {
            boolean isExist = false;
            for (int i = 0; i < liveInfo.getChannelSize(); i++) {
                if (cId.equals(liveInfo.getChannelId(i))) {
                    isExist = true;
                    break;
                }
            }

            if (!isExist) {
                if (TextUtils.isEmpty(channelId)) {
                    channelId = liveInfo.getChannelId(0);
                }
            } else {
                channelId = cId;
            }
        }

        getContext().getSharedPreferences(CONFIG_FILE, Context.MODE_PRIVATE).edit().putString(CHANNEL_KEY, channelId).commit();

        mediaController.setChannelId(channelId);
        mediaController.setPlayType(type);

        processHandler.sendEmptyMessage(PROCESS_NEXT);
    }

    /**
     * 开始播放
     */
    private void play() {
        currentStatus = STATUS_DONE;

        String url = getCurPlayUrl();
        if (TextUtils.isEmpty(url)) {
            postOnWasuError(IMediaListener.WASU_ERROR_PLAYER, "没有获取到播放串");
            WLog.e(TAG, "没有获取到播放串");
            return;
        }

        try {
            videoView.setVideoPath(url, null);
        } catch (Exception e) {
            postOnWasuError(IMediaListener.WASU_ERROR_PLAYER, "播放地址无效");
            WLog.e(TAG, "播放地址无效");
            e.printStackTrace();
            return;
        }

        videoView.start();

        processHandler.sendEmptyMessage(PROCESS_NEXT);
    }

    public String getCurPlayUrl() {
        if (liveInfo != null) {
            ILiveAssets.Type type = liveInfo.getType(channelId);
            if (ILiveAssets.Type.HTTP == type) {
                return liveInfo.getHttpUrl(channelId);
            } else if (ILiveAssets.Type.P2P == type) {
                return liveInfo.getP2pFccs(channelId);
            }
        }
        return null;
    }
    //////////////////////////////////////////////////////////////////////////////////

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

    // //////////////////////////////////IMediaControl//////////////////////////////////////////////

    /**
     * 首页直播/轮播调用
     *
     * @param jsonUrl
     * @param channelId
     */
    public void play(String jsonUrl, int channelId) {

        mediaController.clear();
        if (isFullScreen) {
            requestFocus();
        }

        this.type = TYPE_MAIN_PAGE;
        this.liveJsonUrl = jsonUrl;
        this.channelId = String.valueOf(channelId);

        currentStatus = STATUS_INIT;
        processHandler.sendEmptyMessage(PROCESS_NEXT);
    }

    /**
     * 首页直播/轮播调用
     *
     * @param channelId
     */
    public void play(int type, String channelId) {

        mediaController.clear();
        if (isFullScreen) {
            requestFocus();
        }

        this.type = type;
        this.channelId = channelId;

        currentStatus = STATUS_INIT;
        processHandler.sendEmptyMessage(PROCESS_NEXT);
    }

    /**
     * WR.livePlay(String jsonUrl) ——直播播放调用
     *
     * @param jsonData
     */
    public void play(String jsonData, String channelId) {
        mediaController.clear();
        if (isFullScreen) {
            requestFocus();
        }

        this.type = TYPE_SUBJECT;
        this.jsonData = jsonData;
        this.channelId = channelId;

        currentStatus = STATUS_INIT;
        processHandler.sendEmptyMessage(PROCESS_NEXT);
    }

    @Override
    public void setVideoPath(String path, UrlProperty property) throws IllegalArgumentException {
        videoView.setVideoPath(path, property);
    }

    @Override
    public void setVideoClips(int startTime, int endTime) {
        videoView.setVideoClips(startTime, endTime);
    }

    @Override
    public void start() {
        videoView.start();
    }

    @Override
    public void resume(String url) {
        videoView.resume(url);
    }

    @Override
    public void pause() {
        videoView.pause();
    }

    @Override
    public void suspend() {
        videoView.suspend();
    }

    @Override
    public void seekTo(int msec) {
        videoView.seekTo(msec);
    }

    @Override
    public void stopPlayback() {
        videoView.stopPlayback();
    }

    @Override
    public void stopPlayback(boolean clearAdStatus) {
        stopPlayback();
    }

    @Override
    public int getDuration() {
        return videoView.getDuration();
    }

    @Override
    public int getCurrentPosition() {
        return videoView.getCurrentPosition();
    }

    @Override
    public int getCurrentADPosition() {
        return videoView.getCurrentADPosition();
    }

    @Override
    public int getCurrentADDuration() {
        return videoView.getCurrentADDuration();
    }

    @Override
    public boolean isPlaying() {
        return videoView.isPlaying();
    }

    @Override
    public boolean isPreparing() {
        return videoView.isPreparing();
    }

    @Override
    public void setPlayType(PlayType type) {
        videoView.setPlayType(type);
    }

    @Override
    public int getVideoWidth() {
        return videoView.getVideoWidth();
    }

    @Override
    public int getVideoHeight() {
        return videoView.getVideoHeight();
    }

    @Override
    public boolean isInPlaybackState() {
        return videoView.isInPlaybackState();
    }

    @Override
    public View getMediaControl() {
        return this;
    }

    @Override
    public void addObserver(IMediaListener listener) {
        videoView.addObserver(listener);
        mediaListeners.add(listener);
    }

    @Override
    public void removeObserver(IMediaListener listener) {
        videoView.removeObserver(listener);
        mediaListeners.remove(listener);
    }

    @Override
    public void setInterceptListener(IMediaInterceptListener listener) {

    }

    @Override
    public void postOnStart() {

    }

    @Override
    public void postOnPreparing() {

    }

    @Override
    public void postOnPrepareComplete() {

    }

    @Override
    public void postOnSeeking() {

    }

    @Override
    public void postOnSeekcomplete() {

    }

    @Override
    public void postOnPause() {

    }

    @Override
    public void postOnResume() {

    }

    @Override
    public void postOnStop() {

    }

    @Override
    public void postOnCompletion() {

    }

    @Override
    public void postOnInfo(int i, int i1) {

    }

    @Override
    public void postOnError(int i, int i1) {

    }

    // //////////////////////////////////IMediaControl//////////////////////////////////////////////

    // //////////////////////////////////IMediaListener////////////////////////////////////
    @Override
    public void onStart(MediaPlayer mp) {
//        WLog.e(TAG,"sendPlayStartStatistics "+liveInfo.getChannelSize());
//
//        int currect = -1;
//        ILiveAssets liveInfo = this.mediaController.getLiveInfo();
//        for (int i=0; i<liveInfo.getChannelSize(); i++){
//            if (mediaController.getChannelId() == liveInfo.getChannelId(i)){
//                currect = i;
//                break;
//            }
//        }

//        if (currect > -1){ // 获取到了当前播放内容
//            PlayInfo playInfo = new PlayInfo(""/*mVideoId*/, liveInfo.getChannelName(liveInfo.getChannelId(currect))/*mVideoName*/,
//                    liveInfo.getHttpUrl(currect+"")/*mVideoUrl*/,""/*mVideoBit*/,""/*mVideoPpv*/, BuildType.SITE_ID/*mVideoSite*/,
//                    ""/*traceid*/,"0"/*price*/,"轮播"/*assetType*/,""+currect/*index*/,"0"/*adfree*/,"1"/*cdnorp2p*/,"0"/*channel*/,
//                    ""/*status*/,"0"/*markprice*/,checkIsVip()/*isvip*/);
        PlayInfo playInfo = new PlayInfo();
        WasuStatistics.getInstance().playBegin(playInfo, "首页直播播放器");
        StartStatisticsTag = true;
//        }
    }

    @Override
    public void onPreparing(MediaPlayer mp) {
        WasuStatistics.getInstance().prepareBegin();
    }

    @Override
    public void onPrepareComplete(MediaPlayer mp) {
        WasuStatistics.getInstance().prepareEnd();
        mediaController.setReady(true);
    }

    @Override
    public void onSeeking(MediaPlayer mp) {
        WasuStatistics.getInstance().seekBegin();
    }

    @Override
    public void onSeekComplete(MediaPlayer mp) {
        WasuStatistics.getInstance().seekEnd();
    }

    @Override
    public void onProgress(int position, int duration, int buffingPercent) {
        //每隔10秒重置定时器
        if ((position / 1000) % 10 == 0) {
            ScreenSaverModule.getInstance().updateUserActionTime();
        }
    }

    @Override
    public void onPause(MediaPlayer mp) {
        WasuStatistics.getInstance().onPause();
    }

    @Override
    public void onResume(MediaPlayer mp) {
        WasuStatistics.getInstance().onResume();
        if (!StartStatisticsTag){
            PlayInfo playInfo = new PlayInfo();
            WasuStatistics.getInstance().playBegin(playInfo, "首页直播播放器");
            StartStatisticsTag = true;
        }
    }

    @Override
    public void onStop(MediaPlayer mp) {
        if (StartStatisticsTag) {
            if(liveInfo == null)
                return;
            WLog.e(TAG, "sendPlayStartStatistics " + liveInfo.getChannelSize());
            int currect = -1;
            ILiveAssets liveInfo = this.mediaController.getLiveInfo();
            if (liveInfo != null && liveInfo.getChannelSize() > 0) {
                for (int i = 0; i < liveInfo.getChannelSize(); i++) {
                    if (mediaController.getChannelId() == liveInfo.getChannelId(i)) {
                        currect = i;
                        break;
                    }
                }
                if (currect > -1) { // 获取到了当前播放内容
                    PlayInfo playInfo = new PlayInfo(""/*mVideoId*/, liveInfo.getChannelName(liveInfo.getChannelId(currect))/*mVideoName*/,
                            getCurPlayUrl()/*mVideoUrl*/, ""/*mVideoBit*/, ""/*mVideoPpv*/, BuildType.SITE_ID/*mVideoSite*/,
                            ""/*traceid*/, "0"/*price*/, "轮播"/*assetType*/, "" + currect/*index*/, "1"/*adfree*/, "0"/*cdnorp2p*/, "0"/*channel*/,
                            ""/*status*/, "0"/*markprice*/, checkIsVip()/*isvip*/);

                    WLog.e(TAG, "onStop setPlayinfo = " + getCurPlayUrl());
                    WasuStatistics.getInstance().addPageElem(playInfo);
                    WasuStatistics.getInstance().setPlayinfo(playInfo, "首页直播播放器");
                }
            }
            // 播放完成
            WasuStatistics.getInstance().playEnd(0, 0);
            StartStatisticsTag = false;
        }
    }

    @Override
    public void onCompletion(MediaPlayer mp) {

    }

    @Override
    public void onError(MediaPlayer mp, int what, int extra) {
        WLog.e(TAG, "播放器错误:" + what + "," + extra);

    }

    @Override
    public void onInfo(MediaPlayer mp, int what, int extra) {
        if (what == MediaPlayer.MEDIA_INFO_BUFFERING_START) {
            WasuStatistics.getInstance().bufferBegin();
        } else if (what == MediaPlayer.MEDIA_INFO_BUFFERING_END) {
            WasuStatistics.getInstance().bufferEnd();
        }
    }

    @Override
    public void onStatusChanged(MediaPlayer mp, int currentStatus) {

    }

    @Override
    public void onAdStatusChanged(int status, int extra) {
        switch (status) {
            case IMediaListener.AD_START:

                break;
            case IMediaListener.AD_END:

                break;
        }
    }

    /**
     * @param errorCode WASU_ERROR_AUTH = 设备授权注册失败
     *                  WASU_ERROR_QUERY_PRICE = 资产询价失败
     *                  WASU_ERROR_PAY = 资产支付失败
     *                  WASU_ERROR_PLAYER = 播放器异常
     *                  WASU_ERROR_UPM_TOKEN_EXPIRE = token严重超期
     * @param extra
     */
    @Override
    public void onWasuError(int errorCode, String extra) {
        if (NetUtils.isNetConnected(getContext())) {
            switch (errorCode) {
                case IMediaListener.WASU_ERROR_AUTH:
                    WLog.e(TAG, "设备授权注册失败");
                    break;
                case IMediaListener.WASU_ERROR_QUERY_PRICE:
                    WLog.e(TAG, "资产询价失败");
                    break;
                case IMediaListener.WASU_ERROR_PAY:
                    WLog.e(TAG, "资产支付失败");
                    break;
                case IMediaListener.WASU_ERROR_PLAYER:
                    WLog.e(TAG, "播放器异常:" + extra);
                    break;
                case IMediaListener.WASU_ERROR_UPM_TOKEN_EXPIRE:
                    WLog.e(TAG, "token严重超期");
                    break;
            }
        } else {
            WLog.e(TAG, "网络出错,请检查您的网络设置");
        }
    }

    @Override
    public void onWasuPlayLimit(int status, String extra) {
        if (status == IMediaListener.WASU_PLAY_IN_PAY) {

        } else if (status == IMediaListener.WASU_PLAY_IN_PREVIEW) {

        } else if (status == IMediaListener.WASU_PLAY_FREE) {

        }
    }

    /***********************************************************************************/
    private void postOnWasuError(int status, String extra) {
        if (mediaListeners == null) {
            return;
        }

        for (IMediaListener l : mediaListeners) {
            l.onWasuError(status, extra);
        }
    }

    private void postOnWasuPlayLimit(int status, String extra) {
        if (mediaListeners == null) {
            return;
        }

        for (IMediaListener l : mediaListeners) {
            l.onWasuPlayLimit(status, extra);
        }
    }

    @Override
    public void onStateChanged(int state) {
        if (videoView == null) {
            return;
        }

        if (AppUtil.ETHERNET_CONNECTED == state || AppUtil.WIFI_CONNECTED == state) {
            if (!isCover()) {
                play();
            }
        }
    }

    private boolean isCover() {
        Rect rect = new Rect();
        boolean isCover = getGlobalVisibleRect(rect);
        if (isCover) {
            if (rect.width() < getMeasuredWidth() || rect.height() < getMeasuredHeight()) {
                return true;
            } else {
                return false;
            }
        } else {
            return true;
        }
    }

}