package com.bokecc.cloudclass.demo.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bokecc.cloudclass.demo.R;
import com.bokecc.cloudclass.demo.base.TitleActivity;
import com.bokecc.cloudclass.demo.base.TitleOptions;
import com.bokecc.cloudclass.demo.global.Config;
import com.bokecc.cloudclass.demo.view.EllipsizeEndTextView;
import com.bokecc.common.utils.Tools;
import com.bokecc.room.drag.view.activity.SaasAssistantRoomActivity;
import com.bokecc.room.drag.view.activity.SaasInspectorRoomActivity;
import com.bokecc.room.drag.view.activity.SaasMeetingStudentRoomActivity;
import com.bokecc.room.drag.view.activity.SaasStudentRoomActivity;
import com.bokecc.room.drag.view.activity.SaasTeacherRoomActivity;
import com.bokecc.room.drag.view.base.CCRoomActivity;
import com.bokecc.room.ui.view.activity.InspectorRoomActivity;
import com.bokecc.room.ui.view.activity.StudentRoomActivity;
import com.bokecc.room.ui.view.activity.TeacherRoomActivity;
import com.bokecc.sskt.base.CCAtlasClient;
import com.bokecc.sskt.base.bean.CCCityInteractBean;
import com.bokecc.sskt.base.callback.CCAtlasCallBack;
import com.bokecc.sskt.base.common.util.SharedPreferencesUtils;

import static com.bokecc.sskt.base.CCAtlasClient.ASSISTANT;
import static com.bokecc.sskt.base.CCAtlasClient.INSPECTOR;
import static com.bokecc.sskt.base.CCAtlasClient.PRESENTER;
import static com.bokecc.sskt.base.CCAtlasClient.TALKER;

/**
 * 登录界面
 */
public class ValidateActivity extends TitleActivity<ValidateActivity.ValidateViewHolder> {

    //房间类型是新房间
    private final String ROOM_TYPE_SAAS = "32";
    private String mTemplate;//布局方式，==32为新课堂
    private int mLayoutMode;//新课堂布局方式
    private int mClassDirection;//横屏/竖屏

    private String mRoomId;//房间id
    private String mAccountId;//账号id
    private int mRole = 0;//角色
    private boolean isNoPwd;//是否需要密码
    private String mNickName;
    private String mPwd;

    /**选择的区域代码*/
    private String mAreaCode;

//    private EventBus mEventBus = EventBus.getDefault();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
//        InteractSessionManager mInteractSessionManager = InteractSessionManager.getInstance();
//        mInteractSessionManager.addInteractListeners();
//        mInteractSessionManager.setEventBus(mEventBus);

        super.onCreate(savedInstanceState);

        setTitle(R.string.join_class_title);

//        EventBus.getDefault().register(this);//注册EventBus
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_validate;
    }

