package com.zztrapp.zztrapp.ui.mine.activity;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;

import com.bumptech.glide.Glide;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.zztrapp.zztrapp.R;
import com.zztrapp.zztrapp.base.BaseActivity;
import com.zztrapp.zztrapp.bean.CreateUserBean;
import com.zztrapp.zztrapp.bean.GetAppNameBean;
import com.zztrapp.zztrapp.bean.HttpResult;
import com.zztrapp.zztrapp.bean.LoginBean;
import com.zztrapp.zztrapp.databinding.ActivityLoginBinding;
import com.zztrapp.zztrapp.http.HttpMethods;
import com.zztrapp.zztrapp.http.ISubscriberOnNextListener;
import com.zztrapp.zztrapp.http.ProgressSubscriber;
import com.zztrapp.zztrapp.http.RxApiManager;
import com.zztrapp.zztrapp.ui.MainActivity;
import com.zztrapp.zztrapp.utilcode.klogs.KLog;
import com.zztrapp.zztrapp.utilcode.mUtil.EncryptUtil;
import com.zztrapp.zztrapp.utilcode.util.SPUtils;
import com.zztrapp.zztrapp.utilcode.util.ToastUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

public class LoginActivity extends BaseActivity {

    private ActivityLoginBinding binding;
    private List<String> permissionList = new ArrayList<>();
    private boolean isHaveAllPermission = false;
    private String checkKey;
    private LoginBean result;

    @Override
    public View getLayoutId() {
        return binding.getRoot();
    }

