package com.gensee.playerdemo;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
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.InitParam;
import com.gensee.entity.LiveInfo;
import com.gensee.entity.MedalPraiseResult;
import com.gensee.entity.PayInfo;
import com.gensee.entity.PingEntity;
import com.gensee.entity.RewardResult;
import com.gensee.eventbu.EventListener;
import com.gensee.eventbu.EventbuSDK;
import com.gensee.extention.RoomDataEvent;
import com.gensee.fragement.ChatFragment;
import com.gensee.fragement.DocFragment;
import com.gensee.fragement.QaFragment;
import com.gensee.fragement.UsersFragment;
import com.gensee.fragement.ViedoFragment;
import com.gensee.fragement.VoteFragment;
import com.gensee.holder.HongbaoHolder;
import com.gensee.holder.MedalPraiseHolder;
import com.gensee.net.AbsRtAction.ErrCode;
import com.gensee.player.OnPlayListener;
import com.gensee.player.Player;
import com.gensee.routine.UserInfo;
import com.gensee.taskret.OnTaskRet;
import com.gensee.understands.UnderStandEvent;
import com.gensee.utils.GenseeLog;
import com.gensee.view.ILocalVideoView;
import com.gensee.view.beauty.GSLocalVideoView;
import com.gensee.vote.Vote;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

