package com.sjkj.appthreefloor_tsgz.login;

import android.content.Intent;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import androidx.lifecycle.ViewModelProvider;

import com.sjkj.appthreefloor_tsgz.BuildConfig;
import com.sjkj.appthreefloor_tsgz.R;
import com.sjkj.appthreefloor_tsgz.activity.MainActivity;
import com.sjkj.appthreefloor_tsgz.app.App;
import com.sjkj.appthreefloor_tsgz.bean.LogInRsaBean;
import com.sjkj.appthreefloor_tsgz.bean.LoginBean;
import com.sjkj.appthreefloor_tsgz.bean.MenuMainItemBean;
import com.sjkj.appthreefloor_tsgz.databinding.ActivityLoginBinding;
import com.sjkj.appthreefloor_tsgz.net.LoginGetKeyRequest;
import com.sjkj.appthreefloor_tsgz.net.LoginRequest;
import com.sjkj.appthreefloor_tsgz.utils.AppSystemUtils;
import com.sjkj.appthreefloor_tsgz.utils.LongClickUtils;
import com.sjkj.appthreefloor_tsgz.utils.RSAUtils;
import com.sjkj.base_lib.app.AppManager;
import com.sjkj.base_lib.entity.Params;
import com.sjkj.base_lib.net.domain.interactor.ProcessErrorSubscriber;
import com.sjkj.base_lib.utils.AppTools;
import com.sjkj.base_lib.utils.ToastUtils;
import com.sjkj.base_lib.view.BaseLoginActivity;
import com.sjkj.base_lib.weight.LoadingDialog;

import java.util.ArrayList;

public class LoginActivity extends BaseLoginActivity {

    private ActivityLoginBinding binding;
    private LoginViewModel viewModel;

    private LoginGetKeyRequest loginGetKeyRequest = new LoginGetKeyRequest(App.getInstance());
    public LoginRequest loginRequest = new LoginRequest(App.getInstance());

    @Override
    public int initLayout() {
        isLogin = true;
        return R.layout.activity_login;
    }

    @Override
    public void initBinding() {
        binding = (ActivityLoginBinding) getViewDataBinding();
        viewModel = new ViewModelProvider(this, new ViewModelProvider.NewInstanceFactory()).get(LoginViewModel.class);
        binding.setViewModel(viewModel);
        binding.setLifecycleOwner(this);
    }

    @Override
    public void initView() {
        super.initView();
        binding.configTv.setVisibility(BuildConfig.DEBUG ? View.VISIBLE : View.INVISIBLE);
        if (BuildConfig.DEBUG) {
            binding.configTv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(LoginActivity.this, ConfigActivity.class));
                }
            });
        } else {
            LongClickUtils.setLongClick(new Handler(), binding.configTv, 2500, new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    startActivity(new Intent(LoginActivity.this, ConfigActivity.class));
                    return true;
                }
            });
        }
    }

    @Override
    public void loadData() {
        viewModel.username.set(AppTools.getUserName());
        viewModel.password.set(AppTools.getPassword());
    }

    @Override
    public void initListener() {
        binding.submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(viewModel.username.get())) {
                    ToastUtils.show("用户名不能为空");
                    return;
                }
                if (TextUtils.isEmpty(viewModel.password.get())) {
                    ToastUtils.show("密码不能为空");
                    return;
                }
                //getLoginKey();
                login();
            }
        });
//        binding.forgetPwdTv.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                startActivity(new Intent(LoginActivity.this, UpdatePasswordActivity.class));
//            }
//        });
    }

    /**
     * 获取秘钥
     */
    private void getLoginKey() {
        showLoadingDialog();
        loginGetKeyRequest.execute(new ProcessErrorSubscriber<LogInRsaBean>() {
            @Override
            public void onError(Throwable e) {
                super.onError(e);
                hideLoadingDialog(LoadingDialog.LOADING_FAILED);
                if (!TextUtils.isEmpty(e.getMessage()) && e.getMessage().contains("connect")) {
                    ToastUtils.show("连接服务器失败,检查网络连接。");
                } else {
                    ToastUtils.show(e.getMessage() + "");
                }
            }

            @Override
            public void onNext(LogInRsaBean bean) {
                super.onNext(bean);
                //公钥加密
                String encryptBytes = "";
                try {
                    encryptBytes = RSAUtils.encryptPublicKey(viewModel.password.get().getBytes(), bean.getPublicKey());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                viewModel.password2.set(encryptBytes);
                viewModel.sessionId.set(bean.getSessionId());
                login();
            }
        });

    }

    /**
     * 登录接口
     */
    public void login() {
//        if (TextUtils.isEmpty(viewModel.username.get())) {
//            ToastUtils.show("用户名不能为空");
//            return;
//        }
//        if (TextUtils.isEmpty(viewModel.password.get())) {
//            ToastUtils.show("密码不能为空");
//            return;
//        }
        Params params = new Params();
        // params.put("loginType", "mobile");
        params.put("username", viewModel.username.get());
        params.put("password", viewModel.password.get());
        //params.put("code", "5521");
        //params.put("sessionId", viewModel.sessionId.get());
        //params.put("deviceid", PushUtils.getRegistrationId());
        loginRequest.setParams(params);
        loginRequest.execute(new ProcessErrorSubscriber<Object>() {
            @Override
            public void onError(Throwable e) {
                super.onError(e);
                hideLoadingDialog(LoadingDialog.LOADING_FAILED);
                Intent intent = new Intent(AppManager.getAppManager().currentActivity(), MainActivity.class);
                AppManager.getAppManager().currentActivity().startActivity(intent);
                hideLoadingDialog(LoadingDialog.LOADING_SUCCESS);
                finish();
                if (!TextUtils.isEmpty(e.getMessage()) && e.getMessage().contains("connect")) {
                    ToastUtils.show("连接服务器失败,检查网络连接。");
                } else {
                    ToastUtils.show(e.getMessage() + "");
                }
            }

            @Override
            public void onNext(Object data) {
                super.onNext(data);
                try {
                    hideLoadingDialog(LoadingDialog.LOADING_SUCCESS);
                    AppTools.setToken(data.toString());
                    // AppTools.setNickName(data.getUsername());
                    AppTools.setUserName(viewModel.username.get());
                    AppTools.setPassword(viewModel.password.get());

                    Intent intent = new Intent(AppManager.getAppManager().currentActivity(), MainActivity.class);
                    AppManager.getAppManager().currentActivity().startActivity(intent);
                    hideLoadingDialog(LoadingDialog.LOADING_SUCCESS);
                    finish();


                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

    }
}