package com.casic.dcms.ui;

import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;

import com.casic.dcms.R;
import com.casic.dcms.base.AndroidxBaseActivity;
import com.casic.dcms.bean.LoginResultBean;
import com.casic.dcms.bean.PublicKeyBean;
import com.casic.dcms.databinding.ActivityLoginBinding;
import com.casic.dcms.mvp.presenter.impl.AuthenticatePresenterImpl;
import com.casic.dcms.mvp.presenter.impl.LoginPresenterImpl;
import com.casic.dcms.mvp.view.IAuthenticateView;
import com.casic.dcms.mvp.view.ILoginInView;
import com.casic.dcms.utils.AuthenticationHelper;
import com.casic.dcms.utils.Constant;
import com.casic.dcms.utils.OtherUtils;
import com.casic.dcms.utils.RSAUtils;
import com.casic.dcms.utils.SaveKeyValues;
import com.casic.dcms.utils.StatusBarColorUtil;
import com.casic.dcms.utils.StringHelper;
import com.casic.dcms.utils.ToastHelper;
import com.casic.dcms.widgets.InputDialog;
import com.gyf.immersionbar.ImmersionBar;

import java.nio.charset.StandardCharsets;
import java.security.PublicKey;

public class LoginActivity extends AndroidxBaseActivity<ActivityLoginBinding> implements IAuthenticateView, ILoginInView {

    private final Context context = LoginActivity.this;
    private AuthenticatePresenterImpl authenticatePresenter;
    private LoginPresenterImpl loginPresenter;

    @Override
    protected void setupTopBarLayout() {
        //设置状态栏黑色字体图标
        StatusBarColorUtil.setColor(this, ContextCompat.getColor(this, R.color.white));
        ImmersionBar.with(this).statusBarDarkFont(true).init();//沉浸式状态栏
    }

    @Override
    protected void initData() {
        String userAccount = StringHelper.getUserAccount();
        String userPassword = (String) SaveKeyValues.getValue("userPassword", "");
        viewBinding.userNameView.setText(userAccount);
        viewBinding.userPasswordView.setText(userPassword);
        viewBinding.rememberPasswordView.setChecked(!TextUtils.isEmpty(userAccount) && !TextUtils.isEmpty(userPassword));
        viewBinding.rememberPasswordView.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                if (!isChecked) {
                    try {
                        SaveKeyValues.removeKey("userPassword");
                    } catch (NullPointerException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    @Override
    protected void initEvent() {
        authenticatePresenter = new AuthenticatePresenterImpl(this);
        loginPresenter = new LoginPresenterImpl(this);
        EditText editText = viewBinding.inputLayout.getEditText();
        assert editText != null;
        editText.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 (editable.toString().trim().length() > 12) {
                    viewBinding.inputLayout.setError("密码长度超出限制");
                } else {
                    viewBinding.inputLayout.setError(null);
                }
            }
        });
        //点击输入法键盘"完成"
        editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    authenticatePresenter.onReadyRetrofitRequest();
                    return true;
                }
                return false;
            }
        });
        viewBinding.loginButton.setChangeAlphaWhenPress(true);
        viewBinding.loginButton.setOnClickListener(v -> authenticatePresenter.onReadyRetrofitRequest());
        viewBinding.changeServerConfigButton.setChangeAlphaWhenPress(true);
        viewBinding.changeServerConfigButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String defaultValue = (String) SaveKeyValues.getValue(Constant.IP_KEY,
                        "http://111.198.10.15:11409");
                new InputDialog.Builder().setContext(context)
                        .setTitle("请输入后台服务器地址")
                        .setDefaultValue(defaultValue)
                        .setHintText("请输入服务器地址")
                        .setNegativeButton("取消")
                        .setPositiveButton("保存")
                        .setOnDialogClickListener(new InputDialog.OnDialogButtonClickListener() {
                            @Override
                            public void onCancelClick() {

                            }

                            @Override
                            public void onConfirmClick(@NonNull String input) {
                                SaveKeyValues.putValue(Constant.IP_KEY, input);
                                ToastHelper.showToast("服务器地址修改成功", ToastHelper.SUCCESS);
                            }
                        }).build().show();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        //自动登录
        boolean autoLogin = (boolean) SaveKeyValues.getValue("autoLogin", false);
        viewBinding.autoLoginView.setChecked(autoLogin);
        if (autoLogin) {
            authenticatePresenter.onReadyRetrofitRequest();
        }
    }

    @Override
    public void showProgress() {
        OtherUtils.showLoadingDialog(this, "登录中，请稍后");
    }

    @Override
    public void authenticateResult(PublicKeyBean result) {
        if (result.getCode() == 200) {
            String keyString = result.getData().getPublicKey();
            AuthenticationHelper.savePublicKey(keyString);
            PublicKey publicKey = RSAUtils.keyStrToPublicKey(keyString);
            String account = viewBinding.userNameView.getText().toString();
            String userPassword = viewBinding.userPasswordView.getText().toString();
            SaveKeyValues.putValue("autoLogin", viewBinding.autoLoginView.isChecked());

            if (TextUtils.isEmpty(account)) {
                ToastHelper.showToast("用户名不能为空", ToastHelper.WARING);
                return;
            }
            //判断是否是手机号，先区分是手机号还是账号
            if (account.startsWith("1")) {
                if (!StringHelper.isPhoneNumber(account)) {
                    ToastHelper.showToast("手机号格式不对，可以改为账号登录", ToastHelper.WARING);
                    return;
                }
            }
            if (TextUtils.isEmpty(userPassword)) {
                ToastHelper.showToast("密码不能为空", ToastHelper.WARING);
                return;
            }
            if (viewBinding.rememberPasswordView.isChecked()) {
                StringHelper.saveUserAccount(account);
                SaveKeyValues.putValue("userPassword", userPassword);
            }
            String dataByPublicKey =
                    RSAUtils.encryptDataByPublicKey(userPassword.getBytes(StandardCharsets.UTF_8), publicKey);
            //登录并获取Token，POST请求
            loginPresenter.onReadyRetrofitRequest(account, dataByPublicKey);
        }
    }

    @Override
    public void obtainDataFail() {
        ToastHelper.showToast("登录失败", ToastHelper.ERROR);
    }

    @Override
    public void obtainLoginResult(LoginResultBean result) {
        String token = result.getData().getToken();
        if (!TextUtils.isEmpty(token)) {
            //获取用户信息
            AuthenticationHelper.saveToken(token);
            //验证成功登录
            startActivity(new Intent(this, MainActivity.class));
            finish();
        }
    }

    @Override
    public void loginFail() {
        ToastHelper.showToast("登录失败，请检查账号密码", ToastHelper.ERROR);
    }

    @Override
    public void hideProgress() {
        OtherUtils.dismissLoadingDialog();
    }

    @Override
    protected void onDestroy() {
        authenticatePresenter.disposeRetrofitRequest();
        loginPresenter.disposeRetrofitRequest();
        super.onDestroy();
    }
}