@SuppressLint("NewApi")
public class PlayerDemoActivityEx extends Activity implements
		OnPlayListener, android.view.View.OnClickListener, OnItemClickListener ,RoomDataEvent.Callback{

    private static final String TAG = "PlayerDemoActivity";
    private SharedPreferences preferences;
	private FrameLayout topFrameLayout;
	private LinearLayout midtabsLayout;
	private View rlBottom;
	private Player mPlayer;
	
	private Button mBtnUser;
	private Button mBtnQa;
	private Button mBtnDoc;
	private Button mBtnVote;
	private Button mBtnPublicChat;

	private RelativeLayout relTip;
	private TextView txtTip;
	
	private ProgressBar mProgressBar;
	private ChatFragment mChatFragment;
	private DocFragment mDocFragment;
	private ViedoFragment mViedoFragment;
	private QaFragment mQaFragment;
	private VoteFragment mVoteFragment;
	private UsersFragment mUsersFragment;
	private FragmentManager mFragmentManager;

	private GSLocalVideoView localVideoViewEx;
	private View locVideoGroup;
	
	private int videoWidth = 320,videoHeight = 180;
	
	private AlertDialog audioDialog;
	private AlertDialog videoDialog;

	private boolean bJoinSuccess = false;
	private HongbaoHolder hongbaoHolder;

	private Intent serviceIntent;

	private int inviteMediaType;
	private MedalPraiseHolder medalPraisHolder;
	private Timer timer;

	interface HANDlER {
		int USERINCREASE = 1;
		int USERDECREASE = 2;
		int USERUPDATE = 3;
		int SUCCESSJOIN = 4;
		int SUCCESSLEAVE = 5;
		int CACHING = 6;
		int CACHING_END = 7;
		int RECONNECTING = 8;
	}

	public void setInviteMediaType(int type, boolean isOpen) {
		if ((type & INVITE_AUIDO) == INVITE_AUIDO) {
			if (!isOpen){
				inviteMediaType &= ~ INVITE_AUIDO;
			}
		}
	}

	private Handler mHandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case HANDlER.USERDECREASE:
					if(mUsersFragment != null){
						mUsersFragment.leaveInfo((UserInfo) (msg.obj));
					}
					break;
				case HANDlER.USERINCREASE:
				case HANDlER.USERUPDATE:
					if(mUsersFragment != null){
						mUsersFragment.addInfo((UserInfo) (msg.obj));
					}
					break;
				case HANDlER.SUCCESSJOIN:

					mBtnDoc.setEnabled(true);
					mBtnQa.setEnabled(true);
					mBtnUser.setEnabled(true);
					mBtnVote.setEnabled(true);
					mBtnPublicChat.setEnabled(true);
					mProgressBar.setVisibility(View.GONE);
					bJoinSuccess = true;
					if (mViedoFragment != null) {
						mViedoFragment.onJoin(bJoinSuccess);
					}
					if(hongbaoHolder != null){
						hongbaoHolder.setUserId(mPlayer.getSelfInfo().getUserId());
					}
					break;
				case HANDlER.SUCCESSLEAVE:
					dialog();
					break;
				case HANDlER.CACHING:
					showTip(true, "正在缓冲...");
					relTip.setVisibility(View.VISIBLE);
					break;
				case HANDlER.CACHING_END:
					showTip(false, "");
					break;
				case HANDlER.RECONNECTING:
					showTip(true, "正在重连...");
					break;
				default:
					break;
			}
		}
	};

	protected void onSaveInstanceState(Bundle outState) {
		outState.putBoolean(ConfigApp.PARAMS_JOINSUCCESS, bJoinSuccess);
		outState.putBoolean(
				ConfigApp.PARAMS_VIDEO_FULLSCREEN,
				getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
//		if (bJoinSuccess) {
//			if(mInfoFragment != null){
//				mInfoFragment.onSaveInstanceState(outState);
//			}
//		}
	};

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		boolean bJoinSuccess = savedInstanceState
				.getBoolean(ConfigApp.PARAMS_JOINSUCCESS);
		boolean bVideoFullScreen = savedInstanceState
				.getBoolean(ConfigApp.PARAMS_VIDEO_FULLSCREEN);
		if (bVideoFullScreen) {
			videoFullScreen();
		}
		if (bJoinSuccess) {
			joinLive(ConfigApp.getIns().getInitParam());
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
				WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
//		GenseeConfig.viColorSpace = AVConfig.GS_I420;
		setContentView(R.layout.player_demo_layout_ex);
		preferences = getPreferences(MODE_PRIVATE);
		initWidget();
	}

	public void initWidget() {
		topFrameLayout = (FrameLayout) findViewById(R.id.top_framelayout);
		midtabsLayout = (LinearLayout) findViewById(R.id.ly_midtabs);
		rlBottom = findViewById(R.id.top3_rl);

		relTip = (RelativeLayout) findViewById(R.id.rl_tip);
		txtTip = (TextView) findViewById(R.id.tv_tip);
		
		mBtnUser = (Button) findViewById(R.id.bnt_user);
		mBtnQa = (Button) findViewById(R.id.bnt_qa);
		mBtnDoc = (Button) findViewById(R.id.bnt_doc);
		mBtnVote = (Button) findViewById(R.id.bnt_vote);
		mBtnPublicChat = (Button) findViewById(R.id.bnt_public_chat);
		mProgressBar = (ProgressBar) findViewById(R.id.progress);
		locVideoGroup = findViewById(R.id.locVideoGroup);
		localVideoViewEx = (GSLocalVideoView) findViewById(R.id.localvideoview);
		localVideoViewEx.setOrientation(ILocalVideoView.ORIENTATION_PORTRAIT);



		mPlayer = new Player();
		mPlayer.setLocalVideoView(localVideoViewEx);
		mPlayer.registerExtension(new RoomDataEvent(this));

		mFragmentManager = getFragmentManager();

		
		mBtnUser.setOnClickListener(this);
		mBtnQa.setOnClickListener(this);
		mBtnVote.setOnClickListener(this);
		mBtnDoc.setOnClickListener(this);
		mBtnPublicChat.setOnClickListener(this);
		locVideoGroup.findViewById(R.id.btnCloseLocalVideo).setOnClickListener(this);

		videoViewNormalSize();
		//需要红包功能的话做红包初始化
		hongbaoHolder = new HongbaoHolder(this,mHandler);
		//注册hongbao，否则无法抢红包
        mPlayer.registerRedEnvelop(hongbaoHolder.getHongbao());

        //需要点赞勋章功能需要做初始化
		medalPraisHolder = new MedalPraiseHolder(this, mHandler);
		//勋章点赞句柄(对象)注册到SDK中
//		mPlayer.registerExtension(medalPraisHolder.getMedalPraise());

//		EventbuSDK eventbuSDK = new EventbuSDK();
//		eventbuSDK.setListener(new EventListener() {
//			@Override
//			public void onUnderstands(UnderStandEvent underStandEvent) {
//				GenseeLog.d(TAG,"onUnderstands " + underStandEvent);
//			}
//
//			@Override
//			public void onVotePublish(Vote vote) {
//
//			}
//
//			@Override
//			public void onVoteAnswer(Vote vote) {
//
//			}
//
//			@Override
//			public void onVoteDeadline(Vote vote) {
//
//			}
//		});
		//EventSDK句柄(对象)注册到Player中
//		mPlayer.registerExtension(eventbuSDK);

		initModule();
		join();
		GenseeLog.i(TAG, "initWidget end");

	}

	private void join(){
		joinLive(ConfigApp.getIns().getInitParam());
	}

	@Override
	protected void onResume() {
		super.onResume();
//		if (mPlayer != null && bJoinSuccess) {
//			mPlayer.audioSet(false);
//			mPlayer.videoSet(false);
//		}
	}
	
	@Override
	protected void onPause() {
		super.onPause();
//		if (mPlayer != null && bJoinSuccess) {
//			mPlayer.audioSet(true);
//			mPlayer.videoSet(true);
//		}
	}

	public void joinLive(InitParam p) {
		if (p == null) {
			return;
		}
		if (!bJoinSuccess) {
//			mProgressBar.setVisibility(View.VISIBLE);
			showTip(true, "正在玩命加入...");
			mPlayer.join(getApplicationContext(), p, this);
//			finish();
		} else {
			dialogLeave();
		}
	}

	private void initModule() {
		FragmentTransaction ft = mFragmentManager.beginTransaction();
		processChatFragment(ft);
		processQaFragment(ft);
		processVoteFragment(ft);
		processVideoFragment(ft);
		processUsersFragment(ft);
		hideFragment(ft);
		processDocFragment(ft);
		ft.commit();
	}

	private void showTip(final boolean isShow, final String tip) {
		runOnUiThread(new Runnable() {

			@Override
			public void run() {
				if (isShow) {
					if (relTip.getVisibility() != View.VISIBLE) {
						relTip.setVisibility(View.VISIBLE);
					}
					txtTip.setText(tip);
				} else {
					relTip.setVisibility(View.GONE);
				}

			}
		});
	}

	/**************************************** OnPlayListener ********************************************/
	@Override
	public void onJoin(int result) {
		String msg = null;
		switch (result) {
		case JOIN_OK:

			msg = "加入成功";
			mHandler.sendEmptyMessage(HANDlER.SUCCESSJOIN);
			break;
		case JOIN_CONNECTING:
			msg = "正在加入";
			break;
		case JOIN_CONNECT_FAILED:
			msg = "连接失败";
			break;
		case JOIN_RTMP_FAILED:
			msg = "连接服务器失败";
			break;
		case JOIN_TOO_EARLY:
			msg = "直播还未开始";
			break;
		case JOIN_LICENSE:
			msg = "人数已满";
			break;
		default:
			msg = "加入返回错误" + result;
			break;
		}
		showTip(false, "");
		toastMsg(msg);
	}

	@Override
	public void onUserJoin(UserInfo info) {
		// 用户加入
		mHandler.sendMessage(mHandler.obtainMessage(HANDlER.USERINCREASE, info));
		if (info.isMiniClassTeacher()) {
			medalPraisHolder.setTeacherInfo(info);
		} else if (info.getUserId() == mPlayer.getSelfInfo().getUserId()) {
			medalPraisHolder.setSelfId(info.getUserId());
		}
	}

	@Override
	public void onUserLeave(UserInfo info) {
		// 用户离开
		mHandler.sendMessage(mHandler.obtainMessage(HANDlER.USERDECREASE, info));
		if (info.isMiniClassTeacher()) {
			medalPraisHolder.setTeacherInfo(null);
		}
	}

	@Override
	public void onUserUpdate(UserInfo info) {
		// 用户更新
		mHandler.sendMessage(mHandler.obtainMessage(HANDlER.USERUPDATE, info));
	}

	@Override
	public void onReconnecting() {
		GenseeLog.d(TAG, "onReconnecting");
		//断线重连
		mHandler.sendEmptyMessage(HANDlER.RECONNECTING);
	}

	@Override
	public void onLeave(int reason) {
		// 当前用户退出
		// bJoinSuccess = false;
		String msg = null;
		switch (reason) {
		case LEAVE_NORMAL:
			msg = "您已经退出直播间";
			break;
		case LEAVE_KICKOUT:
			msg = "您已被踢出直播间";
			mHandler.sendEmptyMessage(HANDlER.SUCCESSLEAVE);
			break;
		case LEAVE_TIMEOUT:
			msg = "连接超时，您已经退出直播间";
			break;
		case LEAVE_CLOSE:
			msg = "直播已经停止";
			break;
		case LEAVE_UNKNOWN:
			msg = "您已退出直播间，请检查网络、直播间等状态";
			break;
		case LEAVE_RELOGIN:
			msg = "被踢出直播间（相同用户在其他设备上加入）";
			break;
		default:
			break;
		}
		if (null != msg) {
			showErrorMsg(msg);
		}
	}

	/**
	 * 缓冲变更
	 * 
	 * @param isCaching
	 *            true 缓冲/false 缓冲完成
	 */
	@Override
	public void onCaching(boolean isCaching) {
		GenseeLog.d(TAG, "onCaching isCaching = " + isCaching);
//		mHandler.sendEmptyMessage(isCaching ? HANDlER.CACHING
//				: HANDlER.CACHING_END);
		toastMsg(isCaching ? "正在缓冲" : "缓冲完成");
	}

	/**
	 * 文档切换
	 * 
	 * @param docType
	 *            文档类型（ppt、word、txt、png）
	 * @param docName
	 *            文档名称
	 */
	@Override
	public void onDocSwitch(int docType, String docName) {

	}

//	@Override
	public void outputLog(String s) {

	}


	/**
	 * 视频开始
	 */
	@Override
	public void onVideoBegin() {
		GenseeLog.d(TAG, "onVideoBegin");
		toastMsg("视频开始");
	}

	/**
	 * 视频结束
	 */
	@Override
	public void onVideoEnd() {
		GenseeLog.d(TAG, "onVideoEnd");
		toastMsg("视频已停止");
	}

	/**
	 * 音频电频值
	 */
	@Override
	public void onAudioLevel(int level) {

	}

	/**
	 * 错误响应
	 * 
	 * @param errCode
	 *            错误码 请参考文档
	 */
	@Override
	public void onErr(int errCode) {
		GenseeLog.i(TAG, "onErr code = " + errCode);
		String msg = null;
		switch (errCode) {
		case ErrCode.ERR_DOMAIN:
			msg = "域名domain不正确";
			break;
		case ErrCode.ERR_TIME_OUT:
			msg = "请求超时，稍后重试";
			break;
		case ErrCode.ERR_SITE_UNUSED:
			msg = "站点不可用，请联系客服或相关人员";
			break;
		case ErrCode.ERR_UN_NET:
			msg = "网络不可用，请检查网络连接正常后再试";
			break;
		case ErrCode.ERR_SERVICE:
			msg = "service  错误，请确认是webcast还是training";
			break;
		case ErrCode.ERR_PARAM:
			msg = "initparam参数不全";
			break;
		case ErrCode.ERR_THIRD_CERTIFICATION_AUTHORITY:
			msg = "第三方认证失败";
			break;
		case ErrCode.ERR_NUMBER_UNEXIST:
			msg = "编号不存在";
			break;
		case ErrCode.ERR_TOKEN:
			msg = "口令错误";
			break;
		case ErrCode.ERR_LOGIN:
			msg = "站点登录帐号或登录密码错误";
			break;
		default:
			msg = "错误：errCode = " + errCode;
			break;
		}
		showTip(false, "");
		if (msg != null) {
			toastMsg(msg);
		}
	}
	
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.bnt_user:
			FragmentTransaction ft = mFragmentManager.beginTransaction();
			hideFragment(ft);
			processUsersFragment(ft);
			ft.commit();
			break;
		case R.id.bnt_qa:
			FragmentTransaction ftqa = mFragmentManager.beginTransaction();
			hideFragment(ftqa);
			processQaFragment(ftqa);
			ftqa.commit();
			break;
		case R.id.bnt_vote:
			FragmentTransaction ftvote = mFragmentManager.beginTransaction();
			hideFragment(ftvote);
			processVoteFragment(ftvote);
			ftvote.commit();
			break;
		case R.id.bnt_doc:
			FragmentTransaction ftdoc = mFragmentManager.beginTransaction();
			hideFragment(ftdoc);
			processDocFragment(ftdoc);
			ftdoc.commit();
			break;
		case R.id.bnt_public_chat:
			FragmentTransaction ftChat = mFragmentManager.beginTransaction();
			hideFragment(ftChat);
			processChatFragment(ftChat);
			ftChat.commit();
			break;
		case R.id.btnCloseLocalVideo:
			close(INVITE_VIDEO);
			inviteMediaType &= ~INVITE_VIDEO;
			break;
		default:
			break;
		}
	}

	private void processVideoFragment(FragmentTransaction ft) {
		if (mViedoFragment == null) {
			mViedoFragment = new ViedoFragment(mPlayer);
			mViedoFragment.setHongBaoHolder(hongbaoHolder);
			mViedoFragment.setMedalPraiseHolder(medalPraisHolder);
			ft.add(R.id.top_framelayout, mViedoFragment);
		} else {
			ft.show(mViedoFragment);
		}
//		if (null != mViedoFragment) {
//			mViedoFragment.setVideoViewVisible(true);
//		}
	}

	
	private void processUsersFragment(FragmentTransaction ft){
		if(mUsersFragment==null){
			mUsersFragment = new UsersFragment(this);
			ft.add(R.id.fragement_update, mUsersFragment);
		}else{
			ft.show(mUsersFragment);
		}
	}
