package com.easemob.helpdeskdemo.ui;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.easemob.helpdeskdemo.Constant;
import com.easemob.helpdeskdemo.DemoMessageHelper;
import com.easemob.helpdeskdemo.Preferences;
import com.easemob.helpdeskdemo.R;
import com.hyphenate.chat.AgoraMessage;
import com.hyphenate.chat.ChatClient;
import com.hyphenate.chat.ChatManager;
import com.hyphenate.chat.Conversation;
import com.hyphenate.chat.EMClient;
import com.hyphenate.helpdesk.Error;
import com.hyphenate.helpdesk.callback.Callback;
import com.hyphenate.helpdesk.callback.ValueCallBack;
import com.hyphenate.helpdesk.easeui.util.IntentBuilder;
import com.hyphenate.helpdesk.easeui.widget.ToastHelper;

import java.util.Locale;
import java.util.Random;

public class CallInterfaceActivity extends Activity {

    private static final String TAG = "CallInterfaceActivity";
    private TextView mWelcomeWordsTv;
    private TextView mMenuTv;
    private TextView mGetWelcomeMenuTv;
    private TextView mGetTwoWelcomeMenuTv;
    private String mName;
    private TextView mTextView;
    private TextView mCurrentUserName;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_call_interface);
        findViewById(R.id.chatBt).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(mName)){
                    Toast.makeText(CallInterfaceActivity.this, "请先登录！", Toast.LENGTH_LONG).show();
                    return;
                }

                Intent intent = new Intent(CallInterfaceActivity.this, TestLoginActivity.class);
                intent.putExtra("name", mName);
                startActivity(intent);
            }
        });

        findViewById(R.id.loginBt).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 登录
                Intent intent = new Intent(CallInterfaceActivity.this, TestLoginActivity.class);
                startActivityForResult(intent, 0);
            }
        });

        EditText et = findViewById(R.id.et);
        findViewById(R.id.ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String s = et.getText().toString();
                if (TextUtils.isEmpty(s)){
                    Toast.makeText(CallInterfaceActivity.this, "不能为空！", Toast.LENGTH_LONG).show();
                    return;
                }

                mName = Preferences.getInstance().getLocalUserName();
                if (TextUtils.isEmpty(mName)){
                    Toast.makeText(CallInterfaceActivity.this, "请先登录！", Toast.LENGTH_LONG).show();
                    return;
                }

                AgoraMessage.asyncInitLanguage(ChatClient.getInstance().tenantId(),
                        s, Preferences.getInstance().getAppKey(), mName, new ValueCallBack<String>() {
                            @Override
                            public void onSuccess(String value) {

                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(CallInterfaceActivity.this, "初始化语言成功！", Toast.LENGTH_LONG).show();
                                    }
                                });
                            }

                            @Override
                            public void onError(int error, String errorMsg) {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(CallInterfaceActivity.this, "初始化语言失败！", Toast.LENGTH_LONG).show();
                                    }
                                });
                            }
                        });
            }
        });

        mWelcomeWordsTv = findViewById(R.id.welcomeWordsTv);
        findViewById(R.id.welcomeWordsBt).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(mName)){
                    Toast.makeText(CallInterfaceActivity.this, "请先登录！", Toast.LENGTH_LONG).show();
                    return;
                }

                ChatManager.getInstance().getEnterpriseWelcome(mName, new ValueCallBack<String>() {
                    @Override
                    public void onSuccess(String value) {
                        if (isFinishing()){
                            return;
                        }
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mWelcomeWordsTv.setText(value);
                            }
                        });
                    }

                    @Override
                    public void onError(int error, String errorMsg) {
                        runOnUiThread(new Runnable() {
                            @SuppressLint("SetTextI18n")
                            @Override
                            public void run() {
                                mWelcomeWordsTv.setText("errorCode = "+error+", errorMsg = "+errorMsg);
                            }
                        });
                    }
                });
            }
        });

        mMenuTv = findViewById(R.id.menuTv);
        findViewById(R.id.menuBt).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(mName)){
                    Toast.makeText(CallInterfaceActivity.this, "请先登录！", Toast.LENGTH_LONG).show();
                    return;
                }

                AgoraMessage.getSkillGroupMenuWithVisitorUserName(ChatClient.getInstance().tenantId(), mName, new ValueCallBack<String>() {
                    @Override
                    public void onSuccess(String value) {
                        if (isFinishing()){
                            return;
                        }
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mMenuTv.setText(value);
                            }
                        });
                    }

                    @Override
                    public void onError(int error, String errorMsg) {
                        runOnUiThread(new Runnable() {
                            @SuppressLint("SetTextI18n")
                            @Override
                            public void run() {
                                mMenuTv.setText("errorCode = "+error+", errorMsg = "+errorMsg);
                            }
                        });
                    }
                });
            }
        });


        // 访客端获取欢迎语菜单
        mGetWelcomeMenuTv = findViewById(R.id.getWelcomeMenuTv);
        findViewById(R.id.getWelcomeMenuBt).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(mName)){
                    Toast.makeText(CallInterfaceActivity.this, "请先登录！", Toast.LENGTH_LONG).show();
                    return;
                }

                String target = Preferences.getInstance().getCustomerAccount();

                ChatClient.getInstance().chatManager().getAppRelevanceSkillGroupMenuWithVisitorUserName(target, mName, new ValueCallBack<String>() {
                    @Override
                    public void onSuccess(String value) {
                        runOnUiThread(new Runnable() {
                            @SuppressLint("SetTextI18n")
                            @Override
                            public void run() {
                                mGetWelcomeMenuTv.setText(value);
                            }
                        });
                    }

                    @Override
                    public void onError(int error, String errorMsg) {
                        runOnUiThread(new Runnable() {
                            @SuppressLint("SetTextI18n")
                            @Override
                            public void run() {
                                mGetWelcomeMenuTv.setText("errorCode = "+error+", errorMsg = "+errorMsg);
                            }
                        });

                    }
                });

            }
        });

        // 访客端获取企业欢迎语
        mGetTwoWelcomeMenuTv = findViewById(R.id.getTwoWelcomeMenuTv);
        findViewById(R.id.getTwoWelcomeBt).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(mName)){
                    Toast.makeText(CallInterfaceActivity.this, "请先登录！", Toast.LENGTH_LONG).show();
                    return;
                }

                String target = Preferences.getInstance().getCustomerAccount();
                ChatClient.getInstance().chatManager().getAppRelevanceEnterpriseWelcomeWithVisitorUserName(target, mName, new ValueCallBack<String>() {
                    @Override
                    public void onSuccess(String value) {
                        runOnUiThread(new Runnable() {
                            @SuppressLint("SetTextI18n")
                            @Override
                            public void run() {
                                mGetTwoWelcomeMenuTv.setText(value);
                            }
                        });
                    }

                    @Override
                    public void onError(int error, String errorMsg) {
                        runOnUiThread(new Runnable() {
                            @SuppressLint("SetTextI18n")
                            @Override
                            public void run() {
                                mGetTwoWelcomeMenuTv.setText("errorCode = "+error+", errorMsg = "+errorMsg);
                            }
                        });
                    }
                });

            }
        });

        name1 = Preferences.getInstance().getLocalUserName();
        mTextView = findViewById(R.id.textView);
        mTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTextView.setText(Preferences.getInstance().getLocalUserName()+"");
            }
        });

        View out = findViewById(R.id.out);
        out.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 退出
                ChatClient.getInstance().logout(true, new Callback() {
                    @Override
                    public void onSuccess() {
                        Log.e(TAG,"退出 onSuccess");
                    }

                    @Override
                    public void onError(int i, String s) {
                        Log.e(TAG,"退出 onError");
                    }
                    @Override
                    public void onProgress(int i, String s) {

                    }
                });
            }
        });

        View login = findViewById(R.id.login);
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 登录
                createRandomAccountThenLoginChatServer2();
            }
        });

        View login2 = findViewById(R.id.login2);
        login2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 登录
                final String uname = name1;
                final String upwd = Constant.DEFAULT_ACCOUNT_PWD;
                Log.e(TAG,"登录第一个账户 uname = "+uname);
                Log.e(TAG,"upwd = "+upwd);
                //登录环信服务器
                login(uname, upwd);
            }
        });

        View login3 = findViewById(R.id.login3);
        login3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 登录
                final String uname = name2;
                final String upwd = Constant.DEFAULT_ACCOUNT_PWD;
                Log.e(TAG,"登录第二个账户 uname = "+uname);
                Log.e(TAG,"upwd = "+upwd);
                //登录环信服务器
                login(uname, upwd);
            }
        });

        // 获取当前用户名
        mCurrentUserName = findViewById(R.id.currentUserName);
        String name = ChatClient.getInstance().currentUserName();
        name = TextUtils.isEmpty(name) ? "未登录" : name;
        mCurrentUserName.setText(name);


        // 随机注册并登录
        View login4 = findViewById(R.id.login4);
        login4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                login();
            }
        });



        // 是否收到初始化通知用户登录
        TextView notifyTv = findViewById(R.id.notifyTv);
        notifyTv.setText(sNeedLogin ? "收到登录通知" : "无");

        // 退出当前用户
        View logout = findViewById(R.id.logout);
        logout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ChatClient.getInstance().logout(true, new Callback() {
                    @Override
                    public void onSuccess() {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mCurrentUserName.setText("退出成功");
                            }
                        });
                    }

                    @Override
                    public void onError(int i, String s) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mCurrentUserName.setText("退出失败："+s);
                            }
                        });
                    }

                    @Override
                    public void onProgress(int i, String s) {

                    }
                });
            }
        });

        // 随机用户名
        TextView userName = findViewById(R.id.userName);
        TextView userPassword = findViewById(R.id.userPassword);
        TextView userNameTwo = findViewById(R.id.userNameTwo);
        TextView userPasswordTwo = findViewById(R.id.userPasswordTwo);
        TextView userNameThree = findViewById(R.id.userNameThree);
        TextView userPasswordThree = findViewById(R.id.userPasswordThree);


        String loginName = getNeedLoginName(this);
        String loginPassword = getNeedLoginPassword(this);
        if (!TextUtils.isEmpty(loginName) && !TextUtils.isEmpty(loginPassword)){
            userName.setText("用户名："+loginName);
            userPassword.setText("密码："+loginPassword);
        }

        // 随机获取用户名和密码
        View getNameAndPassword = findViewById(R.id.getNameAndPassword);
        getNameAndPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String randomAccount = getRandomAccount();
                ChatClient.getInstance().register(randomAccount, "123456", new Callback() {
                    @Override
                    public void onSuccess() {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                saveLoginName(randomAccount);
                                saveLoginPassword("123456");
                                userName.setText("用户名："+randomAccount);
                                userPassword.setText("密码：123456");

                                userNameTwo.setText("");
                                userPasswordTwo.setText("");

                                userNameThree.setText("");
                                userPasswordThree.setText("");
                            }
                        });
                    }

                    @Override
                    public void onError(int code, String error) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                saveLoginName("");
                                saveLoginPassword("");

                                userName.setText("注册用户名失败，"+error);
                                userPassword.setText("密码：123456");

                                userNameTwo.setText("");
                                userPasswordTwo.setText("");

                                userNameThree.setText("");
                                userPasswordThree.setText("");
                            }
                        });
                    }

                    @Override
                    public void onProgress(int progress, String status) {

                    }
                });
            }
        });


        // 随机用户名
        String loginNameTwo = getNeedLoginName(this);
        String loginPasswordTwo = getNeedLoginPassword(this);

        if (!TextUtils.isEmpty(loginNameTwo) && TextUtils.isEmpty(loginPasswordTwo)){
            userNameTwo.setText("用户名："+loginNameTwo);
            userPasswordTwo.setText("密码：空");
        }

        View getNameAndPasswordTwo = findViewById(R.id.getNameAndPasswordTwo);
        getNameAndPasswordTwo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String randomAccount = getRandomAccount();
                ChatClient.getInstance().register(randomAccount, "123456", new Callback() {
                    @Override
                    public void onSuccess() {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                saveLoginName(randomAccount);
                                saveLoginPassword("");

                                userNameTwo.setText("用户名："+randomAccount);
                                userPasswordTwo.setText("密码：空");

                                userName.setText("");
                                userPassword.setText("");

                                userNameThree.setText("");
                                userPasswordThree.setText("");
                            }
                        });
                    }

                    @Override
                    public void onError(int code, String error) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                saveLoginName("");
                                saveLoginPassword("");

                                userNameTwo.setText("注册用户名失败，"+error);
                                userPasswordTwo.setText("密码：123456");

                                userName.setText("");
                                userPassword.setText("");

                                userNameThree.setText("");
                                userPasswordThree.setText("");
                            }
                        });
                    }

                    @Override
                    public void onProgress(int progress, String status) {

                    }
                });
            }
        });


        // 随机用户名
        String loginNameThree = getNeedLoginName(this);
        String loginPasswordThree = getNeedLoginPassword(this);
        // 随机密码
        if (TextUtils.isEmpty(loginNameThree) && !TextUtils.isEmpty(loginPasswordThree)){
            userNameThree.setText("用户名：空");
            userPasswordThree.setText("密码："+loginPasswordThree);
        }

        View getNameAndPasswordThree = findViewById(R.id.getNameAndPasswordThree);
        getNameAndPasswordThree.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String randomAccount = getRandomAccount();
                ChatClient.getInstance().register(randomAccount, "123456", new Callback() {
                    @Override
                    public void onSuccess() {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                saveLoginName("");
                                saveLoginPassword("123456");

                                userNameThree.setText("用户名：空");
                                userPasswordThree.setText("密码：123456");

                                userName.setText("");
                                userPassword.setText("");

                                userNameTwo.setText("");
                                userPasswordTwo.setText("");
                            }
                        });
                    }

                    @Override
                    public void onError(int code, String error) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                saveLoginName("");
                                saveLoginPassword("");

                                userNameThree.setText("注册用户名失败，"+error);
                                userPasswordThree.setText("密码：123456");

                                userName.setText("");
                                userPassword.setText("");

                                userNameTwo.setText("");
                                userPasswordTwo.setText("");
                            }
                        });
                    }

                    @Override
                    public void onProgress(int progress, String status) {

                    }
                });
            }
        });


        // 清除随机获取用户名和密码
        View clearBt = findViewById(R.id.clearBt);
        clearBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveLoginName("");
                saveLoginPassword("");

                userName.setText("");
                userPassword.setText("");

                userNameTwo.setText("");
                userPasswordTwo.setText("");

                userNameThree.setText("");
                userPasswordThree.setText("");

                AgoraMessage.saveVisitorRegion(ChatClient.getInstance().currentUserName(), new ValueCallBack<String>() {
                    @Override
                    public void onSuccess(String value) {
                        Log.e("ppppppppppp","saveVisitorRegion = "+value);
                    }

                    @Override
                    public void onError(int error, String errorMsg) {
                        Log.e("ppppppppppp","saveVisitorRegion errorMsg = "+errorMsg);
                    }
                });
            }
        });

        // 显示IM状态
        TextView checkImLogin = findViewById(R.id.checkImLogin);
        // 检测IM状态
        View checkImBt = findViewById(R.id.checkImBt);
        checkImBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean loggedIn = EMClient.getInstance().isLoggedIn();
                boolean connected = EMClient.getInstance().isConnected();
                boolean loggedInBefore = ChatClient.getInstance().isLoggedInBefore();
                checkImLogin.setText(String.format(Locale.CHINA,"loggedIn = %b\nconnected = %b\nloggedInBefore = %b",
                        loggedIn, connected, loggedInBefore));
            }
        });

    }

    private static String name1;
    private static String name2;

    private void createRandomAccountThenLoginChatServer() {
        // 自动生成账号,此处每次都随机生成一个账号,为了演示.正式应从自己服务器获取账号
        final String uname = Preferences.getInstance().getUserName();
        final String upwd = Constant.DEFAULT_ACCOUNT_PWD;
        name2 = uname;
        // createAccount to huanxin server
        // if you have a account, this step will ignore
        ChatClient.getInstance().register(uname, upwd, new Callback() {
            @Override
            public void onSuccess() {
                Log.e(TAG,"注册随机用户 uname = "+uname);
                Log.e(TAG,"upwd = "+upwd);
                Log.e(TAG,"register success");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //登录环信服务器
                        login(uname, upwd);
                    }
                });
            }

            @Override
            public void onError(final int errorCode, String error) {
                Log.e(TAG,"register error");
            }

            @Override
            public void onProgress(int progress, String status) {

            }
        });
    }

    private void login(String uname, String upwd){
        ChatClient.getInstance().login(uname, upwd, new Callback() {
            @Override
            public void onSuccess() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.e(TAG,"登录成功 = "+uname);
                        toChatActivity();
                    }
                });
            }

            @Override
            public void onError(int code, String error) {
                Log.e(TAG,"onError = "+error);
            }

            @Override
            public void onProgress(int progress, String status) {
            }
        });
    }

    private void toChatActivity() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //此处演示设置技能组,如果后台设置的技能组名称为[shouqian|shouhou],这样指定即分配到技能组中.
                //为null则不按照技能组分配,同理可以设置直接指定客服scheduleAgent
                String queueName = null;
                switch (Constant.MESSAGE_TO_AFTER_SALES){
                    case Constant.MESSAGE_TO_AFTER_SALES:
                        queueName = "shouhou";
                        break;
                    case Constant.MESSAGE_TO_PRE_SALES:
                        queueName = "shouqian";
                        break;
                    default:
                        break;
                }
                Bundle bundle = new Bundle();
                bundle.putInt(Constant.INTENT_CODE_IMG_SELECTED_KEY, Constant.MESSAGE_TO_AFTER_SALES);
                //设置点击通知栏跳转事件
                Conversation conversation = ChatClient.getInstance().chatManager().getConversation(Preferences.getInstance().getCustomerAccount());
                String titleName = null;
                if (conversation.officialAccount() != null){
                    titleName = conversation.officialAccount().getName();
                }

                Log.e(TAG, "getCustomerAccount = "+Preferences.getInstance().getCustomerAccount());
                // AgoraMessage.newAgoraMessage().setVecImServiceNumber(Preferences.getInstance().getCustomerAccount());
                // 进入主页面
                Intent intent = new IntentBuilder(CallInterfaceActivity.this)
                        .setTargetClass(ChatActivity.class)
                        .setVisitorInfo(DemoMessageHelper.createVisitorInfo())
                        .setServiceIMNumber(Preferences.getInstance().getCustomerAccount())
                        .setScheduleQueue(DemoMessageHelper.createQueueIdentity(queueName))
                        .setTitleName(titleName)
