package com.navinfo.outdoor.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.github.lazylibrary.util.MD5;
import com.lzy.okgo.model.HttpParams;
import com.navinfo.outdoor.R;
import com.navinfo.outdoor.api.Constant;
import com.navinfo.outdoor.base.BaseActivity;
import com.navinfo.outdoor.bean.LoginOauthTokenBean;
import com.navinfo.outdoor.bean.UserBean;
import com.navinfo.outdoor.bean.UserDetailBean;
import com.navinfo.outdoor.http.Callback;
import com.navinfo.outdoor.http.HttpInterface;
import com.navinfo.outdoor.http.OkGoBuilder;
import com.navinfo.outdoor.room.PoiEntity;
import com.navinfo.outdoor.util.Base64;
import com.navinfo.outdoor.util.Md5Util;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

/**
 * 登录页
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener {
    private TextView tvRegister;
    private android.widget.EditText etLoginName;
    private android.widget.EditText etLoginPaw;
    private TextView tvForgetPaw;
    private Button btnLogin;
    private SharedPreferences navInfo;
    private SharedPreferences.Editor navInfoEditor;
    private TextView tvStatement;
    private CheckBox cbStatement;

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {//加上判断
            EventBus.getDefault().register(this);
        }

    }

    @Override
    protected int getLayout() {
        return R.layout.activity_login;
    }

    @Override
    protected void initData() {
        super.initData();
    }

    @Subscribe
    public void onEvent(Message data) {
        if (data.what == Constant.REGISTER_WORD) {
            if ((boolean) data.obj) {
                etLoginName.setText(Constant.USER_NAME);
                etLoginPaw.setText(Constant.PASS_WORD);
            }
        }
    }

    @Override
    protected void initView() {
        super.initView();
        navInfoEditor = getSharedPreferences(Constant.SHARED_PREFERENCES, Context.MODE_PRIVATE).edit();
        navInfo = getSharedPreferences(Constant.SHARED_PREFERENCES, Context.MODE_PRIVATE);
        tvRegister = findViewById(R.id.tv_register);
        etLoginName = findViewById(R.id.et_login_name);
        etLoginPaw = findViewById(R.id.et_login_paw);
        tvForgetPaw = findViewById(R.id.tv_forget_paw);
        cbStatement = findViewById(R.id.iv_login_check);
        btnLogin = findViewById(R.id.btn_login);
        btnLogin.setOnClickListener(this::onClick);
        tvStatement = findViewById(R.id.tv_statement);
        tvStatement.setOnClickListener(this::onClick);
        tvRegister.setOnClickListener(this);
        tvForgetPaw.setOnClickListener(this);
        if (navInfo!=null){
            String user_name = navInfo.getString("user_name", null);
            if (user_name!=null&&!user_name.equals("")){
                etLoginName.setText(user_name);
            }
            String pass_word = navInfo.getString("pass_word", null);
            if (pass_word!=null&&!pass_word.equals("")){
                etLoginPaw.setText(pass_word);
            }
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_register:
                Intent register = new Intent(this, FragmentManagement.class);
                register.putExtra("tag", 5);
                startActivity(register);
                break;
            case R.id.tv_forget_paw:
                Intent forgetPaw = new Intent(this, FragmentManagement.class);
                forgetPaw.putExtra("tag", 6);
                startActivity(forgetPaw);
                break;
            case R.id.btn_login:
                String name = etLoginName.getText().toString().trim();
                if (name == null || name.equals("")) {
                    Toast.makeText(this, "请输入账号", Toast.LENGTH_SHORT).show();
                    return;
                }
                String paw = etLoginPaw.getText().toString().trim();
                if (paw == null || paw.equals("")) {
                    Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!cbStatement.isChecked()){
                    Toast.makeText(this, "请先同意免责协议", Toast.LENGTH_SHORT).show();
                    return;
                }else {
                    initLogIn(name, paw);
                }

                break;

            case R.id.tv_statement:
                Intent stateIntent = new Intent(this, StatementActivity.class);
                startActivity(stateIntent);
                break;
        }
    }

    private void initLogIn(String name, String paw) {
        try {
            HttpParams httpParams = new HttpParams();
            httpParams.put("username", name);
            long time = System.currentTimeMillis();
            httpParams.put("password", Base64.desEncrypt(time + Md5Util.toMD5(paw)));
            httpParams.put("grant_type", "password");
            httpParams.put("datetime", time);
            showLoadingDialog();
            OkGoBuilder.getInstance().Builder(this)
                    .url(HttpInterface.USER_LOGIN_OAUTH_TOKEN)
                    .cls(LoginOauthTokenBean.class)
                    .params(httpParams)
                    .postRequest(new Callback<LoginOauthTokenBean>() {
                        @Override
                        public void onSuccess(LoginOauthTokenBean response, int id) {
                            dismissLoadingDialog();
                            if (response.getCode()==200){
                                LoginOauthTokenBean.BodyBean body = response.getBody();
                                if (body.getUserId()!=null&&!body.getUserId().equals("")){
                                    Constant.initRootFolder(body.getUserId());
                                }
                                navInfoEditor.putString("access_token",body.getAccess_token());
                                navInfoEditor.putString("refresh_token",body.getRefresh_token());
                                navInfoEditor.putString("userId",body.getUserId());
                                navInfoEditor.putString("pass_word",paw);
                                navInfoEditor.putString("user_name",name);
                                navInfoEditor.commit();
                                Constant.ACCESS_TOKEN=body.getAccess_token();
                                Constant.REFRESH_TOKEN=body.getRefresh_token();
                                Constant.USERID=body.getUserId();
                                Constant.PASS_WORD=paw;
                                initGetUserInfo();//获取用户信息
                                Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(LoginActivity.this, response.getMessage(), Toast.LENGTH_SHORT).show();
                                dismissLoadingDialog();
                            }
                        }

                        @Override
                        public void onError(Throwable e, int id) {
                            dismissLoadingDialog();
                            Toast.makeText(LoginActivity.this, e.getMessage() + "", Toast.LENGTH_SHORT).show();
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void initGetUserInfo() {
        OkGoBuilder.getInstance().Builder(this)
                .url(HttpInterface.USER_DETAIL_BY_USER_ID)
                .token(Constant.ACCESS_TOKEN)
                .params(new HttpParams())
                .cls(UserDetailBean.class)
                .getRequest(new Callback<UserDetailBean>() {
                    @Override
                    public void onSuccess(UserDetailBean response, int id) {
                        dismissLoadingDialog();
                        if (response.getCode()==200){
                            UserDetailBean.BodyBean body = response.getBody();
                            if (body!=null){
                                navInfoEditor.putString("username",body.getUsername());
                                Constant.USER_NAME=body.getUsername();
                                navInfoEditor.putString("mobile",body.getMobile());
                                Constant.MOBILE=body.getMobile();
                                navInfoEditor.putInt("sex",body.getSex());//0:女  1：男
                                Constant.SEX=body.getSex();
                                navInfoEditor.putString("qq",body.getQq());
                                Constant.QQ=body.getQq();
                                navInfoEditor.putString("wechat",body.getWechat());
                                Constant.WECHAT=body.getWechat();
                                UserDetailBean.BodyBean.UserBankcardBean userBankcard = body.getUserBankcard();
                                if (userBankcard!=null){//存储银行卡信息
                                    navInfoEditor.putString("bankAccount",userBankcard.getBankAccount());//银行卡编号
                                    Constant.BANKACCOUNT=userBankcard.getBankAccount();
                                    navInfoEditor.putString("idNumber",userBankcard.getIdNumber());//银行卡账号
                                    Constant.ID_NUMBER=userBankcard.getIdNumber();
                                }
                                UserDetailBean.BodyBean.UserAuthBean userAuth = body.getUserAuth();
                                if (userAuth!=null){//存储身份证信息
                                    navInfoEditor.putString("name",userAuth.getName());//身份证姓名
                                    Constant.NAME=userAuth.getName();
                                    navInfoEditor.putString("idnum",userAuth.getIdnum());//身份证号码
                                    Constant.ID_NUM=userAuth.getIdnum();
                                    navInfoEditor.putInt("auditstatus",userAuth.getAuditstatus());//审核状态
                                    Constant.AUDITSTATUS=userAuth.getAuditstatus();
                                    navInfoEditor.putString("auditmsg",userAuth.getAuditmsg());//审核信息
                                    Constant.AUDITMSG=userAuth.getAuditmsg();
                                }
                                navInfoEditor.commit();
                            }
                            Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
                            startActivity(intent);
                            finish();
                        }else {
                            Toast.makeText(LoginActivity.this, response.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Throwable e, int id) {
                      dismissLoadingDialog();
                        Toast.makeText(LoginActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });


    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }
    @Override
    public void onDestroy() {
        if (EventBus.getDefault().isRegistered(this))//加上判断
            EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}
