package com.casic.dcms.view;

import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;

import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.casic.dcms.R;
import com.casic.dcms.databinding.ActivityPasswordBinding;
import com.casic.dcms.model.ActionResultBean;
import com.casic.dcms.utils.AuthenticationHelper;
import com.casic.dcms.utils.RSAUtils;
import com.casic.dcms.utils.StringHelper;
import com.casic.dcms.utils.ViewGroupKit;
import com.casic.dcms.vm.UserViewModel;
import com.pengxh.androidx.lite.base.AndroidxBaseActivity;
import com.pengxh.androidx.lite.kit.ContextKit;
import com.pengxh.androidx.lite.kit.StringKit;
import com.pengxh.androidx.lite.utils.ActivityStackManager;
import com.pengxh.androidx.lite.utils.LoadState;
import com.pengxh.androidx.lite.utils.LoadingDialog;
import com.pengxh.androidx.lite.widget.dialog.AlertMessageDialog;

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

/**
 * @author : Pengxh
 * @time : 2021/4/14 13:20
 * @email : 290677893@qq.com
 */
public class ChangePasswordActivity extends AndroidxBaseActivity<ActivityPasswordBinding> {

    private final Context context = this;
    private UserViewModel userViewModel;

    @Override
    protected void setupTopBarLayout() {
        ViewGroupKit.initImmersionBar(binding.rootView, this, true, R.color.white);

        binding.titleBarLayout.titleView.setText("修改密码");
        binding.titleBarLayout.leftBackView.setOnClickListener(v -> finish());
    }

    @Override
    protected void observeRequestState() {

    }

    @Override
    protected void initOnCreate(@Nullable Bundle savedInstanceState) {
        EditText newPsdEditText = binding.newPsdLayout.getEditText();
        assert newPsdEditText != null;
        newPsdEditText.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) {
                    binding.newPsdLayout.setError("密码长度超出限制");
                } else {
                    binding.newPsdLayout.setError(null);
                }
            }
        });

        EditText confirmPsdEditText = binding.confirmPsdLayout.getEditText();
        assert confirmPsdEditText != null;
        confirmPsdEditText.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) {
                    binding.confirmPsdLayout.setError("密码长度超出限制");
                } else {
                    binding.confirmPsdLayout.setError(null);
                }
            }
        });

        userViewModel = new ViewModelProvider(this).get(UserViewModel.class);
    }

    @Override
    protected void initEvent() {
        binding.changePasswordButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String oldPassword = binding.originalEditView.getText().toString();
                if (TextUtils.isEmpty(oldPassword)) {
                    StringKit.show(context, "请先输入原密码");
                    return;
                }
                String newPassword = binding.newEditView.getText().toString();
                if (TextUtils.isEmpty(newPassword)) {
                    StringKit.show(context, "请先输入新密码");
                    return;
                }
                String confirmPassword = binding.confirmEditView.getText().toString();
                if (TextUtils.isEmpty(confirmPassword)) {
                    StringKit.show(context, "请再次输入新密码");
                    return;
                }
                if (!newPassword.equals(confirmPassword)) {
                    StringKit.show(context, "新密码和确认密码输入不一致，请重新输入");
                    return;
                }
                if (newPassword.length() < 6 || newPassword.length() > 12) {
                    StringKit.show(context, "新密码长度不正确，请重新输入");
                    return;
                }
                if (!StringHelper.isLetterAndDigit(newPassword)) {
                    StringKit.show(context, "新密码请输入6-12位的数字字母组合");
                    return;
                }
                //数据校验OK，可以修改密码
                PublicKey publicKey = RSAUtils.keyStrToPublicKey(AuthenticationHelper.getPublicKey());
                String oldPassKey = RSAUtils.encryptDataByPublicKey(oldPassword.getBytes(StandardCharsets.UTF_8), publicKey);
                String newPassKey = RSAUtils.encryptDataByPublicKey(newPassword.getBytes(StandardCharsets.UTF_8), publicKey);
                userViewModel.changePassword(context, oldPassKey, newPassKey);
            }
        });
        userViewModel.changePwdResult.observe(this, new Observer<ActionResultBean>() {
            @Override
            public void onChanged(ActionResultBean resultBean) {
                if (resultBean.getCode() == 200) {
                    new AlertMessageDialog.Builder()
                            .setContext(context)
                            .setTitle("温馨提示")
                            .setMessage("密码已修改成功，请重新登录")
                            .setPositiveButton("确定")
                            .setOnDialogButtonClickListener(new AlertMessageDialog.OnDialogButtonClickListener() {
                                @Override
                                public void onConfirmClick() {
                                    AuthenticationHelper.removeToken();
                                    ContextKit.navigatePageTo(context, LoginActivity.class);
                                    ActivityStackManager.finishAllActivity();
                                }
                            })
                            .build().show();
                }
            }
        });
        userViewModel.loadState.observe(this, new Observer<LoadState>() {
            @Override
            public void onChanged(LoadState loadState) {
                if (loadState == LoadState.Loading) {
                    LoadingDialog.show(ChangePasswordActivity.this, "密码修改中，请稍后");
                } else {
                    LoadingDialog.dismiss();
                }
            }
        });
    }
}