package com.casic.dcms.view;

import android.content.Context;
import android.os.Bundle;
import android.view.View;

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

import com.casic.dcms.databinding.ActivityLoginBinding;
import com.casic.dcms.model.LoginResultBean;
import com.casic.dcms.model.PublicKeyBean;
import com.casic.dcms.utils.AuthenticationHelper;
import com.casic.dcms.utils.LocaleConstant;
import com.casic.dcms.utils.RSAUtils;
import com.casic.dcms.vm.AuthenticateViewModel;
import com.casic.dcms.vm.UserViewModel;
import com.gyf.immersionbar.ImmersionBar;
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.LoadState;
import com.pengxh.androidx.lite.utils.LoadingDialog;
import com.pengxh.androidx.lite.utils.SaveKeyValues;

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

public class LoginActivity extends AndroidxBaseActivity<ActivityLoginBinding> {

    private final Context context = LoginActivity.this;
    private String account;
    private String userPassword;
    private AuthenticateViewModel authenticateViewModel;
    private UserViewModel userViewModel;

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

    @Override
    protected void observeRequestState() {
        userViewModel.loadState.observe(this, new Observer<LoadState>() {
            @Override
            public void onChanged(LoadState loadState) {
                if (loadState == LoadState.Loading) {
                    LoadingDialog.show(LoginActivity.this, "登录中，请稍后");
                } else {
                    LoadingDialog.dismiss();
                }
            }
        });
    }

    @Override
    protected void initOnCreate(@Nullable Bundle savedInstanceState) {
        binding.userNameView.setText((String) SaveKeyValues.getValue(LocaleConstant.ACCOUNT, ""));
        binding.userPasswordView.setText((String) SaveKeyValues.getValue(LocaleConstant.PASSWORD, ""));

        authenticateViewModel = new ViewModelProvider(this).get(AuthenticateViewModel.class);
        authenticateViewModel.keyModel.observe(this, new Observer<PublicKeyBean>() {
            @Override
            public void onChanged(PublicKeyBean result) {
                if (result.getCode() == 200) {
                    String keyString = result.getData().getPublicKey();
                    AuthenticationHelper.savePublicKey(keyString);
                    PublicKey publicKey = RSAUtils.keyStrToPublicKey(keyString);

                    String dataByPublicKey = RSAUtils.encryptDataByPublicKey(userPassword.getBytes(StandardCharsets.UTF_8), publicKey);
                    userViewModel.login(context, account, dataByPublicKey);
                }
            }
        });

        userViewModel = new ViewModelProvider(this).get(UserViewModel.class);
        userViewModel.loginResult.observe(this, new Observer<LoginResultBean>() {
            @Override
            public void onChanged(LoginResultBean loginResultBean) {
                if (loginResultBean.getCode() == 200) {
                    AuthenticationHelper.saveToken(loginResultBean.getData().getToken());
                    /**
                     * 获取token之后保存用户信息
                     * */
                    userViewModel.getUserData(context);
                    //验证成功登录
                    ContextKit.navigatePageTo(context, MainActivity.class);
                    finish();
                }
            }
        });
    }

    @Override
    protected void initEvent() {
        binding.loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                account = binding.userNameView.getText().toString().trim();
                userPassword = binding.userPasswordView.getText().toString().trim();
                if (account.isEmpty()) {
                    StringKit.show(context, "用户名不能为空");
                    return;
                }
                if (userPassword.isEmpty()) {
                    StringKit.show(context, "密码不能为空");
                    return;
                }
                SaveKeyValues.putValue(LocaleConstant.ACCOUNT, account);
                SaveKeyValues.putValue(LocaleConstant.PASSWORD, userPassword);

                authenticateViewModel.getPublicKey(context);
            }
        });
    }
}