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 androidx.annotation.Nullable;

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.base.code.binary.Base64;

import com.rs.macall.androidx.basemodel.base.BaseViewBindActivity;
import com.rs.macall.androidx.basemodel.callback.PermissionListener;

import com.rs.macall.androidx.basemodel.utils.DateUitls;
import com.rs.macall.androidx.basemodel.utils.HandlerUtils;
import com.rs.macall.androidx.basemodel.utils.LogUtils;
import com.rs.macall.androidx.basemodel.utils.StringUtil;
import com.rs.macall.androidx.basemodel.utils.ToastUtil;
import com.rs.macall.androidx.basemodel.view.Watermark;

import com.ycgis.macall.personalcenter.R;
import com.ycgis.macall.personalcenter.databinding.ActivityStartBinding;
import com.ycgis.macall.personalcenter.p.app.RuanseeApplication;
import com.ycgis.macall.personalcenter.p.app.UserData;
import com.ycgis.macall.personalcenter.p.request.ApiModel;
import com.ycgis.macall.personalcenter.util.AhdsAddressUtils;
import com.ycgis.macall.personalcenter.util.ReadDeviceInfo;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

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

public class StartActivity extends BaseViewBindActivity<ActivityStartBinding> implements PermissionListener {

    private Handler myHandler;

    private final String[] permissionList = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA,
            Manifest.permission.CHANGE_NETWORK_STATE,
            Manifest.permission.ACCESS_NETWORK_STATE,
            Manifest.permission.READ_PHONE_STATE};

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

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

    @Override
    protected void init() {
        myHandler = HandlerUtils.getActivity(this);
    }

    @Override
    protected void readInstanceState(Bundle savedInstanceState) {

    }

    //杏花公园   百汇    瑶东北村    B   C   金葡萄A
    @Override
    protected void start() {
        if (!this.isTaskRoot()) {
            Intent mainIntent = getIntent();
            String action = mainIntent.getAction();
            if (mainIntent.hasCategory(Intent.CATEGORY_LAUNCHER) && action.equals(Intent.ACTION_MAIN)) {
                finish();
                return;
            }
        }
        Watermark.getInstance().clean();
        viewBinding.startMsg.setText("正在检测应用权限...");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(permissionList, this);
        } else {
            initPage();
        }
    }

    private void initPage() {
//        ParamMap map = new ParamMap();
//        map.put("主板",Build.BOARD);
//        map.put("cpu指令集",Build.CPU_ABI);
//        map.put("设备参数",Build.DEVICE);
//        map.put("显示屏参数",Build.DISPLAY);
//        map.put("硬件名称",Build.FINGERPRINT);
//        map.put("硬件制造商",Build.MANUFACTURER );
//        map.put("手机制造商",Build.PRODUCT  );
//        map.put("TYPE   ",Build.TYPE );
//        LogUtils.e("设备信息：",new Gson().toJson(map.apply()));
//        String ip = com.ycgis.macall.personalcenter.util.IPAddressUtils.getLocalIpAddress();
//        RuanseeApplication.getAppCache()
//        RuanseeApplication.saveData("equipmentIP", ip);
        getImei();
        viewBinding.startMsg.setText("正在初始化应用...");
        myHandler.sendEmptyMessageDelayed(1, 800);
    }

    @SuppressLint({"MissingPermission", "HardwareIds"})
    private void getImei() {
        String imei = RuanseeApplication.getAppCache().getImei();
        if (StringUtil.isNullOrEmpty(imei)) {
            imei = ReadDeviceInfo.getDeviceId(getContext());
            if (StringUtil.isNullOrEmpty(imei)) {
                imei = ReadDeviceInfo.getIMEI1(getContext());
            }
            RuanseeApplication.getAppCache().setImei(imei);
        }
        String 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);
        }

