package io.openim.android.demo.ui.login;

import static io.openim.android.demo.vm.LoginVM.LoginTypeEmail;
import static io.openim.android.demo.vm.LoginVM.LoginTypeEmailVCode;
import static io.openim.android.demo.vm.LoginVM.LoginTypeMobile;
import static io.openim.android.demo.vm.LoginVM.LoginTypeVCode;

import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.text.InputType;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;

import com.hbb20.CountryCodePicker;

import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import io.openim.android.demo.databinding.ActivityLoginH5Binding;
import io.openim.android.demo.ui.ServerConfigActivity;
import io.openim.android.demo.ui.main.MainActivity;
import io.openim.android.demo.vm.LoginVM;
import io.openim.android.ouicore.base.BaseActivity;
import io.openim.android.ouicore.base.BaseApp;
import io.openim.android.ouicore.utils.Constants;
import io.openim.android.ouicore.utils.LanguageUtil;
import io.openim.android.ouicore.utils.OnDedrepClickListener;
import io.openim.android.ouicore.utils.RegexValid;
import io.openim.android.ouicore.utils.SharedPreferencesUtil;
import io.openim.android.ouicore.utils.SinkHelper;
import io.openim.android.ouicore.widget.BottomPopDialog;
import io.openim.android.ouicore.widget.WaitDialog;

public class LoginH5Activity extends BaseActivity<LoginVM, ActivityLoginH5Binding> implements LoginVM.ViewAction {

    public static final String FORM_LOGIN = "form_login";
    private WaitDialog waitDialog;
    private Timer timer;
    //验证码倒计时
    private int countdown = 60;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BaseApp.inst().removeCacheVM(LoginVM.class);
        bindVM(LoginVM.class, true);
        bindViewDataBinding(ActivityLoginH5Binding.inflate(getLayoutInflater()));
        setLightStatus();
        SinkHelper.get(this).setTranslucentStatus(null);

        initView();

        click();
        listener();
    }

    void initView() {
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) view.ivCancel.getLayoutParams();
        layoutParams.setMargins(0, SinkHelper.getStatusBarHeight(), 0, 0);
        view.ivCancel.setLayoutParams(layoutParams);
        waitDialog = new WaitDialog(this);
        view.loginContent.setLoginVM(vm);
        view.setLoginVM(vm);

        CountryCodePicker.Language language = buildDefaultLanguage();
        view.countryCode.changeDefaultLanguage(language);