//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onInteractEvent(Boolean event) {
//    }

    @Override
    protected ValidateViewHolder getViewHolder(View contentView) {
        return new ValidateViewHolder(contentView);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Config.CITYNAME) {
            CCCityInteractBean mCityName = (CCCityInteractBean) data.getSerializableExtra("selected_city");
            mAreaCode = mCityName.getdataareacode();

            TitleOptions.Builder builder = new TitleOptions.Builder();
            TitleOptions options = builder.leftStatus(TitleOptions.VISIBLE).
                    leftResId(R.drawable.title_back).
                    rightResId(R.drawable.layer_list).
                    rightStatus(TitleOptions.VISIBLE).
                    titleStatus(TitleOptions.VISIBLE).title(Tools.getString(R.string.join_class_title)).
                    cityStatus(TitleOptions.VISIBLE).city(mCityName.getdataloc()).
                    onTitleClickListener(new TitleOptions.OnLeftClickListener() {
                        @Override
                        public void onLeft() {
                            finish();
                        }

                        @Override
                        public void onRight() {
                            goCityListActivity();
                        }
                    }).build();
            setTitleOptions(options);
        }else if(requestCode == Config.REQUEST_UPDATE_FLAG){
            /*
             * CCAtlasClient.UPDATE_GENERAL_FLAG 为提示性更新，可以关闭弹窗，点击立即更新则回调至此处个性化处理
             * CCAtlasClient.UPDATE_FORCE_FLAG 为强制性更新，弹窗不可关闭，点击立即更新则回调至此处个性化处理
             */
            if(resultCode == CCAtlasClient.UPDATE_GENERAL_FLAG||resultCode == CCAtlasClient.UPDATE_FORCE_FLAG){
                /*CCVersionInfo versionInfo = (CCVersionInfo) data.getSerializableExtra("versionInfo");
                if(versionInfo!=null){
                    String updateDesc = versionInfo.getUpdateDesc();
                    int versionCheck = versionInfo.getVersionCheck();
                    Tools.log("versionCheck: "+versionCheck);
                    Tools.log(updateDesc);
                }*/
                //处理更新逻辑
                Tools.openSystemBrowser(this,Config.CC_CLASS_UPDATE_URL);
            }
        }
    }

    /**
     * 跳转到节点选择列表
     */
    private void goCityListActivity(){
        Intent intent = new Intent(this, CityListActivity.class);
        intent.putExtra(Config.KEY_ROOM_ACCOUNTID,mAccountId);
        intent.putExtra(Config.KEY_ROOM_ROOMID,mRoomId);
        intent.putExtras(getIntent().getExtras());
        startActivityForResult(intent, Config.CITYSTATUS_RESULT_CODE);
    }

    @Override
    protected void onBindViewHolder(ValidateViewHolder holder) {
        mRoomId = getIntent().getStringExtra(Config.KEY_ROOM_ROOMID);
        mAccountId = getIntent().getStringExtra(Config.KEY_ROOM_ACCOUNTID);
        mRole = getIntent().getIntExtra(Config.KEY_ROOM_ROLE, mRole);
        mLayoutMode = getIntent().getIntExtra(Config.KEY_ROOM_LAYOUT_MODE, 0);
        mTemplate = getIntent().getStringExtra(Config.KEY_ROOM_TEMPLATE);
        mClassDirection = getIntent().getIntExtra(Config.KEY_CLASS_DIRECTION, 0);


        //标题栏
        TitleOptions.Builder builder = new TitleOptions.Builder();
        TitleOptions options = builder.leftStatus(TitleOptions.VISIBLE).
                leftResId(R.drawable.title_back).
                rightResId(R.drawable.layer_list).
                rightStatus(TitleOptions.VISIBLE).
                titleStatus(TitleOptions.VISIBLE).title(Tools.getString(R.string.join_class_title)).
                cityStatus(TitleOptions.VISIBLE).city(Tools.getString(R.string.cc_demo_beijing)).
                onTitleClickListener(new TitleOptions.OnLeftClickListener() {
                    @Override
                    public void onLeft() {
                        finish();
                    }

                    @Override
                    public void onRight() {
                        goCityListActivity();
                    }
                }).build();
        setTitleOptions(options);

        //设置房间名和简介
        String roomName = getIntent().getStringExtra(Config.KEY_ROOM_NAME);
        holder.mRoomName.setText(Html.fromHtml(roomName));
        String roomDesc = getIntent().getStringExtra(Config.KEY_ROOM_DESC);
        if (!TextUtils.isEmpty(roomDesc)) {
            holder.mRoomDesc.setMaxLines(2);
            holder.mRoomDesc.setText(Html.fromHtml(roomDesc));
        } else {
            holder.mRoomDesc.setVisibility(View.GONE);
        }

        //设置用户名和密码
        mNickName = getIntent().getStringExtra(Config.KEY_ROOM_USERNAME);
        if(TextUtils.isEmpty(mNickName)){//从本地数据库中获取
            mNickName = SharedPreferencesUtils.getString(getApplicationContext(),mRoomId + "&" + mAccountId + "&" + mRole + "-name","");
        }
        holder.mNickname.setText(mNickName);
        if (!TextUtils.isEmpty(mNickName)) {
            holder.mNickname.setSelection(mNickName.length());
        }
        isNoPwd = getIntent().getBooleanExtra(Config.KEY_LOGIN_NO_PWD, false);
        if (isNoPwd) {
            holder.mPwdLayout.setVisibility(View.GONE);
            holder.mPwdBottomLine.setVisibility(View.GONE);
        } else {
            holder.mPwdLayout.setVisibility(View.VISIBLE);
            holder.mPwdBottomLine.setVisibility(View.VISIBLE);

            mPwd = getIntent().getStringExtra(Config.KEY_ROOM_PWD);
            if(TextUtils.isEmpty(mPwd)){
                mPwd = SharedPreferencesUtils.getString(getApplicationContext(),mRoomId + "&" + mAccountId + "&" + mRole + "-password","");
            }
            holder.mPassword.setText(mPwd);
            if (!TextUtils.isEmpty(mPwd)) {
                holder.mPassword.setSelection(mPwd.length());
            }
        }
    }

