package com.ycgis.macall.personalcenter.v.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.anhui.police.auth.AuthUser;
import com.anhui.police.auth.sdk.AuthConfig;
import com.anhui.police.auth.sdk.AuthSDK;
import com.anhui.police.auth.sdk.AuthType;
import com.anhui.police.auth.sdk.callback.IAuthTaskType;
import com.anhui.police.auth.sdk.callback.IAuthUserListener;

import com.google.gson.JsonObject;

import com.rs.macall.androidx.basemodel.base.BaseViewBindActivity;
import com.rs.macall.androidx.basemodel.callback.BaseRecycleBtnClickListener;
import com.rs.macall.androidx.basemodel.callback.PermissionListener;
import com.rs.macall.androidx.basemodel.callback.SimpleListClickListener;
import com.rs.macall.androidx.basemodel.utils.HandlerUtils;
import com.rs.macall.androidx.basemodel.utils.LogUtils;
import com.rs.macall.androidx.basemodel.utils.SmartRefreshLayoutHelp;
import com.rs.macall.androidx.basemodel.utils.StringUtil;
import com.rs.macall.androidx.basemodel.utils.ToastUtil;
import com.rs.macall.androidx.basemodel.utils.TypConversion;

import com.ycgis.macall.personalcenter.R;
import com.ycgis.macall.personalcenter.databinding.ActivityAuthenticationBinding;
import com.ycgis.macall.personalcenter.m.adapterbean.AuthManageItem;
import com.ycgis.macall.personalcenter.p.app.RuanseeApplication;
import com.ycgis.macall.personalcenter.p.callback.BaseRequestCallback;
import com.ycgis.macall.personalcenter.p.request.ApiModel;
import com.ycgis.macall.personalcenter.p.request.RetrofitService;
import com.ycgis.macall.personalcenter.util.ReadDeviceInfo;
import com.ycgis.macall.personalcenter.v.adapter.AuthManageAdapter;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * 认证管理
 */
public class AuthenticationActivity extends BaseViewBindActivity<ActivityAuthenticationBinding> implements PermissionListener {
    private AuthManageAdapter adapter;

    private Handler myHandler;
    private String imei = "", imsi = "";
    private boolean isRefresh = false;

    private AuthType authType;

    @Override
    protected ActivityAuthenticationBinding getViewBinding() {
        return ActivityAuthenticationBinding.inflate(getLayoutInflater());
    }

    @Override
    protected boolean isImmersiveStatusBar() {
        return true;
    }

    @Override
    protected void init() {
        viewBinding.rvAuthe.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
        SmartRefreshLayoutHelp.setPullDownToRefresh(getContext(), viewBinding.srlAuthe);
        myHandler = HandlerUtils.getActivity(this);
        AuthSDK.getDefault().getToken(0.8f, iAuth);
    }

    @Override
    protected void readInstanceState(Bundle savedInstanceState) {

    }

    @Override
    protected void start() {
        viewBinding.authTitle.leftImage.setImageDrawable(getDrawables(R.drawable.back_cliener));
        viewBinding.authTitle.titleleft.setOnClickListener(v -> finish());
        viewBinding.authTitle.contentTitle.setText(R.string.authManage);
        String[] needPermissions = {Manifest.permission.READ_PHONE_STATE, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(needPermissions, this);
        } else {
            initPage();
        }
    }

    private void initPage() {
        getImei();
        viewBinding.srlAuthe.setOnRefreshListener(refreshLayout -> getData());
    }

