package com.gensee.voddemo;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.gensee.common.GenseeConfig;
import com.gensee.config.ConfigApp;
import com.gensee.entity.BroadCastMsg;
import com.gensee.entity.ChatMsg;
import com.gensee.entity.DocInfo;
import com.gensee.entity.PageInfo;
import com.gensee.media.IVideoIndication;
import com.gensee.media.PlaySpeed;
import com.gensee.media.VODPlayer;
import com.gensee.media.VODPlayer.OnVodPlayListener;
import com.gensee.playerdemo.R;
import com.gensee.utils.DateUtil;
import com.gensee.utils.GenseeLog;
import com.gensee.utils.StringUtil;
import com.gensee.view.GSDocViewGx;
import com.gensee.view.GSGLVideoView;
import com.gensee.view.GSGPUVideoView;
import com.gensee.vod.OnVodChatListener;
import com.gensee.vod.VodChat;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class PlayActivity extends Activity implements OnVodPlayListener, OnClickListener, OnSeekBarChangeListener {

    private static final String TAG = "PlayActivity";
    private VODPlayer mVodPlayer;
    private IVideoIndication mGSVideoView;
    //private GSDocView mDocView;
    private GSDocViewGx mGlDocView;
    private SeekBar mSeekBarPlayViedo;
    private Button btnDocList;
    private ListView lvChapterList;
    private ChapterListAdapter chapterListAdapter;

    private Button stopVeidoPlay;
    private Button btnMute;
    private Button replyVedioPlay;
    private TextView mNowTimeTextview;
    private TextView mAllTimeTextView;

    private ImageButton mPauseScreenplay;
    private SeekBar mVolumeSeekBar;
    private TextView mVolumeTextView;
    private boolean isTouch = false;

    private static final int DURITME = Toast.LENGTH_SHORT;
    private static final String DURATION = "DURATION";

    private int VIEDOPAUSEPALY = 0;
    private int speedItem = 0;

    private List<ChapterInfo> chapterList;

    private int lastPostion = 0;
    private String idOrPath = "";

    interface MSG {
        int MSG_ON_INIT = 1;
        int MSG_ON_STOP = 2;
        int MSG_ON_POSITION = 3;
        int MSG_ON_VIDEOSIZE = 4;
        int MSG_ON_PAGE = 5;
        int MSG_ON_SEEK = 6;
        int MSG_ON_AUDIOLEVEL = 7;
        int MSG_ON_ERROR = 8;
        int MSG_ON_PAUSE = 9;
        int MSG_ON_RESUME = 10;
    }

    protected Handler myHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG.MSG_ON_INIT:

                    int max = msg.getData().getInt(DURATION);
                    mSeekBarPlayViedo.setMax(max);
                    max = max / 1000;
                    GenseeLog.i(TAG, "MSG_ON_INIT duration = " + max);
                    mAllTimeTextView.setText(getTime(max));
                    mPauseScreenplay.setImageResource(R.drawable.icon_pause);
//				mVodPlayer.seekTo(2000);
//				if (ConfigApp.mutePlay) {
//					mVodPlayer.mute();
//					btnMute.setText("取消静音");
//				}
                    break;
                case MSG.MSG_ON_STOP:
                    updatePos(0);
                    break;
                case MSG.MSG_ON_VIDEOSIZE:

                    break;
                case MSG.MSG_ON_PAGE:
                    int position = (Integer) msg.obj;
                    int nSize = chapterList.size();
                    for (int i = 0; i < nSize; i++) {
                        ChapterInfo chapterInfo = chapterList.get(i);
                        if (chapterInfo.getPageTimeStamp() == position) {
                            if (null != chapterListAdapter) {
                                chapterListAdapter.setSelectedPosition(i);
                            }
                            break;
                        }
                    }
                    break;
                case MSG.MSG_ON_PAUSE:
                    VIEDOPAUSEPALY = 1;
                    mPauseScreenplay.setImageResource(R.drawable.icon_play);
                    break;
                case MSG.MSG_ON_RESUME:
                    VIEDOPAUSEPALY = 0;
                    mPauseScreenplay.setImageResource(R.drawable.icon_pause);
                    break;
                case MSG.MSG_ON_POSITION:
                    if (isTouch) {
                        return;
                    }
                case MSG.MSG_ON_SEEK:
                    isTouch = false;
                    updatePos((Integer) msg.obj);
                    break;
                case MSG.MSG_ON_AUDIOLEVEL:

                    break;
                case MSG.MSG_ON_ERROR:
                    int errorCode = (Integer) msg.obj;
                    switch (errorCode) {
                        case ERR_PAUSE:
                            Toast.makeText(getApplicationContext(), "暂停失败", DURITME)
                                    .show();
                            break;
                        case ERR_PLAY:
                            Toast.makeText(getApplicationContext(), "播放失败", DURITME)
                                    .show();
                            break;
                        case ERR_RESUME:
                            Toast.makeText(getApplicationContext(), "恢复失败", DURITME)
                                    .show();
                            break;
                        case ERR_SEEK:
                            Toast.makeText(getApplicationContext(), "进度变化失败", DURITME)
                                    .show();
                            break;
                        case ERR_STOP:
                            Toast.makeText(getApplicationContext(), "停止失败", DURITME)
                                    .show();
                            break;
                        case RESULT_LICENSE:
                            Toast.makeText(getApplicationContext(), "并发不足，请联系主办方调整并发！", DURITME)
                                    .show();
                            break;
                        case RESULT_LOCAL_FILE_UNCOMPLETE:
                            Toast.makeText(getApplicationContext(), "初始化失败，请检查网络或换个网络再试！", DURITME)
                                    .show();
                            break;
                        default:
                            break;
                    }
                    break;
                default:
                    break;
            }
            super.handleMessage(msg);
        }

    };

    /**
     * 返回时间字符串
     *
     * @param time 单位为秒的时间
     * @return 返回时分秒字符串
     */
    private String getTime(long time) {
        return String.format("%02d", time / 3600) + ":"
                + String.format("%02d", time % 3600 / 60) + ":"
                + String.format("%02d", time % 3600 % 60);
    }

    private void updatePos(int anyPosition) {
        mSeekBarPlayViedo.setProgress(anyPosition);
        anyPosition = anyPosition / 1000;
        mNowTimeTextview.setText(getTime(anyPosition));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        GenseeLog.d(TAG, "onCreate this = " + this.hashCode());
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_play);
        //lastPostion = getPreferences(MODE_PRIVATE).getInt("lastPos", 0);
        mGSVideoView = findViewById(R.id.gsvideoview);
        mGlDocView = (GSDocViewGx) findViewById(R.id.playGlDocView);
        mSeekBarPlayViedo = (SeekBar) findViewById(R.id.seekbarpalyviedo);
        stopVeidoPlay = (Button) findViewById(R.id.stopveidoplay);
        btnMute = (Button) findViewById(R.id.btnMute);
        mPauseScreenplay = (ImageButton) findViewById(R.id.pauseresumeplay);
        replyVedioPlay = (Button) findViewById(R.id.replayvedioplay);
        mNowTimeTextview = (TextView) findViewById(R.id.palynowtime);
        mAllTimeTextView = (TextView) findViewById(R.id.palyalltime);
        btnDocList = (Button) findViewById(R.id.doc_list_btn);
        btnMute.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mVodPlayer.getMuteStatus()) {
                    // 当前静音，取消静音
                    mVodPlayer.unMute();
                    btnMute.setText("静音");
                    GenseeLog.d("PlayActivity", "unMute status:" + mVodPlayer.getMuteStatus());
                } else {
                    // 当前未静音，执行静音
                    mVodPlayer.mute();
                    btnMute.setText("取消静音");
                    GenseeLog.d("PlayActivity", "mute status:" + mVodPlayer.getMuteStatus());
                }
            }
        });
        btnDocList.setOnClickListener(this);
        chapterListAdapter = new ChapterListAdapter();
        chapterList = new ArrayList<ChapterInfo>();
        lvChapterList = (ListView) findViewById(R.id.doc_lv);
        lvChapterList.setAdapter(chapterListAdapter);
        lvChapterList.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                ChapterInfo chapterInfo = chapterList.get(position);
                if (null != mVodPlayer) {
                    mVodPlayer.seekTo(chapterInfo.getPageTimeStamp());
                }
            }
        });

        mSeekBarPlayViedo.setOnSeekBarChangeListener(this);
        //mDocView.setOnDocViewClickedListener(this);
        // mDocView.showAdaptViewWidth();

        stopVeidoPlay.setOnClickListener(this);
        replyVedioPlay.setOnClickListener(this);

        mPauseScreenplay.setOnClickListener(this);
        findViewById(R.id.speed).setOnClickListener(this);
        findViewById(R.id.offlinge_msgs).setOnClickListener(this);
        String localpath = getIntent().getStringExtra("play_path");
        if (StringUtil.isEmpty(localpath)) {
            findViewById(R.id.offlinge_msgs).setVisibility(View.GONE);
        }
        initPlayer();
        initVolumeControl();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    private void initPlayer() {

        String vodIdOrLocalPath = getVodIdOrLocalPath();
        if (vodIdOrLocalPath == null) {
            Toast.makeText(this, "路径不对", Toast.LENGTH_SHORT).show();
            return;
        }

        idOrPath = vodIdOrLocalPath;
        GenseeConfig.vodCacheCount = 5;
        if (mVodPlayer == null) {
            mVodPlayer = new VODPlayer();
            mVodPlayer.setGSVideoView(mGSVideoView);
            mVodPlayer.setGSDocViewGx(mGlDocView);
            mVodPlayer.play(vodIdOrLocalPath, this, "", false);
        }
    }

    private String getVodIdOrLocalPath() {
        String vodId = getIntent().getStringExtra("play_param");
        String localpath = getIntent().getStringExtra("play_path");
        GenseeLog.d(TAG, "path = " + localpath + " vodId = " + vodId);
        String vodIdOrLocalPath = null;
        if (!StringUtil.isEmpty(localpath)) {
            vodIdOrLocalPath = localpath;
        } else if (!StringUtil.isEmpty(vodId)) {
            vodIdOrLocalPath = vodId;
        }
        return vodIdOrLocalPath;
    }

    @Override
    public void onInit(int result, boolean haveVideo, int duration,
                       final List<DocInfo> docInfos) {
        // 为了复现客户的使用场景，mute在一收到onInit就调用
        if (ConfigApp.mutePlay) {
            mVodPlayer.mute();
            myHandler.post(new Runnable() {
                @Override
                public void run() {
                    btnMute.setText("取消静音");
                }
            });
        }
        GenseeLog.d(TAG, "onInit result = " + result);
        int pos = 0;
        if (ConfigApp.getIns().positions.containsKey(idOrPath)) {
            pos = ConfigApp.getIns().positions.get(idOrPath);
        }
        if (pos >= duration - 1000) {
            pos = 0;
        }
        Message message = new Message();
        message.what = MSG.MSG_ON_INIT;
        Bundle bundle = new Bundle();
        bundle.putInt(DURATION, duration);
        message.setData(bundle);
        myHandler.sendMessage(message);
        int finalPos = pos;
        myHandler.post(new Runnable() {
            @Override
            public void run() {
                GenseeLog.d(TAG, "onInit " + finalPos);
                if (finalPos > 0) {
                    mVodPlayer.seekTo(finalPos);

                }
                updateDoclist(docInfos);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    public void onPlayStop() {
        myHandler.sendMessage(myHandler.obtainMessage(MSG.MSG_ON_STOP, 0));
    }

    @Override
    public void onPosition(int position) {
        GenseeLog.d(TAG, "onPosition pos = " + position);
        lastPostion = position;
        myHandler.sendMessage(myHandler.obtainMessage(MSG.MSG_ON_POSITION,
                position));
    }

    @Override
    public void onVideoSize(int position, int videoWidth, int videoHeight) {
        myHandler.sendMessage(myHandler.obtainMessage(MSG.MSG_ON_VIDEOSIZE, 0));
    }


    @Override
    public void onSeek(int position) {
        myHandler.sendMessage(myHandler
                .obtainMessage(MSG.MSG_ON_SEEK, position));
    }

    @Override
    public void onAudioLevel(int level) {
        myHandler.sendMessage(myHandler.obtainMessage(MSG.MSG_ON_AUDIOLEVEL,
                level));
    }

    @Override
    public void onError(int errCode) {
        myHandler.sendMessage(myHandler
                .obtainMessage(MSG.MSG_ON_ERROR, errCode));
    }

    @Override
    public void onPlayPause() {
        myHandler.sendMessage(myHandler.obtainMessage(MSG.MSG_ON_PAUSE, 0));
    }

    @Override
    public void onPlayResume() {
        myHandler.sendMessage(myHandler.obtainMessage(MSG.MSG_ON_RESUME, 0));
    }


    @Override
    public void onPageSize(int position, int w, int h) {
        //文档翻页切换，开始显示
        myHandler.sendMessage(myHandler
                .obtainMessage(MSG.MSG_ON_PAGE, position));

    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress,
                                  boolean fromUser) {

    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        isTouch = true;

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        if (null != mVodPlayer) {
            int pos = seekBar.getProgress();
            GenseeLog.d(TAG, "onStopTrackingTouch pos = " + pos);
            mVodPlayer.seekTo(pos);

        }

    }

    @Override
    public void onClick(View currenView) {
        if (currenView.getId() == R.id.stopveidoplay) {
            boolean ret = mVodPlayer.stop();
            mSeekBarPlayViedo.setMax(0);
            Toast.makeText(this, ret ? "操作成功" : "操作失败", DURITME).show();
        } else if (currenView.getId() == R.id.replayvedioplay) {
            isTouch = false;
            String vodIdOrLocalPath = getVodIdOrLocalPath();
            if (vodIdOrLocalPath == null) {
                Toast.makeText(this, "路径不对", Toast.LENGTH_SHORT).show();
                return;
            }
            //重新播放时  将速度恢复为正常速度，如果要保持上一次速度播放，设置为上一次速度
            speedItem = 0;
            mVodPlayer.setSpeed(PlaySpeed.SPEED_NORMAL, null);
            mVodPlayer.setGSVideoView(mGSVideoView);
            mVodPlayer.setGSDocViewGx(mGlDocView);
            mVodPlayer.play(vodIdOrLocalPath, this, "", false);

        } else if (currenView.getId() == R.id.pauseresumeplay) {
            if (VIEDOPAUSEPALY == 0) {
                mVodPlayer.pause();
            } else if (VIEDOPAUSEPALY == 1) {
                mVodPlayer.resume();
            }
        } else if (currenView.getId() == R.id.doc_list_btn) {
            if (lvChapterList.getVisibility() == View.VISIBLE) {
                lvChapterList.setVisibility(View.GONE);
            } else {
                lvChapterList.setVisibility(View.VISIBLE);
            }
        } else if (currenView.getId() == R.id.speed) {
            switchSpeed();
        } else if (currenView.getId() == R.id.offlinge_msgs) {
            String localpath = getIntent().getStringExtra("play_path");
            VodChat vc = new VodChat();
            vc.setChatListener(new OnVodChatListener() {
                @Override
                public void onChatHistory(String vodId, List<ChatMsg> chatMsgs, int pageIndex, boolean more) {
                    GenseeLog.d(TAG, "onChatHistory size " + chatMsgs.size());
                    final StringBuilder sb = new StringBuilder("离线聊天消息" + chatMsgs.size() + "条");
                    for (ChatMsg msg : chatMsgs) {
                        sb.append('\n').append(msg.getSender()).append(':').append(msg.getContent());
                    }
                    myHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(), sb.toString(), Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            });

            vc.getChatHistory("", localpath, 0);
        }

    }

    /**
     * 变速播放
     */
    private void switchSpeed() {
        new AlertDialog.Builder(this)
                .setSingleChoiceItems(R.array.speeds, speedItem,
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                speedItem = which;
                                PlaySpeed ps = PlaySpeed.SPEED_NORMAL;
                                switch (which) {
                                    case 0:
                                        ps = PlaySpeed.SPEED_NORMAL;
                                        break;
                                    case 1:
                                        ps = PlaySpeed.SPEED_125;
                                        break;
                                    case 2:
                                        ps = PlaySpeed.SPEED_150;
                                        break;
                                    case 3:
                                        ps = PlaySpeed.SPEED_175;
                                        break;
                                    case 4:
                                        ps = PlaySpeed.SPEED_200;
                                        break;
                                    case 5:
                                        ps = PlaySpeed.SPEED_250;
                                        break;
                                    case 6:
                                        ps = PlaySpeed.SPEED_300;
                                        break;
                                    case 7:
                                        ps = PlaySpeed.SPEED_350;
                                        break;
                                    case 8:
                                        ps = PlaySpeed.SPEED_400;
                                        break;

                                    default:
                                        break;
                                }
                                mVodPlayer.setSpeed(ps, null);
                                dialog.dismiss();
                            }
                        }).create().show();
    }

    private void stopPlay() {
        if (mVodPlayer != null) {
            mVodPlayer.stop();
        }
    }

    private void release() {
        stopPlay();
        if (mVodPlayer != null) {
            mVodPlayer.release();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (!TextUtils.isEmpty(idOrPath)) {
            GenseeLog.d(TAG, "onStop " + lastPostion);
            ConfigApp.getIns().positions.put(idOrPath, lastPostion);
        }
    }

    @Override
    public void onBackPressed() {
//		getPreferences(MODE_PRIVATE).edit().putInt("lastPos", lastPostion).commit();
        release();
        super.onBackPressed();
    }

    @Override
    public void onCaching(boolean isCatching) {
        // TODO Auto-generated method stub

    }

    private class ChapterListAdapter extends BaseAdapter {
        private List<ChapterInfo> pageList;
        private int selectedPosition = 0;

        public void setSelectedPosition(int position) {
            selectedPosition = position;
            notifyDataSetChanged();
            lvChapterList.setSelection(position);
        }

        public ChapterListAdapter() {
            pageList = new ArrayList<ChapterInfo>();
        }

        public void notifyData(List<ChapterInfo> pageList) {
            this.pageList.clear();
            this.pageList.addAll(pageList);
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return pageList.size();
        }

        @Override
        public Object getItem(int position) {
            return pageList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder = null;
            if (null == convertView) {
                convertView = LayoutInflater.from(parent.getContext()).inflate(
                        R.layout.doc_list_item_ly, null);
                viewHolder = new ViewHolder(convertView);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }

            viewHolder.init((ChapterInfo) getItem(position), position);
            return convertView;
        }

        private class ViewHolder {
            private TextView tvChapter;
            private TextView tvTitle;
            private TextView tvTime;
            private LinearLayout lyChapter;

            private String getChapterTime(long time) {
                return getTime(time / 1000);
            }

            public ViewHolder(View view) {
                tvChapter = (TextView) view.findViewById(R.id.chapter_title);
                tvTitle = (TextView) view.findViewById(R.id.doc_title);
                tvTime = (TextView) view.findViewById(R.id.chapter_time);
                lyChapter = (LinearLayout) view.findViewById(R.id.chapter_ly);
            }

            public void init(ChapterInfo chapterInfo, int position) {
                tvChapter.setText(chapterInfo.getPageTitle());
                tvTime.setText(getChapterTime(chapterInfo.getPageTimeStamp()));
                tvTitle.setText(chapterInfo.getDocName());

                if (selectedPosition == position) {
                    lyChapter.setBackgroundResource(R.color.red);
                } else {
                    lyChapter.setBackgroundResource(R.color.transparent);
                }
            }
        }

    }

    @Override
    public void onVideoStart() {
        GenseeLog.d(TAG, "onVideoStart");
        toast("onVideoStart");
    }

    @Override
    public void onVideoEnd() {
        GenseeLog.d(TAG, "onVideoEnd");
        toast("onVideoEnd");
    }

    @Override
    public void onFirstFrameNfy() {

    }

    @Override
    public void onChat(List<ChatMsg> arg0) {
        //ChatMsg msg = chatMsgs.get(0);
        // msg.getRichText()//富文本
        // msg.getSender()//发送者名称
        // msg.getSenderId()//发送者id
        // msg.getContent()//纯文本
        // msg.getTimeStamp()//相对与播放开始的时间  单位毫秒
    }

    @Override
    public void onDocInfo(final List<DocInfo> arg0) {
        myHandler.post(new Runnable() {
            @Override
            public void run() {
                updateDoclist(arg0);
            }
        });
    }

    /**
     * msg 的时候，id代表要删除的聊天消息id，user的时候，代表用户id，强转为long型后进行用户id匹配删除该id说有的聊天消息
     *
     * @param type msg(CHATCENSOR_MSG) / user(CHATCENSOR_USER)
     * @param id   msgId/userId
     */
    @Override
    public void onChatCensor(String type, String id) {

    }

    /**
     * 点播中广播消息回调,
     * 规则：
     * 1、随着播放时间点回放                录制开始第10秒发了一条广播消息，那么点播播放到第10秒才会回调该消息（显示）
     * 2、前进拖动时忽略拖的时间段内的消息  从第5秒拖到11秒，不显示第5到11秒之间的广播消息
     * 3、后退拖会重复拖动时间内的消息      从第11秒拖到5秒，又会回调第5-11秒之间的广播消息
     *
     * @param list 广播消息列表
     */
    @Override
    public void onBroadCastMsg(List<BroadCastMsg> list) {
        if (list == null) {
            return;
        }
        StringBuilder sb = new StringBuilder("广播消息：");
        for (BroadCastMsg m : list) {
            if (m != null) {
                long time = m.getTime();//实际发送的时间，某年某月某日，单位秒
                String sender = m.getSender();//发送者
                long timestamp = m.getTimestamp();//相对于播放时间的时间戳，单位毫秒
                String content = m.getContent();//消息内容
                sb.append("\n发送者:" + sender).append("\n内容：" + content).append("\n发送时间：" + DateUtil.getStringDateShort(time));
            }
        }
        toast(sb.toString());

    }

    /**
     * 播放器布局
     *
     * @param timeStamp 时间戳
     * @param layout    布局类型，取值如下
     *                  0 //文档为主
     *                  1 //视频最大化
     *                  2 //文档最大化
     *                  3 //视频为主
     */
    @Override
    public void onLayoutSet(int timeStamp, int layout) {
        GenseeLog.d("onLayoutSet timeStamp = " + timeStamp + " layout = " + layout);
        String msg = "文档为主";
        switch (layout) {
            case 0:
                msg = "文档为主";
                break;
            case 1:
                msg = "视频最大化";
                break;
            case 2:
                msg = "文档最大化";
                break;
            case 3:
                msg = "视频为主";
                break;
        }
        GenseeLog.d("onLayoutSet timeStamp = " + timeStamp + " layout = " + layout + " msg = " + msg);
        toast("布局变更为：" + msg);
    }

    @Override
    public void onRecordInfo(long l, long l1, long l2) {
        GenseeLog.d(TAG, "onRecordInfo " + l + " " + l1 + " " + l2);

    }

    private void toast(final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), msg, DURITME).show();
            }
        });
    }

    private void updateDoclist(List<DocInfo> docInfoList) {
        if (docInfoList != null && docInfoList.size() > 0) {
            chapterList.clear();
            for (DocInfo docInfo : docInfoList) {
                List<PageInfo> pageInfoList = docInfo.getPages();
                if (null != pageInfoList && pageInfoList.size() > 0) {
                    for (PageInfo pageInfo : pageInfoList) {

                        ChapterInfo chapterInfo = new ChapterInfo();
                        chapterInfo.setDocId(docInfo.getDocId());
                        chapterInfo
                                .setDocName(docInfo.getDocName());
                        chapterInfo.setDocPageNum(docInfo
                                .getPageNum());
                        chapterInfo.setDocType(docInfo.getType());

                        chapterInfo.setPageTimeStamp(pageInfo
                                .getTimeStamp());
                        chapterInfo.setPageTitle(pageInfo
                                .getTitle());
                        chapterList.add(chapterInfo);
                    }
                }
            }
            if (chapterListAdapter != null) {
                chapterListAdapter.notifyData(chapterList);
            }
        }
    }

    private void initVolumeControl() {
        mVolumeSeekBar = (SeekBar) findViewById(R.id.volume_seekbar);
        mVolumeTextView = (TextView) findViewById(R.id.volume_text);

        if (mVolumeSeekBar != null && mVodPlayer != null) {
            float currentVolume = mVodPlayer.getAudioVolume();
            int progress = (int) (currentVolume * 100);
            mVolumeSeekBar.setProgress(progress);
            updateVolumeDisplay(progress);

            mVolumeSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    if (fromUser && mVodPlayer != null) {
                        float volume = progress / 100.0f;
                        mVodPlayer.setAudioVolume(volume);
                        updateVolumeDisplay(progress);
                        GenseeLog.d(TAG, "Volume changed: " + progress + "%");
                    }
                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {
                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {
                }
            });
        }
    }

    private void updateVolumeDisplay(int progress) {
        if (mVolumeTextView != null) {
            mVolumeTextView.setText(progress + "%");
        }
    }
}