//	private void processInfoFragment(FragmentTransaction ft){
//		if(mInfoFragment==null){
//			mInfoFragment = new JoinInfoFragment();
//			ft.add(R.id.fragement_update, mInfoFragment);
//		}else{
//			ft.show(mInfoFragment);
//			mInfoFragment = new JoinInfoFragment();
//		}
//	}
	private void processQaFragment(FragmentTransaction ft) {
		if (mQaFragment == null) {
			mQaFragment = new QaFragment(mPlayer);
			ft.add(R.id.fragement_update, mQaFragment);
		} else {
			ft.show(mQaFragment);
		}
	}

	private void processVoteFragment(FragmentTransaction ft) {
		if (mVoteFragment == null) {
			mVoteFragment = new VoteFragment(mPlayer);
			ft.add(R.id.fragement_update, mVoteFragment);
		} else {
			ft.show(mVoteFragment);
		}
	}

	private void processDocFragment(FragmentTransaction ft) {
		if (mDocFragment == null) {
			mDocFragment = new DocFragment(mPlayer);
			ft.add(R.id.fragement_update, mDocFragment);
		} else {
			ft.show(mDocFragment);
		}

//		if (null != mViedoFragment) {
//			mViedoFragment.setVideoViewVisible(false);
//		}
	}

	private void processChatFragment(FragmentTransaction ft) {
		if (mChatFragment == null) {
			mChatFragment = new ChatFragment(mPlayer);
			ft.add(R.id.fragement_update, mChatFragment);
		} else {
			ft.show(mChatFragment);
		}
	}

	public void hideFragment(FragmentTransaction ft) {

		if (mUsersFragment != null) {
			ft.hide(mUsersFragment);
		}
		if (mVoteFragment != null) {
			ft.hide(mVoteFragment);
		}
		if (mChatFragment != null) {
			ft.hide(mChatFragment);
		}
		if (mQaFragment != null) {
			ft.hide(mQaFragment);
		}
		if (mDocFragment != null) {
			ft.hide(mDocFragment);
		}
//		if(mInfoFragment != null){
//			ft.hide(mInfoFragment);
//		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {

		UserInfo chatTarget = (UserInfo)parent.getAdapter().getItem(position);
//		if(chatTarget != null){
//			FragmentTransaction ft = mFragmentManager.beginTransaction();
//			hideFragment(ft);
//			if (mChatFragment == null) {
//				mChatFragment = new ChatFragment(mPlayer);
//				ft.add(R.id.fragement_update, mChatFragment);
//			} else {
//				ft.show(mChatFragment);
//			}
//
//			if (chatTarget.getUserId() == UserListAdapter.PUBLIC_CHAT_TAG) {
//				// 切换为公共聊天
//				mChatFragment.setChatPerson(null);
//			} else {
//				// 切换为与chatTarget聊天
//				mChatFragment.setChatPerson(chatTarget);
//			}
//			ft.commit();
//		}
	}

	public void exit() {
		Intent mHomeIntent = new Intent(Intent.ACTION_MAIN);
		mHomeIntent.addCategory(Intent.CATEGORY_HOME);
		mHomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
				| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
		startActivity(mHomeIntent);
	}

	protected void dialog() {

		AlertDialog.Builder builder = new Builder(PlayerDemoActivityEx.this);
		builder.setMessage("你已经被踢出");
		builder.setTitle("提示");
		builder.setPositiveButton("确认", new OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {

				dialog.dismiss();
				finish();
				// onFinshAll();
			}
		});

		AlertDialog alertDialog = builder.create();
		alertDialog.setCanceledOnTouchOutside(false);
		alertDialog.show();
	}

	public void dialogLeave() {
		AlertDialog.Builder builder = new Builder(PlayerDemoActivityEx.this);
		builder.setMessage("确定离开");
		builder.setTitle("提示");
		builder.setPositiveButton("确认", new OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {

				// release();
				dialog.dismiss();
				finish();
			}
		});
		builder.setNegativeButton("取消", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {

				// mPlayer.leave();
				// mPlayer.release();
				dialog.dismiss();
			}
		});

		AlertDialog alertDialog = builder.create();
		alertDialog.setCanceledOnTouchOutside(false);
		alertDialog.show();
	}

	@Override
	public void onBackPressed() {
		if (bJoinSuccess) {
			dialogLeave();
		} else {
			super.onBackPressed();
		}
	}

	@Override
	protected void onDestroy() {
		stopLogService();
		releasePlayer();
		// onFinshAll();
		super.onDestroy();
	}

	private void releasePlayer() {
		cancelTimer();
		if (null != mPlayer && bJoinSuccess) {
			mPlayer.leave();
			bJoinSuccess = false;
		}
        mPlayer.release();
	}

	private void showErrorMsg(final String sMsg) {
		runOnUiThread(new Runnable() {

			@Override
			public void run() {
				AlertDialog.Builder builder = new Builder(
						PlayerDemoActivityEx.this);
				builder.setTitle("提示");
				builder.setMessage(sMsg);
				builder.setPositiveButton("确认", new OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {

						dialog.dismiss();
						finish();
					}
				});

				AlertDialog alertDialog = builder.create();
				alertDialog.setCanceledOnTouchOutside(false);
				alertDialog.show();
			}
		});

	}

	public void toastMsg(final String msg) {
		if (msg != null) {
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					Toast.makeText(getApplicationContext(), msg,
							Toast.LENGTH_SHORT).show();
				}
			});
		}
	}


	private void startLogService() {
		serviceIntent = new Intent(this, LogCatService.class);
		startService(serviceIntent);
	}

	private void stopLogService() {
		if (null != serviceIntent) {
			stopService(serviceIntent);
		}
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
			localVideoViewEx.setOrientation(ILocalVideoView.ORIENTATION_LANDSCAPE);
			videoFullScreen();
			updateLocalVideoViewSize(true);
		} else {
			localVideoViewEx.setOrientation(ILocalVideoView.ORIENTATION_PORTRAIT);
			updateLocalVideoViewSize(false);
			videoNormalScreen();
		}
	}

	private void videoFullScreen() {
		mDocFragment.showView(false);
		LayoutParams p = topFrameLayout.getLayoutParams();
		p.height = LayoutParams.MATCH_PARENT;
		topFrameLayout.setLayoutParams(p);
		rlBottom.setVisibility(View.GONE);
		midtabsLayout.setVisibility(View.GONE);
	}

	private void videoViewNormalSize(){
		LayoutParams p = topFrameLayout.getLayoutParams();
		p.height = getResources().getDisplayMetrics().widthPixels * videoHeight/ videoWidth;
		topFrameLayout.setLayoutParams(p);
	}
	
	private void videoNormalScreen() {
		mDocFragment.showView(true);
		videoViewNormalSize();
		rlBottom.setVisibility(View.VISIBLE);
		midtabsLayout.setVisibility(View.VISIBLE);
	}

	@Override
	public void onPublish(boolean isPlaying) {
		toastMsg(isPlaying ? "直播（上课）中" : "直播暂停（下课）");
	}

	@Override
	public void onPageSize(int pos, int w, int h) {
		//文档开始显示
		toastMsg("文档分辨率 w = " + w + " h = " + h);
	}

	/**
	 * 直播主题
	 */
	@Override
	public void onSubject(String subject) {
		GenseeLog.d(TAG, "onSubject subject = " + subject);

	}

	/**
	 * 在线人数
	 * 
	 * @param total
	 */
	public void onRosterTotal(int total) {
		GenseeLog.d(TAG, "onRosterTotal total = " + total);
	}

	/**
	 * 系统广播消息
	 */
	@Override
	public void onPublicMsg(BroadCastMsg msg) {
		String content = msg.getContent();//广播消息内容
		long senderId = msg.getSenderId();//发送者用户id
		long time = msg.getTime();//基于1970的秒数，直接fomat为指定格式
		String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH).format(new Date(time*1000));
		GenseeLog.d(TAG, "广播消息："+date +" "+ msg);
		toastMsg("广播消息："+ date + " senderId = " + senderId + " 内容 = " + content);
	}

	// int INVITE_AUIDO = 1;//only audio
	// int INVITE_VIDEO = 2;//only video
	// int INVITE_MUTI = 3;//both audio and video
	@Override
	public void onInvite(final int type,final boolean isOpen) {
		runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				postInvite(type, isOpen);
			}
		});
	}
	private void postInvite(final int type, boolean isOpen){
		if (isOpen) {
			if ((inviteMediaType & type) == type) {
				GenseeLog.w("postInvite two times same type = " + type
						+ " isOpen = " + isOpen);
				return;
			}
			String media = "音频";
			if ((type & INVITE_AUIDO) == INVITE_AUIDO) {
				media = "音频";
				if (audioDialog == null) {
					audioDialog = new AlertDialog.Builder(this)
							.setPositiveButton("接受",
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											accept(type, true);
											inviteMediaType |= INVITE_AUIDO;
											dialogAudioDismiss();
										}
									})
							.setNegativeButton("拒绝",
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											accept(type, false);
											inviteMediaType &= ~INVITE_AUIDO;
											dialogAudioDismiss();
										}
									}).create();
				}
				audioDialog.setMessage("老师邀请你打开" + media);
				audioDialog.show();
			}
			if ((type&INVITE_VIDEO) == INVITE_VIDEO) {
				media = "视频";
				if (videoDialog == null) {
					videoDialog = new AlertDialog.Builder(this)
							.setPositiveButton("接受",
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											accept(type, true);
											inviteMediaType |= INVITE_VIDEO;
											dialogVideoDismiss();
										}
									})
							.setNegativeButton("拒绝",
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											accept(type, false);
											inviteMediaType &= ~INVITE_VIDEO;
											dialogVideoDismiss();
										}
									}).create();
				}
				videoDialog.setMessage("老师邀请你打开" + media);
				videoDialog.show();
			}
		} else {
			if ((type & INVITE_AUIDO) == INVITE_AUIDO) {
				dialogAudioDismiss();
			}
			if ((type&INVITE_VIDEO) == INVITE_VIDEO) {
				dialogVideoDismiss();
			}
			close(type);
			inviteMediaType &= ~type;
		}
	}

	private void close(int type) {
		// 关闭时，不需要响应inviteAck
		// 接受的处理
		if (type == INVITE_AUIDO) {
			acceptOpenMic(false);
		} else if (type == INVITE_VIDEO) {
			locVideoGroup.setVisibility(View.GONE);
			acceptOpenCamera(false);
		} else if (type == INVITE_MUTI) {
			acceptOpenMic(false);
			locVideoGroup.setVisibility(View.GONE);
			acceptOpenCamera(false);
		} else {
			GenseeLog.d("close invalid type = " + type);
		}
	}
	
	private void accept(int type, boolean isAccept) {
		// 邀请应答回应
		mPlayer.inviteAck(type, isAccept, null);

		// 根据不同类型邀请做相应的操作
		if (isAccept) {
			if (type == INVITE_AUIDO) {
				// 接受语音邀请情况下打开mic
				acceptOpenMic(true);
			} else if (type == INVITE_VIDEO) {
				// 接受视频邀请情况下打开本地视频，并把本地预览view显示出来
				locVideoGroup.setVisibility(View.VISIBLE);
				updateLocalVideoViewSize(getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
				acceptOpenCamera(true);
			} else if (type == INVITE_MUTI) {
				locVideoGroup.setVisibility(View.VISIBLE);
				acceptOpenMic(true);
				acceptOpenCamera(true);
				updateLocalVideoViewSize(getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
			}
		}
	}
	
	private void updateLocalVideoViewSize(boolean isLand) {
		RelativeLayout.LayoutParams p = (RelativeLayout.LayoutParams) localVideoViewEx
				.getLayoutParams();
		if (isLand) {
			p.height = p.width * 3 / 4;
			p.topMargin = 0;
			p.bottomMargin = 0;

		} else {
			p.height = p.width * 4 / 3;
			p.topMargin = (p.width - p.height) / 2;
			p.bottomMargin = (p.width - p.height) / 2;
		}
		localVideoViewEx.setLayoutParams(p);
	}


	private void acceptOpenMic(boolean isAccept) {
		mPlayer.openMic(this, isAccept, null);
	}

	private void micVolume(boolean isAccept){
		//需要显示本地mic音量大小的情况下，参考如下代码，定时调用mPlayer.getAudioLevel()获取大小并刷新UI，建议不要在主线程调用，避免界面卡顿
		if (isAccept) {
			timer = new Timer();
			timer.schedule(new TimerTask() {
				@Override
				public void run() {
					//获得大小  刷新ui 大小为0-10区间，也就是有10个档位，请根据实际需求来换算成对应的界面上的档位。
					int level = mPlayer.getAudioLevel();
//					GenseeLog.d(TAG, "micVolume audio level " + level);
				}
			}, 0, 500);
		} else {
			cancelTimer();
		}
	}
	private void cancelTimer(){
		if (timer != null) {
			timer.cancel();
			timer = null;
		}
	}
	private void acceptOpenCamera(boolean isAccept) {
		mPlayer.openCamera(this, isAccept, null);
		// VideoParam p = new VideoParam(1280,720 , 15, 1);
		// localVideoViewEx.open(p, VideoActivity.this);
	}

	private void dialogAudioDismiss() {
		if (null != audioDialog) {
			audioDialog.dismiss();
			audioDialog = null;
		}
	}

	private void dialogVideoDismiss() {
		if (null != videoDialog) {
			videoDialog.dismiss();
			videoDialog = null;
		}
	}

	@Override
	public void onMicNotify(int notify) {
		GenseeLog.d(TAG, "onMicNotify notify = " + notify);
		switch (notify) {
		case MicNotify.MIC_COLSED:
			runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					mViedoFragment.onMicColesed();
//					micVolume(false);
				}
			});
			mPlayer.inviteAck(INVITE_AUIDO, false, null);
			break;
		case MicNotify.MIC_OPENED:
			runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					mViedoFragment.onMicOpened(INVITE_AUIDO);
//					micVolume(true);
				}
			});
			break;
		case MicNotify.MIC_OPEN_FAILED:
			runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					toastMsg("麦克风打开失败，请重试并允许程序打开麦克风");
				}
			});
			mPlayer.openMic(this, false, null);
			mPlayer.inviteAck(INVITE_AUIDO, false, null);
			break;
		default:
			break;
		}
	}

	@Override
	public void onLiveText(String language, String text) {
		toastMsg("文字直播\n语言：" + language + "\n内容：" + text);
	}

	@Override
	public void onLottery(int cmd, String info) {
		//cmd 1:start, 2: stop, 3: abort
		toastMsg("抽奖\n指令：" + (cmd == 1 ? "开始" : (cmd == 2 ? "结束" : "取消"))
				+ "\n结果：" + info);
	}

	@Override
	public void onRollcall(final int timeOut) {
		mHandler.post(new Runnable() {
			private AlertDialog dialog = null;
			private int itimeOut;
			
			private void rollcallAck(final boolean isAccept){
				mHandler.removeCallbacks(this);
				mPlayer.rollCallAck(isAccept, new OnTaskRet() {
					
					@Override
					public void onTaskRet(boolean arg0, int arg1, String arg2) {
						toastMsg(arg0 ? (isAccept ? "本次签到成功" : "您本次未签到") : "操作失败");
					}
				});
			}
			
			@Override
			public void run() {
				if(dialog == null){
					this.itimeOut = timeOut;
					dialog = new AlertDialog.Builder(PlayerDemoActivityEx.this).setMessage("").setPositiveButton("签到", new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							rollcallAck(true);
						}
					}).setCancelable(false).create();
					dialog.show();
				}
				dialog.setMessage("点名倒计时剩余秒数：" + itimeOut);
				itimeOut --;
				if (itimeOut < 0) {
					dialog.dismiss();
					rollcallAck(false);//超时应答false
				} else {
					mHandler.postDelayed(this, 1000);
				}
			}
		});
		
	}
	
	@Override
	public void onFileShare(int cmd,String fileName,String fileUrl) {
		//cmd:1:add, 2: remove
		//TODO 应用层根据需要进行界面显示后可以调用  player的
	}

	@Override
	public void onFileShareDl(int ret,String fileUrl,String filePath) {
		
	}

	@Override
	public void onVideoSize(int width, int height, boolean iaAs) {
		GenseeLog.d(TAG, "onVideoSize");
		toastMsg("onVideoSize width = " +  width +  " height = " + height + " isAs = " + iaAs);
		//如果明确视频尺寸比例，或中途不会变化，初始化确定好比例，可以不用这段代码
		if(videoHeight != height || videoWidth != width){
			videoHeight = height;
			videoWidth = width;
			mHandler.post(new Runnable() {
				
				@Override
				public void run() {
					int orientation = getRequestedOrientation();
					if (orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT
							|| orientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT){
						videoViewNormalSize();
					}
				}
			});
		}
	}

	/**
	 * 播放器布局变更，组织者切换设置选项中的web布局
	 * 0 //文档为主
	 * 1 //视频最大化
	 * 2 //文档最大化
	 * 3 //视频为主
	 * @param layout 变更后的类型
	 */
	@Override
	public void onModuleFocus(int layout) {
		String msg = "文档为主";
		switch (layout){
			case 0:
				msg = "文档为主";
				break;
			case 1:
				msg = "视频最大化";
				break;
			case 2:
				msg = "文档最大化";
				break;
			case 3:
				msg = "视频为主";
				break;
		}
		toastMsg("布局变更为：" + msg);
	}

	@Override
	public void onScreenStatus(boolean isAs) {
		toastMsg("onScreenStatus isAs = " + isAs);
	}

	@Override
	public void onIdcList(List<PingEntity> arg0) {
		mViedoFragment.onIdcList(arg0);
	}

	@Override
	public void onCameraNotify(int notify) {
		// TODO Auto-generated method stub
	}

	@Override
	public void onGotoPay(PayInfo info) {
		//用info.getOrderInfo()作为支付参数调用支付宝进行支付流程;
	}

	/**
	 * 红包和打赏信息的回调
	 * @param result 回到信息
	 */
	@Override
	public void onRedBagTip(final RewardResult result) {
		GenseeLog.d(TAG, "onRedBagTip " + result);
	}




	@Override
	public void onRewordEnable(boolean arg0, boolean arg1) {
		// TODO Auto-generated method stub
	}

	@Override
	public void onThirdVote(String url) {
		toastMsg("第三方投票："+url);
	}

	@Override
	public void onGetUserInfo(UserInfo[] arg0) {
		// TODO Auto-generated method stub
	}

	@Override
	public void onVideoDataNotify() {
		// TODO Auto-generated method stub
	}

	@Override
	public void onLiveInfo(LiveInfo info) {
		// TODO Auto-generated method stub
	}

    @Override
    public void onHongbaoEnable(boolean enable) {
        if(mViedoFragment != null){
            mViedoFragment.showHongbaoButton(enable);
        }
    }

	@Override
    public void onDoubleTeacherStatusChange(int i) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mUsersFragment != null) {
                    mUsersFragment.cleanUsers();
                }
            }
        });
        //TODO
        toastMsg("正在切换到" + (i == 0 ? "分课" : "总课"));
    }

	@Override
	public void onAutoSwitchIdcSuccess() {

	}

	@Override
	public void onCdnEnable(String s, String[] strings) {

	}

	@Override
	public void onPlayerType(PlayerType playerType) {

	}

	@Override
	public void onRoomData(String key, String value) {
		GenseeLog.d(TAG,"onRoomData key = " + key + " value = " + value);
		if (SCREEN_LOCK.equals(key)){
			mHandler.postDelayed(new Runnable() {
				@Override
				public void run() {
					toastMsg("1".equals(value)?"老师已开启锁屏功能":"老师已关闭锁屏功能");
				}
			},2000);
		}
	}
}