    @Override
    protected void initBinding() {
        binding = ActivityLoginBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void init() {
        mImmersionBar.reset();
        mImmersionBar.transparentStatusBar()
                .statusBarDarkFont(true)
                .flymeOSStatusBarFontColor(R.color.black)
                .init();  //修改flyme OS状态栏字体颜色;
        // 权限申请
        setPermissions();

        //todo 方便测试 后续注释即可
//        String n = "11010242090002";
//        String n = "210202420100246011";
//        String n = "14010542190006601";
//        String p = "888888Qq!";
        //市质控账号是
//        String n = "110000";
//        String p = "888888Qq!";
//        binding.username.setText(n);
//        binding.password.setText(p);

        binding.toLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String username = binding.username.getText().toString();
                String password = binding.password.getText().toString();
                String captcha = binding.captcha.getText().toString();
                if (TextUtils.isEmpty(username)) {
                    ToastUtils.make().setGravity(Gravity.CENTER, 0, 0).show("请输入账号");
                } else if (TextUtils.isEmpty(password)) {
                    ToastUtils.make().setGravity(Gravity.CENTER, 0, 0).show("请输入密码");
                } else if (TextUtils.isEmpty(captcha)) {
                    ToastUtils.make().setGravity(Gravity.CENTER, 0, 0).show("请输入验证码");
                } else {
                    if (isHaveAllPermission) {
//                        toLogin(username, EncryptUtils.encryptMD5ToString(password), captcha);
                        toLogin(EncryptUtil.encrypt(username), EncryptUtil.encrypt(password), captcha);
                    } else {
                        startSetting();
                    }
                }
            }
        });
        binding.randomImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                randomImage(true);
            }
        });

        getAppName();
        randomImage(true);
    }

    @Override
    protected void initOnClick() {

    }

    //登录
    private void toLogin(String username, String password, String captcha) {
        ISubscriberOnNextListener<HttpResult<LoginBean>> iSubscriberOnNextListener = new ISubscriberOnNextListener<HttpResult<LoginBean>>() {

            @Override
            public void onNext(HttpResult<LoginBean> httpResult) {
                if (httpResult.getCode() == 200) {
                    result = httpResult.getResult();
                    SPUtils.getInstance().put("authorization", result.getToken());
                    createUser();
                } else {
                    randomImage(false);
                    ToastUtils.make().setGravity(Gravity.CENTER, 0, 0).show(httpResult.getMessage());
                }
            }

            @Override
            public void onError(int code, String message) {
                randomImage(false);
                ToastUtils.make().setGravity(Gravity.CENTER, 0, 0).show(message);
            }
        };
        ProgressSubscriber<HttpResult<LoginBean>> httpResultProgressSubscriber = new ProgressSubscriber<>(iSubscriberOnNextListener, LoginActivity.this, true);
        RxApiManager.get().add("login", httpResultProgressSubscriber);
        HttpMethods.getInstance(LoginActivity.this).login(httpResultProgressSubscriber, username, password, captcha, checkKey);
    }

    //获取网易云会议账号信息
    private void createUser() {
        ISubscriberOnNextListener<HttpResult<CreateUserBean>> iSubscriberOnNextListener = new ISubscriberOnNextListener<HttpResult<CreateUserBean>>() {
            @Override
            public void onNext(HttpResult<CreateUserBean> httpResult) {
                if (httpResult.getCode() == 200) {
                    SPUtils.getInstance().put("isLogin", true);
                    SPUtils.getInstance().put("userName",  result.getUserInfo().getUsername());
//                    SPUtils.getInstance().put("parcelName",  result.getUserInfo().getWrdkmc());
                    SPUtils.getInstance().put("realname",  result.getUserInfo().getRealname());
//                    String address =  result.getUserInfo().getProvinceName() +  result.getUserInfo().getCityName() +  result.getUserInfo().getCountyName();
//                    SPUtils.getInstance().put("address", address);
                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
//                    SPUtils.getInstance().put("userType",  result.getUserInfo().getUserType());//0是土地使用权人，1是市质控
                    //网易云会议账号信息
                    SPUtils.getInstance().put("accountId",  httpResult.getResult().getUserUuid());
                    SPUtils.getInstance().put("accountToken",  httpResult.getResult().getUserToken());
                    startActivity(intent);
                    finish();
                } else {
                    ToastUtils.make().setGravity(Gravity.CENTER, 0, 0).show(httpResult.getMessage());
                }
            }

            @Override
            public void onError(int code, String message) {
                ToastUtils.make().setGravity(Gravity.CENTER, 0, 0).show(message);
            }
        };
        ProgressSubscriber<HttpResult<CreateUserBean>> httpResultProgressSubscriber = new ProgressSubscriber<>(iSubscriberOnNextListener, this, true);
        RxApiManager.get().add("createUser", httpResultProgressSubscriber);
        HttpMethods.getInstance(this).createUser(httpResultProgressSubscriber);
    }

    private void randomImage(boolean showDialog) {
        int min = 100000;
        int max = 999999;
        Random random = new Random();
        int num = random.nextInt(max) % (max - min + 1) + min;
        checkKey = new Date().getTime() + String.valueOf(num);
        ISubscriberOnNextListener<HttpResult<String>> iSubscriberOnNextListener = new ISubscriberOnNextListener<HttpResult<String>>() {

            @Override
            public void onNext(HttpResult<String> httpResult) {
                KLog.e("onNext");
                KLog.e(httpResult.getResult());
                if (httpResult.getCode() == 0) {
                    Glide.with(LoginActivity.this).load(httpResult.getResult()).error(R.mipmap.random_image).centerCrop().into(binding.randomImage);
                } else {
                    binding.randomImage.setImageResource(R.mipmap.random_image);
                    ToastUtils.make().setGravity(Gravity.CENTER, 0, 0).show(httpResult.getMessage());
                }
            }

            @Override
            public void onError(int code, String message) {
                KLog.e("onError"+code);

                binding.randomImage.setImageResource(R.mipmap.random_image);
                ToastUtils.make().setGravity(Gravity.CENTER, 0, 0).show(message);
            }
        };
        ProgressSubscriber<HttpResult<String>> httpResultProgressSubscriber = new ProgressSubscriber<>(iSubscriberOnNextListener, LoginActivity.this, showDialog);
        RxApiManager.get().add("randomImage", httpResultProgressSubscriber);
        HttpMethods.getInstance(LoginActivity.this).randomImage(httpResultProgressSubscriber, checkKey);
    }

    //App描述信息
    private void getAppName() {
        ISubscriberOnNextListener<HttpResult<GetAppNameBean>> iSubscriberOnNextListener = new ISubscriberOnNextListener<HttpResult<GetAppNameBean>>() {

            @Override
            public void onNext(HttpResult<GetAppNameBean> httpResult) {
                if (httpResult.getCode() == 200) {
                    binding.appHint.setText(httpResult.getResult().getAppName());
                } else {
                    ToastUtils.make().setGravity(Gravity.CENTER, 0, 0).show(httpResult.getMessage());
                }
            }

            @Override
            public void onError(int code, String message) {
                ToastUtils.make().setGravity(Gravity.CENTER, 0, 0).show(message);
            }
        };
        ProgressSubscriber<HttpResult<GetAppNameBean>> httpResultProgressSubscriber = new ProgressSubscriber<>(iSubscriberOnNextListener, this, false);
        RxApiManager.get().add("getAppName", httpResultProgressSubscriber);
        HttpMethods.getInstance(this).getAppName(httpResultProgressSubscriber);
    }

    /**
     * 权限申请
     */
    @SuppressLint("WrongConstant")
    private void setPermissions() {
        XXPermissions.with(this)
                // 申请安装包权限
                //.permission(Permission.REQUEST_INSTALL_PACKAGES)
                // 申请单个权限
                .permission(Permission.CAMERA)
                .permission(Permission.ACCESS_COARSE_LOCATION)
                .permission(Permission.ACCESS_FINE_LOCATION)
                // 申请多个权限
                .permission(Permission.Group.STORAGE)
                .permission(Permission.Group.BLUETOOTH)
                .request(new OnPermissionCallback() {

                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        permissionList = permissions;
                        isHaveAllPermission = all;
//                        KLog.e("--onGranted---");
//                        KLog.e(permissions.toString());
//                        KLog.e(all);
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        permissionList = permissions;
//                        KLog.e("--onDenied---");
//                        KLog.e(permissions.toString());
//                        KLog.e(never);
                    }
                });
    }

    private void startSetting() {
        AlertDialog.Builder alertdialogbuilder = new AlertDialog.Builder(LoginActivity.this);
        alertdialogbuilder.setMessage("为了能正常使用，请手动授予相关权限");
        alertdialogbuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                // 如果是被永久拒绝就跳转到应用权限系统设置页面
                XXPermissions.startPermissionActivity(LoginActivity.this, permissionList);
            }
        });
        alertdialogbuilder.setNeutralButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
            }
        });
        final AlertDialog alertdialog1 = alertdialogbuilder.create();
        alertdialog1.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == XXPermissions.REQUEST_CODE) {
            if (XXPermissions.isGranted(this, Permission.CAMERA) && XXPermissions.isGranted(this, Permission.ACCESS_COARSE_LOCATION) && XXPermissions.isGranted(this, Permission.ACCESS_FINE_LOCATION) && XXPermissions.isGranted(this, Permission.Group.STORAGE)) {
                isHaveAllPermission = true;
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        binding = null;
        RxApiManager.get().cancel("getAppName");
        RxApiManager.get().cancel("randomImage");
        RxApiManager.get().cancel("login");
    }
}