package com.uas.module.home.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.maning.mndialoglibrary.MProgressDialog;
import com.maning.mndialoglibrary.MToast;
import com.uas.module.common.base.BaseActionBarActivity;
import com.uas.module.home.R;
import com.uas.module.home.network.grpc.MobileClientAuthenticationInterceptor;
import com.uas.module.widget.core.ClearEditText;
import com.usoftchina.uu.mobile.grpc.api.AccountInfo;
import com.usoftchina.uu.mobile.grpc.api.AccountServiceGrpc;
import com.usoftchina.uu.mobile.grpc.api.AccountSignupRequest;
import com.usoftchina.uu.mobile.grpc.api.AccountSignupResponse;
import com.usoftchina.uu.mobile.grpc.api.ResponseHeader;

import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.StatusRuntimeException;


@Route(path = "/home/register")
public class RegisterActivity extends BaseActionBarActivity {

    public static final String REGEXP_MOBILE_CONTINENT = "1[0-9]{10}";

    private ClearEditText mUsernameEditText, mPhoneEditText, mPasswordEditText, mPasswordConfirmEditText;
    private TextView mConfirmButton, mSuccessButton;
    private LinearLayout mPasswordLinearLayout, mPasswordConfirmLinearLayout, mSuccessLinearLayout;
//    private StrengthView mStrengthView;

    private int male_log = 1;
    private long bir_Timestamp = 1489141231;
    private String md5_password;
    
    @Override
    protected int setTitleId() {
        return R.string.person_register;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_register);
        initView();
    }


    private void initView() {
        mUsernameEditText = findViewById(R.id.personal_reg_username_et);
        mPhoneEditText = findViewById(R.id.personal_reg_phone_et);
        mPasswordEditText = findViewById(R.id.personal_reg_password_et);
        mPasswordConfirmEditText = findViewById(R.id.personal_reg_password_confirm_et);
        mConfirmButton = findViewById(R.id.personal_reg_confirm_tv);
        mPasswordLinearLayout = findViewById(R.id.personal_reg_password_ll);
        mPasswordLinearLayout.setEnabled(false);
        mPasswordConfirmLinearLayout = findViewById(R.id.personal_reg_password_confirm_ll);
        mPasswordConfirmLinearLayout.setEnabled(false);
//        mStrengthView = findViewById(R.id.personal_reg_strength_sv);
        mSuccessLinearLayout = findViewById(R.id.personal_reg_success_ll);
        mSuccessButton = findViewById(R.id.personal_reg_success_btn);

        mPhoneEditText.addTextChangedListener(new EnableTextWatcher());
        mUsernameEditText.addTextChangedListener(new EnableTextWatcher());
        mPasswordConfirmEditText.addTextChangedListener(new EnableTextWatcher());
        mPasswordEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
               if (!StringUtils.isEmpty(editable.toString())){
                   isConfirmEnable();
               }
            }
        });

        mConfirmButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String phone = mPhoneEditText.getText().toString().trim();
                if (!TextUtils.isEmpty(phone) && phone.matches(REGEXP_MOBILE_CONTINENT)) {
                    String password1 = mPasswordEditText.getText().toString();
                    String password2 = mPasswordConfirmEditText.getText().toString();
                    if (password1 != null && password1.equals(password2)) {
                        doRegiter();
                    } else {
                        ToastUtils.showLong("两次输入的密码不一致");
                    }
                } else {
                    if (TextUtils.isEmpty(phone)) {
                        ToastUtils.showLong("手机号为空");
                    } else {
                        ToastUtils.showLong("请填写正确的手机号");
                    }
                }
            }
        });

        mSuccessButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(RegisterActivity.this, LoginActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                finish();
            }
        });
    }


    class EnableTextWatcher implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            isConfirmEnable();
        }
    }


    private void isConfirmEnable() {
        String phone = mPhoneEditText.getText().toString().trim();
        String username = mUsernameEditText.getText().toString().trim();
        String password1 = mPasswordEditText.getText().toString();
        String password2 = mPasswordConfirmEditText.getText().toString();

        if (TextUtils.isEmpty(phone) || TextUtils.isEmpty(username)) {
            mPasswordLinearLayout.setEnabled(false);
            mPasswordEditText.setEnabled(false);
            mPasswordConfirmLinearLayout.setEnabled(false);
            mPasswordConfirmEditText.setEnabled(false);
        } else {
            mPasswordLinearLayout.setEnabled(true);
            mPasswordEditText.setEnabled(true);
            mPasswordConfirmLinearLayout.setEnabled(true);
            mPasswordConfirmEditText.setEnabled(true);
        }

        if (TextUtils.isEmpty(phone) || TextUtils.isEmpty(username) 
                || TextUtils.isEmpty(password1) || TextUtils.isEmpty(password2)) {
            mConfirmButton.setEnabled(false);
        } else {
            mConfirmButton.setEnabled(true);
        }
    }


    private void doRegiter() {
        MProgressDialog.showProgress(this,"");
      new Thread(()->{
          ManagedChannel channel = ManagedChannelBuilder.forAddress("uu-api-test.usoftchina.com", 9620)
                  .intercept(new MobileClientAuthenticationInterceptor())
                  .usePlaintext(true)
                  .build();
          AccountSignupRequest request = AccountSignupRequest.newBuilder()
                  .setMobile(mPhoneEditText.getText().toString())
                  .setEmail("784602819@qq.com")
                  .setRealname(mUsernameEditText.getText().toString())
                  .setSex(AccountInfo.Sex.MALE)
                  .setPassword(mPasswordEditText.getText().toString())
                  .build();
          try {

              AccountSignupResponse response = AccountServiceGrpc.newBlockingStub(channel).signup(request);
              ResponseHeader header = response.getResponseHeader();

              if (header.getSuccess()) {
                  MProgressDialog.dismissProgress();

                  ARouter.getInstance().build("/home/login")
                          .withString("phone",mPhoneEditText.getText().toString())
                          .withString("password",mPasswordEditText.getText().toString())
                          .navigation();
                  LogUtils.d("header:"+header.getMessage());
              } else {
                  MProgressDialog.dismissProgress();
                  runOnUiThread(()-> MToast.makeTextLong(RegisterActivity.this, header.getMessage()));
                  //LogUtils.d("header:"+header.getCode() + "," + header.getMessage());

              }
          } catch (StatusRuntimeException e) {
              MProgressDialog.dismissProgress();
              runOnUiThread(()-> MToast.makeTextLong(RegisterActivity.this, e.getStatus().getDescription()));
             // LogUtils.d("header Exception:"+e.getStatus().getCode() + "," + e.getStatus().getDescription());

          }
      }).start();
    }
}