    private void getData() {
        Map<String, String> param = new HashMap<>();
        param.put("token", RuanseeApplication.getAppCache().getToken());
        param.put("clientType", "MOBILE");
        param.put("deviceFlags", imei);
        param.put("imsi1", imsi);
        param.put("sysCode", RuanseeApplication.getAppCache().getSysmCode());
        param.put("types", "1;2;3;4");
        ApiModel.requestIO(RetrofitService.getBaseInstance().getLoginType("http://20.90.2.2/UniAuth/api/sso/v1/verifyBind", param), new BaseRequestCallback<JsonObject>() {
            @Override
            public void onRequestFailure(String msg) {
                Log.e(TAG, msg);
                HandlerUtils.sendHandlerMessage(myHandler, -245, msg);
            }

            @Override
            public void onRequestSuccess(JsonObject result) {
                Log.w(TAG, result.toString());
                try {
                    JSONObject object = new JSONObject(result.toString());
                    String code = TypConversion.getJsonStr(object, "code");
                    if (!code.equals("200")) {
                        HandlerUtils.sendHandlerMessage(myHandler, -245,
                                TypConversion.strToInt(TypConversion.getJsonStr(object, "code")), 0,
                                TypConversion.getJsonStr(object, "content"));
                        return;
                    }
                    JSONObject object1 = object.getJSONObject("data");
                    AuthManageItem item1 = new AuthManageItem("证书认证",
                            TypConversion.getJsonStr(object1, "1").endsWith("true"), false, AuthType.DIGITAL_CERTIFICATE);
                    item1.setActivate(false);
                    item1.setBaseType(1);
                    AuthManageItem item2 = new AuthManageItem("手势认证",
                            TypConversion.getJsonStr(object1, "2").endsWith("true"), true, AuthType.GESTURE);
                    item2.setActivate(true);
                    item2.setBaseType(1);
                    AuthManageItem item3 = new AuthManageItem("人像认证",
                            TypConversion.getJsonStr(object1, "3").endsWith("true"), false, AuthType.FACE);
                    item3.setActivate(true);
                    item3.setBaseType(1);
                    AuthManageItem item4 = new AuthManageItem("语音认证",
                            TypConversion.getJsonStr(object1, "4").endsWith("true"), false, AuthType.VOICE);
                    item4.setActivate(false);
                    item4.setBaseType(1);
                    AuthManageItem item5 = new AuthManageItem("用户名密码认证",
                            true, true, AuthType.PWD);
                    item5.setBaseType(1);
                    item5.setActivate(true);
                    item5.setType(2);
                    List<AuthManageItem> datalist = new ArrayList<>();
                    datalist.add(item5);
                    datalist.add(item1);
                    datalist.add(item2);
                    datalist.add(item3);
                    datalist.add(item4);
                    AuthType authType = RuanseeApplication.getAppCache().getAuthType();
                    for (AuthManageItem item : datalist) {
                        if (item.getAuthType() == authType) {
                            item.setSelect(true);
                            HandlerUtils.sendHandlerMessage(myHandler, 1555, item.getName());
                        }
                    }
                    HandlerUtils.sendHandlerMessage(myHandler, 152, datalist);
                } catch (JSONException e) {
                    e.printStackTrace();
                    HandlerUtils.sendHandlerMessage(myHandler, -245, "解析错误！");
                }
            }
        });
    }

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case -245:
                if (isRefresh) {
                    isRefresh = false;
                    viewBinding.srlAuthe.finishRefresh();
                }
                if (msg.arg1 == 900) {
                    myHandler.sendEmptyMessageDelayed(2514, 800);
                }
                List<AuthManageItem> list = new ArrayList<>();
                AuthManageItem item = new AuthManageItem("",false,false,null);
                item.setBaseType(-1);
                item.setBaseMessage((String) msg.obj);
                list.add(item);
                initData(list);
                ToastUtil.centered(this, (String) msg.obj);
                break;
            case 152:
                if (isRefresh) {
                    isRefresh = false;
                    viewBinding.srlAuthe.finishRefresh();
                }
                initData((List<AuthManageItem>) msg.obj);
                break;
            case 1555:
                viewBinding.tvDqdlfs.setText((String) msg.obj);
                break;
            case 2514:
//                EventBus.getDefault().post(new BackLogEvent(-401));
                RuanseeApplication.saveData("loginType", "true");
                Intent intent = new Intent(this, StartActivity.class);
                startActivity(intent);
                finish();
                break;
            case 5894:
//                System.exit(0);

//                List<AuthType> types = new ArrayList<>();
//                types.add(RuanseeApplication.getAppCache().getAuthType());
//                AuthConfig config = AuthConfig.builder();
//                config.setThemeColor(ContextCompat.getColor(getApplicationContext(), R.color.colorAccent));
//                config.setAuthMethodType(AuthConfig.AuthMethodType.AUTH_METHOD_DEFAULT);
//                config.setAuthTypes(types);
////                AuthSDK.getDefault().getToken();
//                AuthSDK.init("55b161aefd464849b48986a1073d5622", this, config);
////                EventBus.getDefault().post(new BackLogEvent(-401));
//                intent = new Intent(this, StartActivity.class);
//                RuanseeApplication.saveData("loginType", "true");
//                startActivity(intent);
//                finish();
                break;
        }
    }


    private IAuthUserListener iAuth = new IAuthUserListener() {
        @Override
        public void onAuthTaskCallback(@IAuthTaskType int authTaskType, int authCode, @Nullable @org.jetbrains.annotations.Nullable String authResult,
                                       @Nullable @org.jetbrains.annotations.Nullable AuthUser authUser, @Nullable @org.jetbrains.annotations.Nullable String level) {
            LogUtils.w(TAG, String.format("code:%s  ||  authTaskType:%s  || authResult:%s  || level:%s", authCode, authTaskType, authResult, level));
            if (authCode == 200) {
                RuanseeApplication.getAppCache().setToken(authResult);
                viewBinding.srlAuthe.autoRefresh();
            } else {
                ToastUtil.centered(getContext(), authResult);
                if (authCode == 900 || "token失效".equals(authResult)) {
                    AuthSDK.getDefault().startAuth(this);
                    return;
                }
                ysFinish();
            }
        }
    };

    private void ysFinish() {
        Observable.timer(1500, TimeUnit.MILLISECONDS)
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(@NotNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NotNull Long aLong) {
                        finish();
                    }

                    @Override
                    public void onError(@NotNull Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    //解绑
    private void startUnAuthBinding() {
        if (authType == null) return;
        AuthSDK.getDefault().startUnAuthBinding(RuanseeApplication.getAppCache().getToken(),
                authType, iAuth);
    }

    //绑定
    private void startAuthBinding() {
        if (authType == null) return;
        AuthSDK.getDefault().startAuthBinding(
                RuanseeApplication.getAppCache().getToken(),
                authType, iAuth);
    }

    private void initData(List<AuthManageItem> data) {
        viewBinding.srlAuthe.finishRefresh();
        if (adapter == null) {
            adapter = new AuthManageAdapter(this, data);
            viewBinding.rvAuthe.setAdapter(adapter);
            adapter.setBtnClickListener(new BaseRecycleBtnClickListener() {
                @Override
                public void onSingleClick(View v, int position, int what, Object msg) {
                    AuthManageItem item = adapter.getDataItem(position);
                    authType = item.getAuthType();
                    if (item.getType() == 2) {
                        Intent intent = new Intent(AuthenticationActivity.this, UpdatePasswordActivity.class);
                        intent.putExtra("imei", imei);
                        intent.putExtra("imsi", imsi);
                        startActivity(intent);
                        return;
                    }
                    if (item.getAuthType() != null) {
                        if (item.isAutheType()) {       // 先调登录
                            List<AuthType> types = new ArrayList<>();
                            types.add(authType);
                            AuthSDK sdk = AuthSDK.getDefault();
                            AuthConfig config = AuthConfig.builder();
                            config.setThemeColor(ContextCompat.getColor(getApplicationContext(),
                                    R.color.colorPrimaryDark));
                            config.setAuthMethodType(AuthConfig.AuthMethodType.AUTH_METHOD_DEFAULT);
                            config.setAuthTypes(types);
                            if (sdk == null) {
                                AuthSDK.init(RuanseeApplication.getAppCache().getSysmCode(),
                                        AuthenticationActivity.this, config);
                                AuthSDK.getDefault().startAuth(iAuth);
                            } else {
                                sdk.startAuth(config, iAuth);
                            }
                        } else {
                            startAuthBinding();
                        }
                    }
                }
            });
            adapter.setListClickListener(new SimpleListClickListener() {
                @Override
                public void onSingleClick(View v, int pointer) {
                    AuthManageItem item = adapter.getDataItem(pointer);
                    if (!item.isActivate()) {
                        ToastUtil.centered(AuthenticationActivity.this, "暂不支持该方式登录！");
                        return;
                    }
                    if (!item.isAutheType()){
                        ToastUtil.centered(AuthenticationActivity.this,"请先设置该认证方式！");
                        return;
                    }
                    List<AuthManageItem> data = adapter.getData();
                    for (AuthManageItem item1 : data) {
                        item1.setSelect(false);
                    }
                    item.setSelect(true);
                    RuanseeApplication.getAppCache().setAuthType(item.getAuthType());
                    adapter.notifyDataSetChanged();
                    viewBinding.tvDqdlfs.setText(item.getName());
                    ApiModel.uploadOperationLog("3","3","用户切换登录方式");
                    ToastUtil.centered(AuthenticationActivity.this, "登录方式切换成功，下次登录时将使用该模式登录！");
//                    myHandler.sendEmptyMessageDelayed(5894, 500);
                }
            });

        } else {
            adapter.upData(data);
        }
    }

    @SuppressLint({"MissingPermission", "HardwareIds"})
    private void getImei() {
        imei = RuanseeApplication.getAppCache().getImei();
        if (StringUtil.isNullOrEmpty(imei)) {
            imei = ReadDeviceInfo.getDeviceId(getContext());
            if (StringUtil.isNullOrEmpty(imei)) {
                imei = ReadDeviceInfo.getIMEI1(getContext());
                RuanseeApplication.getAppCache().setImei(imei);
            }
        }
        imsi = RuanseeApplication.getAppCache().getImsi();
        if (StringUtil.isNullOrEmpty(imsi)) {
            imsi = ReadDeviceInfo.getIMSI(getContext(), 0);
            if (StringUtil.isNullOrEmpty(imsi)) {
                imsi = ReadDeviceInfo.getIMSI(getContext(), 1);
            }
            RuanseeApplication.getAppCache().setImsi(imsi);
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.e("auth", requestCode + "-->" + resultCode);
        AuthSDK.getDefault().onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onGranted() {
        initPage();
    }

    @Override
    public void onDenied(List<String> deniDPermission) {
        showMissingPermissionDialog();
    }
}