package com.gingersoft.gsa.cloud.login.mvp.ui.activity.mvp.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.gingersoft.gsa.cloud.base.utils.encryption.Aes;
import com.gingersoft.gsa.cloud.base.utils.log.LogUtil;
import com.gingersoft.gsa.cloud.base.utils.other.SPUtils;
import com.gingersoft.gsa.cloud.base.utils.other.TextUtil;
import com.gingersoft.gsa.cloud.constans.UserConstans;
import com.gingersoft.gsa.cloud.login.R;
import com.gingersoft.gsa.cloud.login.R2;
import com.gingersoft.gsa.cloud.login.di.component.DaggerLoginComponent;
import com.gingersoft.gsa.cloud.login.mvp.contract.LoginContract;
import com.gingersoft.gsa.cloud.login.mvp.contract.LoginInterfaceImpl;
import com.gingersoft.gsa.cloud.login.mvp.presenter.LoginPresenter;
import com.gingersoft.gsa.cloud.ui.bean.mode.LoginBean;
import com.gingersoft.gsa.cloud.ui.widget.dialog.LoadingDialog;
import com.google.android.material.textfield.TextInputEditText;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.integration.AppManager;
import com.jess.arms.utils.ArmsUtils;
import com.qmuiteam.qmui.alpha.QMUIAlphaButton;

import java.util.List;
import java.util.Objects;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 12/21/2019 16:23
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
public class LoginActivity extends LoginInterfaceImpl<LoginPresenter> implements LoginContract.View, View.OnClickListener {

    @Inject
    AppManager mAppManager;
    @BindView(R2.id.ed_login_user_account)
    TextInputEditText edAccount;
    @BindView(R2.id.ed_login_user_pwd)
    TextInputEditText edPwd;
    @BindView(R2.id.iv_clear_pwd)
    ImageView icClear;
    @BindView(R2.id.iv_clear_account)
    ImageView icClearAccount;
    @BindView(R2.id.rb_remember_password)
    CheckBox mRbRememberPwd;
    @BindView(R2.id.rb_auto_login)
    CheckBox mRbAutoLogin;
    @BindView(R2.id.ic_look_pwd)
    ImageView mIvSeePwd;
    @BindView(R2.id.btn_gsa_user_login)
    QMUIAlphaButton mBtnLogin;

