package com.beanpodtech.allinone.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.lifecycle.Lifecycle;

import com.alibaba.security.realidentity.RPEventListener;
import com.alibaba.security.realidentity.RPResult;
import com.alibaba.security.realidentity.RPVerify;
import com.aliyun.svideo.common.utils.ToastUtils;
import com.beanpodtech.allinone.R;
import com.beanpodtech.allinone.bean.DescribeVerifyBean;
import com.beanpodtech.allinone.bean.User;
import com.beanpodtech.allinone.bean.VerifyTokenBean;
import com.beanpodtech.allinone.http.UrlConfig;
import com.beanpodtech.allinone.retrofit.BaseObserver;
import com.beanpodtech.allinone.retrofit.RetrofitClient;
import com.beanpodtech.allinone.retrofit.RxScheduler;
import com.beanpodtech.allinone.utils.BoxUtil;
import com.beanpodtech.allinone.utils.Contants;
import com.beanpodtech.allinone.utils.DialogCallback;
import com.beanpodtech.allinone.utils.HttpUtils;
import com.beanpodtech.allinone.utils.OkGoBuilder;
import com.beanpodtech.allinone.utils.OkGoUtil;
import com.beanpodtech.allinone.utils.SoftInputUtil;
import com.beanpodtech.allinone.utils.SpUtil;
import com.beanpodtech.allinone.widget.LoadingView;
import com.lzy.okgo.model.Response;
import com.uber.autodispose.AutoDispose;
import com.uber.autodispose.android.lifecycle.AndroidLifecycleScopeProvider;
import com.zyyoona7.popup.EasyPopup;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 登录页面
 **/
public class LoginActivity extends BaseActivity {
    private Button btn_login;
    private String password_MD5;
    /**
     * 大陆手机号码11位数，匹配格式：前三位固定格式+后8位任意数
     * 此方法中前三位格式有：
     * 13+任意数
     * 145,147,149
     * 15+除4的任意数(不要写^4，这样的话字母也会被认为是正确的)
     * 166
     * <p>
     * <p>
     * 17+3,5,6,7,8
     * 18+任意数
     * 198,199
     */

    public final static String PHONE_PATTERN = "^(1)\\d{10}$";