//						.setScheduleAgent(DemoMessageHelper.createAgentIdentity("ceshiok1@qq.com"))
                        .setShowUserNick(true)
                        .setBundle(bundle)
                        .build();
                startActivity(intent);

                finish();
            }
        });
    }

    private String getRandomAccount(){
        String val = "";
        Random random = new Random();
        for(int i = 0; i < 15; i++){
            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num"; //输出字母还是数字
            if("char".equalsIgnoreCase(charOrNum)){// 字符串
                int choice = random.nextInt(2) % 2 == 0 ? 65 : 97; //取得大写字母还是小写字母
                val += (char) (choice + random.nextInt(26));
            }else if("num".equalsIgnoreCase(charOrNum)){// 数字
                val += String.valueOf(random.nextInt(10));
            }
        }
        return val.toLowerCase(Locale.getDefault());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 1){
            Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();
            mName = data.getStringExtra("name");
        }
    }

    private void saveLoginName(String name){
        SharedPreferences test = getSharedPreferences("test", Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = test.edit();
        edit.putString("test_user_name", name);
        edit.commit();
    }

    private void saveLoginPassword(String password){
        SharedPreferences test = getSharedPreferences("test", Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = test.edit();
        edit.putString("test_user_password", password);
        edit.commit();
    }

    public static volatile boolean sNeedLogin = false;
    public static String sData;
    public static String getNeedLoginName(Context context){
        SharedPreferences test = context.getSharedPreferences("test", Context.MODE_PRIVATE);
        return test.getString("test_user_name","");
    }

    public static String getNeedLoginPassword(Context context){
        SharedPreferences test = context.getSharedPreferences("test", Context.MODE_PRIVATE);
        return test.getString("test_user_password","");
    }

    private void login(){
        createRandomAccountThenLoginChatServer2();
    }

    private void createRandomAccountThenLoginChatServer2() {
        // 自动生成账号,此处每次都随机生成一个账号,为了演示.正式应从自己服务器获取账号
        final String account = Preferences.getInstance().getUserName();
        final String userPwd = Constant.DEFAULT_ACCOUNT_PWD;

        progressDialog = getProgressDialog();
        progressDialog.setMessage(getString(R.string.system_is_regist));
        progressDialog.show();

        // createAccount to huanxin server
        // if you have a account, this step will ignore
        ChatClient.getInstance().register(account, userPwd, new Callback() {
            @Override
            public void onSuccess() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //登录环信服务器
                        ChatClient.getInstance().logout(false, new Callback() {
                            @Override
                            public void onSuccess() {
                                login2(account, userPwd);
                            }

                            @Override
                            public void onError(int i, String s) {
                                login2(account, userPwd);
                            }

                            @Override
                            public void onProgress(int i, String s) {

                            }
                        });

                    }
                });
            }

            @Override
            public void onError(final int errorCode, String error) {
                runOnUiThread(new Runnable() {
                    public void run() {
                        if(progressDialog != null && progressDialog.isShowing()){
                            progressDialog.dismiss();
                        }
                        if (errorCode == Error.NETWORK_ERROR){
                            ToastHelper.show(getBaseContext(), R.string.network_unavailable);
                        }else if (errorCode == Error.USER_ALREADY_EXIST){
                            ToastHelper.show(getBaseContext(), R.string.user_already_exists);
                        }else if(errorCode == Error.USER_AUTHENTICATION_FAILED){
                            ToastHelper.show(getBaseContext(), R.string.no_register_authority);
                        } else if (errorCode == Error.USER_ILLEGAL_ARGUMENT){
                            ToastHelper.show(getBaseContext(), R.string.illegal_user_name);
                        }else {
                            ToastHelper.show(getBaseContext(), R.string.register_user_fail);
                        }
                    }
                });
            }

            @Override
            public void onProgress(int progress, String status) {

            }
        });
    }

    ProgressDialog progressDialog;
    private ProgressDialog getProgressDialog() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(this);
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                }
            });
        }
        return progressDialog;
    }

    private void login2(final String uname, final String upwd) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                progressDialog = getProgressDialog();
                progressDialog.setMessage(getResources().getString(R.string.is_contact_customer));
                if (!progressDialog.isShowing()) {
                    if (isFinishing()){
                        return;
                    }
                    progressDialog.show();
                }
                // login huanxin server
                ChatClient.getInstance().login(uname, upwd, new Callback() {
                    @Override
                    public void onSuccess() {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                progressDialog.dismiss();
                                mCurrentUserName.setText(uname);
                            }
                        });
                    }

                    @Override
                    public void onError(int code, String error) {
                        runOnUiThread(new Runnable() {
                            public void run() {
                                progressDialog.dismiss();
                                ToastHelper.show(getBaseContext(), error);
                                mCurrentUserName.setText(uname);
                            }
                        });
                    }

                    @Override
                    public void onProgress(int progress, String status) {

                    }
                });
            }
        });
    }
}
