package com.stm.asset.page;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;

import androidx.annotation.Nullable;

import com.stm.asset.R;
import com.stm.asset.base.BaseActivity;
import com.stm.asset.base.StmApplication;
import com.stm.asset.http.HttpException;
import com.stm.asset.http.HttpService;
import com.stm.asset.http.RequestCallback;
import com.stm.asset.json.CommonStringJson;
import com.stm.asset.json.ListUserInfo;
import com.stm.asset.keyboard.SafeKeyboardManager;
import com.stm.asset.model.LoginInfo;
import com.stm.asset.utils.NetworkUtil;
import com.stm.asset.utils.PropertyUtil;
import com.stm.asset.view.LoadingDialog;

/**
 * 类名称：LoginActivity
 * 类描述：登录
 * 创建人：story
 * 创建时间：2021-12-10 09:45
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener {

    private EditText accountEt, pwdEt;
    private LinearLayout deleteLayout;

    private boolean isAccountFocus;
    private LoadingDialog loadingDialog;
    private int setBtnClickCount = 0;//IP设置按钮的点击次数
    private long lastClickTime = 0;//上次点击时间

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 禁止app录屏和截屏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
        setContentView(R.layout.activity_login);
        initView();
    }

    private void initView() {
        initTitle();
        titleTxt.setText("登录");
        accountEt = findViewById(R.id.login_account_et);
        pwdEt = findViewById(R.id.login_pwd_et);
        deleteLayout = findViewById(R.id.login_account_delete_layout);
        findViewById(R.id.common_title_back_layout).setOnClickListener(this);
        findViewById(R.id.login_login_btn).setOnClickListener(this);
        deleteLayout.setOnClickListener(this);
        accountEt.addTextChangedListener(textWatcher);
        accountEt.setOnFocusChangeListener(new AccountFocusChangeListener());
        SafeKeyboardManager.initKeyBoard(getString(R.string.app_name));
        SafeKeyboardManager.registKeyboard(this, pwdEt);
        String accountStr = PropertyUtil.getRememberAccount(this);
        accountEt.setText(accountStr);
        loadingDialog = new LoadingDialog(this);
        // 切换IP
        findViewById(R.id.common_title_right_layout).setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_title_back_layout:
                finish();
                break;
            case R.id.login_account_delete_layout:
                accountEt.setText("");
                break;
            case R.id.login_login_btn:
                String accountStr = accountEt.getText().toString();
                String passwordStr = pwdEt.getText().toString();
                if ("".equals(accountStr)) {
                    StmApplication.getInstance().showToastShort("请填写用户名");
                    return;
                }
                if ("".equals(passwordStr)) {
                    StmApplication.getInstance().showToastShort("请填写密码");
                    return;
                }
                if (NetworkUtil.isNetworkAvailable(LoginActivity.this)) {
                    loadingDialog.show();
                    HttpService.getInstance().unionLoginApp(accountStr, passwordStr, login_cb);
                } else {
                    StmApplication.getInstance().showToastShort(getString(R.string.net_settings));
                }
                break;
            case R.id.common_title_right_layout:
                long now = System.currentTimeMillis();
                if(now - lastClickTime < 800) {
                    setBtnClickCount++;
                } else {
                    setBtnClickCount = 1;
                }
                lastClickTime = now;
                if(setBtnClickCount >= 10) {
                    setBtnClickCount = 0;
//                    Intent selectIpIntent = new Intent();
//                    selectIpIntent.setClass(this, SelectIPActivity.class);
//                    startActivityForResult(selectIpIntent, 1);
                }
                break;
        }
    }

    private TextWatcher textWatcher = new TextWatcher() {

        @Override
        public void afterTextChanged(Editable arg0) {
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
        }

        @Override
        public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
            if (!"".equals(arg0.toString()) && isAccountFocus) {
                if (deleteLayout.getVisibility() == View.GONE)
                    deleteLayout.setVisibility(View.VISIBLE);
            } else {
                deleteLayout.setVisibility(View.GONE);
            }
            pwdEt.setText("");
        }

    };

    private RequestCallback<CommonStringJson> login_cb = new RequestCallback<CommonStringJson>(CommonStringJson.class) {
        @Override
        public void onSuccess(CommonStringJson responseInfo) {
            if (responseInfo.isSucess()) {
                StmApplication.getInstance().showToastShort("登录成功");
                String accessToken = responseInfo.getRspData();
                PropertyUtil.setAccessToken(StmApplication.getInstance().getApplicationContext(), accessToken);
                HttpService.getInstance().quryPageHomeUserInfo(accessToken, userInfo_cb);
            } else {
                StmApplication.getInstance().showToastShort(responseInfo.getRspMsg());
                loadingDialog.dismiss();
            }
        }

        @Override
        public void onFailure(HttpException error, String msg) {
            loadingDialog.dismiss();
            StmApplication.getInstance().showToastShort(msg);
        }
    };

    private RequestCallback<ListUserInfo> userInfo_cb = new RequestCallback<ListUserInfo>(ListUserInfo.class) {
        @Override
        public void onSuccess(ListUserInfo responseInfo) {
            loadingDialog.dismiss();
            if (responseInfo.isSucess()) {
                StmApplication.getInstance().showToastShort("登录成功");
                LoginInfo loginInfo = responseInfo.getRspData();
                if (loginInfo != null && loginInfo.getUserInfo() != null) {
                    StmApplication.getInstance().setUserInfo(loginInfo.getUserInfo());
                    finish();
                }
            } else {
                StmApplication.getInstance().showToastShort(responseInfo.getRspMsg());
            }
        }

        @Override
        public void onFailure(HttpException error, String msg) {
            loadingDialog.dismiss();
            StmApplication.getInstance().showToastShort(msg);
        }
    };

    private class AccountFocusChangeListener implements View.OnFocusChangeListener {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus) {
                if (!"".equals(accountEt.getText().toString()))
                    deleteLayout.setVisibility(View.VISIBLE);
            } else {
                if (deleteLayout.getVisibility() == View.VISIBLE)
                    deleteLayout.setVisibility(View.GONE);
            }
            isAccountFocus = hasFocus;
        }
    }

}
