package com.gensee.rtdemo;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.gensee.callback.IMedalPraiseCallback;
import com.gensee.common.RTConstant;
import com.gensee.common.RTSharedPref;
import com.gensee.demo.DemoConfig;
import com.gensee.demo.R;
import com.gensee.media.IVideoIndication;
import com.gensee.net.RtComp;
import com.gensee.praise.PraiseInfo;
import com.gensee.praise.PraiseUserInfo;
import com.gensee.room.RtSimpleImpl;
import com.gensee.routine.IRTEvent;
import com.gensee.routine.UserInfo;
import com.gensee.utils.GenseeLog;
import com.gensee.view.ILocalVideoView;
import com.gensee.view.beauty.GSLocalVideoView;

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

/**
 * Created by pc on 2018/4/2.
 */

public class SmallClassActivity extends Activity implements RtComp.Callback,IMedalPraiseCallback {
    private static final java.lang.String TAG = "SmallClassActivity";
    public final static String PraiseType_Faour = "favour";
    public final static String PraiseType_Medal = "medal";
    private RtSimpleImpl simpleImpl;
    private Button btnJoin;
    private UserInfo self,teacher;
    private RtComp comp;
    private Button btnLeave;
    private IVideoIndication liveVideoView;
    private GSLocalVideoView localVideoView;
    private Map<String, Long> roomData;
    private boolean isCameraOpen;
    private boolean isMicOpen;
    private boolean bInitHostJoin;
    private RelativeLayout localVideoViewRl;
    private RelativeLayout.LayoutParams portraitLayoutParams;

    private boolean isMedalEnable,isFavourEnable;
    private TextView txtMedal,txtFaour,txtRankingList;