//        view.version.setText(Common.getAppPackageInfo().versionName);
        vm.isPhone.setValue(SharedPreferencesUtil.get(this).getInteger(Constants.K_LOGIN_TYPE) == 0);
    }

    public static CountryCodePicker.Language buildDefaultLanguage() {
        Locale locale = LanguageUtil.getCurrentLocale(BaseApp.inst());
        CountryCodePicker.Language language;
        if (locale.getLanguage().equals(Locale.CHINA.getLanguage()))
            language = CountryCodePicker.Language.CHINESE_SIMPLIFIED;
        else language = CountryCodePicker.Language.forCountryNameCode(locale.getLanguage());
        return language;
    }

    private void listener() {
        vm.loinType.observe(this, v -> {
            view.loginContent.edt1.setText("");
            view.loginContent.edt2.setText("");
            if (v == LoginTypeMobile) {//手机号
                //国家区号
                view.llCode.setVisibility(View.VISIBLE);

                view.loginContent.tvLoginTypeTitle.setText(io.openim.android.ouicore.R.string.phone_login);
                view.loginContent.vcTitle.setText(io.openim.android.ouicore.R.string.password);
                view.loginContent.vcLogin.setText(io.openim.android.ouicore.R.string.vc_login);
                view.loginContent.getVC.setVisibility(View.GONE);
                view.loginContent.eyes.setVisibility(View.VISIBLE);
                view.loginContent.edt1.setHint(getString(io.openim.android.ouicore.R.string.input_phone));
                view.loginContent.edt2.setHint(io.openim.android.ouicore.R.string.input_password);
                view.loginContent.edt2.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
                view.loginContent.edt2.setTransformationMethod(PasswordTransformationMethod.getInstance());
                view.loginContent.eyes.setChecked(false);
                view.loginContent.changeLoginType.setText(io.openim.android.ouicore.R.string.email_login);
            } else if (v == LoginTypeVCode) {//验证码
                //国家区号
                view.llCode.setVisibility(View.VISIBLE);

                view.loginContent.tvLoginTypeTitle.setText(io.openim.android.ouicore.R.string.phone_login);
                view.loginContent.edt1.setHint(getString(io.openim.android.ouicore.R.string.input_phone));
                view.loginContent.vcTitle.setText(io.openim.android.ouicore.R.string.vc);
                view.loginContent.vcLogin.setText(io.openim.android.ouicore.R.string.password_login);
                view.loginContent.getVC.setVisibility(View.VISIBLE);
                view.loginContent.eyes.setVisibility(View.GONE);
                view.loginContent.edt2.setHint(io.openim.android.ouicore.R.string.input_verification_code);
                view.loginContent.eyes.setChecked(true);
                view.loginContent.edt2.setInputType(InputType.TYPE_CLASS_NUMBER);
                view.loginContent.edt2.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                view.loginContent.changeLoginType.setText(io.openim.android.ouicore.R.string.email_login);
            } else if (v == LoginTypeEmail) {//邮箱
                //国家区号
                view.llCode.setVisibility(View.GONE);

                view.loginContent.getVC.setVisibility(View.GONE);
                view.loginContent.tvLoginTypeTitle.setText(io.openim.android.ouicore.R.string.mail);
                view.loginContent.vcTitle.setText(io.openim.android.ouicore.R.string.password);
                view.loginContent.vcLogin.setText(io.openim.android.ouicore.R.string.vc_login);
                view.loginContent.eyes.setVisibility(View.VISIBLE);
                view.loginContent.edt2.setHint(io.openim.android.ouicore.R.string.input_password);
                view.loginContent.edt2.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
                view.loginContent.edt1.setHint(getString(io.openim.android.ouicore.R.string.input_mail));
                view.loginContent.changeLoginType.setText(io.openim.android.ouicore.R.string.mobile_login);
                view.loginContent.eyes.setChecked(false);
            } else if (v == LoginTypeEmailVCode) {//邮箱验证码
                //国家区号
                view.llCode.setVisibility(View.GONE);

                view.loginContent.tvLoginTypeTitle.setText(io.openim.android.ouicore.R.string.mail);
                view.loginContent.vcTitle.setText(io.openim.android.ouicore.R.string.vc);
                view.loginContent.edt2.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
                view.loginContent.edt1.setHint(getString(io.openim.android.ouicore.R.string.input_mail));
                view.loginContent.vcLogin.setText(io.openim.android.ouicore.R.string.password_login);
                view.loginContent.getVC.setVisibility(View.VISIBLE);
                view.loginContent.eyes.setVisibility(View.GONE);
                view.loginContent.edt2.setHint(io.openim.android.ouicore.R.string.input_verification_code);
                view.loginContent.eyes.setChecked(true);
                view.loginContent.edt2.setInputType(InputType.TYPE_CLASS_NUMBER);
                view.loginContent.edt2.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                view.loginContent.changeLoginType.setText(io.openim.android.ouicore.R.string.mobile_login);
            }

        });
        vm.account.observe(this, v -> {
            view.loginContent.getVC.setEnabled(!vm.account.getValue().isEmpty());
            submitEnabled();
        });
        vm.pwd.observe(this, v -> submitEnabled());
    }

    private void toRegister() {
        vm.pwd.setValue("");
        vm.account.setValue("");
        startActivity(new Intent(this, RegisterNewActivity.class));
    }

    private final GestureDetector gestureDetector = new GestureDetector(BaseApp.inst(),
            new GestureDetector.SimpleOnGestureListener() {
                @Override
                public boolean onDoubleTap(MotionEvent e) {
                    startActivity(new Intent(LoginH5Activity.this, ServerConfigActivity.class));
                    return super.onDoubleTap(e);
                }
            });

    private void click() {
//        view.welcome.setOnTouchListener((v, event) -> gestureDetector.onTouchEvent(event));
        view.ivCancel.setOnClickListener(new OnDedrepClickListener() {
            @Override
            public void click(View v) {
                finish();
            }
        });
        //右侧按钮
        view.loginContent.changeLoginType.setOnClickListener(v -> {
            if (vm.loinType.val() == LoginTypeVCode) {
                vm.loinType.setValue(LoginTypeEmail);
            } else if (vm.loinType.val() == LoginTypeMobile) {
                vm.loinType.setValue(LoginTypeEmail);
            } else if (vm.loinType.val() == LoginTypeEmail) {
                vm.loinType.setValue(LoginTypeMobile);
            } else if (vm.loinType.val() == LoginTypeEmailVCode) {
                vm.loinType.setValue(LoginTypeMobile);
            }
        });

        view.loginContent.clear.setOnClickListener(v -> view.loginContent.edt1.setText(""));
        view.loginContent.clearPwd.setOnClickListener(v -> view.loginContent.edt2.setText(""));
        view.loginContent.eyes.setOnCheckedChangeListener((buttonView, isChecked) -> view.loginContent.edt2.setTransformationMethod(isChecked ? HideReturnsTransformationMethod.getInstance() : PasswordTransformationMethod.getInstance()));
        view.protocol.setOnCheckedChangeListener((buttonView, isChecked) -> submitEnabled());
        view.registerTv.setOnClickListener(new OnDedrepClickListener() {
            @Override
            public void click(View v) {
                toRegister();
//                BottomPopDialog dialog = new BottomPopDialog(LoginActivity.this);
//                dialog.getMainView().menu1.setText(io.openim.android.ouicore.R.string.phone_register);
//                dialog.getMainView().menu2.setText(io.openim.android.ouicore.R.string.email_register);
//                dialog.getMainView().menu3.setOnClickListener(v1 -> dialog.dismiss());
//                dialog.getMainView().menu1.setOnClickListener(v1 -> {
//                    vm.isPhone.setValue(true);
//                    vm.isFindPassword = false;
//                    toRegister();
//                });
//                dialog.getMainView().menu2.setOnClickListener(v1 -> {
//                    vm.isPhone.setValue(false);
//                    vm.isFindPassword = false;
//                    toRegister();
//                });
//                dialog.show();
            }
        });
        view.submit.setOnClickListener(v -> {
            if (!RegexValid.isValidPhoneNumber(vm.account.val()) && (vm.loinType.val() == LoginTypeVCode || vm.loinType.val() == LoginTypeMobile)) {
                toast(BaseApp.inst().getString(io.openim.android.ouicore.R.string.valid_phone_num));
                return;
            }
            if (!RegexValid.isValidEmail(vm.account.val()) && (vm.loinType.val() == LoginTypeEmail || vm.loinType.val() == LoginTypeEmailVCode)) {
                toast(BaseApp.inst().getString(io.openim.android.ouicore.R.string.email_tips));
                return;
            }
            vm.areaCode.setValue("+" + view.countryCode.getSelectedCountryCode());
            waitDialog.show();
            vm.login((vm.loinType.val() == LoginTypeVCode || vm.loinType.val() == LoginTypeEmailVCode) ? vm.pwd.getValue() : null, 3);
        });
        //验证码登录按钮
        view.loginContent.vcLogin.setOnClickListener(v -> {
            if (vm.loinType.val() == LoginTypeVCode) {//手机验证码
                vm.loinType.setValue(LoginTypeMobile);
            } else if (vm.loinType.val() == LoginTypeMobile) {//手机密码
                vm.loinType.setValue(LoginTypeVCode);
            } else if (vm.loinType.val() == LoginTypeEmail) {//邮箱密码
                vm.loinType.setValue(LoginTypeEmailVCode);
            } else if (vm.loinType.val() == LoginTypeEmailVCode) {//邮箱验证码
                vm.loinType.setValue(LoginTypeEmail);
            } else {
                vm.loinType.setValue(LoginTypeVCode);
            }
        });
        view.loginContent.getVC.setOnClickListener(v -> {
            //正在倒计时中...不触发操作
            if (countdown != 60) return;
            vm.getVerificationCode(3);
        });
        view.loginContent.forgotPasswordTv.setOnClickListener(v -> {
            BottomPopDialog dialog = new BottomPopDialog(LoginH5Activity.this);
            dialog.getMainView().menu1.setText(io.openim.android.ouicore.R.string.forgot_pasword_by_phone);
            dialog.getMainView().menu2.setText(io.openim.android.ouicore.R.string.forgot_pasword_by_email);
            dialog.getMainView().menu3.setOnClickListener(v1 -> dialog.dismiss());
            dialog.getMainView().menu1.setOnClickListener(v1 -> {
                vm.isPhone.setValue(true);
                vm.isFindPassword = true;
                toRegister();
            });
            dialog.getMainView().menu2.setOnClickListener(v1 -> {
                vm.isPhone.setValue(false);
                vm.isFindPassword = true;
                toRegister();
            });
            dialog.show();
        });
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }


    private void submitEnabled() {
        view.submit.setEnabled(!vm.account.getValue().isEmpty() && !vm.pwd.getValue().isEmpty());
    }

    @Override
    public void jump() {
        startActivity(new Intent(this, MainActivity.class).putExtra(FORM_LOGIN, true));
        waitDialog.dismiss();
        finish();
    }

    @Override
    public void err(String msg) {
        waitDialog.dismiss();
        toast(msg);
    }

    @Override
    public void succ(Object o) {
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                countdown--;
                runOnUiThread(new TimerTask() {
                    @Override
                    public void run() {
                        view.loginContent.getVC.setText(countdown + "s");
                    }
                });

                if (countdown <= 0) {
                    runOnUiThread(new TimerTask() {
                        @Override
                        public void run() {
                            view.loginContent.getVC.setText(io.openim.android.ouicore.R.string.get_vc);
                            countdown = 60;
                            timer.cancel();
                            timer = null;
                        }
                    });
                }
            }
        }, 0, 1000);
    }

    @Override
    public void initDate() {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != timer) {
            timer.cancel();
            timer = null;
        }
    }
}
