package com.casic.dcms.ui;


import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;

import com.casic.dcms.R;
import com.casic.dcms.base.BaseActivity;
import com.casic.dcms.bean.LoginResultBean;
import com.casic.dcms.bean.PublicKeyBean;
import com.casic.dcms.mvp.presenter.AuthenticatePresenterImpl;
import com.casic.dcms.mvp.presenter.LoginPresenterImpl;
import com.casic.dcms.mvp.view.IAuthenticateView;
import com.casic.dcms.mvp.view.ILoginView;
import com.casic.dcms.utils.AuthenticationHelper;
import com.casic.dcms.utils.Constant;
import com.casic.dcms.utils.RSAUtils;
import com.casic.dcms.utils.SaveKeyValues;
import com.casic.dcms.utils.StringHelper;
import com.casic.dcms.utils.ToastHelper;
import com.casic.dcms.widgets.InputDialog;
import com.qmuiteam.qmui.alpha.QMUIAlphaImageButton;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;

import java.security.PublicKey;

import butterknife.BindView;
import butterknife.OnClick;

public class LoginActivity extends BaseActivity implements View.OnClickListener, IAuthenticateView, ILoginView {

    private static final String TAG = "LoginActivity";

    @BindView(R.id.userNameView)
    EditText userNameView;
    @BindView(R.id.userPasswordView)
    EditText userPasswordView;
    @BindView(R.id.loginButton)
    QMUIRoundButton loginButton;
    @BindView(R.id.rememberPasswordView)
    CheckBox rememberPasswordView;
    @BindView(R.id.autoLoginView)
    CheckBox autoLoginView;
    @BindView(R.id.changeServerConfigButton)
    QMUIAlphaImageButton changeServerConfigButton;

    private QMUITipDialog loadingDialog;
    private AuthenticatePresenterImpl authenticatePresenter;
    private LoginPresenterImpl loginPresenter;

    @Override
    public int initLayoutView() {
        return R.layout.activity_login;
    }

    @Override
    protected void setupTopBarLayout() {
        //设置状态栏黑色字体图标
        QMUIStatusBarHelper.setStatusBarLightMode(this);
    }

    @Override
    public void initData() {
        String userAccount = StringHelper.getUserAccount();
        String userPassword = (String) SaveKeyValues.getValue("userPassword", "");
        userNameView.setText(userAccount);
        userPasswordView.setText(userPassword);
        if (!TextUtils.isEmpty(userAccount) && !TextUtils.isEmpty(userPassword)) {
            rememberPasswordView.setChecked(true);
        } else {
            rememberPasswordView.setChecked(false);
        }
        rememberPasswordView.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (!isChecked) {
                    SaveKeyValues.removeKey("userPassword");
                }
            }
        });
        loadingDialog = new QMUITipDialog.Builder(this)
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                .setTipWord("登录中，请稍后")
                .create();
    }

    @Override
    public void initEvent() {
        loginButton.setChangeAlphaWhenPress(true);
        changeServerConfigButton.setChangeAlphaWhenPress(true);
        authenticatePresenter = new AuthenticatePresenterImpl(this);
        loginPresenter = new LoginPresenterImpl(this);
    }

    @OnClick({R.id.loginButton, R.id.changeServerConfigButton})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.loginButton:
                //验证公钥
                authenticatePresenter.onReadyRetrofitRequest();
                break;
            case R.id.changeServerConfigButton:
                new InputDialog.Builder()
                        .setContext(this)
                        .setTitle("修改服务器地址和端口")
                        .setOnDialogClickListener(new InputDialog.OnDialogClickListener() {
                            @Override
                            public void onConfirmClick(String serverValue, String portValue) {
                                if (!TextUtils.isEmpty(serverValue) && !TextUtils.isEmpty(portValue)) {
                                    String serverConfig = "http:" + serverValue + ":" + portValue;
                                    SaveKeyValues.putValue(Constant.IP_KEY, serverConfig);
                                    ToastHelper.showToast("服务器地址修改成功", ToastHelper.SUCCESS);
                                }
                            }

                            @Override
                            public void onCancelClick() {

                            }
                        }).build().show();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //自动登录
        boolean autoLogin = (boolean) SaveKeyValues.getValue("autoLogin", false);
        autoLoginView.setChecked(autoLogin);
        if (autoLogin) {
            authenticatePresenter.onReadyRetrofitRequest();
        }
    }

    @Override
    public void showProgress() {
        loadingDialog.show();
    }

    @Override
    public void authenticateResult(PublicKeyBean result) {
        if (result.isSuccess()) {
            String keyString = result.getData().getPublicKey();
            AuthenticationHelper.savePublicKey(keyString);

            PublicKey publicKey = RSAUtils.keyStrToPublicKey(keyString);
            String account = userNameView.getText().toString();
            String userPassword = userPasswordView.getText().toString();
            if (autoLoginView.isChecked()) {
                SaveKeyValues.putValue("autoLogin", true);
            } else {
                SaveKeyValues.putValue("autoLogin", false);
            }
            if (TextUtils.isEmpty(account)) {
                ToastHelper.showToast("用户名不能为空", ToastHelper.WARING);
                return;
            }
            if (TextUtils.isEmpty(userPassword)) {
                ToastHelper.showToast("密码不能为空", ToastHelper.WARING);
                return;
            }
            if (rememberPasswordView.isChecked()) {
                StringHelper.saveUserAccount(account);
                SaveKeyValues.putValue("userPassword", userPassword);
            }
            String dataByPublicKey = RSAUtils.encryptDataByPublicKey(userPassword.getBytes(), publicKey);
            //登录并获取Token，POST请求
            loginPresenter.onReadyRetrofitRequest(account, dataByPublicKey);
        }
    }

    @Override
    public void obtainLoginResult(LoginResultBean result) {
        String token = result.getData().getToken();
        if (!TextUtils.isEmpty(token)) {
            //获取用户信息
            AuthenticationHelper.saveToken(token);
            //验证成功登录
            startActivity(new Intent(this, MainActivity.class));
            finish();
        }
    }

    @Override
    public void loginFail() {
        ToastHelper.showToast("登录失败，请检查账号密码", ToastHelper.ERROR);
    }

    @Override
    public void hideProgress() {
        loadingDialog.dismiss();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (authenticatePresenter != null) {
            authenticatePresenter.disposeRetrofitRequest();
        }
        if (loginPresenter != null) {
            loginPresenter.disposeRetrofitRequest();
        }
    }
}