//        if(StringUtil.isNullOrEmpty(imei)){
//            imei = DeviceIdentifier.getIMEI(this);;
//        }
//        //5eb3e978a849befa
//        String oaid = ReadDeviceInfo.getOAID(getContext());
//        if ( DeviceID.supportedOAID(this)){
//            oaid = DeviceIdentifier.getOAID(this);
//        }
//        LogUtils.w("oaid",oaid);
//        ToastUtil.centered(getContext(),String.format(" IMEI = %S  || imsi = %S  || oaid = %S ",imei,imsi,oaid));
    }

    private void setFormal() {
//        RuanseeApplication.getAppCache().setIpAndPort("192.168.43.183", "8081");
        RuanseeApplication.getAppCache().setIpAndPort("20.90.2.2", "80");
//        getAccessToken();
//        if (RuanseeApplication.isHFVersion) {
//            PService ps = new PService(this);
//            try {
//                viewBinding.tvLoadMsg.setText("单点登录成功！");
//                RuanseeApplication.getUserData().setUserCode(ps.getUserAccount());
//                RuanseeApplication.getUserData().setUserName(ps.getPoliceName());
//                RuanseeApplication.getUserData().setDeptCode(ps.getZZJGDm());
//                RuanseeApplication.getUserData().setDeptName(ps.getZZJGName());
//                RuanseeApplication.getUserData().setIdCardNum(ps.getSFZ());
//                if (!RuanseeApplication.getUserData().isValidOrNot()) {
//                    viewBinding.tvLoadMsg.setText("无效的用户！");
//                    ysFinish();
//                    return;
//                }
//                viewBinding.tvLoadMsg.setText("正在获取用户信息！");
//                getUserDeptName();
//            } catch (Exception e) {
//                viewBinding.tvLoadMsg.setText("用户登录失败！获取用户失败！");
//                ysFinish();
//            }
//        } else {
            boolean isUpdateAuthType = RuanseeApplication.getBooleanValue("isUpdateAuthType", false);
            if (isUpdateAuthType) {
                AuthSDK sdk = AuthSDK.getDefault();
                List<AuthType> types = new ArrayList<>();
                types.add(RuanseeApplication.getAppCache().getAuthType());
                AuthConfig config = AuthConfig.builder().setAuthTypes(types);
                if (sdk == null) {
                    AuthSDK.init(RuanseeApplication.getAppCache().getSysmCode(),
                            getContext(), config);
                    AuthSDK.getDefault().startAuth(iTokenListener);
                } else {
                    sdk.startAuth(config, iTokenListener);
                }
            } else {
                AuthSDK.getDefault().getToken(0.8f, iTokenListener);
            }
//        }
    }

    private IAuthUserListener iTokenListener = new IAuthUserListener() {

        @Override
        public void onAuthTaskCallback(@IAuthTaskType int authTaskType, int authCode, @Nullable @org.jetbrains.annotations.Nullable String authResult,
                                       @Nullable @org.jetbrains.annotations.Nullable com.anhui.police.auth.AuthUser authUser,
                                       @Nullable @org.jetbrains.annotations.Nullable String level) {
            LogUtils.v(TAG, authCode + "  ：  " + authResult);
            if (authCode == 200) {
                switch (authTaskType) {
                    case 0://getToken
                    case 2:// 绑定验证因子(手势、人脸)
                        AuthSDK.getDefault().getUserInfo(authResult, this);
                        RuanseeApplication.getAppCache().setToken(authResult);
                        RuanseeApplication.saveData("isUpdateAuthType",false);
                        break;
                    case 1://使用token换取用户信息
                        setAppUserInfo(authUser);
                        break;
                    case 3://使用用户名密码、手势、数字证书、人脸等方式验证用户身份

                        break;
                    case 4:// 设置用户信息

                        break;
                    case 5://解绑 验证因子(手势)

                        break;
                    default:
                        viewBinding.startMsg.setText(authResult);
                        ToastUtil.centered(StartActivity.this, "错误码：" + authCode + "  mes: " + authResult);
                        AuthSDK.getDefault().startAuth(this);
                        break;
                }
            } else {
                ToastUtil.centered(StartActivity.this, authResult);
                if (authCode>=900&&authCode<1000) {
                    List<AuthType> types = new ArrayList<>();
                    types.add(RuanseeApplication.getAppCache().getAuthType());
                    AuthConfig config = AuthConfig.builder().setAuthTypes(types);
                    AuthSDK.getDefault().startAuth(config,iTokenListener);
                    return;
                }
                viewBinding.startMsg.setText(authResult);
                ysFinish();
            }
        }
    };

    private void setAppUserInfo(com.anhui.police.auth.AuthUser authUser){
        UserData userData = RuanseeApplication.getUserData();
        if (authUser == null) {
            ToastUtil.centered(StartActivity.this, "获取用户数据失败!!!");
            return;
        }
        viewBinding.startMsg.setText("单点登录成功！");
        userData.setUserCode(authUser.getUserNum());
        userData.setUserName(authUser.getRealName());
        userData.setDeptCode(authUser.getOrgId());
        userData.setDeptName(authUser.getOrgName());
        userData.setIdCardNum(authUser.getCode());
        userData.setPhone1(authUser.getWorkPhone());
//                    userData.setPhone2(authUser.getPhoneNum());
        userData.setPhoto(authUser.getProfilePhoto());
        userData.setPolice_role(authUser.getPoliceTypeName());
        if (!userData.isValidOrNot()) {
            viewBinding.startMsg.setText("无效的用户！");
            ysFinish();
            return;
        }
        userData.setIp(RuanseeApplication.getAppCache().getLocalIp());
        ApiModel.uploadOperationLog("3","3","用户登录应用");
        String substring = RuanseeApplication.getUserData().getDeptCode().substring(0, 4);
        RuanseeApplication.getUserData().setDepartmentCode(substring);
        RuanseeApplication.getUserData().setDepartmentName(AhdsAddressUtils.getAddressNameByCode(RuanseeApplication.getUserData().getDeptCode()));

        String s = userData.toJson();

        String s1 = Base64.encodeBase64String(s.getBytes());
        RuanseeApplication.getAppCache().setUserInfo(s1);
        initWatermark();
        viewBinding.startMsg.setText("正在获取用户信息！");
        myHandler.sendEmptyMessageDelayed(2, 800);
    }

    private void initWatermark() {
        Watermark instance = Watermark.getInstance();
        instance.clean();
        instance.addLabel(getString(R.string.app_name))
                .addLabel(String.format("%s(%s)", RuanseeApplication.getUserData().getUserName(), RuanseeApplication.getUserData().getUserCode()))
                .addLabel(DateUitls.date2Str(new Date(),"yyyy-MM-dd"))
                .setTextSize(14);
        instance.show(getActivity());
    }

    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() {

                    }
                });
    }

    @Override
    public void handleMessage(Message msg) {
        if (msg.what == 1) {
            viewBinding.startMsg.setText("正在登录...");
//            setTestUer();
            setFormal();
        } else if (msg.what == 2) {
            viewBinding.startMsg.setText("正在加载数据...");
            myHandler.sendEmptyMessageDelayed(3, 800);
        } else if (msg.what == 3) {
            viewBinding.AVLoadingIndicatorView.smoothToHide();
            startActivity(new Intent(getContext(), MainActivity.class));
            finish();
        }
    }

    private void setTestUer() {
//        RuanseeApplication.getAppCache().setIpAndPort("20.90.2.2", "80");
        RuanseeApplication.getAppCache().setIpAndPort("192.168.0.129", "8081");
//        RuanseeApplication.getAppCache().setIpAndPort("192.168.0.233", "8081");
//        RuanseeApplication.getAppCache().setIpAndPort("192.168.43.98", "8081");
        UserData userData = RuanseeApplication.getUserData();
        userData.setUserCode("999013");
        userData.setUserName("陈乐(测试账号)");
//        userData.setDeptCode("340112000000");
        userData.setDeptCode("340512000000");
        userData.setPhone1("18815654126");
        userData.setDeptName("安徽省公安厅科技信息化处应用指导科");
        userData.setIdCardNum("342422199306041413");
        String dept_name = "省厅";
        try {
            String substring = RuanseeApplication.getUserData().getDeptCode().substring(0, 4);
            RuanseeApplication.getUserData().setDepartmentCode(substring);
            dept_name = AhdsAddressUtils.getAddressNameByCode(RuanseeApplication.getUserData().getDeptCode());
            RuanseeApplication.getUserData().setDepartmentName(dept_name);
        } catch (Exception e) {
            e.printStackTrace();
        }

        initWatermark();
        myHandler.sendEmptyMessageDelayed(2, 800);
    }

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

    }

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