package com.bokecc.cloudclass.demo.activity;

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;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.method.PasswordTransformationMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.bokecc.cloudclass.demo.R;
import com.bokecc.cloudclass.demo.adapter.HomeActivityViewPagerAdapter;
import com.bokecc.cloudclass.demo.base.BaseActivity;
import com.bokecc.cloudclass.demo.global.Config;
import com.bokecc.cloudclass.demo.scan.QrCodeActivity;
import com.bokecc.cloudclass.demo.view.ClearEditLayout;
import com.bokecc.common.application.ApplicationData;
import com.bokecc.common.utils.Tools;
import com.bokecc.room.drag.common.observer.AudRemoveObservable;
import com.bokecc.room.drag.common.utils.PermissionDialogUtils;
import com.bokecc.room.drag.listener.PermissionDialogAgreeListenter;
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.CCRoomInfo;
import com.bokecc.sskt.base.bean.UpdateInfo;
import com.bokecc.sskt.base.callback.CCAtlasCallBack;
import com.bokecc.sskt.base.common.dialog.CustomTextViewDialog;
import com.bokecc.sskt.base.common.network.CCRequestCallback;
import com.bokecc.sskt.base.common.network.UpdateRequest;
import com.bokecc.sskt.base.common.util.SharedPreferencesUtils;

import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;

import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

/**
 * 主界面
 */
@RuntimePermissions
public class HomeActivity extends BaseActivity {

    //房间类型是新房间
    private final String ROOM_TYPE_SAAS = "32";
    private TextView mVersion;
    private ClearEditLayout mClearEditLayout;
    private ClearEditLayout mClearEditLayoutCode;
    private ClearEditLayout mClearEditLayoutName;
    private ClearEditLayout mClearEditLayoutPwd;
    private View diveUrl;
    private View diveCode;
    private TextView mTvTypeUrl;
    private TextView mTvTypeCode;
    private final int QR_REQUEST_CODE = 111;

    private final int url_type = 0;//url地址
    private final int code_type = 1;//参课码
    private int type = url_type;
    private String classCode;

    private int classDirection = 0;
    private LinearLayout llOrientation;
    private CCRoomInfo roomDes;
    public static final int CLASS_NUMBER_LENGTH = 9;
    private boolean isShowPwd = false;
    private boolean isShowOri = false;
    private ViewPager viewPager;
    private HomeActivityViewPagerAdapter adapter;
    private TextView tvPolicy;