//    @Override
//    protected void onDestroy() {
//        super.onDestroy();
////        mEventBus.unregister(this);
//    }

    /**
     * 保存用户信息到本地
     */
    private void saveUserMsg() {
        SharedPreferencesUtils.saveString(getApplicationContext(),mRoomId + "&" + mAccountId + "&" + mRole + "-name", mNickName);
        if (!isNoPwd)
            SharedPreferencesUtils.saveString(getApplicationContext(),mRoomId + "&" + mAccountId + "&" + mRole + "-password", mPwd);
    }

    /**
     *
     */
    final class ValidateViewHolder extends TitleActivity.ViewHolder {

        ImageView mIcon;
        TextView mRoomName;
        EllipsizeEndTextView mRoomDesc;
        EditText mNickname;
        LinearLayout mPwdLayout;
        View mPwdBottomLine;
        EditText mPassword;

        ValidateViewHolder(View view) {
            super(view);

            mIcon = findViewById(R.id.id_validate_room_icon);
            mRoomName = findViewById(R.id.id_validate_room_name);
            mRoomDesc = findViewById(R.id.id_validate_room_desc);
            mNickname = findViewById(R.id.id_validate_nickname);
            mPwdLayout = findViewById(R.id.id_validate_passwd_layout);
            mPwdBottomLine = findViewById(R.id.id_validate_passwd_bottom_line);
            mPassword = findViewById(R.id.id_validate_passwd);
            mPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());

            findViewById(R.id.id_validate_room).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    goRoom();
                }
            });
        }

        private String getEditTextValue(EditText editText) {
            return editText.getText().toString().trim();
        }

        /**
         * 跳转到直播间内
         */
        private void goRoom() {
            Tools.hideSoftInput(ValidateActivity.this);//收起键盘

            mNickName = getEditTextValue(mNickname);
            mPwd = getEditTextValue(mPassword);

            if (TextUtils.isEmpty(mNickName)) {
                toastOnUiThread(Tools.getString(R.string.cc_demo_write_info));
                return;
            }

            if(!isNoPwd && TextUtils.isEmpty(mPwd)){
                toastOnUiThread(Tools.getString(R.string.cc_demo_write_pwd));
                return;
            }

            if (mLayoutMode == 4 && mRole == ASSISTANT){
                Tools.showToast(R.string.cc_demo_no_role,false);
                return;
            }

            //开始登录
            showProgress();
            CCAtlasClient.getInstance().login(mRoomId, mAccountId, mRole, mNickName, mPwd, "Android",new CCAtlasCallBack<String>() {
                        @Override
                        public void onSuccess(String sessionid) {
                            dismissProgress();
                            saveUserMsg();
                            join(sessionid);
                        }

                        @Override
                        public void onFailure(int errCode, String errMsg) {
                            dismissProgress();
                            toastOnUiThread(errMsg);
                        }
                    });
        }

    }

    /**
     * 加入直播间
     * @param mSeesionid
     */
    private void join(String mSeesionid) {
        Tools.log("role = " +  mRole + "accountId = " + mAccountId + "roomid = " + mRoomId +"username = " +"isNoPwd = " + isNoPwd +"template = " + mTemplate);
        if (TextUtils.equals(ROOM_TYPE_SAAS, mTemplate)) {//新房间
            Intent intent = new Intent();
            if (mLayoutMode != 5) {
                if (mRole == PRESENTER) {
                    intent.setClass(this, SaasTeacherRoomActivity.class);
                } else if (mRole == INSPECTOR) {
                    intent.setClass(this, SaasInspectorRoomActivity.class);
                } else if (mRole == ASSISTANT) {
                    intent.setClass(this, SaasAssistantRoomActivity.class);
                } else {
                    intent.setClass(this, SaasStudentRoomActivity.class);
                }
            } else {
                if (mRole == TALKER){
                    intent.setClass(this, SaasMeetingStudentRoomActivity.class);
                } else {
                    toastOnUiThread(Tools.getString(R.string.cc_demo_no_role));
                }
            }
            intent.putExtra(CCRoomActivity.SeesionidKey, mSeesionid);
            intent.putExtra(CCRoomActivity.RoomIdKey, mRoomId);
            intent.putExtra(CCRoomActivity.UserAccountKey, mAccountId);
            intent.putExtra(CCRoomActivity.AreaCodeKey, mAreaCode);
//            if (mLayoutMode == 1 || mLayoutMode == 2 || mLayoutMode == 3 || mLayoutMode == 4) {
                intent.putExtra(CCRoomActivity.KeyLayoutMode, mLayoutMode);
//            } else {
//                intent.putExtra(CCRoomActivity.KeyLayoutMode, 0);
//            }
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivityForResult(intent,Config.REQUEST_UPDATE_FLAG);
        }else{
            if (mRole == CCAtlasClient.PRESENTER) {
                Intent intent = new Intent(ValidateActivity.this, TeacherRoomActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.putExtra(com.bokecc.room.ui.view.base.CCRoomActivity.SeesionidKey, mSeesionid);
                intent.putExtra(com.bokecc.room.ui.view.base.CCRoomActivity.RoomIdKey, mRoomId);
                intent.putExtra(com.bokecc.room.ui.view.base.CCRoomActivity.UserAccountKey, mAccountId);
                intent.putExtra(com.bokecc.room.ui.view.base.CCRoomActivity.AreaCodeKey, mAreaCode);
                intent.putExtra(com.bokecc.room.ui.view.base.CCRoomActivity.ScreenDirectionKey, mClassDirection);
                startActivity(intent);
            } else if (mRole == TALKER) {
                Intent intent = new Intent(ValidateActivity.this, StudentRoomActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.putExtra(com.bokecc.room.ui.view.base.CCRoomActivity.SeesionidKey, mSeesionid);
                intent.putExtra(com.bokecc.room.ui.view.base.CCRoomActivity.RoomIdKey, mRoomId);
                intent.putExtra(com.bokecc.room.ui.view.base.CCRoomActivity.UserAccountKey, mAccountId);
                intent.putExtra(com.bokecc.room.ui.view.base.CCRoomActivity.AreaCodeKey, mAreaCode);
                intent.putExtra(com.bokecc.room.ui.view.base.CCRoomActivity.ScreenDirectionKey, mClassDirection);
                startActivity(intent);
            } else if (mRole == INSPECTOR) {
                Intent intent = new Intent(ValidateActivity.this, InspectorRoomActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.putExtra(com.bokecc.room.ui.view.base.CCRoomActivity.SeesionidKey, mSeesionid);
                intent.putExtra(com.bokecc.room.ui.view.base.CCRoomActivity.RoomIdKey, mRoomId);
                intent.putExtra(com.bokecc.room.ui.view.base.CCRoomActivity.UserAccountKey, mAccountId);
                intent.putExtra(com.bokecc.room.ui.view.base.CCRoomActivity.AreaCodeKey, mAreaCode);
                intent.putExtra(com.bokecc.room.ui.view.base.CCRoomActivity.ScreenDirectionKey, mClassDirection);
                startActivity(intent);
            } else {
                toastOnUiThread(Tools.getString(R.string.cc_demo_no_role));
            }
        }
    }

}
