package com.baoshi.swms.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.baoshi.swms.R;
import com.baoshi.swms.bean.User;
import com.baoshi.swms.bean.dto.Login;
import com.baoshi.swms.net.callback.WasHandlerCallback;
import com.baoshi.swms.net.subscribe.WasBaseSubscribe;
import com.baoshi.swms.net.subscribe.WasSubscribe;
import com.baoshi.swms.util.GlobalStorage;
import com.baoshi.swms.util.Hint;
import com.baoshi.swms.util.StringUtil;
import com.google.gson.Gson;

/**
 * 登录Activity
 */
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {

    private String username;
    private String password;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        registerEvent();
    }

    private void registerEvent() {
        Button submit = findViewById(R.id.login_submit);
        submit.setOnClickListener(this);
    }


    private boolean check() {
        EditText usernameView = findViewById(R.id.login_user_name);
        EditText passwordView = findViewById(R.id.login_password);
        username = StringUtil.trimLeft(usernameView.getText().toString());
        password = StringUtil.trimLeft(passwordView.getText().toString());
        if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)){
            Hint.toastShort(LoginActivity.this, "账号名或密码为空", Hint.COMMON);
            return false;
        }
        return true;
    }
    @Override
    public void onClick(View v) {
        if (!check()){
            return;
        };
        ProgressDialog dialog = Hint.showProgressDialog("登录中", LoginActivity.this);
        WasSubscribe.login(username, password, new WasHandlerCallback<Login>() {
            @Override
            public void onSuccess(Login result) {
                Gson gson = new Gson();
                GlobalStorage storage = GlobalStorage.getGlobalStorage();
                storage.put("token", result.getToken());
                storage.put("menu", result.getMenu());
                storage.put("user", gson.toJson(result.getUser(),User.class));
                WasBaseSubscribe.refreshSingleton();//因为此处为登录请求为了防止请求头的设定，需要在成功后清除当前 NETWORK单例对象
                startActivity(new Intent(LoginActivity.this, MenuActivity.class));
                super.onSuccess(result);
            }
            @Override
            public void onFinally(){
                dialog.dismiss();
            }
        });
    }
}