    /**选择的区域代码*/
    private String mAreaCode;
    final static long DURATION = 2 * 1000;//规定有效时间
    long[] mHits = new long[3];
    private static final String HTTP_DNS_ENABLE = "httpDnsEnable";
    private boolean httpDnsEnable;
    private boolean needOpenLive = false;
    private String liveUrl = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        handleScheme();
        update();
        initObserver();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_home_new;
    }

    @Override
    protected void onViewCreated() {
        mVersion = findViewById(R.id.id_main_version);
        mVersion.setText("v" + Tools.getVersionName());
        tvPolicy = findViewById(R.id.tv_policy);

        final TextView tvLanguage = findViewById(R.id.tv_switch_langage);
        int language = SharedPreferencesUtils.getInt(getApplicationContext(),LANGUAGE_KEY,LANGUAGE_CHINESE);
//        LanguageUtils.saveLanguage(language);
//        com.bokecc.room.drag.common.utils.LanguageUtils.saveLanguage(getApplicationContext(),language);
        if (language == LANGUAGE_CHINESE) {
            tvLanguage.setText(R.string.language_chinese);
        }else if(language == LANGUAGE_JAPANESE){
            tvLanguage.setText(R.string.language_japanese);
        } else {
            tvLanguage.setText(R.string.language_english);
        }

        findViewById(R.id.switch_language).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                findViewById(R.id.switch_language).setClickable(false);
                int language = SharedPreferencesUtils.getInt(getApplicationContext(),LANGUAGE_KEY,LANGUAGE_CHINESE);
                if (language == LANGUAGE_CHINESE) {
                    tvLanguage.setText(R.string.language_english);
                    SharedPreferencesUtils.saveInt(getApplicationContext(),LANGUAGE_KEY, LANGUAGE_ENGLISH);
                } else if(language == LANGUAGE_ENGLISH) {
                    tvLanguage.setText(R.string.language_japanese);
                    SharedPreferencesUtils.saveInt(getApplicationContext(),LANGUAGE_KEY, LANGUAGE_JAPANESE);
                } else {
                    tvLanguage.setText(R.string.language_chinese);
                    SharedPreferencesUtils.saveInt(getApplicationContext(),LANGUAGE_KEY,LANGUAGE_CHINESE);
                }

                SharedPreferencesUtils.saveInt(getApplicationContext(),LANGUAGE_KEY,SharedPreferencesUtils.getInt(getApplicationContext(),LANGUAGE_KEY,LANGUAGE_CHINESE));

                changeAppLanguage(HomeActivity.this.getClass());

            }
        });

        findViewById(R.id.operation).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                go(OperationActivity.class);
            }
        });

        findViewById(R.id.id_scan).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PermissionDialogUtils.showPermissionDialog(HomeActivity.this,
                       new String[]{Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO, Manifest
                               .permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.WRITE_EXTERNAL_STORAGE}
                               ,"'云互动'想访问你的摄像头，麦克风及存储，如果不允许则无法进行扫码登录", new PermissionDialogAgreeListenter() {
                    @Override
                    public void onClickAgree() {
                        scan();
                    }
                });
            }
        });

        findViewById(R.id.id_link_go).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (type == url_type) {
                    goByLink();
                } else {
                    classCode = mClearEditLayoutCode.getText().toString().trim();
                    String myUsername = mClearEditLayoutName.getText();
                    String myPassword = mClearEditLayoutPwd.getText().toString();
                    if (mClearEditLayoutPwd.getVisibility() == View.VISIBLE && TextUtils.isEmpty(myPassword)){
                        Tools.showToast(R.string.cc_demo_write_info,false);
                        return;
                    } else if (TextUtils.isEmpty(myUsername)){
                        Tools.showToast(R.string.cc_demo_write_info,false);
                        return;
                    } else if (classCode.length() < CLASS_NUMBER_LENGTH
                      || TextUtils.isEmpty(roomDes.getRoomId()) || TextUtils.isEmpty(roomDes.getUserid())){
                        Tools.showToast(R.string.cc_demo_enter_correct_code,false);
                        return;
                    }

                    goRoom();
                }
            }
        });
        httpDnsEnable = SharedPreferencesUtils.getBoolean(this, HTTP_DNS_ENABLE, true);
        setHttpDnsEnable(httpDnsEnable);
        mVersion.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);
                mHits[mHits.length - 1] = SystemClock.uptimeMillis();
                if (mHits[mHits.length - 1] - mHits[0] < DURATION) {
                    mHits = new long[3];
                    httpDnsEnable = !httpDnsEnable;
                    SharedPreferencesUtils.saveBoolean(getApplicationContext(), HTTP_DNS_ENABLE, httpDnsEnable);
                    setHttpDnsEnable(httpDnsEnable);
                }
            }
        });

        initSelectStyleView();
        initViewPager();
        initPolicy();
    }

    private void setHttpDnsEnable(boolean httpDnsEnable) {
        ApplicationData.getInstance().setHttpDnsEnable(httpDnsEnable);
        if (httpDnsEnable) {
            mVersion.setTextColor(Color.parseColor("#999999"));
            mVersion.setText("v" + Tools.getVersionName());
        } else {
            mVersion.setTextColor(Color.parseColor("#ff0000"));
            mVersion.setText("v" + Tools.getVersionName()+"->测试环境已关闭HttpDns");
        }
    }

    private void initPolicy(){
        String policy = "登录即代表你同意《隐私协议》";
        tvPolicy.setMovementMethod(LinkMovementMethod.getInstance());
        SpannableString spannableString = new SpannableString(policy);
        spannableString.setSpan(new ClickableSpan() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(HomeActivity.this, PolicyActivity.class);
                startActivity(intent);
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                ds.setUnderlineText(false);
            }
        }, policy.indexOf("《") + 1, policy.indexOf("》"), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#ff842f")), policy.indexOf("《") + 1, policy.indexOf("》"), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tvPolicy.setText(spannableString);
    }

    private void initViewPager(){
        viewPager = findViewById(R.id.view_pager);
        ArrayList<View> list = initViewPagerView();
        adapter = new HomeActivityViewPagerAdapter(list);
        viewPager.setAdapter(adapter);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                if (i == 0){
                    selectUrlType();
                } else {
                    selectCodeType();
                }
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
    }

    private ArrayList<View> initViewPagerView(){
        ArrayList<View> views = new ArrayList<>();
        View urlView = View.inflate(this,R.layout.home_activity_url_pager,null);
        View codeView = View.inflate(this,R.layout.home_activity_code_pager,null);

        views.add(urlView);
        views.add(codeView);

        mClearEditLayout = urlView.findViewById(R.id.id_link_url);
        mClearEditLayout.setOnClearClickListener(new ClearEditLayout.OnClearClickListener() {
            @Override
            public void onCloseClick() {
                SharedPreferencesUtils.saveString(getApplicationContext(),Config.CC_KEY_CLASSROOM_URL,"");
            }
        });
        initSelectOrientationView(codeView);

        mClearEditLayoutCode = codeView.findViewById(R.id.id_link_code);
        mClearEditLayoutName = codeView.findViewById(R.id.id_user_name);
        mClearEditLayoutPwd = codeView.findViewById(R.id.id_passwd);

        mClearEditLayoutCode.setHint(Tools.getString(R.string.cc_demo_enter_code));
        mClearEditLayoutName.setHint(Tools.getString(R.string.cc_demo_enter_username));
        mClearEditLayoutPwd.setHint(Tools.getString(R.string.cc_demo_enter_pwd));

        mClearEditLayoutCode.setMaxLength(CLASS_NUMBER_LENGTH);
        mClearEditLayoutCode.setInputType(EditorInfo.TYPE_CLASS_NUMBER);

        mClearEditLayoutPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
        mClearEditLayoutCode.setOnEditTextChangedListener(new ClearEditLayout.OnEditTextChangedListener() {
            @Override
            public void onChanged(Editable s) {
                if (s.length() >= CLASS_NUMBER_LENGTH){
                    String inputS = s.toString().substring(0,CLASS_NUMBER_LENGTH);
                    mRole = inputS.substring(CLASS_NUMBER_LENGTH - 1,CLASS_NUMBER_LENGTH);
                    getRoomInfo(Integer.parseInt(inputS));
                }
            }
        });

        return views;
    }

    private void initSelectOrientationView(View view) {
        llOrientation = view.findViewById(R.id.ll_select_orientation);
        final View llh = view.findViewById(R.id.ll_h);
        final View llv = view.findViewById(R.id.ll_v);
        final RadioButton rbh = view.findViewById(R.id.rbh);
        final RadioButton rbv = view.findViewById(R.id.rbv);

        rbv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                rbv.setChecked(true);
                rbh.setChecked(false);
                llh.setBackgroundColor(Color.TRANSPARENT);
                llv.setBackgroundResource(R.drawable.home_radio_button_bg);
                classDirection = 0;
            }
        });

        rbh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                rbh.setChecked(true);
                rbv.setChecked(false);
                llv.setBackgroundColor(Color.TRANSPARENT);
                llh.setBackgroundResource(R.drawable.home_radio_button_bg);
                classDirection = 1;
            }
        });
    }


    private void initSelectStyleView() {
        diveUrl = findViewById(R.id.dive_url);
        diveCode = findViewById(R.id.dive_code);
        mTvTypeUrl = findViewById(R.id.tv_type_url);
        mTvTypeCode = findViewById(R.id.tv_type_code);

        findViewById(R.id.rl_select_url).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                viewPager.setCurrentItem(url_type);
            }
        });

        findViewById(R.id.rl_select_code).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                viewPager.setCurrentItem(code_type);
            }
        });
    }

    private void selectCodeType() {
        mClearEditLayoutCode.setVisibility(View.VISIBLE);
        mClearEditLayoutName.setVisibility(View.VISIBLE);
        mClearEditLayout.setVisibility(View.GONE);
        if (isShowPwd){
            mClearEditLayoutPwd.setVisibility(View.VISIBLE);
        } else {
            mClearEditLayoutPwd.setVisibility(View.GONE);
        }

        if (isShowOri){
            llOrientation.setVisibility(View.VISIBLE);
        } else {
            llOrientation.setVisibility(View.GONE);
        }
        diveUrl.setVisibility(View.GONE);
        diveCode.setVisibility(View.VISIBLE);

        mTvTypeCode.setTextColor(Color.parseColor("#121F2C"));
        mTvTypeCode.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
        mTvTypeUrl.setTextColor(Color.parseColor("#666666"));
        mTvTypeUrl.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
        type = code_type;
    }

    private void selectUrlType() {
        mClearEditLayout.setVisibility(View.VISIBLE);
        mClearEditLayoutCode.setVisibility(View.GONE);
        mClearEditLayoutName.setVisibility(View.GONE);
        if (llOrientation.getVisibility() == View.VISIBLE){
            llOrientation.setVisibility(View.GONE);
        }
        if (mClearEditLayoutPwd.getVisibility() == View.VISIBLE){
            mClearEditLayoutPwd.setVisibility(View.GONE);
        }
        diveUrl.setVisibility(View.VISIBLE);
        diveCode.setVisibility(View.GONE);

        mTvTypeUrl.setTextColor(Color.parseColor("#121F2C"));
        mTvTypeUrl.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
        mTvTypeCode.setTextColor(Color.parseColor("#666666"));
        mTvTypeCode.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
        type = url_type;
    }

    @Override
    protected void onResume() {
        super.onResume();
        setLastUrl();
        if (needOpenLive) {
            needOpenLive = false;
            openLive();
        }
    }

    /**
     * 设置上一次的地址
     */
    private void setLastUrl() {
        if (TextUtils.isEmpty(mClearEditLayout.getText())) {
            String lastUrl = SharedPreferencesUtils.getString(getApplicationContext(),Config.CC_KEY_CLASSROOM_URL,"");
            if (!TextUtils.isEmpty(lastUrl)) {
                mClearEditLayout.setText(lastUrl);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        HomeActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

//    /**
//     * 扫码权限判断
//     */
    void scan() {
        HomeActivityPermissionsDispatcher.goScanWithPermissionCheck(this);
    }

    @NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO, Manifest
            .permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void goScan() {
        Intent intent = new Intent(this, QrCodeActivity.class);
        startActivityForResult(intent, QR_REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == QR_REQUEST_CODE && resultCode == RESULT_OK && data != null) {
            Bundle bundle = data.getExtras();
            if (bundle == null) return;
            String result = bundle.getString("result");
            if (result.startsWith("https://view.csslcloud.net/api/view/index")) {
                //直播研讨会
                liveUrl = result;
                openLive();
            } else {
                parseUrl(result);
            }
            Log.d("HOMEACTIVITY","url ==" + result);
        }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){
                //处理更新逻辑
                Tools.openSystemBrowser(this,Config.CC_CLASS_UPDATE_URL);
            }
        }
    }

    @OnShowRationale({Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO, Manifest
            .permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showRationaleForCamera(PermissionRequest request) {
        showRationaleDialog(request);
    }
    @NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO, Manifest
            .permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_COARSE_LOCATION})
    void showRationale(PermissionRequest request){
        showRationaleDialog(request);
    }

    private void showRationaleDialog(final PermissionRequest request) {
        new AlertDialog.Builder(this)
                .setPositiveButton(Tools.getString(R.string.cc_demo_allow), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(@NonNull DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton(Tools.getString(R.string.cc_demo_forbidden), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(@NonNull DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .setCancelable(false)
                .setMessage(Tools.getString(R.string.cc_demo_camera_hint))
                .show();
    }

    @OnNeverAskAgain({Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO, Manifest
            .permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void onCameraNeverAskAgain() {
        Tools.showToast(R.string.cc_demo_camera_tip,false);
    }

    @NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO, Manifest
            .permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void goByLink() {
        String url = mClearEditLayout.getText();
        if (TextUtils.isEmpty(url)) {
            Tools.showToast(Tools.getString(R.string.cc_demo_input_link));
            return;
        }
        parseUrl(url);
    }

    /**
     * 处理scheme
     */
    private void handleScheme() {
        Intent intent = getIntent();
        if (intent != null) {
            String scheme = intent.getStringExtra("scheme");
            if (scheme != null && scheme.length() > 0) {
                parseUrl(scheme);
            }
        }
    }

    /**
     * 软件更新接口
     */
    private void update() {
        new UpdateRequest(this, new CCRequestCallback<UpdateInfo>() {
            @Override
            public void onSuccess(UpdateInfo response) {
                if (response != null) {
                    updateDialog(response);
                }
            }

            @Override
            public void onFailure(int errorCode, String errorMsg) {
                Tools.log(errorMsg);
            }
        });
    }

    /**
     * 更新对话框
     *
     * @param response
     */
    private void updateDialog(final UpdateInfo response) {
        CustomTextViewDialog dialog = new CustomTextViewDialog(this);
        dialog.setTitle(Tools.getString(R.string.cc_demo_app_update));
        dialog.setMessage(response.getUpdate_infos());
        if (response.isIs_force()) {
            dialog.setBtn(Tools.getString(R.string.cc_demo_confirm), new CustomTextViewDialog.CustomClickListener() {
                @Override
                public void onLeftClickListener() {

                }

                @Override
                public void onRightClickListener() {

                }

                @Override
                public void onOneBtnClickListener() {
                    Tools.openSystemBrowser(HomeActivity.this, response.getUrl());
                    finish();
                }
            });
        }else{
            dialog.setBtn( getString(R.string.cc_demo_cancel), getString(R.string.cc_demo_confirm),new CustomTextViewDialog.CustomClickListener() {
                @Override
                public void onLeftClickListener() {

                }

                @Override
                public void onRightClickListener() {
                    Tools.openSystemBrowser(HomeActivity.this, response.getUrl());
                }

                @Override
                public void onOneBtnClickListener() {

                }
            });
        }
    }


    //房间id
    private String mRoomId = "";
    //账号id
    private String mAccountId = "";
    //角色
    private String mRole;
    //显示模式
    private String template;
    //用户名（支持scheme）
    private String username = "";
    //密码（支持scheme）
    private String password;


    /**
     * 解析url地址
     *
     * @param url
     */
    private void parseUrl(String url) {
        if (TextUtils.isEmpty(url)) {
            Tools.showToast(R.string.cc_demo_url_is_empty,false);
            return;
        }

        url = url.trim();

        try {
            Uri uri = Uri.parse(url);
            template = uri.getQueryParameter("template");
            mAccountId = uri.getQueryParameter("userid");
            mRoomId = uri.getQueryParameter("roomid");
            mRole = uri.getQueryParameter("role");
            username = uri.getQueryParameter("username");
            password = uri.getQueryParameter("password");

            //兼容
            if (TextUtils.isEmpty(mRole)) {
                try {
                    String arr[] = url.split("\\?|&");
                    String hosts[] = (arr[0].substring("https://".length(), arr[0].length())).split("/");
                    mRole = hosts[hosts.length - 1];
                } catch (Exception e) {
                    e.printStackTrace();
                    Tools.handleException(e);
                }
            }

            //字段判空,三个必填字段
            if (TextUtils.isEmpty(mAccountId) || TextUtils.isEmpty(mRoomId) || TextUtils.isEmpty(mRole)) {
                Tools.showToast(R.string.cc_demo_url_is_error,false);
                return;
            }

            getRoomInfo(url);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 通过房间id获取房间信息
     * @param url
     */
    private void getRoomInfo(final String url) {
        showProgress();
        CCAtlasClient.getInstance().getRoomInfo(mRoomId, new CCAtlasCallBack<CCRoomInfo>() {
            @Override
            public void onSuccess(CCRoomInfo des) {
                SharedPreferencesUtils.saveString(getApplicationContext(),Config.CC_KEY_CLASSROOM_URL, url);//储存url地址
                switch (mRole) {
                    case "presenter":
                        newIntent(CCAtlasClient.PRESENTER, mAccountId, mRoomId, username, password, false, des, template);
                        break;
                    case "inspector":
                        newIntent(CCAtlasClient.INSPECTOR, mAccountId, mRoomId, username, password, des.getInspectorAuthtype() == 2, des, template);
                        break;
                    case "talker":
                        newIntent(CCAtlasClient.TALKER, mAccountId, mRoomId, username, password, des.getTalkerAuthtype() == 2, des, template);
                        break;
                    case "aul":
                        newIntent(CCAtlasClient.AULOW, mAccountId, mRoomId, username, password, des.getTalkerAuthtype() == 2, des, template);
                        break;
                    case "aum":
                        newIntent(CCAtlasClient.AUMIDDLE, mAccountId, mRoomId, username, password, des.getTalkerAuthtype() == 2, des, template);
                        break;
                    case "auh":
                        newIntent(CCAtlasClient.AUHIGH, mAccountId, mRoomId, username, password, des.getTalkerAuthtype() == 2, des, template);
                        break;
                    case "assistant":
                        newIntent(ASSISTANT, mAccountId, mRoomId, username, password, false, des, template);
                        break;
                    default:
                        newIntent(-1, mAccountId, mRoomId, username, password, des.getTalkerAuthtype() == 2, des, template);
                        break;
                }

                dismissProgress();
            }

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

    /**
     * 跳转
     *
     * @param role
     * @param accountId
     * @param roomid
     * @param username
     * @param pwd
     * @param roomDes
     * @param template
     */
    private void newIntent(int role, String accountId, String roomid, String username, String pwd, boolean isNoPwd, CCRoomInfo roomDes, String template) {
        Log.d("HOMEACTIVITY","template ==" + template);
        try {
            if (!TextUtils.isEmpty(template)) {
                int templateInt = Integer.valueOf(template);
            }
        } catch (Exception e){
            Tools.showToast("您输入的链接有误");
            return;
        }
        Tools.log("role = " +  role + "accountId = " + accountId + "roomid = " + roomid +"username = " + username +"pwd = " + pwd +"isNoPwd = " + isNoPwd +"template = " + template);
        Intent intent = new Intent(HomeActivity.this, DirectionActivity.class);
        intent.putExtra(Config.KEY_ROOM_ROLE, role);
        intent.putExtra(Config.KEY_ROOM_ACCOUNTID, accountId);
        intent.putExtra(Config.KEY_ROOM_ROOMID, roomid);
        intent.putExtra(Config.KEY_ROOM_NAME, roomDes.getName());
        intent.putExtra(Config.KEY_ROOM_DESC, roomDes.getDesc());
        intent.putExtra(Config.KEY_LOGIN_NO_PWD, isNoPwd);
        intent.putExtra(Config.KEY_ROOM_LAYOUT_MODE, roomDes.getLayoutMode());
        intent.putExtra(Config.KEY_ROOM_TEMPLATE, TextUtils.isEmpty(template) ? "" : template);
        intent.putExtra(Config.KEY_ROOM_USERNAME,TextUtils.isEmpty(username) ? "" : username);
        intent.putExtra(Config.KEY_ROOM_PWD,TextUtils.isEmpty(pwd) ? "" : pwd);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        startActivity(intent);
    }

    /**
     * 通过参课码获取房间信息
     * @param classNo
     */
    private void getRoomInfo(int classNo) {
        showProgress();
        CCAtlasClient.getInstance().getRoomInfo(classNo, new CCAtlasCallBack<CCRoomInfo>() {
            @Override
            public void onSuccess(CCRoomInfo des) {
                roomDes = des;

                if (des.getTemplateType() != Integer.parseInt(ROOM_TYPE_SAAS)){
                    isShowOri = true;
                    llOrientation.setVisibility(View.VISIBLE);
                } else {
                    isShowOri = false;
                    llOrientation.setVisibility(View.GONE);
                }

                if(Integer.parseInt(mRole) == CCAtlasClient.PRESENTER ||Integer.parseInt(mRole) == CCAtlasClient.ASSISTANT){
                    mClearEditLayoutPwd.setVisibility(View.VISIBLE);
                    isShowPwd = true;
                }else if((Integer.parseInt(mRole) == CCAtlasClient.INSPECTOR) && des.getInspectorAuthtype() != 2){
                    mClearEditLayoutPwd.setVisibility(View.VISIBLE);
                    isShowPwd = true;
                }else if((Integer.parseInt(mRole) == CCAtlasClient.TALKER || Integer.parseInt(mRole) == CCAtlasClient.AULOW) && des.getTalkerAuthtype() != 2){
                    mClearEditLayoutPwd.setVisibility(View.VISIBLE);
                    isShowPwd = true;
                }else {
                    isShowPwd = false;
                    mClearEditLayoutPwd.setVisibility(View.GONE);
                }
                dismissProgress();
            }

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

    /**
     * 跳转到直播间内
     */
    private void goRoom() {
        Tools.hideSoftInput(HomeActivity.this);//收起键盘
        //取最后一位作为角色
        String myRole = mClearEditLayoutCode.getText().trim().substring(CLASS_NUMBER_LENGTH - 1,CLASS_NUMBER_LENGTH);
        //开始登录
        showProgress();
        CCAtlasClient.getInstance().login(roomDes.getRoomId(), roomDes.getUserid(), Integer.parseInt(myRole), mClearEditLayoutName.getText().toString(), mClearEditLayoutPwd.getText().toString(),"Android", new CCAtlasCallBack<String>() {
            @Override
            public void onSuccess(String sessionid) {
                dismissProgress();
                join(sessionid);
            }

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

    /**
     * 加入直播间
     * @param mSeesionid
     */
    private void join(String mSeesionid) {
        if (TextUtils.equals(ROOM_TYPE_SAAS, type == url_type ? template : String.valueOf(roomDes.getTemplateType()))) {
            Intent intent = new Intent();
            if (roomDes.getLayoutMode() != 5) {
                if (Integer.parseInt(mRole) == PRESENTER) {
                    intent.setClass(this, SaasTeacherRoomActivity.class);
                } else if (Integer.parseInt(mRole) == INSPECTOR) {
                    intent.setClass(this, SaasInspectorRoomActivity.class);
                } else if (Integer.parseInt(mRole) == ASSISTANT) {
                    if (roomDes.getLayoutMode() == 4){
                        Tools.showToast(R.string.cc_demo_no_role,false);
                        return;
                    }
                    intent.setClass(this, SaasAssistantRoomActivity.class);
                } else {
                    intent.setClass(this, SaasStudentRoomActivity.class);
                }
            } else {
                if (Integer.parseInt(mRole) == TALKER){
                    intent.setClass(this, SaasMeetingStudentRoomActivity.class);
                } else {
                    Tools.showToast(R.string.cc_demo_no_role,false);
                }
            }
            intent.putExtra(CCRoomActivity.SeesionidKey, mSeesionid);
            intent.putExtra(CCRoomActivity.RoomIdKey, roomDes.getRoomId());
            intent.putExtra(CCRoomActivity.UserAccountKey, roomDes.getUserid());
            intent.putExtra(CCRoomActivity.AreaCodeKey, mAreaCode);
//            if (roomDes.getLayoutMode() == 1 || roomDes.getLayoutMode() == 2 || roomDes.getLayoutMode() == 3 || roomDes.getLayoutMode() == 4) {
                intent.putExtra(CCRoomActivity.KeyLayoutMode, roomDes.getLayoutMode());
//            } else {
//                intent.putExtra(CCRoomActivity.KeyLayoutMode, 0);
//            }
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivityForResult(intent,Config.REQUEST_UPDATE_FLAG);
        }else{
            //老房间
            if (Integer.parseInt(mRole) == CCAtlasClient.PRESENTER) {
                Intent intent = new Intent(HomeActivity.this, TeacherRoomActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.putExtra(com.bokecc.room.ui.view.base.CCRoomActivity.ScreenDirectionKey, classDirection);
                intent.putExtra(com.bokecc.room.ui.view.base.CCRoomActivity.SeesionidKey, mSeesionid);
                intent.putExtra(com.bokecc.room.ui.view.base.CCRoomActivity.RoomIdKey, roomDes.getRoomId());
                intent.putExtra(com.bokecc.room.ui.view.base.CCRoomActivity.UserAccountKey, roomDes.getUserid());
                intent.putExtra(CCRoomActivity.AreaCodeKey, mAreaCode);
                startActivity(intent);
            } else if (Integer.parseInt(mRole) == TALKER) {
                Intent intent = new Intent(HomeActivity.this, StudentRoomActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.putExtra(com.bokecc.room.ui.view.base.CCRoomActivity.ScreenDirectionKey, classDirection);
                intent.putExtra(com.bokecc.room.ui.view.base.CCRoomActivity.SeesionidKey, mSeesionid);
                intent.putExtra(com.bokecc.room.ui.view.base.CCRoomActivity.RoomIdKey, roomDes.getRoomId());
                intent.putExtra(com.bokecc.room.ui.view.base.CCRoomActivity.UserAccountKey, roomDes.getUserid());
                intent.putExtra(com.bokecc.room.ui.view.base.CCRoomActivity.AreaCodeKey, mAreaCode);
                startActivity(intent);
            } else if (Integer.parseInt(mRole)  == INSPECTOR) {
                Intent intent = new Intent(HomeActivity.this, InspectorRoomActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.putExtra(com.bokecc.room.ui.view.base.CCRoomActivity.ScreenDirectionKey, classDirection);
                intent.putExtra(com.bokecc.room.ui.view.base.CCRoomActivity.SeesionidKey, mSeesionid);
                intent.putExtra(com.bokecc.room.ui.view.base.CCRoomActivity.RoomIdKey, roomDes.getRoomId());
                intent.putExtra(com.bokecc.room.ui.view.base.CCRoomActivity.UserAccountKey, roomDes.getUserid());
                intent.putExtra(com.bokecc.room.ui.view.base.CCRoomActivity.AreaCodeKey, mAreaCode);
                startActivity(intent);
            } else {
                Tools.showToast(R.string.cc_demo_no_role,false);
            }
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mClearEditLayoutCode.onDestory();
    }

    private void initObserver(){
        AudRemoveObservable.getInstance().addObserver(new Observer() {
            @Override
            public void update(Observable o, Object arg) {
                Log.d("CCSDK", "收到转为观众的消息消息 ");
                needOpenLive = true;
            }
        });
    }

    private void openLive(){
        Intent intent = new Intent(this, LiveActivity.class);
        intent.putExtra("liveUrl",liveUrl);
        startActivity(intent);
    }

}