    private EasyPopup agreePopup, mFacePopup; //协议弹窗
    private RelativeLayout mainLayout;
    private CheckBox checkBox;
    private TextView agreeText;
    private Boolean booAgree = false; //是否已经同意协议
    private LoadingView loadingView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BoxUtil.hideBottomUIMenu(this);
    }
    @Override
    public int bindLayout() {
        return R.layout.activity_login;
    }

    @Override
    public void initView(View view) {
        mainLayout = findViewById(R.id.rl_login_main); //根布局
        btn_login = findViewById(R.id.LoginButton);   //登录按钮
        checkBox = findViewById(R.id.cb_login); //checkBox
        agreeText = findViewById(R.id.tv_user_agree); //查看用户协议
        checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                booAgree = isChecked;
                checkBox.setChecked(isChecked);
            }
        });
        loadingView = new LoadingView(LoginActivity.this, R.style.CustomDialog);
        loadingView.setTitle(getResources().getString(R.string.waitloading));
        initPop();  //初始化协议弹窗
        initFacePop();

    }

    /**
     * 正则表达式
     **/
    public static boolean isMatchered(String patternStr, CharSequence input) {
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(input);
        return matcher.find();
    }

    /**
     * MD5加密
     **/
    public static String getMD5(String val) throws NoSuchAlgorithmException {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        md5.update(val.getBytes());
        byte[] bytearray = md5.digest();// 加密
        StringBuffer sb = new StringBuffer();
        for (byte b : bytearray) {
            int i = (b & 0xFF);
            if (i < 0x10) {
                sb.append('0');
            }
            sb.append(Integer.toHexString(i));
        }
        return sb.toString();
    }

    private HashMap<String, String> initJson(String userName, String passWord, String boxId) {
        HashMap<String, String> map = new HashMap<>();
        map.put("userName", userName);
        map.put("passWord", passWord);
        map.put("boxId", boxId);
        return map;
    }


    @Override
    public void widgetClick(View v) {
        switch (v.getId()) {
            case R.id.LoginButton:
                Login();
                break;

            case R.id.tv_user_agree: //用户协议
                //显示弹窗
                agreePopup.dismiss();
                agreePopup.showAtLocation(getWindow().getDecorView(), Gravity.CENTER, 0, 0);
                break;

            case R.id.rl_login_main:
                SoftInputUtil.hideSoftInput(this);
                break;

        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        BoxUtil.hideBottomUIMenu(this);
    }

    //登录
    private void Login() {
        if (!booAgree) {
            ToastUtils.showInCenter(this, "请先阅读并勾选用户个人信息保护政策");
            return;
        }
        String input_uesrname = ((EditText) findViewById(R.id.usename)).getText().toString();
        String input_password = ((EditText) findViewById(R.id.password)).getText().toString();
        if (input_uesrname.length() == 0 || input_password.length() == 0) {
            Toast.makeText(LoginActivity.this, "请输入用户名跟密码", Toast.LENGTH_SHORT).show();
        } else {
            if (isMatchered(PHONE_PATTERN, input_uesrname)) {
                try {
                    password_MD5 = getMD5(input_password);
                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                }
                String boxId = BoxUtil.getDeviceSN();
                OkGoBuilder.getInstance().method(OkGoBuilder.PSOT).Builder(LoginActivity.this).cls(User.class).requestBody(HttpUtils.getRequestJson(initJson(input_uesrname, password_MD5, boxId))).url(UrlConfig.LOGIN)
                        .callback(new OkGoUtil<User>(User.class) {
                            @Override
                            public void onSuccess(Response<User> response) {
                                User body = response.body();
                                if (body.getcode() == 0) {
                                    saveUser(body);
                                    if (body.isHaveFaceUrl()) {
                                        startActivity(new Intent(LoginActivity.this, HomeActivity.class));
                                        finish();
                                    } else {
                                        mFacePopup.showAtLocation(getWindow().getDecorView(), Gravity.CENTER, 0, 0);
                                    }

                                } else if (body.getcode() == -1) {
                                    Toast.makeText(LoginActivity.this, "用户名不存在", Toast.LENGTH_SHORT).show();
                                } else if (body.getcode() == -2) {
                                    Toast.makeText(LoginActivity.this, "密码错误", Toast.LENGTH_SHORT).show();
                                }
                            }

                            @Override
                            public void onError(Response<User> response) {
                                super.onError(response);
                                Toast.makeText(LoginActivity.this, R.string.neterror, Toast.LENGTH_SHORT).show();

                            }
                        }).build();
            } else {
                Toast.makeText(LoginActivity.this, "请输入正确的用户名", Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 获取verifyToken
     */
    private void getVerifyToken() {
        loadingView.show();
        Map<String, Object> mMap = new HashMap<>();
        mMap.put("type", "1");
        RetrofitClient.getInstance().getApi().getVerifyToken(mMap)
                .compose(RxScheduler.Obs_io_main())
                .subscribe(new BaseObserver<VerifyTokenBean>() {
                    @Override
                    public void onSuccess(VerifyTokenBean data) {
                        loadingView.dismiss();
                        startFace(data.getVerifyToken());
                    }

                    @Override
                    public void onFailure(Throwable e, String errorMsg) {
                        loadingView.dismiss();
                        showToast(errorMsg);
                    }
                });
    }

    /**
     * 调用人脸识别进行录入
     * @param token
     */
    private void startFace(String token) {
        RPVerify.startByNative(LoginActivity.this, token, new RPEventListener() {
            @Override
            public void onFinish(RPResult auditResult, String code, String msg) {
                if (auditResult == RPResult.AUDIT_PASS) {
                    // 认证通过。建议接入方调用实人认证服务端接口DescribeVerifyResult来获取最终的认证状态，并以此为准进行业务上的判断和处理。
                    getDescribeVerifyResult();
                } else if (auditResult == RPResult.AUDIT_FAIL) {
                    // 认证不通过。建议接入方调用实人认证服务端接口DescribeVerifyResult来获取最终的认证状态，并以此为准进行业务上的判断和处理。
                    showToast("认证不通过,请重新认证");
                } else if (auditResult == RPResult.AUDIT_NOT) {
                    // 未认证，具体原因可通过code来区分（code取值参见错误码说明），通常是用户主动退出或者姓名身份证号实名校验不匹配等原因，导致未完成认证流程。
                    showToast("未认证");
                }
            }
        });
    }

    /**
     * 调用DescribeVerifyResult查询实人认证结果。
     */
    private void getDescribeVerifyResult() {
        loadingView.show();
        Map<String, Object> mMap = new HashMap<>();
        mMap.put("type", "1");
        RetrofitClient.getInstance().getApi().getDescribeVerifyResult(mMap)
                .compose(RxScheduler.Obs_io_main())
                .subscribe(new BaseObserver<DescribeVerifyBean>() {
                    @Override
                    public void onSuccess(DescribeVerifyBean data) {
                        showToast("录入成功");
                        loadingView.dismiss();
                        startActivity(new Intent(LoginActivity.this, HomeActivity.class));
                        finish();
                    }

                    @Override
                    public void onFailure(Throwable e, String errorMsg) {
                        loadingView.dismiss();
                        showToast(errorMsg);
                    }
                });
    }


    private void initPop() {  //初始化协议弹窗
        agreePopup = EasyPopup.create()
                .setContext(this)
                .setContentView(R.layout.pop_agree)
                .setWidth(WindowManager.LayoutParams.WRAP_CONTENT)
                .setHeight(WindowManager.LayoutParams.WRAP_CONTENT)
                .setOutsideTouchable(true)
                .setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
                .setBackgroundDimEnable(true)
                .setDimValue(0.3f)
                .setDimColor(Color.BLACK)
                .apply();

        TextView agreeBtn = agreePopup.findViewById(R.id.tv_agree_btn);
        ImageView closeIv = agreePopup.findViewById(R.id.pop_close);
        agreeBtn.setOnClickListener(v -> {
            booAgree = true;
            checkBox.setChecked(true);
            agreePopup.dismiss();
        });
        closeIv.setOnClickListener(v -> agreePopup.dismiss());

    }

    private void initFacePop() {  //初始化协议弹窗
        mFacePopup = EasyPopup.create()
                .setContext(this)
                .setContentView(R.layout.pop_face)
                .setWidth(WindowManager.LayoutParams.WRAP_CONTENT)
                .setHeight(WindowManager.LayoutParams.WRAP_CONTENT)
                .setOutsideTouchable(true)
                .setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
                .setBackgroundDimEnable(true)
                .setDimValue(0.3f)
                .setDimColor(Color.BLACK)
                .apply();

        TextView agreeBtn = mFacePopup.findViewById(R.id.tv_face_btn);
        agreeBtn.setOnClickListener(v -> {
            getVerifyToken();
        });

    }

    @Override
    public void initListener() {
        btn_login.setOnClickListener(this);
        agreeText.setOnClickListener(this);
        mainLayout.setOnClickListener(this);

    }

    @Override
    public void initData(Context mContext) {
//        IPUtils.getDeviceStatus(SpUtil.getInstace().getString(Contants.USER_ID, null), handler);
    }

    private void saveUser(User body) {
        SpUtil.getInstace().save(Contants.USER_NAME, body.getuserName());
        SpUtil.getInstace().save(Contants.USER_AVATAR, body.getavatar());
        SpUtil.getInstace().save(Contants.TOKEN, body.gettoken());
        Log.d(TAG, "saveUser: aaa" + body.gettoken());
        SpUtil.getInstace().save(Contants.USER_ID, body.getUserId());
        SpUtil.getInstace().save(Contants.LOGIN_STATE, false);
        SpUtil.getInstace().save(Contants.USER_PASSWORD, password_MD5);
        SpUtil.getInstace().save(Contants.USER_SCHOOLNAME, body.getSchoolName());
        SpUtil.getInstace().save(Contants.USER_GRADE, body.getGrade());
        SpUtil.getInstace().save(Contants.USER_BRANCHNAME, body.getBranchName());
        SpUtil.getInstace().save(Contants.USER_BRANCHSCHOOL, body.getBranchSchool());
        SpUtil.getInstace().save(Contants.USER_BIRTHDAY, body.getBirthday());
        SpUtil.getInstace().save(Contants.USER_ADDRESS, body.getAddress());
        SpUtil.getInstace().save(Contants.USER_PARENTNAME, body.getParentName());
        SpUtil.getInstace().save(Contants.USER_NICKNAME, body.getnickName());
        SpUtil.getInstace().save(Contants.IS_PRINCIPAL, body.isPrincipal());
    }
}