    private boolean passwrodVisibility = false;


    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerLoginComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);//SOFT_INPUT_ADJUST_NOTHING
        return R.layout.user_login_activity_login; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        ((ImageView) findViewById(R.id.iv_top_bg)).setAdjustViewBounds(true);
        mPresenter.requestExternalStoragePermission();
        //顯示記住的登錄名
        if (!Objects.equals(SPUtils.get(mContext, UserConstans.LOGIN_USERNAME, ""), "")) {
            edAccount.setText("" + SPUtils.get(mContext, UserConstans.LOGIN_USERNAME, ""));
            mRbRememberPwd.setChecked(true);
        }
        //顯示記住的密碼
        String pwd = Aes.aesDecrypt((String) SPUtils.get(mContext, UserConstans.LOGIN_PASSWORD, ""));
        if (!TextUtil.isEmptyOrNullOrUndefined(pwd)) {
            edPwd.setText(pwd);
            editFocusChange(edPwd, true);
        }
        //自動登陸
        mRbAutoLogin.setOnCheckedChangeListener((buttonView, isChecked) -> {
            //選中自動登陸，選中記住密碼
            if (isChecked) {
                mRbRememberPwd.setChecked(true);
            }
        });
        //記住密碼
        mRbRememberPwd.setOnCheckedChangeListener((buttonView, isChecked) -> {
            //如果用戶沒有選中記住密碼，那麼取消自動登陸選中
            if (!isChecked) {
                mRbAutoLogin.setChecked(false);
            }
        });

        if ((boolean) SPUtils.get(mContext, UserConstans.AUTO_LOGIN, false)) {
            //自動登陸
            mRbAutoLogin.setChecked(true);
        }
        //輸入框監聽
        edPwd.setOnFocusChangeListener(mOnFocusChangeListener);
        edAccount.setOnFocusChangeListener(mOnFocusChangeListener);
        edPwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (edPwd.getText() != null && edPwd.getText().toString().equals("")) {
                    icClear.setVisibility(View.GONE);
                    mIvSeePwd.setVisibility(View.GONE);
                } else {
                    icClear.setVisibility(View.VISIBLE);
                    mIvSeePwd.setVisibility(View.VISIBLE);
                }
                setLoginBtnState();
            }
        });
        edAccount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (edPwd.getText() != null && edAccount.getText() != null && edAccount.getText().toString().equals("")) {
                    icClearAccount.setVisibility(View.GONE);
                } else {
                    icClearAccount.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                String str = s.toString();
                if (str.contains("/r") || str.contains("\n")) {
                    edAccount.setText(str.replace("/r", "").replace("\n", ""));
                    edPwd.requestFocus();
                    if (edPwd.getText() != null) {
                        edPwd.setSelection(edPwd.getText().length());
                    }
                }
                setLoginBtnState();
            }
        });
    }

    private View.OnFocusChangeListener mOnFocusChangeListener = this::editFocusChange;

    /**
     * 設置登陸按鈕狀態
     */
    private void setLoginBtnState() {
        if (edAccount.getText() != null && edAccount.getText().toString().length() > 0 && edPwd.getText() != null && edPwd.getText().toString().length() >= 6) {
            mBtnLogin.setBackgroundDrawable(getResources().getDrawable(R.drawable.shape_app_btn));
        } else {
            mBtnLogin.setBackgroundDrawable(getResources().getDrawable(R.drawable.shape_app_btn_unclickable));
        }
    }

    private void editFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
            if (v.getId() == R.id.ed_login_user_pwd) {
                //密碼框獲得焦點
                if (edPwd.getText() != null && edPwd.getText().toString().length() > 0) {
                    icClear.setVisibility(View.VISIBLE);
                    mIvSeePwd.setVisibility(View.VISIBLE);
                } else {
                    icClear.setVisibility(View.GONE);
                    mIvSeePwd.setVisibility(View.GONE);
                }
            } else if (v.getId() == R.id.ed_login_user_account) {
                //賬號框獲得焦點
                if (edAccount.getText() != null && edAccount.getText().toString().length() > 0) {
                    icClearAccount.setVisibility(View.VISIBLE);
                } else {
                    icClearAccount.setVisibility(View.GONE);
                }
            }
            setLoginBtnState();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        killBeforeActivty();
    }

    private void killBeforeActivty() {
        List<Activity> activities = mAppManager.getActivityList();
        for (int i = activities.size() - 1; i >= 0; i--) {
            if (i < activities.size()) {
                Activity activity = activities.get(i);
                if (!activity.getClass().getName().equals(getClass().getName())) {
                    LogUtil.d(TAG, "killBeforeActivty: " + i + " - " + activity.getClass().getSimpleName());
                    mAppManager.killActivity(activity.getClass());
                    mAppManager.removeActivity(activity);
                }
            }
        }
    }

    @Override
    public void initIntent() {

    }

    @Override
    public void initTopBar() {

    }

    @Override
    public void initLanguage() {

    }

    @Override
    public void initLayoutParams() {

    }

    @Override
    public void initLayoutVisible() {

    }

    @Override
    public void showLoading(String message) {
        if (message != null)
            LoadingDialog.showDialogForLoading(this, message, true);
        else
            LoadingDialog.showDialogForLoading(this);
    }

    @Override
    public void hideLoading() {
        LoadingDialog.cancelDialogForLoading();
    }

    @Override
    public void showMessage(@NonNull String message) {
        ArmsUtils.makeText(this, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    public void loginSuccess(LoginBean loginBean) {
        super.loginSuccess(loginBean);
        //記住密碼
        RememberPwd();
        //自動登陸
        autoLogin();
    }

    /**
     * 記住密碼
     */
    private void RememberPwd() {
        if (mRbRememberPwd.isChecked()) {
            //登陸成功後，如果選中了記住密碼，則保存密碼
            SPUtils.put(mContext, UserConstans.LOGIN_USERNAME, edAccount.getText().toString());
            //將密碼加密再保存
            SPUtils.put(mContext, UserConstans.LOGIN_PASSWORD, Aes.aesEncrypt(edPwd.getText().toString()).replaceAll("\r|\n", ""));
        } else {
            SPUtils.put(mContext, UserConstans.LOGIN_USERNAME, "");
            SPUtils.put(mContext, UserConstans.LOGIN_PASSWORD, "");
        }
    }

    private void autoLogin() {
        SPUtils.put(mContext, UserConstans.AUTO_LOGIN, mRbAutoLogin.isChecked());
    }

    @OnClick({R2.id.btn_gsa_user_login, R2.id.iv_clear_pwd, R2.id.iv_clear_account, R2.id.tv_remember_pwd_text, R2.id.ic_look_pwd, R2.id.tv_auto_login_text, R2.id.tv_forget_pwd})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ic_look_pwd:
                passwrodVisibility = !passwrodVisibility;
                if (passwrodVisibility) {
                    //如果选中，显示密码
                    mIvSeePwd.setImageDrawable(getResources().getDrawable(R.mipmap.ic_password_show));
                    edPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    //否则隐藏密码
                    mIvSeePwd.setImageDrawable(getResources().getDrawable(R.mipmap.ic_password_hide));
                    edPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
                edPwd.setSelection(edPwd.getText() == null ? 0 : edPwd.getText().toString().length());
                break;
            case R.id.tv_remember_pwd_text:
                //記住密碼
                mRbRememberPwd.toggle();
                break;
            case R.id.tv_auto_login_text:
                //自動登陸
                mRbAutoLogin.toggle();
                if (mRbAutoLogin.isChecked()) {
                    mRbRememberPwd.setChecked(true);
                }
                break;
            case R.id.btn_gsa_user_login:
                //登陸
                if (edPwd.getText() == null || edPwd.getText().length() < 6) {
                    edPwd.setError("請輸入6~20位長度的密碼");
                } else if (edAccount.getText() == null || edAccount.getText().length() <= 0) {
                    edAccount.setError("請輸入賬戶名或手機號");
                } else {
                    mPresenter.login(edAccount.getText().toString(), edPwd.getText().toString());
                }
                break;
            case R.id.iv_clear_account:
                //清空賬號框
                edAccount.setText("");
                icClearAccount.setVisibility(View.GONE);
                break;
            case R.id.iv_clear_pwd:
                //清空密碼框
                edPwd.setText("");
                icClear.setVisibility(View.GONE);
                break;
            case R.id.tv_forget_pwd:
                //忘記密碼
                startActivity(new Intent(this, RecoverPasswordActivity.class));
                break;
        }
    }

}
