package com.genlot.ninglottery.module.login;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.EditText;

import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.genlot.nativesdk.SystemNI;
import com.genlot.ninglottery.R;
import com.genlot.ninglottery.base.BaseMVPActivity;
import com.genlot.ninglottery.base.InjectPresenter;
import com.genlot.ninglottery.game.GameActivity;
import com.genlot.ninglottery.game.GameManager;
import com.genlot.ninglottery.model.Constant;
import com.genlot.ninglottery.module.function.FunctionActivity;
import com.genlot.ninglottery.toolkit.AppTool;
import com.genlot.ninglottery.toolkit.LogTool;
import com.genlot.ninglottery.widget.Diaolog.BaseDialog;
import com.genlot.ninglottery.widget.Diaolog.CommonDialog;
import com.genlot.ninglottery.widget.Diaolog.ViewConvertListener;

import butterknife.OnClick;

/**
 * @author ZhuYongKang
 * @description 登录界面
 * @date 2019/8/16
 */
public class LoginActivity extends BaseMVPActivity implements ILoginView{

    private EditText etUser, etPassword, etAdminPassword;

    @InjectPresenter
    LoginPresenter mPresenter;

    @OnClick(R.id.bt_login)
    public void loginClick() {
        showLoginDialog();
    }

    @OnClick(R.id.bt_setting)
    public void settingClick() {
        showAdminLoginDialog();
    }

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

    @Override
    public void initViews(Bundle savedInstanceState) {
        if (checkUpdate()) {
            mPresenter.update();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        showLoginDialog();
    }

    private void showLoginDialog() {
        CommonDialog.newInstance().setLayoutId(R.layout.dialog_login).setConvertListener((ViewConvertListener) (holder, dialog) -> {
            etUser = holder.getView(R.id.et_username);
            etPassword = holder.getView(R.id.et_password);
            holder.setOnClickListener(R.id.bt_no, v -> dialog.dismiss());
            holder.setOnClickListener(R.id.bt_yes, v -> login(dialog));
        })
                .setSize(ScreenUtils.getScreenWidth(),ScreenUtils.getScreenHeight())
                .setOutCancel(false)
                .show(getSupportFragmentManager());

    }

    public void login(BaseDialog dialog) {
        String username = etUser.getText().toString().trim();
        String password = etPassword.getText().toString().trim();
        if (TextUtils.isEmpty(username)) {
            ToastUtils.showShort("用户名不能为空");
            return;
        }
        if (TextUtils.isEmpty(password)) {
            ToastUtils.showShort("密码不能为空");
            return;
        }
        dialog.dismiss();
        if (GameManager.isTrainMode) {
            GameManager.setStationAddress("测试站地址");
            onLoginSuccess();
        } else {
            mPresenter.login(username, password);
        }
    }

    private void showAdminLoginDialog() {
        CommonDialog.newInstance().setLayoutId(R.layout.dialog_admin_login).setConvertListener((ViewConvertListener) (holder, dialog) -> {
            etAdminPassword = holder.getView(R.id.et_admin_password);
            holder.setOnClickListener(R.id.bt_no, v -> dialog.dismiss());
            holder.setOnClickListener(R.id.bt_setting, v -> adminLogin(dialog));
        })
                .setSize(ScreenUtils.getScreenWidth(),ScreenUtils.getScreenHeight())
                .setOutCancel(false)
                .show(getSupportFragmentManager());
    }

    public void adminLogin(BaseDialog dialog) {
        String adminPassword = etAdminPassword.getText().toString().trim();
        if (TextUtils.isEmpty(adminPassword)) {
            ToastUtils.showShort("管理员密码不能为空");
            return;
        }
        if (!Constant.ADMIN_PASSWORD.equals(adminPassword.toLowerCase())) {
            ToastUtils.showShort("管理员密码不正确");
            return;
        }
        Intent intent = new Intent(this, FunctionActivity.class);
        intent.putExtra(Constant.IS_ADMIN, true);
        startActivity(intent);
        dialog.dismiss();
    }

    private boolean checkUpdate() {
        if (SystemNI.isEnforceUpdate()) {
            return AppTool.compareVersion(AppTool.getServerVersion(), AppTool.getAppVersionName(this));
        }
        return false;
    }

    @Override
    public void onLoginFailed(int errorCode) {
        dismissLoading();
        if(!AppTool.isNetworkAvalible(this)){
            ToastUtils.showShort("网络异常，请检查网络!");
            return;
        }
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("[");
        stringBuilder.append(errorCode);
        stringBuilder.append("]");
        if(errorCode == -1){
            stringBuilder.append("系统错误");
        }else if(errorCode == -2){
            stringBuilder.append("系统繁忙");
        }else if(errorCode == -3){
            stringBuilder.append("通讯失败");
        }else if(errorCode == -4){
            stringBuilder.append("通讯超时");
        }else if(errorCode == -5){
            stringBuilder.append("通讯中断请重试");
        }else if(errorCode == -6){
            stringBuilder.append("投注机DOM disc损坏，请联系维护人员");
        }else if(errorCode == -1001){
            stringBuilder.append("投注机校验码不匹配");
        }else if(errorCode == -1002){
            stringBuilder.append("投注机已登录，不能重复登录");
        }else if(errorCode == -1003){
            stringBuilder.append("投注终端已经被禁用");
        }else if(errorCode == -1004){
            stringBuilder.append("投注终端状态未知");
        }else if(errorCode == -1005){
            stringBuilder.append("未注册的投注站点号");
        }else if(errorCode == -1006){
            stringBuilder.append("被注销的站点号");
        }else if(errorCode == -1009){
            stringBuilder.append("该站点没有该工号的操作员");
        }else if(errorCode == -1010){
            stringBuilder.append("密码错误");
        }else if(errorCode == -1011){
            stringBuilder.append("该版本投注机已不被后台支持，请下载最新版本");
        }else if(errorCode == -1012){
            stringBuilder.append("没有注册投注机的认证信息");
        }else if(errorCode == -1318){
            stringBuilder.append("通讯停止");
        }else if(errorCode == -1309){
            stringBuilder.append("发送交易请求失败");
        }else{
            LogTool.logE("ErrorCode =" + errorCode);
            stringBuilder.append("通讯异常");
        }
        ToastUtils.showShort(stringBuilder.toString());
    }

    @Override
    public void onLoginSuccess() {
        dismissLoading();
        Intent intent = new Intent(LoginActivity.this, GameActivity.class);
        GameManager.setUser(etUser.getText().toString().trim());
        GameManager.setPassword(etPassword.getText().toString().trim());
        startActivity(intent);
    }

}