    private void initViews() {
        btnJoin = (Button) findViewById(R.id.btnJoin);
        btnJoin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                btnJoin.setEnabled(false);
                btnJoin.setText("正在加入。。。");
                comp = new RtComp(getApplicationContext(),
                        SmallClassActivity.this);
//				comp.setbAttendeeOnly(true);
                comp.initWithGensee(DemoConfig.getIns().getInitParam());
            }
        });
        btnLeave = (Button) findViewById(R.id.btnLeave);
        btnLeave.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                leaveCast();
            }
        });
        //设置视频View
        liveVideoView = (IVideoIndication) findViewById(R.id.liveVideoView);
        simpleImpl.setVideoView(liveVideoView);
        localVideoViewRl = (RelativeLayout) findViewById(R.id.localVideoViewRl);
        //设置本地视频view
        localVideoView = (GSLocalVideoView)findViewById(R.id.localVideoView);
        localVideoView.setOrientation(ILocalVideoView.ORIENTATION_PORTRAIT_16_9);
        findViewById(R.id.btnCloseVideo).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                videoCloseCamera();
            }
        });
        findViewById(R.id.btnCloseAudio).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                audioCloseMic();
            }
        });
        txtMedal = (TextView) findViewById(R.id.medal);//老师角色时，代表可发勋章数量和发勋章事件，非老师角色时代表收到的勋章数量
        txtMedal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(self.isHost()){//TODO 是老师的话，可以选择发勋章给某个学生
                    final List<UserInfo> userList = simpleImpl.getRtSdk().getAllUsers();
                    new AlertDialog.Builder(SmallClassActivity.this).setSingleChoiceItems(new BaseAdapter() {
                        @Override
                        public int getCount() {
                            return userList == null?0:userList.size();
                        }

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

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

                        @Override
                        public View getView(int position, View convertView, ViewGroup parent) {
                            TextView view;
                            if(convertView == null){
                                view = new TextView(SmallClassActivity.this);
                            }else {
                                view = (TextView) convertView;
                            }
                            view.setText(((UserInfo)getItem(position)).getName());
                            return view;
                        }
                    },0, new DialogInterface.OnClickListener(){
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            UserInfo selectedUser = userList.get(which);
                            if(!selectedUser.isHost())//勋章是老师发给其他人，不能发给自己
                            {
                                simpleImpl.getRtSdk().sendPraise(IMedalPraiseCallback.TYPE_MEDAL,selectedUser.getId(),selectedUser.getName(),"很认真，很好",null);

                            }
                            dialog.dismiss();

                        }
                    }).setTitle("选择").create().show();
                }
            }
        });
        txtFaour = (TextView)findViewById(R.id.faour);//老师角色时，代表收到点赞的数量，非老师代表可点数量和事件
        txtFaour.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!self.isHost()&&teacher!= null){//TODO 不是老师且老师已经加入的话，可以给老师点赞
                    simpleImpl.getRtSdk().sendPraise(IMedalPraiseCallback.TYPE_FAOUR, teacher.getId(),teacher.getName(),"",null);
                }

            }
        });
        txtRankingList = (TextView) findViewById(R.id.rankingList);
        txtRankingList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //获取  勋章获得排行榜top10
                simpleImpl.getRtSdk().getPraiseRecvList(IMedalPraiseCallback.TYPE_MEDAL,10,null);
            }
        });
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_smallclass);
        PrefUtil.initPref(this);
        roomData = new HashMap<String, Long>();
        initRoomData();
        simpleImpl = new RtSimpleImpl(){
            /**
             * 上下讲台,上下提问席等房间状态变化.
             * 需要在这里做打开摄像头/麦克风等操作
             * @param key 用户状态
             * @param value 用户id
             */
            @Override
            public void onRoomData(String key, long value) {
                GenseeLog.d(TAG, "onRoomData key = " + key + "value = " + value);
                if (!bInitHostJoin) {
                    dispatchRoomData(key, value);
                }else{
                    //其他人上讲台
                    if (RTConstant.RTRoomDataKey.KEY_USER_ROSTRUM.equals(key))
                    {
                        if(null != self && (roomData.get(RTConstant.RTRoomDataKey.KEY_USER_ROSTRUM) == self.getId()) && (self.getId() != value))
                        {
                            //组织者不在讲台上
                            roomData.put(key, value);
                        }
                    }
                }

                roomData.put(key, value);
            }

            @Override
            public void onJoin(boolean b) {

            }

            @Override
            public void onRoomUserJoin(UserInfo userInfo) {
                if(userInfo.isHost()){//老师加入
                    teacher = userInfo;
                }
                super.onRoomUserJoin(userInfo);
            }

            @Override
            public void onRoomUserLeave(UserInfo userInfo) {
                if(userInfo.equals(teacher)){//老师退出
                    teacher = null;
                }
                super.onRoomUserLeave(userInfo);
            }

            @Override
            public Context onGetContext() {
                return getBaseContext();
            }

            @Override
            public void onVideoJoin(UserInfo user) {
                GenseeLog.d(TAG, "onVideoJoin() called with: user = [" + user + "]");
                super.onVideoJoin(user);
                boolean bSelfActived = PrefUtil.getIns().getInt(PrefUtil.VIDEO_SELF_ACTIVED) == 1;
                if(null != self && self.getId() == user.getId() && bSelfActived)
                {
                    GenseeLog.d(TAG, "onVideoJoin bSelfActived = " + bSelfActived );
                    simpleImpl.getRtSdk().videoActive(self.getId(), bSelfActived, null);
                    onVideoActived(user,bSelfActived);
                }
            }

            @Override
            public void onVideoActived(UserInfo user, boolean bActived) {
                GenseeLog.d(TAG, "onVideoActived() called with: user = [" + user + "], bActived = [" + bActived + "]");
                super.onVideoActived(user, bActived);
                if(null != self && !bInitHostJoin)
                {
                    //观看端当前的直播视频是自己
                    if(self.getId() == user.getId())
                    {
                        //自己的直播视频状态
                        PrefUtil.getIns().putInt(PrefUtil.VIDEO_SELF_ACTIVED, bActived ? 1 : 0);
                        if(bActived && !isCameraOpen)
                        {
                            return;
                        }
                    }
                    else if((self.getId() != user.getId() && bActived))
                    {
                        //其他人设置为直播视频 && 自己是直播视频的时候
                        boolean bSelfActived = PrefUtil.getIns().getInt(PrefUtil.VIDEO_SELF_ACTIVED) == 1;
                        if(bSelfActived) {
                            PrefUtil.getIns().putInt(PrefUtil.VIDEO_SELF_ACTIVED, 0);
                        }
                    }
                }
            }

            @Override
            protected void onVideoStart() {}

            @Override
            protected void onVideoEnd() {}

            @Override
            public void onVideoCameraOpened() {
                isCameraOpen = true;
                ToastOnUiThread("摄像头打开");
                processLocalViewSize();
            }

            @Override
            public void onVideoCameraClosed() {
                isCameraOpen = false;
                ToastOnUiThread("摄像头关闭");
            }

            @Override
            public void onAudioMicOpened() {
                isMicOpen = true;
                ToastOnUiThread("麦克风打开");
            }

            @Override
            public void onAudioMicClosed() {
                isMicOpen = false;
                ToastOnUiThread("麦克风关闭");
            }

            @Override
            public void onSettingSet(String key, int val) {
                //勋章功能是否开启
                if(RTSharedPref.KEY_MEDAL_ENABLE.equals(key)){
                    isMedalEnable = val != 0;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            txtMedal.setVisibility(isMedalEnable?View.VISIBLE:View.INVISIBLE);
                            txtRankingList.setVisibility(isMedalEnable?View.VISIBLE:View.GONE);

                        }
                    });
                }
                //点赞功能是否开启
                else if(RTSharedPref.KEY_FAVOUR_ENABLE.equals(key)){
                    isFavourEnable = val != 0;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            txtFaour.setVisibility(isFavourEnable?View.VISIBLE:View.INVISIBLE);
                        }
                    });
                }
            }

            @Override
            public void onRoomClassReuninCmd() {
                //切到主课堂
                simpleImpl.getRtSdk().switchRoomToMainClass();
            }

            @Override
            public void onRoomClassSeparateCmd() {
                //切到主课堂
                simpleImpl.getRtSdk().switchRoomToSubClass();
            }

            /**
             * result 0 表示加入房间（直播间、会议室、课堂）成功  其他代表加入失败  失败后最好以对话框通知用户本次操作失败了
             */
            @Override
            public void onRoomJoin(final int result, UserInfo self, boolean svrFailover) {
                super.onRoomJoin(result, self,svrFailover);
                GenseeLog.d(TAG, "onRoomJoin() called with: result = [" + result + "], self = [" + self + "], svrFailover = [" + svrFailover + "]");
                if (result == 0) {
                    simpleImpl.getRtSdk().setLocalVideoView(localVideoView);
                    SmallClassActivity.this.self = self;
                    bInitHostJoin = null != self && self.IsHost();
                    if(self.isHost())
                    {//组织者自己上讲台
                        getRtSdk().roomSetData(RTConstant.RTRoomDataKey.KEY_USER_ROSTRUM, self.getId(),null);
                    }
                    //如果有勋章点赞的需求，才初始化点赞和勋章
                    if (isFavourEnable || isMedalEnable) {
                        //-1为取默认值，-2代表不初始化该功能
                        simpleImpl.getRtSdk().initMedalPraise(SmallClassActivity.this, isMedalEnable ? -1 : -2, isFavourEnable ? -1 : -2);
                    }
//
//                    simpleImpl.getRtSdk().getPraiseTotal(MedalPraise.PraiseType_Faour,null);
//                    simpleImpl.getRtSdk().getPraiseTotal(MedalPraise.PraiseType_Medal,null);
//
//                    simpleImpl.getRtSdk().getPraiseRecvList(MedalPraise.PraiseType_Faour,100,null);
//                    simpleImpl.getRtSdk().getPraiseRecvList(MedalPraise.PraiseType_Medal,100,null);


                }

                runOnUiThread(new Runnable() {
                    public void run() {
                        String resultDesc = null;
                        switch (result) {
                            //加入成功  除了成功其他均需要正常提示给用户
                            case IRTEvent.IRoomEvent.JoinResult.JR_OK:
                                btnJoin.setText("已加入");
                                AlertUtil.toast(SmallClassActivity.this, "您已加入成功");
                                break;
                            //加入错误
                            case IRTEvent.IRoomEvent.JoinResult.JR_ERROR:
                                resultDesc = "加入失败，重试或联系管理员";
                                break;
                            //课堂被锁定
                            case IRTEvent.IRoomEvent.JoinResult.JR_ERROR_LOCKED:
                                resultDesc = "直播间已被锁定";
                                break;
                            //老师（组织者已经加入）
                            case IRTEvent.IRoomEvent.JoinResult.JR_ERROR_HOST:
                                resultDesc = "老师已经加入，请以其他身份加入";
                                break;
                            //加入人数已满
                            case IRTEvent.IRoomEvent.JoinResult.JR_ERROR_LICENSE:
                                resultDesc = "人数已满，联系管理员";
                                break;
                            //音视频编码不匹配
                            case IRTEvent.IRoomEvent.JoinResult.JR_ERROR_CODEC:
                                resultDesc = "编码不匹配";
                                break;
                            //超时
                            case IRTEvent.IRoomEvent.JoinResult.JR_ERROR_TIMESUP:
                                resultDesc = "已经超过直播结束时间";
                                break;
                            default:
                                resultDesc = "其他结果码：" + result + "联系管理员";
                                break;
                        }
                        if(resultDesc != null){
                            AlertUtil.showDialog(SmallClassActivity.this, resultDesc, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    leave(false);
                                }
                            }, null);
                        }
                    }
                });
            }

            //退出完成 关闭界面
            @Override
            protected void onRelease(final int reason) {
                if(null != self)
                {
                    if(isSelfOnAsker())
                    {
                        String selfAskerId = getAskerIdByUserId(self.getId());
                        if(!"".equals(selfAskerId))
                        {//下提问席
                            getRtSdk().roomSetData(selfAskerId, 0, null);
                        }
                    }
                    if(roomData.get(RTConstant.RTRoomDataKey.KEY_USER_ROSTRUM) == self.getId())
                    {//下讲台
                        getRtSdk().roomSetData(RTConstant.RTRoomDataKey.KEY_USER_ROSTRUM, 0, null);
                    }
                }
                initRoomData();
                //reason 退出原因
                runOnUiThread(new Runnable() {
                    @SuppressLint("NewApi")
                    @Override
                    public void run() {
                        String msg = "已退出";
                        switch (reason) {
                            //用户自行退出  正常退出
                            case IRTEvent.IRoomEvent.LeaveReason.LR_NORMAL:
                                msg = "您已经成功退出";
                                break;
                            //LR_EJECTED = LR_NORMAL + 1; //被踢出
                            case IRTEvent.IRoomEvent.LeaveReason.LR_EJECTED:
                                msg = "您已被踢出";
                                break;
                            //LR_TIMESUP = LR_NORMAL + 2; //时间到
                            case IRTEvent.IRoomEvent.LeaveReason.LR_TIMESUP:
                                msg = "时间已过";
                                break;
                            //LR_CLOSED = LR_NORMAL + 3; //直播（课堂）已经结束（被组织者结束）
                            case IRTEvent.IRoomEvent.LeaveReason.LR_CLOSED:
                                msg = "直播间已经被关闭";
                                break;

                            default:
                                break;
                        }
                        if (isDestroyed()) {
                            return;
                        }
                        //这里可以弹出对话框，确定后在关闭界面
                        AlertUtil.showDialog(SmallClassActivity.this, msg, new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                //确认关闭界面
                                finish();
                            }
                        }, null);
                    }
                });
            }
        };

        initViews();
    }

    private void processLocalViewSize() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                DisplayMetrics mDisplayMetrics = new DisplayMetrics();
                getWindowManager().getDefaultDisplay().getMetrics(mDisplayMetrics);
                int screenWidth = mDisplayMetrics.heightPixels;
                screenWidth = (int) (screenWidth * 3/10);
                int modWidth = screenWidth % 16;
                if(modWidth > 0) {
                    screenWidth = screenWidth + (16 - modWidth);
                }
                int nHeigth = screenWidth  * 9 / 16;
                RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams)localVideoViewRl.getLayoutParams();
                lp.width = screenWidth;
                lp.height = nHeigth;
                localVideoViewRl.setLayoutParams(lp);

                portraitLayoutParams = new RelativeLayout.LayoutParams(localVideoView.getLayoutParams());
                portraitLayoutParams .width = screenWidth;
                int needHeight = portraitLayoutParams .width  * 4 / 3;
                int margin = (needHeight - nHeigth) / 2;
                portraitLayoutParams.height = needHeight;
                portraitLayoutParams.topMargin = -margin;
                portraitLayoutParams.bottomMargin = -margin;
                portraitLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, 1);
                localVideoView .setLayoutParams(portraitLayoutParams);
            }
        });


    }

    /**
     * 在这里处理教室中状态变化
     * @param key 用户状态,上下讲台/提问席
     * @param value 用户id
     */
    private void dispatchRoomData(String key, long value) {
        //讲台
        if (RTConstant.RTRoomDataKey.KEY_USER_ROSTRUM.equals(key)){
            if (value == 0) {
                if(isSelfOnRostrum() &&  !isSelfOnAsker())
                {
                    audioCloseMic();
                    videoCloseCamera();
                }
            } else {
                //自己上讲台了
                if (self != null && value == self.getId()) {
                    ToastOnUiThread("上讲台");
                    if(roomData.get(RTConstant.RTRoomDataKey.KEY_USER_ASKER) == value //在提问席1
                            || roomData.get(RTConstant.RTRoomDataKey.KEY_USER_ASKER_1) == value //在提问席2
                            || roomData.get(RTConstant.RTRoomDataKey.KEY_USER_ASKER_2) == value //在提问席3
                            || roomData.get(RTConstant.RTRoomDataKey.KEY_USER_ASKER_3) == value) //在提问席4
                    {
                        String askeIdx = getAskerIdByUserId(value);
                        if(!"".equals(askeIdx))
                        {//原来在提问席,现在上讲台了,将原来提问席的自己清除
                            simpleImpl.getRtSdk().roomSetData(askeIdx, 0, null);
                        }
                    }

                    simpleImpl.getRtSdk().roomHanddown(false, null);
                    if(!isMicOpen)
                    {
                        if(roomData.get(RTConstant.RTRoomDataKey.KEY_USER_ROSTRUM) == self.getId() && PrefUtil.getIns().getInt(PrefUtil.MIC_STATUS) != 1)
                        {
                            return;
                        }
                        audioOpenMic();
                    }
                    if (!isCameraOpen)
                    {
                        if(roomData.get(RTConstant.RTRoomDataKey.KEY_USER_ROSTRUM) == self.getId() && PrefUtil.getIns().getInt(PrefUtil.CAMERA_STATUS) != 1)
                        {
                            return;
                        }
                        //将VIDEO_SELF_ACTIVED标志置为直播视频状态，onVideoJoin的时候调用videoActived
                        PrefUtil.getIns().putInt(PrefUtil.VIDEO_SELF_ACTIVED, 1);
                        videoOpenCamera();
                    }
                    else
                    {
                        GenseeLog.i(TAG,"KEY_USER_ROSTRUM self videoActive true");
                        simpleImpl.getRtSdk().videoActive(self.getId(), true, null);
                    }
                }else{
                    //其他人上讲台
                    if(null != self && roomData.get(RTConstant.RTRoomDataKey.KEY_USER_ROSTRUM) == self.getId() && self.getId() != value)
                    {
                        simpleImpl.getRtSdk().audioCloseMic(null);
                        videoCloseCamera();
                    }

                }
            }
        } else if (RTConstant.RTRoomDataKey.KEY_USER_ASKER.equals(key)
                    || RTConstant.RTRoomDataKey.KEY_USER_ASKER_1.equals(key)
                    || RTConstant.RTRoomDataKey.KEY_USER_ASKER_2.equals(key)
                    || RTConstant.RTRoomDataKey.KEY_USER_ASKER_3.equals(key)) {

                if (value == 0) {
                    if (roomData.get(key) == self.getId() && roomData.get(RTConstant.RTRoomDataKey.KEY_USER_ROSTRUM) != self.getId()) {
                        //下提问席 且 自己不在讲台上
                        simpleImpl.getRtSdk().audioCloseMic(null);
                        videoCloseCamera();
                        ToastOnUiThread("下提问席");
                    }
                } else if (value == self.getId()) {
                    //上提问席
                    ToastOnUiThread("上提问席");
                    if(roomData.get(RTConstant.RTRoomDataKey.KEY_USER_ROSTRUM) == value)
                    {
                        //如果自己在讲台,先下讲台
//					videoCloseCamera();
//					audioCloseMic();
                        simpleImpl.getRtSdk().roomSetData(RTConstant.RTRoomDataKey.KEY_USER_ROSTRUM, 0, null);
                    }
                    if(!isMicOpen)
                    {
                        if(isSelfOnAsker() && PrefUtil.getIns().getInt(PrefUtil.MIC_STATUS) != 1)
                        {
                            return;
                        }
                        audioOpenMic();
                    }
                    if (!isCameraOpen)
                    {
                        if(isSelfOnAsker() && PrefUtil.getIns().getInt(PrefUtil.CAMERA_STATUS) != 1)
                        {
                            return;
                        }
                        videoOpenCamera();
                    }
                    else
                    {
                        if(null != self && self.getId() == simpleImpl.getVideoActiveId())
                        {
                            simpleImpl.getRtSdk().videoActive(self.getId(), false, null);
                        }
                    }
                    simpleImpl.getRtSdk().roomHanddown(false, null);
                }
                else
                {
                    if(value != self.getId() && roomData.get(key) == self.getId())
                    {
                        //提问席上被人替换
                        simpleImpl.getRtSdk().audioCloseMic(null);
                        videoCloseCamera();
                    }
                }
            }
    }

    private void ToastOnUiThread(final String s) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(SmallClassActivity.this, s, Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void audioCloseMic() {
        GenseeLog.d(TAG, "audioCloseMic() called");
        simpleImpl.getRtSdk().audioCloseMic(null);
    }

    public void audioOpenMic() {
        GenseeLog.d(TAG, "audioOpenMic() called");
        if (!isMicOpen) {
            simpleImpl.getRtSdk().audioOpenMic(null);
        }
    }

    private void videoCloseCamera() {
        GenseeLog.d(TAG, "videoCloseCamera() called");
        simpleImpl.getRtSdk().videoCloseCamera(null);
    }

    private void videoOpenCamera() {
        GenseeLog.d(TAG, "videoOpenCamera() called");
        if (!isCameraOpen) {
            //cancelCurrentVideoActiveId();
            simpleImpl.getRtSdk().videoOpenCamera(null);
        }
    }

    /**
     * 自己是否在提问席
     * @return
     */
    private boolean isSelfOnAsker() {
        if (null == self) {
            return false;
        }
        return roomData.get(RTConstant.RTRoomDataKey.KEY_USER_ASKER) == self.getId()
                || roomData.get(RTConstant.RTRoomDataKey.KEY_USER_ASKER_1) == self.getId()
                || roomData.get(RTConstant.RTRoomDataKey.KEY_USER_ASKER_2) == self.getId()
                || roomData.get(RTConstant.RTRoomDataKey.KEY_USER_ASKER_3) == self.getId();
    }

    /**
     * 自己是否在讲台上
     * @return
     */
    public boolean isSelfOnRostrum() {
        if (null == self) {
            return false;
        }

        return roomData.get(RTConstant.RTRoomDataKey.KEY_USER_ROSTRUM) == self.getId();
    }

    private String getAskerIdByUserId(long value) {
        String askeIdx = roomData.get(RTConstant.RTRoomDataKey.KEY_USER_ASKER) == value ? RTConstant.RTRoomDataKey.KEY_USER_ASKER : "";
        if ("".equals(askeIdx)) {
            askeIdx = roomData.get(RTConstant.RTRoomDataKey.KEY_USER_ASKER_1) == value ? RTConstant.RTRoomDataKey.KEY_USER_ASKER_1 : "";
        }
        if ("".equals(askeIdx)) {
            askeIdx = roomData.get(RTConstant.RTRoomDataKey.KEY_USER_ASKER_2) == value ? RTConstant.RTRoomDataKey.KEY_USER_ASKER_2 : "";
        }
        if ("".equals(askeIdx)) {
            askeIdx = roomData.get(RTConstant.RTRoomDataKey.KEY_USER_ASKER_3) == value ? RTConstant.RTRoomDataKey.KEY_USER_ASKER_3 : "";
        }

        return askeIdx;
    }

    private void initRoomData() {
        roomData.put(RTConstant.RTRoomDataKey.KEY_USER_ROSTRUM, Long.valueOf(-1));
        roomData.put(RTConstant.RTRoomDataKey.KEY_USER_ASKER, Long.valueOf(-1));
        roomData.put(RTConstant.RTRoomDataKey.KEY_USER_ASKER_1, Long.valueOf(-1));
        roomData.put(RTConstant.RTRoomDataKey.KEY_USER_ASKER_2, Long.valueOf(-1));
        roomData.put(RTConstant.RTRoomDataKey.KEY_USER_ASKER_3, Long.valueOf(-1));
    }

    @Override
    public void onInited(String rtParam) {
        GenseeLog.d(TAG, "rtParam = " + rtParam);
        simpleImpl.joinWithParam("", rtParam);
    }

    // int ERR_DOMAIN = -100; // ip(domain)不正确
    // int ERR_TIME_OUT = -101; // 超时
    // int ERR_UNKNOWN = -102; // 未知错误
    // int ERR_SITE_UNUSED = -103; // 站点不可用
    // int ERR_UN_NET = -104; // 无网络
    // int ERR_DATA_TIMEOUT = -105; // 数据过期
    // int ERR_SERVICE = -106; // 服务不正确
    // int ERR_PARAM = -107; // 参数不正确
    // int ERR_THIRD_CERTIFICATION_AUTHORITY = -108 //第三方认证失败
    // int ERR_NUMBER_UNEXIST = 0; // 直播间不存在
    // int ERR_TOKEN = 4; // 口令错误
    // int ERR_LOGIN = 5; // 用户名或密码错误
    // int ERR_WEBCAST_UNSTART = 6; // 直播未开始
    // int ERR_ISONLY_WEB = 7; // 只支持web
    // int ERR_ROOM_UNEABLE = 8; 直播间不可用
    // int ERR_INVALID_ADDRESS = 10; // 无效地址
    // int ERR_ROOM_OVERDUE = 11; // 过期
    // int ERR_AUTHORIZATION_NOT_ENOUGH = 12;授权不够
    // int ERR_UNTIMELY = 13; // 太早
    @Override
    public void onErr(final int errCode) {
        GenseeLog.d(TAG, "onErr = " + errCode);

        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                btnJoin.setText("加入");
                btnJoin.setEnabled(true);
                AlertUtil.showDialog(SmallClassActivity.this, getErrMsg(errCode),
                        new DialogInterface.OnClickListener() {

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

                            }
                        }, null);
            }
        });
    }

    private String getErrMsg(int errCode) {
        String errMsg;
        switch (errCode) {
            case ERR_THIRD_CERTIFICATION_AUTHORITY:
                errMsg = "第三方认证失败";
                break;
            default:
                errMsg = "初始化错误:错误码" + errCode + "，请参考文档中的错误码说明";
                break;
        }
        return errMsg;
    }


    /**
     * 退出的时候请调用
     */
    private void leaveCast(){
        if(comp!= null){
            comp.setCallback(null);
            comp = null;
        }
        AlertDialog.Builder builder =  new AlertDialog.Builder(this);
        builder.setMessage("是否退出直播");
        builder.setPositiveButton("退出", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //退出而不结束
                simpleImpl.leave(false);
            }
        });
        if(self.isHost()){
            //组织者或老师身份，确认是否要结束?
            builder.setMessage("退出-仅离开直播房间，\n退出并结束-将关闭直播房间");
            builder.setNegativeButton("退出并结束", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    simpleImpl.leave(true);//退出并结束
                }
            });
        }
        builder.create().show();

    }


    @Override
    public void onBackPressed() {
        if (self == null) {
            super.onBackPressed();
            return;
        }
        leaveCast();
    }


    /**********************勋章点赞**************************/
    /**
     * 刷新praiseUserInfo.getUserId()这个用户的勋章或点赞的数量
     * （类型为点赞：老师端则刷新收到点赞的数量，学生端刷新剩余点赞数量；类型为勋章：一般只刷新学生端收到的勋章数量）
     * @param type 勋章/点赞
     * @param praiseUserInfo 具体信息
     */
    private void update(final String type,final  PraiseUserInfo praiseUserInfo){
        //根据praiseUserInfo的userId对应的刷新该用户的数据，demo这里只示例刷新当前终端用户的数据
        runOnUiThread(new Runnable() {
            @Override
            public void run() {

                if(PraiseType_Faour.equals(type)){
                    if(praiseUserInfo.getUserId() == self.getId()){
                        txtFaour.setText("点赞" + (self.isHost()?praiseUserInfo.getRecv():praiseUserInfo.getRemain()));
                    }else{
                        //TODO 其他用户
                    }
                }else if(PraiseType_Medal.equals(type)){
                    if(praiseUserInfo.getUserId() == self.getId()){
                        txtMedal.setText("勋章" + (self.isHost()?praiseUserInfo.getRemain(): praiseUserInfo.getRecv()));
                    }else
                    {
                        //TODO 其他用户
                    }
                }
            }
        });



    }

    /**
     * 发送点赞或勋章响应，一般更新发送者的剩余量，只有发送者才会回调
     * @param result 响应结果
     * @param type   类型：点赞和勋章
     * @param praiseUserInfo 发送者的点赞或勋章信息
     */
    @Override
    public void onPraiseInfo(int result, String type, PraiseUserInfo praiseUserInfo) {
        GenseeLog.d(TAG,"onSetPraiseInfo result = " + result + " type = " + type +  praiseUserInfo);
        update(type,praiseUserInfo);

    }

    @Override
    public void onPraiseTotal(int i, final String s,final int total) {
        GenseeLog.d(TAG,"onGetPraiseTotal result = " + i + " type = " + s +  " total = " + total);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if(self.isHost() && PraiseType_Faour.equals(s)){
                    txtFaour.setText("获得点赞" + total);
                }
                else if(!self.isHost()&&PraiseType_Medal.equals(s) ){
                    txtMedal.setText("获得勋章"+total);
                }
            }
        });
    }

    /**
     * 获取勋章排行榜响应
     * @param result 响应结果码
     * @param type 类型：勋章或点赞
     * @param praiseInfos 排行列表
     */
    @Override
    public void onPraiseRecvList(int result, final String type, final PraiseInfo[] praiseInfos) {
        GenseeLog.d(TAG,"onGetPraiseRecvList result = " + result + " type = " + type +  " len = " + (praiseInfos==null?0:praiseInfos.length));
        if(result == 0){//0 代表成功
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if(PraiseType_Medal.equals(type)){
                        new AlertDialog.Builder(SmallClassActivity.this).setAdapter(new RankingAdapter(praiseInfos),null).setTitle("勋章排行top10").setNegativeButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).create().show();
                    }
                }
            });


        }
    }

    @Override
    public void onSendPraiseInBatch(int i, String s, PraiseUserInfo praiseUserInfo) {

    }


    /**
     * 学生给老师点赞，所有人会响应该函数，praiseUserInfo代表老师的点赞信息，可以更新老师收到的点赞数
     * 老师给学生发勋章，所有人会响应该函数，praiseUserInfo代表该学生的勋章信息，可以更新该学生收到的勋章数目
     * @param type
     * @param senderUserInfo，发送者用户勋章或点赞信息
     * @param time 发送时间 单位：秒
     * @param receiverUserInfo 接收者勋章或点赞信息，praiseUserInfo.getUserId()接收者用户id
     */
    @Override
    public void onPraiseNotify(String type, boolean b, int time,PraiseUserInfo senderUserInfo,PraiseUserInfo receiverUserInfo,String comment) {
        GenseeLog.d(TAG,"onSendPraiseNotify  type = " + type +  " sender = " + senderUserInfo + " receiver = " +receiverUserInfo);
        update(type,receiverUserInfo);
//        simpleImpl.getRtSdk().getPraiseInfo(type,praiseUserInfo.getUserId(),null);
    }


    class RankingAdapter extends BaseAdapter{
        private PraiseInfo[] infos;
        public RankingAdapter(PraiseInfo[] infos){
            this.infos = infos;
        }
        /**
         * How many items are in the data set represented by this Adapter.
         *
         * @return Count of items.
         */
        @Override
        public int getCount() {
            return infos == null?0:infos.length;
        }

        /**
         * Get the data item associated with the specified position in the data set.
         *
         * @param position Position of the item whose data we want within the adapter's
         *                 data set.
         * @return The data at the specified position.
         */
        @Override
        public Object getItem(int position) {
            return infos[position];
        }

        /**
         * Get the row id associated with the specified position in the list.
         *
         * @param position The position of the item within the adapter's data set whose row id we want.
         * @return The id of the item at the specified position.
         */
        @Override
        public long getItemId(int position) {
            return position;
        }

        /**
         * Get a View that displays the data at the specified position in the data set. You can either
         * create a View manually or inflate it from an XML layout file. When the View is inflated, the
         * parent View (GridView, ListView...) will apply default layout parameters unless you use
         * {@link LayoutInflater#inflate(int, ViewGroup, boolean)}
         * to specify a root view and to prevent attachment to the root.
         *
         * @param position    The position of the item within the adapter's data set of the item whose view
         *                    we want.
         * @param convertView The old view to reuse, if possible. Note: You should check that this view
         *                    is non-null and of an appropriate type before using. If it is not possible to convert
         *                    this view to display the correct data, this method can create a new view.
         *                    Heterogeneous lists can specify their number of view types, so that this View is
         *                    always of the right type (see {@link #getViewTypeCount()} and
         *                    {@link #getItemViewType(int)}).
         * @param parent      The parent that this view will eventually be attached to
         * @return A View corresponding to the data at the specified position.
         */
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ItemHolder holder = null;
            if(convertView == null){
                convertView = LayoutInflater.from(SmallClassActivity.this).inflate(R.layout.rank_item_layout,null);
                holder = new ItemHolder(convertView);
                convertView.setTag(holder);
            }else{
                holder = (ItemHolder) convertView.getTag();
            }
            holder.update((PraiseInfo) getItem(position));
            return convertView;
        }

        class ItemHolder{
            private TextView rank;
            private TextView name;
            public ItemHolder(View rootView){
                rank = (TextView) rootView.findViewById(R.id.rank);
                name = (TextView) rootView.findViewById(R.id.name);
            }

            public void update(PraiseInfo info){
                if(info != null){
                    rank.setText(info.getTotal()+"");
                    name.setText(info.getUserName());
                }
            }
        }
    }
}
