package com.hh.arome.ui;

import android.content.ComponentName;
import android.content.Context;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.net.ConnectivityManager;
import android.net.LinkProperties;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkRequest;
import android.os.Build;
import android.os.Bundle;

import com.alibaba.fastjson.JSON;
import com.alipay.arome.aromecli.AromeInit;
import com.alipay.arome.aromecli.AromeInitOptions;
import com.alipay.arome.aromecli.AromeServiceInvoker;
import com.alipay.arome.aromecli.AromeServiceTask;
import com.alipay.arome.aromecli.requst.AromeActivateRequest;
import com.alipay.arome.aromecli.requst.AromeExitAppRequest;
import com.alipay.arome.aromecli.requst.AromeLaunchAppRequest;
import com.alipay.arome.aromecli.requst.AromeSendEventRequest;
import com.alipay.arome.aromecli.response.AromeExitAppResponse;
import com.alipay.arome.aromecli.response.AromeResponse;
import com.alipay.iot.bpaas.api.BPaaSApi;
import com.alipay.iot.bpaas.api.BPaaSInitCallback;
import com.alipay.iot.bpaas.api.service.BPaaSCallback;
import com.alipay.iot.bpaas.api.service.BPaaSResponse;
import com.blankj.utilcode.util.FileUtils;
import com.common.lib_base.aop.annotation.NoDoubleClick;
import com.common.lib_base.common.async.ThreadPoolManager;
import com.common.lib_base.common.local.AppLocalConfigHandler;
import com.common.lib_base.utils.GlideUtils;
import com.common.lib_base.utils.NetworkUtils;
import com.common.lib_base.utils.StringUtils;
import com.common.lib_base.utils.ui.ToastUtils;


import android.app.Activity;
import android.content.Intent;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.RemoteException;
import android.text.Editable;
import android.text.InputType;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.alipay.iot.bpaas.api.InnerApi;
import com.alipay.iot.bpaas.api.ipc.IpcChannel;
import com.alipay.iot.bpaas.api.ipc.IpcListener;
import com.common.print.BasePrinter;
import com.common.print.many.base.IPrinter;
import com.common.print.bean.PrintBean;
import com.common.print.callback.PrintInitResultCallback;
import com.common.print.utils.BitmapUtils;
import com.common.usb.qr.QrUsb;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.hh.arome.BuildConfig;
import com.hh.arome.MyApplication;
import com.hh.arome.R;
import com.hh.arome.bean.AlipayUserInfoRequestBean;
import com.hh.arome.bean.AlipayUserInfoResultBean;
import com.hh.arome.bean.BizContentBean;
import com.hh.arome.bean.DeviceConfigRequestBean;
import com.hh.arome.bean.DeviceConfigResultBean;
import com.hh.arome.bean.HeartBeatRequestBean;
import com.hh.arome.bean.InvokeScanFaceBean;
import com.hh.arome.bean.LogcatAddRequestBean;
import com.hh.arome.bean.SimpleResultBean;
import com.hh.arome.bean.ThreeElementsBean;
import com.hh.arome.bean.ampe.AmpeAppletRequestBean;
import com.hh.arome.bean.ampe.AmpeAppletResultBean;
import com.hh.arome.bean.ampe.AmpeActionDataBean;
import com.hh.arome.bean.face.StartReadyBpaasServiceBean;
import com.hh.arome.common.ConfigData;
import com.hh.arome.common.Constants;
import com.hh.arome.common.IAppLocalConfig;
import com.hh.arome.common.MockData;
import com.hh.arome.common.deviceui.BaseDeviceUI;
import com.hh.arome.common.deviceui.IDeviceUI;
import com.hh.arome.common.microphone.IMicroPhoneResultCallback;
import com.hh.arome.common.microphone.IMicroPhoneSizeCallback;
import com.hh.arome.common.microphone.IMicroPhoneStateCallback;
import com.hh.arome.common.microphone.MicrophoneRecorder;
import com.hh.arome.common.microphone.ZlwRecordManager;
import com.hh.arome.common.scan.idcard.IDCardScan;
import com.hh.arome.common.scan.idcard.bean.IDCardInfoBean;
import com.hh.arome.common.scan.idcard.callback.IDCardInitResultCallback;
import com.hh.arome.common.scan.idcard.callback.IDCardScanResultCallback;
import com.hh.arome.common.voice.MTTSDemo;
import com.hh.arome.helper.Serial.SerialPortFinder;
import com.hh.arome.mvp.contract.AlipayUserInfoContract;
import com.hh.arome.mvp.contract.DeviceConfigContract;
import com.hh.arome.mvp.contract.HeartbeatContract;
import com.hh.arome.mvp.contract.LogcatAddContract;
import com.hh.arome.mvp.contract.ThreeElementsContract;
import com.hh.arome.mvp.presenter.AlipayUserInfoPresenter;
import com.hh.arome.mvp.presenter.DeviceConfigPresenter;
import com.hh.arome.mvp.presenter.HeartbeatPresenter;
import com.hh.arome.mvp.presenter.LogcatAddPresenter;
import com.hh.arome.mvp.presenter.ThreeElementsPresenter;
import com.hh.arome.services.keeplive.LocalService;
import com.hh.arome.services.keeplive.MyJobService;
import com.hh.arome.services.keeplive.RemoteService;
import com.hh.arome.ui.base.BaseHHActivity;
import com.hh.arome.utlis.DateUtil;
import com.hh.arome.utlis.IdCardUtils;
import com.common.print.bean.PrintContentBean;
import com.hh.arome.utlis.device.DeviceUtils;
import com.hh.arome.utlis.device.FaceScenicUtile;
import com.hh.arome.utlis.log.AppLogUtils;
import com.hh.arome.utlis.log.LogType;
import com.hh.hhomc.IAidlInterface;
import com.hh.hhomc.AppMessageBean;
import com.hh.hhomc.IAidlCallBack;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.silencefun.comtest.MyFunc;
import com.silencefun.comtest.SerialHelper;
import com.silencefun.comtest.been.ComBean;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;


import static com.hh.arome.common.Constants.Ampe.ACTION_DEVICE;
import static com.hh.arome.common.Constants.Ampe.ACTION_ENTERIDNUMBER;
import static com.hh.arome.common.Constants.Ampe.ACTION_FACE;
import static com.hh.arome.common.Constants.Ampe.ACTION_FACE_PERSONCARD;
import static com.hh.arome.common.Constants.Ampe.ACTION_IDCARD_CLOSE;
import static com.hh.arome.common.Constants.Ampe.ACTION_IDCard;
import static com.hh.arome.common.Constants.Ampe.ACTION_INIT_FACE;
import static com.hh.arome.common.Constants.Ampe.ACTION_MICROPHONE_STATE;
import static com.hh.arome.common.Constants.Ampe.ACTION_PRINT;
import static com.hh.arome.common.Constants.Ampe.ACTION_QR;
import static com.hh.arome.common.Constants.Ampe.ACTION_SCAN_FACE;
import static com.hh.arome.common.Constants.Ampe.ACTION_SPEECH;
import static com.hh.arome.common.Constants.Ampe.ACTION_SPEECH_STOP;
import static com.hh.arome.common.Constants.Ampe.ACTION_START_INFRARED_INDUCTION_LISTENER;
import static com.hh.arome.common.Constants.Ampe.ACTION_START_MICROPHONE;
import static com.hh.arome.common.Constants.Ampe.ACTION_START_MICROPHONE_LISTENER;
import static com.hh.arome.common.Constants.Ampe.ACTION_STOP_INFRARED_INDUCTION_LISTENER;
import static com.hh.arome.common.Constants.Ampe.ACTION_STOP_MICROPHONE;
import static com.hh.arome.common.Constants.Ampe.ACTION_STOP_MICROPHONE_LISTENER;
import static com.hh.arome.common.Constants.Ampe.AMPE_EVENT;
import static com.hh.arome.common.Constants.Ampe.EVENT_IDCard_LISTENER;
import static com.hh.arome.common.Constants.Ampe.EVENT_INFRARED_INDUCTION_LISTENER;
import static com.hh.arome.common.Constants.Ampe.EVENT_MICROPHONE_LISTENER;
import static com.hh.arome.common.Constants.Ampe.EVENT_QR_LISTENER;
import static com.hh.arome.common.Constants.LogcatValue.LINE;
import static com.hh.arome.common.Constants.LogcatValue.LOG_NODE_AIDL;
import static com.hh.arome.common.Constants.LogcatValue.LOG_NODE_APPLET;
import static com.hh.arome.common.Constants.LogcatValue.LOG_NODE_DEVICE;
import static com.hh.arome.common.Constants.LogcatValue.LOG_NODE_FACE;
import static com.hh.arome.common.Constants.LogcatValue.LOG_NODE_IDCARD;
import static com.hh.arome.common.Constants.LogcatValue.LOG_NODE_INFRARED_INDUCTION;
import static com.hh.arome.common.Constants.LogcatValue.LOG_NODE_MICROPHONE;
import static com.hh.arome.common.Constants.LogcatValue.LOG_NODE_NET;
import static com.hh.arome.common.Constants.LogcatValue.LOG_NODE_NET_CONFIG_QUERY;
import static com.hh.arome.common.Constants.LogcatValue.LOG_NODE_QR;
import static com.hh.arome.common.Constants.LogcatValue.LOG_NODE_SPEECH;
import static com.hh.arome.common.Constants.LogcatValue.LOG_PRINT;
import static com.hh.arome.common.Constants.LogcatValue.LOG_SPEECH;
import static com.hh.arome.common.Constants.LogcatValue.NET_CRASH;
import static com.hh.arome.common.Constants.LogcatValue.NET_ERROR;
import static com.hh.arome.common.Constants.LogcatValue.NET_LOGCAT;
import static com.hh.arome.common.Constants.LogcatValue.NODE;
import static com.hh.arome.common.Constants.LogcatValue.WARP;
import static com.hh.arome.common.Constants.SERVER_ACTION.CLOSE_APP;
import static com.hh.arome.common.Constants.SERVER_ACTION.REBOOT;
import static com.hh.arome.common.Constants.Url.API_CONFIG_QUERY;
import static com.hh.arome.common.Constants.Value.CAMERA_BRAND;
import static com.hh.arome.common.Constants.Value.INDUCTION_CODE;
import static com.hh.arome.common.Constants.Value.INDUCTION_INSTRUCT;
import static com.hh.arome.common.Constants.Value.INDUCTION_PEOPLE_NO;
import static com.hh.arome.common.Constants.Value.INDUCTION_PEOPLE_YES;
import static com.hh.arome.common.Constants.Value.TIME_HEARTBEAT;
import static com.hh.arome.common.Constants.Value.TIME_INDUCTION_INTERVAL;
import static com.hh.arome.common.Constants.Value.TOKEN;


public class MainActivity extends BaseHHActivity implements DeviceConfigContract.View,
        HeartbeatContract.View, View.OnClickListener, LogcatAddContract.View,
        AlipayUserInfoContract.View, ThreeElementsContract.View,
//        PrintUtile.OnPrintBaseListener
        BasePrinter.OnPrintBaseListener {

    private static final int REQUEST_CODE = 11;
    FaceScenicUtile faceScenicUtile;

    DeviceConfigPresenter mDeviceConfigPresenter;
    HeartbeatPresenter mHeartbeatPresenter;
    LogcatAddPresenter mLogcatAddPresenter;
    AlipayUserInfoPresenter mAlipayUserInfoPresenter;

    Button tv_exit, tv_scan, tv_idcard_jump, tv_idcard;
    Button tv_logcat, tv_error, tv_crash, tv_send_message;

    // aidl消息发送者，标识收到的消息来自哪个app
    String aidlSender = "HHArome";

    String localDeviceSN;

    Gson gson = new Gson();

    Handler mMainHandler = new Handler();

    String deviceModel = DeviceUtils.getDeviceModel();


    // 当前状态
    private int STATUSES;// 0
    private Button tv_qr;
    private ImageView iv_test;
    private LinearLayout item_btn_test;

    //小票打印机
    private Button tv_init_scan;
    private Button tv_record_start;
    private Button tv_record_stop;
    Button tv_print;
    private TextView tv_idcard_info;
    private TextView tv_scan_result;
    private Button tv_voice;

    @Override
    public int setLayout() {
        if (Constants.DeviceModel.D2.equals(deviceModel)) {
            return R.layout.activity_main_hp;
        } else {
            return R.layout.activity_main;
        }
    }

    @Override
    protected void initView() {
        super.setHideTopBar();

        AppLogUtils.e(mTag + "initView");

        String deviceDisplay = DeviceUtils.getDeviceDisplay();
        AppLogUtils.e("deviceDisplay=" + deviceDisplay);
        String androidVersion = DeviceUtils.getAndroidVersion();
        AppLogUtils.e("androidVersion=" + androidVersion);
        String deviceSN = DeviceUtils.getDeviceSN();
        AppLogUtils.e("deviceSN=" + deviceSN);


//        ArrayList<AppInfoBean> appList = AppUtils.getAppList(this);
//        for (AppInfoBean appInfoBean : appList) {
//            AppLogUtils.e(appInfoBean.appName+"   "+appInfoBean.getVersionName()+"   "+appInfoBean.packageName);
//        }

        tv_scan = findViewById(R.id.tv_scan);
        tv_exit = findViewById(R.id.tv_exit);
        tv_idcard_jump = findViewById(R.id.tv_idcard_jump);
        tv_idcard = findViewById(R.id.tv_idcard);

        tv_logcat = findViewById(R.id.tv_logcat);
        tv_error = findViewById(R.id.tv_error);
        tv_crash = findViewById(R.id.tv_crash);

        tv_send_message = findViewById(R.id.tv_send_message);

        tv_time = findViewById(R.id.tv_time);
        tv_net_no = findViewById(R.id.tv_net_no);
        iv_net_wifi = findViewById(R.id.iv_net_wifi);
        iv_net_flow = findViewById(R.id.iv_net_flow);
        iv_net_line = findViewById(R.id.iv_net_line);
        iv_setting = findViewById(R.id.iv_setting);

        tv_version = findViewById(R.id.tv_version);
        tv_sn = findViewById(R.id.tv_sn);
        tv_applet_name = findViewById(R.id.tv_applet_name);
        tv_enter_applet = findViewById(R.id.tv_enter_applet);

        tv_config_status = findViewById(R.id.tv_config_status);

        item_root = findViewById(R.id.item_root);
        iv_setting.setOnClickListener(this);
        tv_enter_applet.setOnClickListener(this);


        tv_scan.setOnClickListener(this);
        tv_idcard.setOnClickListener(this);
        tv_exit.setOnClickListener(this);
        tv_logcat.setOnClickListener(this);
        tv_error.setOnClickListener(this);
        tv_crash.setOnClickListener(this);
        tv_idcard_jump.setOnClickListener(this);
        tv_qr = findViewById(R.id.tv_qr);
        tv_qr.setOnClickListener(this);
        tv_send_message.setOnClickListener(this);
        iv_test = findViewById(R.id.iv_test);

        tv_init_scan = findViewById(R.id.tv_init_scan);
        tv_init_scan.setOnClickListener(this);

        tv_record_start = findViewById(R.id.tv_record_start);
        tv_record_stop = findViewById(R.id.tv_record_stop);
        tv_record_start.setOnClickListener(this);
        tv_record_stop.setOnClickListener(this);
        tv_print = findViewById(R.id.tv_print);
        tv_print.setOnClickListener(this);

        item_btn_test = findViewById(R.id.item_btn_test);

        tv_idcard_info = findViewById(R.id.tv_idcard_info);

        if (!Constants.IS_DEBUG) {
            // 正式版，隐藏
//            UIUtils.setViewGone(item_btn_test);
        }


        tv_scan_result = findViewById(R.id.tv_scan_result);
        tv_voice = findViewById(R.id.tv_voice);
        tv_voice.setOnClickListener(this);
    }


    public void setConfigStatusText(String text) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tv_config_status.setText(text);
            }
        });

    }


    TextView tv_time, tv_net_no;
    ImageView iv_net_wifi, iv_net_flow, iv_net_line, iv_setting;
    TextView tv_version, tv_sn, tv_applet_name, tv_enter_applet, tv_config_status;
    RelativeLayout item_root;

    IAppLocalConfig localConfig;

    HeartBeatRequestBean heartBeatRequestBean;

    String netType;
    boolean isNetAvailable;


    private ConnectivityManager.NetworkCallback networkCallback;
    private ConnectivityManager connectivityManager;
    private String IDNumber = "";

    @Override
    public void ThreeElementsContract(ThreeElementsBean threeElementsBean) {
        try {
            if (EnterWindowManager != null && EnterView != null) {
                EnterWindowManager.removeView(EnterView);
                EnterWindowManager = null;
                EnterView = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        String BizContent = IdCardUtils.decrypt(
                deviceConfigBean.getManualInIdCardAuth().getPrivateKey(),
                threeElementsBean.getBizContent());
        BizContentBean bizContentBean = new Gson().fromJson(BizContent, BizContentBean.class);
        AppLogUtils.i("常口换取三要素返回", "国密解密内容  " + BizContent);
        IDNumber = bizContentBean.getSfzh();
        OperatingTimeHandler.removeCallbacks(OperatingTimeRunnable);
        OperatingTimeHandler.removeCallbacksAndMessages(null);
        CardOrCode = "enterIDNumber";
        invokePersonCard(bizContentBean.getXm(), bizContentBean.getSfzh(),
                bizContentBean.getXp());
    }

    //打印完成
    @Override
    public void PrintingComplete() {
        sendPrint();
    }

    @Override
    public void PrintingFail(String msg) {
        sendPrint();
    }


    private void sendPrint(){

        ConfigData.taskStatus = "complete";

        AmpeActionDataBean ampeActionDataBean = ampeActionMap.get(ACTION_PRINT);
        if (ampeActionDataBean == null) {
            AppLogUtils.e("ampeActionDataBean == null");
            return;
        }
        AromeServiceInvoker.BridgeCallback bridgeCallback = null;
        try {
            bridgeCallback = ampeActionDataBean.getBridgeCallback();
        } catch (NullPointerException e) {
            e.printStackTrace();
        }

        AmpeAppletResultBean bean = new AmpeAppletResultBean();
        bean.setAction(ACTION_PRINT);
        bean.setEvent(ampeActionDataBean.getEvent());
        bean.setTaskId(ampeActionDataBean.getTaskId());
        bean.setSuccess(true);
        bean.setMessage("小票打印完成");
        // 回传处理结果给小程序
        try {
            JsonObject jsonObject = gson.toJsonTree(bean).getAsJsonObject();
            if (bridgeCallback != null) {
                bridgeCallback.callback(jsonObject.toString());
            }
//            // 日志开始----------------begin
//            // 日志行数——对应web端"日志标签"
//            String logLine = (new Throwable().getStackTrace())[0].toString();
//            // 日志节点
//            String logNode = "ACTION_PRINT--小票--回传处理结果给小程序";
//            // 日志内容
//            StringBuilder logContentSb = new StringBuilder();
//            logContentSb.append(logNode).append(WARP)
//                    .append("jsonObject = ").append(jsonObject);
//            // 开始保存本地日志
//            AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
//                    .append(LINE)
//                    .append(logLine).append(WARP)
//                    .append(NODE)
//                    .append(logContentSb)
//                    .toString()
//            );
//
//            // 开始网络在线日志
//            LogcatAddRequestBean logBean = new LogcatAddRequestBean();
//            logBean.setLogType(NET_LOGCAT);
//            // 对应web端"日志标签"
//            logBean.setLogTag(logLine + WARP + LOG_NODE_APPLET + LOG_PRINT);
//            logBean.setLogContent(logContentSb.toString());
//            requestLogcatAdd(logBean);
//            // 日志开始----------------end
//            // 打印编译器输出日志
//            AppLogUtils.e(logContentSb);


            // 日志打印和保存（本地和网络）
            logPrintSave(NET_LOGCAT,
                    (new Throwable().getStackTrace())[0].toString(),
                    ACTION_PRINT + "--小票--回传处理结果给小程序",
                    "jsonObject = " + jsonObject
            );


        } catch (Throwable t) {
            AppLogUtils.e("onCalled--t" + t);
        }
    }

    private class NetworkCallbackImpl extends ConnectivityManager.NetworkCallback {
        @Override
        public void onAvailable(Network network) {
            super.onAvailable(network);
            //
            AppLogUtils.e("网络--连接--onAvailable");

            isNetAvailable = true;
            netLogcatNum = 0;

            getNetType();

        }

        @Override
        public void onLosing(Network network, int maxMsToLive) {
            super.onLosing(network, maxMsToLive);
            AppLogUtils.e("网络--onLosing");
        }

        @Override
        public void onLost(Network network) {
            super.onLost(network);
            AppLogUtils.e("网络--断开--onLost");

            isNetAvailable = false;

            getNetType();
        }

        @Override
        public void onCapabilitiesChanged(Network network, NetworkCapabilities networkCapabilities) {
            super.onCapabilitiesChanged(network, networkCapabilities);
            AppLogUtils.i("网络-onCapabilitiesChanged");
        }

        @Override
        public void onLinkPropertiesChanged(Network network, LinkProperties linkProperties) {
            super.onLinkPropertiesChanged(network, linkProperties);
            AppLogUtils.i("网络-onLinkPropertiesChanged");
        }
    }


    // 麦克风
    public void microphoneEvent() {

        if (!Constants.DeviceModel.T1YB01.equals(deviceModel)) {
            // 非Y9
            return;
        }

        zlwRecordManager = ZlwRecordManager.getInstance(mContext);

        deleteRecordAllFile();

    }


    IDeviceUI iDeviceUI;
    IPrinter iPrinter;

    int displayWidth;
    int displayHeight;


    @Override
    protected void initData() {

//        if (Constants.DeviceModel.D2.equals(DeviceUtils.getDeviceModel())) {
//            iPrintBase = IPrintBase.getInstance(this);
//            iPrintBase.getIDCardScanEngine(this);
//            //打印机上电
//            iPrintBase.isPowerOnPrint();
//            PrintUtile.setListener(this);
//        }

        initNet();

        localConfig = AppLocalConfigHandler.create(mContext.getApplicationContext(), IAppLocalConfig.class);

        localDeviceSN = DeviceUtils.getDeviceSN();
        AppLogUtils.e("localDeviceSN:" + localDeviceSN);

        tv_version.setText("版本号：" + DeviceUtils.getAppVersionName(this));
        tv_sn.setText("SN号：" + localDeviceSN);

        // 获取设备宽高
        DisplayMetrics dm = getResources().getDisplayMetrics();
        displayWidth = dm.widthPixels;
        displayHeight = dm.heightPixels;
        AppLogUtils.e("displayWidth:" + displayWidth);
        AppLogUtils.e("displayHeight:" + displayHeight);

        // 各类业务配置放后面

        // 先初始化下语音，防止首次没有声音
        MTTSDemo.getInstance(mContext);

        iDeviceUI = BaseDeviceUI.getInstance().getDeviceUI();
        AppLogUtils.e("补光灯关闭");
        // 补光灯关闭
        iDeviceUI.hideFillLight(mActivity);


        // 打印机
        iPrinter = BasePrinter.getInstance().getPrinter(mContext.getApplicationContext());

        BasePrinter.getInstance().setListener(this);


//        getNetType();


        // 权限
        requestPermissionsMethod();

//        // 网络请求
//        requestNetData();

        EventBus.getDefault().register(this);


        // 时间
        resh.mHandler.postDelayed(resh.runnableTime, 1000);// 每兩秒執行一次runnable.


        // 绑定aidl远程服务
        bindService();


        Intent intent = getIntent();
        if (intent != null) {
            boolean exist = intent.getBooleanExtra("IsExist", false);
            if (exist) {
                closeApp();
            }
        }

        // 删除日志
        AppLogUtils.deleteFileLog(LogType.Logcat, 7);
        AppLogUtils.deleteFileLog(LogType.Error, 7);
        AppLogUtils.deleteFileLog(LogType.Crash, 7);


        // 可能导致收到两次广播
        LocalService.startService(this);
        RemoteService.startService(this);
        MyJobService.Companion.StartJob(this);


        // 语音
//        BaiduVoice.getInstance(mContext).init();

        // 小程序通道
        appletListen();

        // 麦克风
        microphoneEvent();

        deleteAllPicture();

//        mMainHandler.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                finish();
//            }
//        },10*1000);

    }

    private void initNet() {
        networkCallback = new NetworkCallbackImpl();
        NetworkRequest.Builder builder = new NetworkRequest.Builder();
        NetworkRequest request = builder.build();
        connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        connectivityManager.registerNetworkCallback(request, networkCallback);


        tv_net_no.setVisibility(View.VISIBLE);
        iv_net_wifi.setVisibility(View.GONE);
        iv_net_flow.setVisibility(View.GONE);
        iv_net_line.setVisibility(View.GONE);
    }

    private void requestNetData() {
        // 开始请求

        // 在线配置接口
        mDeviceConfigPresenter = new DeviceConfigPresenter(this);

        DeviceConfigRequestBean mDeviceConfigRequestBean = new DeviceConfigRequestBean();
        mDeviceConfigRequestBean.setSn(localDeviceSN);
        mDeviceConfigRequestBean.setToken(Constants.Value.TOKEN);
        mDeviceConfigPresenter.requestDeviceConfig(mDeviceConfigRequestBean);

        setConfigStatusText(netType + " 请求在线配置...");


        mLogcatAddPresenter = new LogcatAddPresenter(this);

        mAlipayUserInfoPresenter = new AlipayUserInfoPresenter(this);
    }

    private void getNetType() {

        runOnUiThread(new Runnable() {
            @Override
            public void run() {


                tv_net_no.setVisibility(View.GONE);
                iv_net_wifi.setVisibility(View.GONE);
                iv_net_flow.setVisibility(View.GONE);
                iv_net_line.setVisibility(View.GONE);

                boolean isNetworkAvaiable = NetworkUtils.isNetworkAvaiable(getApplicationContext());
                if (isNetworkAvaiable) {

                    netType = NetworkUtils.getNetType(getApplicationContext());

                    AppLogUtils.e("netType--" + netType);
                    if (StringUtils.isNotNull(netType)) {
                        if (netType.contains("WIFI")) {
                            iv_net_wifi.setVisibility(View.VISIBLE);
                        } else if (netType.contains("MOBILE")) {
                            iv_net_flow.setVisibility(View.VISIBLE);
                        }
                    }

                    // 网络请求
                    requestNetData();


                } else {
                    tv_net_no.setVisibility(View.VISIBLE);
                }


            }
        });


    }


    @Override
    protected void initListener() {


    }


    @NoDoubleClick
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_setting:

                startActivity(PasswordActivity.class);
                // 关闭当前，其余activity返回会重启MainActivity
//                finish();

                break;
            case R.id.tv_enter_applet:
                if (deviceConfigBean != null) {


                    // 日志打印和保存（本地和网络）
                    logPrintSave(NET_LOGCAT,
                            (new Throwable().getStackTrace())[0].toString(),
                            "点击进入小程序操作---");

//                    // 日志行数
//                    String logLine = (new Throwable().getStackTrace())[0].toString();
//                    // 日志节点
//                    String logNodeTag = "点击进入小程序操作---";
//
//                    // 开始保存本地日志
//                    AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
//                            .append(LINE)
//                            .append(logLine).append(WARP)
//                            .append(NODE)
//                            .append(logNodeTag)
//                            .toString()
//                    );
//
//                    // 开始网络在线日志
//                    LogcatAddRequestBean bean = new LogcatAddRequestBean();
//                    bean.setLogType(NET_LOGCAT);
//                    // 对应web端"日志标签"
//                    bean.setLogTag(logLine + WARP + LOG_NODE_APPLET);
//                    bean.setLogContent(logNodeTag);
//                    requestLogcatAdd(bean);


                    initAndActive(deviceConfigBean);
                } else {
                    AppLogUtils.e("deviceConfigBean--null");
                }
                break;

            case R.id.tv_init_scan:

                isInitFace = true;
                initAbcpFace();

                break;
            case R.id.tv_scan:

                AppLogUtils.e(" Config.mSessionId:" + ConfigData.mSessionId);


                // 获取启动Bpaas刷脸的参数
                StartReadyBpaasServiceBean bpaasServiceBean = getStartReadyBpaasServiceBean();

                invokeScanFace(bpaasServiceBean);


                break;
            case R.id.tv_idcard:

                AppLogUtils.e("点击读身份证");

                IDCardScan.with(mActivity, idCardReaderBrand).startScanIDCard(new IDCardScanResultCallback() {
                    @Override
                    public void onIDCardScanSuccess(IDCardInfoBean idCardInfoBean) {
                        AppLogUtils.e(idCardInfoBean.toString());

                        String photoBase64 = idCardInfoBean.getPhotoBase64();
                        if (StringUtils.isNotNull(photoBase64)) {
                            byte[] decode = Base64.decode(photoBase64, Base64.DEFAULT);
                            Bitmap mBitmap = BitmapFactory.decodeByteArray(decode, 0, decode.length);

                            iv_test.setImageBitmap(mBitmap);
                        }


                        tv_idcard_info.setText(idCardInfoBean.toString());


                    }

                    @Override
                    public void onIDCardError(String resCode, String resMsg) {
                        ToastUtils.showLongToast("resCode:" + resCode + "---resMsg:" + resMsg);
                        AppLogUtils.e("resCode:" + resCode + "---resMsg:" + resMsg);
                    }
                });

                break;
            case R.id.tv_idcard_jump:

                AppLogUtils.e("tv_idcard_jump");


//                new Handler().postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        Intent intent1 = new Intent(MainActivity.this, IDCardScanActivity.class);
//                        intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                        startActivity(intent1);
//                    }
//                }, 500); //延时10s执行run内代码


//                Intent intent1 = new Intent(MainActivity.this, PasswordActivity.class);
//                intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                startActivity(intent1);


                break;

            case R.id.tv_exit:

                AppLogUtils.e("tv_exit");
                tv_idcard_info.setText("");
                iv_test.setImageBitmap(null);
//                closeApp();

                break;
            case R.id.tv_logcat:

                if (!hasPermission) {
                    com.blankj.utilcode.util.ToastUtils.showShort("未获取到文件写入权限");
                    return;
                }
                AppLogUtils.saveLog(LogType.Logcat, "测试logcat日志");


                break;
            case R.id.tv_error:

                if (!hasPermission) {
                    com.blankj.utilcode.util.ToastUtils.showShort("未获取到文件写入权限");
                    return;
                }
                AppLogUtils.saveLog(LogType.Error, "测试error日志");


                break;
            case R.id.tv_crash:

                if (!hasPermission) {
                    com.blankj.utilcode.util.ToastUtils.showShort("未获取到文件写入权限");
                    return;
                }
                TextView textView = null;
                textView.setText("执行后闪退记录日志");

                break;

            case R.id.tv_qr:

                startQrCodeSeria();

//                BaseBroadcastScan.getInstance().getBaseBroadcastScan(mContext, new IScanResultCallback() {
//                    @Override
//                    public void scanResult(String code) {
//                        AppLogUtils.e("code:"+code);
//                    }
//                });
                break;
            case R.id.tv_send_message:

                sendAppInfoMessage();

                break;

            case R.id.tv_record_start:


                startMircophoneListener(800);
                break;
            case R.id.tv_record_stop:

                stopMicrophoneListener();

                break;
            case R.id.tv_print:
                ThreadPoolManager.getInstance().executeIOTask(new Runnable() {
                    @Override
                    public void run() {
                PrintBean.PrintConfigDTO printConfigDTO=new PrintBean.PrintConfigDTO();
                printConfigDTO.setPrintContent(0);
                printConfigDTO.setPrintSpeed(3);
                printConfigDTO.setPrintPageType(1);
                printConfigDTO.setPrintPotency(5);
                iPrinter.printBitmap(printConfigDTO,"1111",0,0);
                    }
                });
                break;
            case R.id.tv_voice:
                AppLogUtils.e("tv_voice");
                MTTSDemo.getInstance(mContext).speak("语音测试，昨天是星期一，晴天不下雨，数字12345", 1.0f, 1.0f, 0);
//                MTTSDemo.getInstance(mContext).speak("语音测试");


                // 第二段语音，
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        MTTSDemo.getInstance(mContext).speak("第二段语音测试，昨天是星期二，数字6789", 1.0f, 1.0f, 1);
                    }
                }, 1500);

                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        MTTSDemo.getInstance(mContext).speakStop();
                    }
                }, 3000);


//                BaiduVoice.getInstance(mContext).Speak("百度语音测试");

                break;
        }
    }


    public void deleteAllPicture() {

        // 来自打印图片
        String path = "/storage/emulated/0/Android/data/com.hh.arome/files/picture";

        boolean orExistsDir = FileUtils.createOrExistsDir(path);

        if (!orExistsDir) {
            AppLogUtils.e("没有该图片文件");
            return;
        } else {
            AppLogUtils.e("有该图片文件");
        }

        File file = new File(path);
        File[] files = file.listFiles();
        if (files != null) {
            for (File logFile : files) {
                FileUtils.delete(logFile);
            }
        } else {
        }

    }


    public void deleteRecordAllFile() {
        // 删除之前的录音文件
        if (zlwRecordManager != null) {
            zlwRecordManager.deleteRecordFile();
        }
    }


    private void stopMicrophoneListener() {
        // 结束录音，主动推送
        zlwRecordManager.stopRecordSize(new IMicroPhoneSizeCallback() {
            @Override
            public void onSizeSuccess(String result) {
                sendMicrophoneMessageToApplet(result);
            }
        });
    }

    private void startMircophoneListener(int intervalTime) {


        isCloseMicrophoneMessage = false;

        if (zlwRecordManager == null) {
            zlwRecordManager = ZlwRecordManager.getInstance(mContext);
        }

        // 开始录音，主动推送的
        zlwRecordManager.startRecordSize(intervalTime, new IMicroPhoneSizeCallback() {
            @Override
            public void onSizeSuccess(String result) {
                AppLogUtils.e("开始录音，主动推送的--result:" + result);
                sendMicrophoneMessageToApplet(result);
            }
        });
    }

    private void sendMicrophoneMessageToApplet(String result) {
        AppLogUtils.e("isCloseMicrophoneMessage:" + isCloseMicrophoneMessage,
                "result:" + result);
        // 关闭了，不返回
        if (isCloseMicrophoneMessage) {
            return;
        }

        if (StringUtils.isNull(result)) {
            return;
        }

        JSONObject object = new JSONObject();
        try {
            // 勿动key，对外的文档key
            object.put("voiceContent", result);
        } catch (Throwable t) {

        }
        // 主动推送给小程序
        sendMessageToApplet(EVENT_MICROPHONE_LISTENER, object.toString());
    }

    MicrophoneRecorder recorder;
    ZlwRecordManager zlwRecordManager;


    // 初始化ampe
    private void initAndActive(final DeviceConfigResultBean ampeConfigResultBean) {

        AppLogUtils.e("初始化小程序配置");
        setConfigStatusText("初始化小程序配置");


        // 主题参数配置
        Bundle themeConfig = new Bundle();
        // 不需要登录
        themeConfig.putBoolean("needLogin", false);
        //是否隐藏状态栏 默认false——根据下拉通知栏配置
//        themeConfig.putBoolean("hideStatusBar", false);
        themeConfig.putBoolean("hideStatusBar", forbidPullDown);
        //是否隐藏导航栏 默认false
        themeConfig.putBoolean("hideNavigationBar", false);
        //是否隐藏标题栏胶囊按钮 默认false不隐藏，true隐藏。配置右上角三个圆点和X
        themeConfig.putBoolean("hideOptionMenu", hideNavigationBar);
//        themeConfig.putBoolean("hideOptionMenu", true);
        //超时时间 单位秒，默认30秒 建议传大于10的值
//        themeConfig.putInt("timeOut", 30);
        int appletOperationTimeout = localConfig.getAppletOperationTimeout();
        AppLogUtils.e("appletOperationTimeout:" + appletOperationTimeout);
        if (appletOperationTimeout > 0) {
            themeConfig.putInt("operationTimeoutPeriod", appletOperationTimeout);
        } else {
            themeConfig.putInt("operationTimeoutPeriod", 30);
        }


//        // 初始化多窗口设置
//        final int[] rect = new int[]{0, 0, 1000, 1600};
//        //是否使用freeform打开小程序 默认false
        themeConfig.putBoolean("enableFloatWindow", false);
//        //freeform窗口大小 需配合enableFloatWindow 值为true使用
//        themeConfig.putIntArray("windowBounds", rect);


//         配置黑名单 黑名单中的小程序可全屏显示
//        如果enableFloatWindow值为true，需要全屏显示的小程序配置到黑名单中可全屏显示
//        ArrayList<String> blackList = new ArrayList<>();
//        blackList.add("2021002163620647");
//        themeConfig.putStringArrayList("floatWindowBlacklist", blackList);

        AppLogUtils.e("displayWidth--" + displayWidth);
        AppLogUtils.e("displayHeight--" + displayHeight);

        //竖屏配置，若没有可以不配置
        Bundle portrait = new Bundle();
        //竖屏默认默认值是2 可参考https://opendocs.alipay.com/mini/00v8et?pathHash=8d2d3fa2#3.1%20%E5%90%AF%E5%8A%A8
        portrait.putInt("showType", 2);


        //横屏配置，若没有可以不配置
        Bundle landscape = new Bundle();
        //横屏默认值是123
        landscape.putInt("showType", 2);


        if (deviceModel.contains(Constants.DeviceModel.ZP_A50)) {
            // 紫鹏X5的配置。按照获取的值左右有边距
            //竖屏配置的宽度  默认750 小程序显示的宽度750就是按给定窗口的大小显示，如果是375则是给定窗口大小的一半显示
            portrait.putInt("launchWidth", 750);
            // 横屏配置的宽度
            landscape.putInt("launchWidth", 750);
        } else {
            //竖屏配置的宽度  默认750 小程序显示的宽度750就是按给定窗口的大小显示，如果是375则是给定窗口大小的一半显示
            portrait.putInt("launchWidth", displayWidth);
            // 横屏配置的宽度
            landscape.putInt("launchWidth", displayWidth);
        }


        themeConfig.putBundle("portrait", portrait);
        themeConfig.putBundle("landscape", landscape);


        // 设备信息配置
        Bundle deviceConfig = new Bundle();
        //用于接收广播的应用包名
        deviceConfig.putString("packageName", getPackageName());
        deviceConfig.putBoolean("needLogin", false);

        // 防止小程序页面左右有白边
        deviceConfig.putString("needRealMetrics", "yes");


        int loginMode = 0;
        if (appletOperationTimeout > 0) {
            loginMode = 2;
        }
        AppLogUtils.e("loginMode:" + loginMode);

        final AromeInitOptions options = new AromeInitOptions.Builder()
                // 小程序页面上的悬浮框  0 手动登入登出 1 悬浮球头像露出，用户可登出 可选配置  2 提示超时退出通知
                .loginMode(loginMode)
                //硬件名称 可选配置
                //.hardwareName("")
                .deviceConfig(deviceConfig)//设备信息配置，一般来说，如果不需要接收广播不需要该配置
                //全局主题参数配置，AromeLaunchRequest中的themeConfig是局部配置，影响范围为这一次启动小程序
                //局部配置优先级高于全局配置
                .themeConfig(themeConfig)
                .build();

        AromeActivateRequest activateRequest = new AromeActivateRequest();
        activateRequest.deviceId = ampeConfigResultBean.getSn();
        activateRequest.hostAppId = ampeConfigResultBean.getAmpeAppid();
        activateRequest.productId = Long.parseLong(ampeConfigResultBean.getProductId());//你自己的productId
        activateRequest.signature = ampeConfigResultBean.getSignature();

        // 日志打印和保存（本地和网络）
        logPrintSave(NET_LOGCAT,
                (new Throwable().getStackTrace())[0].toString(),
                "小程序初始化---入参---",
                "deviceId = " + ampeConfigResultBean.getSn(),
                "hostAppId = " + ampeConfigResultBean.getAmpeAppid(),
                "productId = " + ampeConfigResultBean.getProductId(),
                "signature = " + ampeConfigResultBean.getSignature()
        );

        // 日志开始----------------begin
        // 日志行数——对应web端"日志标签"
//        String logLine = (new Throwable().getStackTrace())[0].toString();
//        // 日志节点
//        String logNode = "小程序初始化---入参---";
//        // 日志内容
//        StringBuilder logContentSb = new StringBuilder();
//        logContentSb.append(logNode).append(WARP)
//                .append("deviceId = ").append(ampeConfigResultBean.getSn()).append(WARP)
//                .append("hostAppId = ").append(ampeConfigResultBean.getAmpeAppid()).append(WARP)
//                .append("productId = ").append(ampeConfigResultBean.getProductId()).append(WARP)
//                .append("signature = ").append(ampeConfigResultBean.getSignature());
//
//        // 开始保存本地日志
//        AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
//                .append(LINE)
//                .append(logLine).append(WARP)
//                .append(NODE)
//                .append(logContentSb)
//                .toString()
//        );
//
//        // 开始网络在线日志
//        LogcatAddRequestBean bean = new LogcatAddRequestBean();
//        bean.setLogType(NET_LOGCAT);
//        // 对应web端"日志标签"
//        bean.setLogTag(logLine + WARP + LOG_NODE_APPLET);
//        bean.setLogContent(logContentSb.toString());
//        requestLogcatAdd(bean);
//        // 日志开始----------------end
//
//        AppLogUtils.e(logContentSb);

        AromeInit.initAndActivate(options, activateRequest, new AromeInit.Callback() {
            @Override
            public void postInit(boolean success, int errorCode, String errorMsg) {
                // 非主线程中


                logPrintSave(NET_LOGCAT,
                        (new Throwable().getStackTrace())[0].toString(),
                        "小程序初始化结果initAndActivate---",
                        "postInit result",
                        "success = " + success,
                        "errorCode = " + errorCode,
                        "errorMsg = " + errorMsg
                );

                // 日志开始----------------begin
                // 日志行数——对应web端"日志标签"
//                String logLine = (new Throwable().getStackTrace())[0].toString();
                // 日志节点
//                String logNode = "小程序初始化结果initAndActivate---";
//                // 日志内容
//                StringBuilder logContentSb = new StringBuilder();
//                logContentSb.append(logNode).append(WARP)
//                        .append("postInit result").append(WARP)
//                        .append("success = ").append(success).append(WARP)
//                        .append("errorCode = ").append(errorCode).append(WARP)
//                        .append("errorMsg = ").append(errorMsg);
//
//                // 开始保存本地日志
//                AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
//                        .append(LINE)
//                        .append(logLine).append(WARP)
//                        .append(NODE)
//                        .append(logContentSb)
//                        .toString()
//                );
//
//                // 开始网络在线日志
//                LogcatAddRequestBean bean = new LogcatAddRequestBean();
//                bean.setLogType(NET_LOGCAT);
//                // 对应web端"日志标签"
//                bean.setLogTag(logLine + WARP + LOG_NODE_APPLET);
//                bean.setLogContent(logContentSb.toString());
//                requestLogcatAdd(bean);
//                // 日志开始----------------end
//
//                AppLogUtils.e(logContentSb);

                if (errorCode == 0) {
                    // 成功
                    appletId = ampeConfigResultBean.getMiniProgramAppid();
                    AppLogUtils.e("initAndActive--appId&appletId:" + appletId);
                    // 启动小程序
                    launchApplet(appletId);
                } else if (errorCode == 2002) {
                    // 可能是设备ampe未授权
                    setConfigStatusText("设备ampe未授权");
                } else if (errorCode == 3 || errorCode == 2007) {
                    // 检查引擎
                    setConfigStatusText("设备ampe启动失败--" + errorCode + "--" + errorMsg + "   请重装引擎");
                } else {
                    setConfigStatusText("设备ampe启动失败--" + errorCode + "--" + errorMsg);
                }


            }

            @Override
            public void serverDied() {


                setConfigStatusText("设备ampe启动失败--serverDied");


                logPrintSave(NET_ERROR,
                        (new Throwable().getStackTrace())[0].toString(),
                        "小程序初始化结果initAndActivate---",
                        "设备ampe启动失败--serverDied");

                // 日志开始----------------begin
                // 日志行数——对应web端"日志标签"
//                String logLine = (new Throwable().getStackTrace())[0].toString();
//                // 日志节点
//                String logNode =
//                // 日志内容
//                StringBuilder logContentSb = new StringBuilder();
//                logContentSb.append(logNode).append(WARP)
//                        .append("serverDied");
//
//                // 开始保存本地日志
//                AppLogUtils.saveLog(LogType.Error, new StringBuilder()
//                        .append(LINE)
//                        .append(logLine).append(WARP)
//                        .append(NODE)
//                        .append(logContentSb)
//                        .toString()
//                );
//
//                // 开始网络在线日志
//                LogcatAddRequestBean bean = new LogcatAddRequestBean();
//                bean.setLogType(NET_ERROR);
//                // 对应web端"日志标签"
//                bean.setLogTag(logLine + WARP + LOG_NODE_APPLET);
//                bean.setLogContent(logContentSb.toString());
//                requestLogcatAdd(bean);
//                // 日志开始----------------end
//
//                AppLogUtils.e(logContentSb);


            }
        });

    }


    /**
     * 日志统一打印
     * 网络和本地保存日志
     *
     * @param logLevel   日志级别
     * @param logLine    日志位置
     * @param logNode    日志节点
     * @param logContent 日志内容
     */
    public void logPrintSave(String logLevel, String logLine, String logNode, Object... logContent) {


        // 日志内容
        StringBuilder logContentSb = new StringBuilder();
        logContentSb.append(logNode)
                .append(WARP);
        for (int i = 0, len = logContent.length; i < len; ++i) {
            Object content = logContent[i];
            logContentSb
                    .append(content)
                    .append(WARP);
        }

        // 编译器输出
//        AppLogUtils.e(logContentSb);


        // 开始保存本地日志----begin---

        // 本地日志级别
        if (logLevel.equalsIgnoreCase(LogType.Crash.getType())) {
            AppLogUtils.saveLog(LogType.Crash, new StringBuilder()
                    .append(LINE)
                    .append(logLine).append(WARP)
                    .append(NODE)
                    .append(logContentSb)
                    .toString()
            );
        } else if (logLevel.equalsIgnoreCase(LogType.Error.getType())) {
            AppLogUtils.saveLog(LogType.Error, new StringBuilder()
                    .append(LINE)
                    .append(logLine).append(WARP)
                    .append(NODE)
                    .append(logContentSb)
                    .toString()
            );
        } else if (logLevel.equalsIgnoreCase(LogType.Logcat.getType())) {
            AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
                    .append(LINE)
                    .append(logLine).append(WARP)
                    .append(NODE)
                    .append(logContentSb)
                    .toString()
            );
        }

//        AppLogUtils.saveLog(localLogType, new StringBuilder()
//                .append(LINE)
//                .append(logLine).append(WARP)
//                .append(NODE)
//                .append(logContentSb)
//                .toString()
//        );
        // 开始保存本地日志----end---


        // 开始网络在线日志----begin---
        LogcatAddRequestBean bean = new LogcatAddRequestBean();

        // 网络日志级别
        if (logLevel.equalsIgnoreCase(NET_ERROR)) {
            bean.setLogType(NET_ERROR);
        } else if (logLevel.equalsIgnoreCase(NET_CRASH)) {
            bean.setLogType(NET_CRASH);
        } else if (logLevel.equalsIgnoreCase(NET_LOGCAT)) {
            bean.setLogType(NET_LOGCAT);
        }


        // TODO 后续注意添加else if
        String nodeName = "";// nodeName需要为中文，上传给OTA后台看
        if (logNode.contains("Microphone")) {
            // 麦克风
            nodeName = LOG_NODE_MICROPHONE;
        } else if (logNode.contains("Infrared") || logNode.contains("Induction")) {
            // 红外感应
            nodeName = LOG_NODE_INFRARED_INDUCTION;
        } else if (logNode.contains("打印") || logNode.contains(ACTION_PRINT)) {
            nodeName = LOG_PRINT;
        } else if (logNode.contains("语音") || logNode.contains(ACTION_SPEECH) || logNode.contains(ACTION_SPEECH_STOP)) {
            nodeName = LOG_SPEECH;
        } else if (logNode.contains("二维码") ||
                logNode.contains(ACTION_QR) ||
                logNode.contains("QR")) {
            nodeName = LOG_NODE_QR;
        } else if (logNode.contains("刷脸") ||
                logNode.contains(ACTION_INIT_FACE) ||
                logNode.contains(ACTION_FACE) ||
                logNode.contains(ACTION_FACE_PERSONCARD)) {
            nodeName = LOG_NODE_FACE;
        } else if (logNode.contains("身份证") ||
                logNode.contains(ACTION_IDCard) ||
                logNode.contains(ACTION_IDCARD_CLOSE) ||
                logNode.contains(EVENT_IDCard_LISTENER)) {
            nodeName = LOG_NODE_IDCARD;
        }


        String appletNodeName = "";
        if (logNode.contains("小程序")) {
            appletNodeName = LOG_NODE_APPLET;
        }

        StringBuilder netNodeSb = new StringBuilder();
        netNodeSb.append(logLine)
                .append(WARP)
                .append(nodeName)
                .append(appletNodeName);

        // 对应web端"日志标签"
        bean.setLogTag(netNodeSb.toString());
        bean.setLogContent(logContentSb.toString());
        requestLogcatAdd(bean);
        // 日志开始----end---


        // 编译器输出
        AppLogUtils.e(
                "netNodeSb=" + netNodeSb,
                "logContentSb:" + logContentSb);


    }


    String appletId;
    //
    boolean isLaunchApplet;

    // 注意还在子线程
    private void launchApplet(String appId) {
        setConfigStatusText("启动小程序...");

//        appId = "2021004124640172";
//        appId = "2021004108612349";


        // 日志打印和保存（本地和网络）
        logPrintSave(NET_LOGCAT,
                (new Throwable().getStackTrace())[0].toString(),
                "启动小程序launchApplet---",
                "appId = " + appId
        );

//        // 日志开始----------------begin
//        // 日志行数——对应web端"日志标签"
//        String logLine = (new Throwable().getStackTrace())[0].toString();
//        // 日志节点
//        String logNode = "启动小程序launchApplet---";
//        // 日志内容
//        StringBuilder logContentSb = new StringBuilder();
//        logContentSb.append(logNode).append(WARP)
//                .append("appId = ").append(appId);
//
//        // 开始保存本地日志
//        AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
//                .append(LINE)
//                .append(logLine).append(WARP)
//                .append(NODE)
//                .append(logContentSb)
//                .toString()
//        );
//
//        // 开始网络在线日志
//        LogcatAddRequestBean bean = new LogcatAddRequestBean();
//        bean.setLogType(NET_LOGCAT);
//        // 对应web端"日志标签"
//        bean.setLogTag(logLine + WARP + LOG_NODE_APPLET);
//        bean.setLogContent(logContentSb.toString());
//        requestLogcatAdd(bean);
//        // 日志开始----------------end
//
//        AppLogUtils.e(logContentSb);


        AromeLaunchAppRequest request = new AromeLaunchAppRequest();
        // 设备信息配置
        Bundle themeConfig = new Bundle();
        // 不需要登录
        themeConfig.putBoolean("needLogin", false);
        //支持指定displayId 如果不指定 直接在默认的屏幕显示
        //themeConfig.putInt("displayId", displayId);
        // 是否使用自定义的
        themeConfig.putBoolean("useCustomTitlebar", true);
        request.themeConfig = themeConfig;
        request.appId = appId;

        //如果需要黑白模式切换的逻辑 query需要传入 "openThemeSwitch=1"
        //不需要可以不传
//        request.query = "";
        // 江西就业之家
//        request.query = "ampe=tzsw";
        request.query = "is_ampe=true";
        //启动前是否关闭所有小程序，默认false，建议传true，减少性能开销
        request.closeAllApp = true;
        //注册硬件能力list
        // 只有注册硬件能力 AromeServiceInvoker.registerBridgeExtension才能收到回调
        request.extensionList = getExtensionList();
        //局部的配置只影响当前这一次启动，如果没有特殊需要可以不传
        //不传则采用初始化配置的全局配置


        // request.themeConfig = themeConfig;
        AromeServiceInvoker.invoke(request, new AromeServiceTask.Callback<AromeResponse>() {
            @Override
            public void onCallback(final AromeResponse aromeResponse) {
                // 此回调不在主线，如需要刷新UI 请自行切线程
                // {success=false, code=1001, message='token invalid!'}
                // {success=true, code=0, message='null'}
                AppLogUtils.e("launchApplet-- onCallback = " + aromeResponse.toString());

                int code = aromeResponse.code;


                if (code == 0 || code == 1000) {
                    isLaunchApplet = true;
                    setConfigStatusText("启动小程序成功");

                    // 防止多次点击，导致建立多个通道，信息也多次
//                    appletListen();
                } else {
                    if (code == 1001) {
                        isLaunchApplet = false;
                        setConfigStatusText("设备ampe未授权");
                    } else {
                        setConfigStatusText("启动小程序失败--" + aromeResponse.toString());
                    }
                }


                // 日志打印和保存（本地和网络）
                logPrintSave(NET_LOGCAT,
                        (new Throwable().getStackTrace())[0].toString(),
                        "启动小程序结果---invoke---",
                        "code = " + code,
                        "aromeResponse = " + aromeResponse.toString()
                );


//                // 日志开始----------------begin
//                // 日志行数——对应web端"日志标签"
//                String logLine = (new Throwable().getStackTrace())[0].toString();
//                // 日志节点
//                String logNode = "启动小程序结果---invoke";
//                // 日志内容
//                StringBuilder logContentSb = new StringBuilder();
//                logContentSb.append(logNode).append(WARP)
//                        .append("code = ").append(code).append(WARP)
//                        .append("aromeResponse = ").append(aromeResponse);
//
//                // 开始保存本地日志
//                AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
//                        .append(LINE)
//                        .append(logLine).append(WARP)
//                        .append(NODE)
//                        .append(logContentSb)
//                        .toString()
//                );
//
//                // 开始网络在线日志
//                LogcatAddRequestBean bean = new LogcatAddRequestBean();
//                bean.setLogType(NET_LOGCAT);
//                // 对应web端"日志标签"
//                bean.setLogTag(logLine + WARP + LOG_NODE_APPLET);
//                bean.setLogContent(logContentSb.toString());
//                requestLogcatAdd(bean);
//                // 日志开始----------------end


            }
        });
    }

    // ampe通道名称
    private ArrayList<String> getExtensionList() {
        ArrayList<String> extensionList = new ArrayList<>();

        extensionList.add("HHCommunication");
        return extensionList;
    }


    /**
     * 1050 未找到运行中的小程序
     */
    public void exitApplet() {
        AppLogUtils.e("exitApplet");
        AromeExitAppRequest request = new AromeExitAppRequest();
        request.appId = appletId;
        AppLogUtils.e("exitApplet--appId&appletId:" + appletId);
        AromeServiceInvoker.invoke(request, new AromeServiceTask.Callback<AromeExitAppResponse>() {
            @Override
            public void onCallback(final AromeExitAppResponse response) {
                AppLogUtils.e("exitApplet--response:" + response);

                startBPaaSServiceFlag = false;

            }
        });
    }


    HashMap<String, AmpeActionDataBean> ampeActionMap = new HashMap<>();

    // 江西的刷脸初始化
    boolean isJxInitFace;
    // 通用版本的刷脸初始化
    boolean isInitFace;

    // 刷脸1：N
    boolean isFace;
    // 是否刷脸1:1
    boolean isFacePersonCard;


    boolean isAppletListen;


    // 小程序指令防抖
    public static final int MIN_ACTION_DELAY_TIME = 1200;
    private long lastActionTime = 0;
    String lastActionName = "";


    public void appletListen() {

        // 防止多次建立通道，导致通道信息接收多次
        if (isAppletListen) {
            AppLogUtils.e("appletListen第二次及以后");
            return;
        }
        isAppletListen = true;

        setConfigStatusText("小程序通道建立成功");
        AppLogUtils.e("appletListen");


        // 日志打印和保存（本地和网络）
        logPrintSave(NET_LOGCAT,
                (new Throwable().getStackTrace())[0].toString(),
                "小程序启动成功---通道建立开始监听---"
        );

//        // 日志开始----------------begin
//        // 日志行数——对应web端"日志标签"
//        String logLine = (new Throwable().getStackTrace())[0].toString();
//        // 日志节点
//        String logNode = "小程序启动成功---通道建立开始监听---";
//        // 日志内容
//        StringBuilder logContentSb = new StringBuilder();
//        logContentSb.append(logNode);
//
//        // 开始保存本地日志
//        AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
//                .append(LINE)
//                .append(logLine).append(WARP)
//                .append(NODE)
//                .append(logContentSb)
//                .toString()
//        );
//
//        // 开始网络在线日志
//        LogcatAddRequestBean bean = new LogcatAddRequestBean();
//        bean.setLogType(NET_LOGCAT);
//        // 对应web端"日志标签"
//        bean.setLogTag(logLine + WARP + LOG_NODE_APPLET);
//        bean.setLogContent(logContentSb.toString());
//        requestLogcatAdd(bean);
//        // 日志开始----------------end


        // 监听小程序发出来的获取硬件配置通知,通道建立
        AromeServiceInvoker.registerBridgeExtension(new AromeServiceInvoker.BridgeExtension() {
            @Override
            public void onCalled(String action, String params, AromeServiceInvoker.BridgeCallback bridgeCallback) {

                // 日志开始----------------begin
                // 日志行数——对应web端"日志标签"
                String logLine = (new Throwable().getStackTrace())[0].toString();
                // 日志节点
                String logNode = "小程序通道建立---入参---";
                // 日志内容
                StringBuilder logContentSb = new StringBuilder();
                logContentSb.append(logNode).append(WARP)
                        .append("onCalled").append(WARP)
                        .append("action = ").append(action).append(WARP)
                        .append("params = ").append(params);

                // 开始保存本地日志
                AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
                        .append(LINE)
                        .append(logLine).append(WARP)
                        .append(NODE)
                        .append(logContentSb)
                        .toString()
                );

                // 开始网络在线日志
                LogcatAddRequestBean bean = new LogcatAddRequestBean();
                bean.setLogType(NET_LOGCAT);
                // 对应web端"日志标签"
                bean.setLogTag(logLine + WARP + LOG_NODE_APPLET);
                bean.setLogContent(logContentSb.toString());
                requestLogcatAdd(bean);
                // 日志开始----------------end


            //    AppLogUtils.e(logContentSb);

//                AppLogUtils.e("action--" + action);
//                AppLogUtils.e("小程序参数params--" + params);

                AmpeAppletRequestBean ampeAppletRequestBean = gson.fromJson(params, AmpeAppletRequestBean.class);

                String actionName = ampeAppletRequestBean.getAction();
                if (StringUtils.isNull(actionName)) {
                    return;
                }


                long currentTime = Calendar.getInstance().getTimeInMillis();

                AppLogUtils.e("小程序通道入参--",
                        "lastActionName:" + lastActionName,
                        "actionName:" + actionName,
                        "lastActionTime:" + lastActionTime,
                        "currentTime:" + currentTime
                );


                if (lastActionName.equals(actionName) &&
                        currentTime - lastActionTime <= MIN_ACTION_DELAY_TIME) {
                    AppLogUtils.e("同一条指令，并且小于指定时间，忽略");
                    return;
                } else {
                    AppLogUtils.e("指令正常执行");
                }

//                if(lastActionName.equals(actionName)){
//                    AppLogUtils.e("同指令判断");
//                    if (currentTime - lastActionTime <= MIN_ACTION_DELAY_TIME) {
//                        AppLogUtils.e("同一条指令，并且小于指定时间，忽略");
//                        return;
//                    }else{
//                        AppLogUtils.e("同指令判断,大于时间");
//                    }
//                }else{
//                    AppLogUtils.e("不同指令正常执行");
//                }

                AppLogUtils.e("指令---1");

                lastActionTime = currentTime;
                // 设置可执行的指令
                lastActionName = actionName;


                if (ACTION_QR.equals(ampeAppletRequestBean.getAction())) { // 二维码

                    AmpeActionDataBean qrBean = new AmpeActionDataBean();
                    qrBean.setTaskId(ampeAppletRequestBean.getTaskId());
                    qrBean.setBridgeCallback(bridgeCallback);
                    qrBean.setEvent(ampeAppletRequestBean.getEvent());
                    ampeActionMap.put(ACTION_QR, qrBean);

                } else if (ACTION_IDCard.equals(ampeAppletRequestBean.getAction())) { // 身份证

                    AppLogUtils.e("ACTION_IDCard");

                    AmpeActionDataBean idCardBean = new AmpeActionDataBean();
                    idCardBean.setTaskId(ampeAppletRequestBean.getTaskId());
                    idCardBean.setBridgeCallback(bridgeCallback);
                    idCardBean.setEvent(ampeAppletRequestBean.getEvent());
                    AmpeAppletRequestBean.ParamsDTO paramsDTO = ampeAppletRequestBean.getParams();
                    if (paramsDTO != null) {
                        String infoTypeStr = paramsDTO.getInfoType();
                        if (StringUtils.isNotNull(infoTypeStr)) {
                            String[] paramsArray = infoTypeStr.split(",");
                            idCardBean.setParamsArray(paramsArray);
                        }
                    }
                    ampeActionMap.put(ACTION_IDCard, idCardBean);


                    AppLogUtils.e("ampeAppletRequestBean.getEvent()--" + ampeAppletRequestBean.getEvent());

                    isCloseIdCardMessage = false;
//                    if(AMPE_EVENT_CLOSE.equals(ampeAppletRequestBean.getEvent())){
//                        // 如果关闭
//                        isCloseIdCardMessage = true;
//                        sendSingleCloseMessageToApplet(ACTION_IDCard,ampeActionMap.get(ACTION_IDCard));
//
//                        // 已经开启刷证，来了个关闭
//                        if(!isReadIDCardComplete){
//                            sendReadIDCardFail("主动关闭");
//                        }
//
//                        return;
//                    }


                    if (1 == idCardReaderBrand) {
                        // NFC在线阅读器
                        // 跳转dialog样式的Activity页面去刷证
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
//                                Intent intent = new Intent(MainActivity.this, IDCardScanActivity.class);
                                Intent intent = new Intent(MainActivity.this, IDCardScanNfcActivity.class);
                                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivity(intent);
                            }
                        }, 500); //延时10s执行run内代码


                    } else {
                        // 直接在当前页面
                        // 根据不同的设备取值


                        // 超时返回
                        localConfig.setScanIdCardOverTime(true);

                        AppLogUtils.e("开始监听身份证，倒计时");

                        isReadIDCardComplete = false;

                        readIDCardCountDownTimer = new CountDownTimer(readIDCardTotalTime, 1000) {
                            public void onTick(long millisUntilFinished) {
                                // 每次间隔，这里更新UI，显示剩余时间
                                AppLogUtils.e("身份证，倒计时--" + millisUntilFinished / 1000);
                            }

                            public void onFinish() {
                                // 倒计时结束时的操作
                                if (!isReadIDCardComplete) {
                                    // 未结束
                                    sendReadIDCardFail("超时");
                                }
                            }
                        };

                        // 开始倒计时
                        readIDCardCountDownTimer.start();


                        IDCardScan.with(mActivity, idCardReaderBrand).startScanIDCard(new IDCardScanResultCallback() {
                            @Override
                            public void onIDCardScanSuccess(IDCardInfoBean idCardInfoBean) {
//                                AppLogUtils.e(idCardInfoBean.toString());

                                isReadIDCardComplete = true;

                                isReadIDCardSuccess = true;

                                // 取消倒计时
                                if (readIDCardCountDownTimer != null) {
                                    readIDCardCountDownTimer.cancel();
                                }

                                AmpeAppletResultBean bean = new AmpeAppletResultBean();
                                bean.setAction(ACTION_IDCard);
                                bean.setEvent(AMPE_EVENT);
                                bean.setTaskId("");
                                bean.setSuccess(true);
                                bean.setMessage("成功");

                                AmpeAppletResultBean.Data dataBean = new AmpeAppletResultBean.Data();
                                dataBean.setName(idCardInfoBean.getIdcardName());
                                dataBean.setIdNum(idCardInfoBean.getIdcardNumber());
                                dataBean.setSex(idCardInfoBean.getSex());
                                dataBean.setBeginTime(idCardInfoBean.getBeginTime());
                                dataBean.setEndTime(idCardInfoBean.getEndTime());
                                dataBean.setBirthDate(idCardInfoBean.getBirth());
                                if (StringUtils.isNotNull(idCardInfoBean.getPhotoBase64())) {
                                    String photoBase64 = idCardInfoBean.getPhotoBase64().replaceAll("\n", "");
                                    dataBean.setPhotoBase64(photoBase64);
                                }
                                dataBean.setNation(idCardInfoBean.getNation());
                                dataBean.setAddress(idCardInfoBean.getAddress());
                                // 设置数据
                                bean.setData(dataBean);

                                // call单次返回
                                receiveIDCardResult(bean);

                                // on持续监听返回
                                handleIdCardResultListener(idCardInfoBean);

                            }

                            @Override
                            public void onIDCardError(String resCode, String resMsg) {
                                AppLogUtils.e("resCode:" + resCode + "---resMsg:" + resMsg);

                                isReadIDCardComplete = true;

                                // 取消倒计时
                                if (readIDCardCountDownTimer != null) {
                                    readIDCardCountDownTimer.cancel();
                                }

                                // 会有同时成功失败的情况，
//                                if(isReadIDCardSuccess){
//                                    return;
//                                }

                                sendReadIDCardFail(resMsg);


                            }
                        });

                    }


//                    startActivity(IDCardScanActivity.class);

//                    ReadCardManager.eid.readIDCard(IDOCRCardType.IDCARD, eidLinkReadCardCallBack, mResultListener);

                } else if (ACTION_IDCARD_CLOSE.equals(ampeAppletRequestBean.getAction())) { // 身份证关闭
                    AppLogUtils.e(ACTION_IDCARD_CLOSE);

                    AmpeActionDataBean faceBean = new AmpeActionDataBean();
                    faceBean.setTaskId(ampeAppletRequestBean.getTaskId());
                    faceBean.setBridgeCallback(bridgeCallback);
                    faceBean.setEvent(ampeAppletRequestBean.getEvent());
                    ampeActionMap.put(ACTION_IDCARD_CLOSE, faceBean);

                    // 标识改变
                    isCloseIdCardMessage = true;
                    // 发送关闭
                    sendSingleCloseMessageToApplet(ACTION_IDCARD_CLOSE, ampeActionMap.get(ACTION_IDCARD_CLOSE));
                    // 已经开启刷证，来了个关闭
                    if (!isReadIDCardComplete) {

                        sendReadIDCardFail("主动关闭");
                        // 取消倒计时
                        if (readIDCardCountDownTimer != null) {
                            readIDCardCountDownTimer.cancel();
                        }

                    }


                } else if (ACTION_INIT_FACE.equals(ampeAppletRequestBean.getAction())) { // 刷脸——初始化startBPass
                    AppLogUtils.e("ACTION_INIT_FACE");

                    AmpeActionDataBean faceBean = new AmpeActionDataBean();
                    faceBean.setTaskId(ampeAppletRequestBean.getTaskId());
                    faceBean.setBridgeCallback(bridgeCallback);
                    faceBean.setEvent(ampeAppletRequestBean.getEvent());
                    ampeActionMap.put(ACTION_INIT_FACE, faceBean);

                    AmpeAppletRequestBean.ParamsDTO paramsFace = ampeAppletRequestBean.getParams();
                    if (paramsFace != null) {
                        ConfigData.serviceId = paramsFace.getServiceId();
                        ConfigData.scope = paramsFace.getScope();
                        ConfigData.query = paramsFace.getQuery();
                    }
//                    startBPaaSServiceFlag = true;


                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            if (isInitFace) {
                                sendInitFaceMessage();
                            } else {
                                // 未初始化，就
                                initAbcpFace();
                                isInitFace = true;
                            }


                        }
                    });


//                    InnerApi.addIpcListener(mIpcListener);
//                    Handler handler = new Handler();
//                    handler.postDelayed(new Runnable() {
//                        @Override
//                        public void run() {
////                                Main_APPStuter.setText("SDK初始化成功");
//                            isAPPStuter = true;
//                            //启动核身服务
////                                startBpaasService(ConfigData.getDeviceConfigResultBean().getTrade(), ConfigData.isNeed1V1, ConfigData.getDeviceConfigResultBean().getGroupId(), 0, ConfigData.mSessionId,
////                                        ConfigData.getDeviceConfigResultBean().getAbcpAppId(), "scanFace", false);
//
//                            // startBpaasService0000
//                            // 获取启动Bpaas刷脸的参数
//                            StartReadyBpaasServiceBean bpaasServiceBean = getStartReadyBpaasServiceBean();
////                                //启动核身服务
//                            startZfbBpaasService(bpaasServiceBean);
//
//
//                        }
//                    }, 500); // 延时3s执行run内代码


                } else if (ACTION_FACE.equals(ampeAppletRequestBean.getAction())) { // 刷脸-1:N
                    AppLogUtils.e("ACTION_FACE");

                    AmpeActionDataBean faceBean = new AmpeActionDataBean();
                    faceBean.setTaskId(ampeAppletRequestBean.getTaskId());
                    faceBean.setBridgeCallback(bridgeCallback);
                    faceBean.setEvent(ampeAppletRequestBean.getEvent());
                    ampeActionMap.put(ACTION_FACE, faceBean);

                    AmpeAppletRequestBean.ParamsDTO paramsFace = ampeAppletRequestBean.getParams();

                    if (paramsFace != null) {
                        ConfigData.serviceId = paramsFace.getServiceId();
                        ConfigData.scope = paramsFace.getScope();
                        ConfigData.query = paramsFace.getQuery();
                    }

                    // 获取启动Bpaas刷脸的参数
                    StartReadyBpaasServiceBean bpaasServiceBean = getStartReadyBpaasServiceBean();
                    //启动核身服务
//                    startBpaasService(bpaasServiceBean);
                    // 唤起刷脸 2222
                    invokeScanFace(bpaasServiceBean);

                } else if (ACTION_FACE_PERSONCARD.equals(ampeAppletRequestBean.getAction())) { // 刷脸-调用 1: 1人证比对服务
                    AppLogUtils.e("ACTION_FACE_PERSONCARD");

                    AmpeActionDataBean faceBean = new AmpeActionDataBean();
                    faceBean.setTaskId(ampeAppletRequestBean.getTaskId());
                    faceBean.setBridgeCallback(bridgeCallback);
                    faceBean.setEvent(ampeAppletRequestBean.getEvent());
                    ampeActionMap.put(ACTION_FACE_PERSONCARD, faceBean);

                    AmpeAppletRequestBean.ParamsDTO paramsFace = ampeAppletRequestBean.getParams();

                    // 唤起刷脸,调用 1: 1人证比对服务 3333
                    invokePersonCard(paramsFace.getCertName(), paramsFace.getCertNo(), paramsFace.getCertPhotoBase64Str());


                } else if (ACTION_SCAN_FACE.equals(ampeAppletRequestBean.getAction())) { // 刷脸-江西人社（天正思维做的）,初始化完后直接刷脸
                    AppLogUtils.e("ACTION_SCAN_FACE");
                    // 针对天正思维做的特殊处理。

                    AmpeActionDataBean faceBean = new AmpeActionDataBean();
                    faceBean.setTaskId(ampeAppletRequestBean.getTaskId());
                    faceBean.setBridgeCallback(bridgeCallback);
                    faceBean.setEvent(ampeAppletRequestBean.getEvent());
                    ampeActionMap.put(ACTION_SCAN_FACE, faceBean);

                    AmpeAppletRequestBean.ParamsDTO paramsFace = ampeAppletRequestBean.getParams();

                    if (paramsFace != null) {
//                        ConfigData.serviceId = paramsFace.getServiceId();
//                        ConfigData.scope = paramsFace.getScope();
//                        ConfigData.query = paramsFace.getQuery();

                        // 聚合授权的scope和对外文档不同。不在外面，在ExtInfo参数里面
                        AmpeAppletRequestBean.ParamsDTO.ExtInfo extInfoBean = paramsFace.getExtInfo();
                        if (extInfoBean != null) {
                            String scopes = extInfoBean.getScopes();
                            String merchantAppId = extInfoBean.getMerchantAppId();

                            if (StringUtils.isNotNull(scopes)) {
                                ConfigData.scope = scopes;
                            }

//                            if (StringUtils.isNotNull(merchantAppId)) {
//                                ConfigData.machineAppId = merchantAppId;
//                            }

                        }
                    }

                    // 获取启动Bpaas刷脸的参数
                    StartReadyBpaasServiceBean bpaasServiceBean = getStartReadyBpaasServiceBean();

                    // 未初始化，先初始化。已初始化，直接唤起刷脸
                    if (!isJxInitFace) {
                        isJxInitFace = true;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtils.showShortToast("刷脸页面初始化...");
                                initAbcpFace();
                            }
                        });
                    } else {
                        //启动核身服务
//                    startBpaasService(bpaasServiceBean);
                        // 唤起刷脸 2222
                        invokeScanFace(bpaasServiceBean);

                    }


                } else if (ACTION_DEVICE.equals(ampeAppletRequestBean.getAction())) { // 设备信息
                    AmpeActionDataBean deviceInfoBean = new AmpeActionDataBean();
                    deviceInfoBean.setTaskId(ampeAppletRequestBean.getTaskId());
                    deviceInfoBean.setBridgeCallback(bridgeCallback);
                    deviceInfoBean.setEvent(ampeAppletRequestBean.getEvent());
                    ampeActionMap.put(ACTION_DEVICE, deviceInfoBean);

                    getDeviceInfo(ampeAppletRequestBean.getEvent(), ampeAppletRequestBean.getTaskId(), bridgeCallback);
                } else if (ACTION_SPEECH.equals(ampeAppletRequestBean.getAction())) { // 语音播报

                    AmpeActionDataBean deviceInfoBean = new AmpeActionDataBean();
                    deviceInfoBean.setTaskId(ampeAppletRequestBean.getTaskId());
                    deviceInfoBean.setBridgeCallback(bridgeCallback);
                    deviceInfoBean.setEvent(ampeAppletRequestBean.getEvent());
                    ampeActionMap.put(ACTION_SPEECH, deviceInfoBean);

                    AmpeAppletRequestBean.ParamsDTO paramsSpeech = ampeAppletRequestBean.getParams();
                    if (paramsSpeech != null) {

                        String text = paramsSpeech.getText();
                        float pitchDefault = 1.0f;
                        float rateDefault = 1.0f;
                        Integer speechQueueDefault = 0;
                        Float pitch = paramsSpeech.getPitch();
                        Float rate = paramsSpeech.getRate();
                        Integer speechQueue = paramsSpeech.getSpeechQueue();
                        if (StringUtils.isNull(text)) {
                            speech(ampeAppletRequestBean.getEvent(), ampeAppletRequestBean.getTaskId(), bridgeCallback, false, "text数据为空");
                            return;
                        }
                        if (pitch != null) {
                            pitchDefault = pitch;
                        }
                        if (rate != null) {
                            rateDefault = rate;
                        }
                        if (speechQueue != null) {
                            speechQueueDefault = speechQueue;
                        }

                        // 开始播报
                        MTTSDemo.getInstance(mContext).speak(text, pitchDefault, rateDefault, speechQueueDefault);
                        // 返回给小程序
                        speech(ampeAppletRequestBean.getEvent(), ampeAppletRequestBean.getTaskId(), bridgeCallback, true, "成功");
                    } else {
                        speech(ampeAppletRequestBean.getEvent(), ampeAppletRequestBean.getTaskId(), bridgeCallback, false, "数据为空");
                    }


                } else if (ACTION_SPEECH_STOP.equals(ampeAppletRequestBean.getAction())) { // 语音播报停止

                    // 将小程序请求的存入
                    AmpeActionDataBean speechStopRequestBean = new AmpeActionDataBean();
                    speechStopRequestBean.setTaskId(ampeAppletRequestBean.getTaskId());
                    speechStopRequestBean.setBridgeCallback(bridgeCallback);
                    speechStopRequestBean.setEvent(ampeAppletRequestBean.getEvent());
                    ampeActionMap.put(ACTION_SPEECH_STOP, speechStopRequestBean);


                    // 返回给小程序的结果
                    AmpeAppletResultBean resultBean = new AmpeAppletResultBean();
                    resultBean.setTaskId(ampeAppletRequestBean.getTaskId());
                    resultBean.setAction(ACTION_SPEECH_STOP);
                    resultBean.setEvent(ampeAppletRequestBean.getEvent());

                    try {
                        // 开始播报停止
                        MTTSDemo.getInstance(mContext).speakStop();

                        resultBean.setSuccess(true);
                        resultBean.setMessage("成功");

                        returnMessageToApplet(ACTION_SPEECH_STOP, speechStopRequestBean, resultBean);


                    } catch (Exception e) {
                        e.printStackTrace();

                        resultBean.setSuccess(false);
                        resultBean.setMessage("失败，" + e.toString());

                        returnMessageToApplet(ACTION_SPEECH_STOP, speechStopRequestBean, resultBean);

                    }


                } else if (ACTION_ENTERIDNUMBER.equals(ampeAppletRequestBean.getAction())) {//手输证件号
                    if (deviceConfigBean.isManualInIdCard()) {
                        if (StringUtils.isNull(deviceConfigBean.getManualInIdCardAuth().getAppId()) ||
                                StringUtils.isNull(deviceConfigBean.getManualInIdCardAuth().getAppSecret()) ||
                                StringUtils.isNull(deviceConfigBean.getManualInIdCardAuth().getAppKey()) ||
                                StringUtils.isNull(deviceConfigBean.getManualInIdCardAuth().getPrivateKey())) {
                            sendMessage("密钥缺失,请检查在线配置");
                            return;
                        }
                        OperatingTime = 30;
                        AmpeActionDataBean enterIDnumberBean = new AmpeActionDataBean();
                        enterIDnumberBean.setTaskId(ampeAppletRequestBean.getTaskId());
                        enterIDnumberBean.setBridgeCallback(bridgeCallback);
                        enterIDnumberBean.setEvent(ampeAppletRequestBean.getEvent());
                        ampeActionMap.put(ACTION_ENTERIDNUMBER, enterIDnumberBean);
                        OperatingTimeHandler.removeCallbacks(OperatingTimeRunnable);
                        OperatingTimeHandler.removeCallbacksAndMessages(null);
                        EnterIDNumberWindowManager(MainActivity.this);
                    } else {
                        sendMessage("该功能未开放,请检查在线配置");
                    }

                } else if (ACTION_PRINT.equals(ampeAppletRequestBean.getAction())) {//小票打印
//                    if (iPrintBase == null) {
//                        AppLogUtils.e("小票打印机未初始化，iPrintBase==null");
//                        return;
//                    }

                    if (iPrinter == null) {
                        iPrinter = BasePrinter.getInstance().getPrinter(getApplicationContext());
                    }

                    AmpeActionDataBean enterIDnumberBean = new AmpeActionDataBean();
                    enterIDnumberBean.setTaskId(ampeAppletRequestBean.getTaskId());
                    enterIDnumberBean.setBridgeCallback(bridgeCallback);
                    enterIDnumberBean.setEvent(ampeAppletRequestBean.getEvent());
                    ampeActionMap.put(ACTION_PRINT, enterIDnumberBean);
                    // 获取参数
                    AmpeAppletRequestBean.ParamsDTO printDTO = ampeAppletRequestBean.getParams();
                    // 实际的打印内容
                    List<PrintContentBean> printContentBeans = new ArrayList<>();
                    List<AmpeAppletRequestBean.ParamsDTO.PrintListBean> listBeans = new ArrayList<>();
                    // 添加打印的内容
                    listBeans.addAll(printDTO.getPrintList());
                    for (int i = 0; i < listBeans.size(); i++) {
                        PrintContentBean printContentBean = new PrintContentBean();
                        if (StringUtils.isNotNull(listBeans.get(i).getText() + "")) {
                            printContentBean.setText(listBeans.get(i).getText());
                            printContentBean.setBold(listBeans.get(i).isBold());
                            printContentBean.setAlgin(listBeans.get(i).getAlgin());
                            printContentBean.setTextSize(listBeans.get(i).getTextSize());
                            printContentBean.setxPosition(listBeans.get(i).getxPosition());
                            printContentBean.setyPosition(listBeans.get(i).getyPosition());
                        }
                        if (StringUtils.isNotNull(listBeans.get(i).getQrCodeText() + "")) {
                            printContentBean.setQrCodeText(listBeans.get(i).getQrCodeText());
                            printContentBean.setHeight(listBeans.get(i).getHeight());
                            printContentBean.setWidth(listBeans.get(i).getWidth());
                        } else if (StringUtils.isNotNull(listBeans.get(i).getImageBase64() + "")) {
                            printContentBean.setImageBase64(listBeans.get(i).getImageBase64());
                            printContentBean.setHeight(listBeans.get(i).getHeight());
                            printContentBean.setWidth(listBeans.get(i).getWidth());
                            printContentBean.setxPosition(listBeans.get(i).getxPosition());
                            printContentBean.setyPosition(listBeans.get(i).getyPosition());
                        }else  if(StringUtils.isNotNull(listBeans.get(i).getLocalPdfPath() + "")){
                            printContentBean.setLocalPdfPath(listBeans.get(i).getLocalPdfPath());
                        }
                        printContentBeans.add(printContentBean);
                    }

                    // 打印配置
                    PrintBean.PrintConfigDTO printConfigDTO = new PrintBean.PrintConfigDTO();
                    if(printDTO.getPrintConfig() == null){
                        // 空
                        printConfigDTO.setPrintPageType(-1);
                    }else{
                        printConfigDTO.setPrintPageType(printDTO.getPrintConfig().getPrintPageType());
                        printConfigDTO.setPrintPotency(printDTO.getPrintConfig().getPrintPotency());
                        printConfigDTO.setPrintSpeed(printDTO.getPrintConfig().getPrintSpeed());
                    }

                    AppLogUtils.e(new Gson().toJson(printContentBeans));
                    // 加判断，防止重复打印
                    if (!ConfigData.taskStatus.equals("doing")) {
                        AppLogUtils.e("打印中");
                        ConfigData.taskStatus = "doing";
//                        iPrintBase.startPrint(printContentBeans);
                        BasePrinter.getInstance().handleDataAndPrint(printContentBeans,printConfigDTO);

                        // 兜底置为完成
                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                ConfigData.taskStatus = "complete";
                            }
                        }, 30 * 1000);

                    }
                } else if (ACTION_START_MICROPHONE.equals(ampeAppletRequestBean.getAction())) {
                    // 开启麦克风——录完一整个返回
                    AmpeActionDataBean startMicroBean = new AmpeActionDataBean();
                    startMicroBean.setTaskId(ampeAppletRequestBean.getTaskId());
                    startMicroBean.setBridgeCallback(bridgeCallback);
                    startMicroBean.setEvent(ampeAppletRequestBean.getEvent());
                    ampeActionMap.put(ACTION_START_MICROPHONE, startMicroBean);

                    if (zlwRecordManager == null) {
                        zlwRecordManager = ZlwRecordManager.getInstance(mContext);
                    }

                    // 语音生成mp3
                    startMicroPhone(ampeAppletRequestBean.getEvent(), ampeAppletRequestBean.getTaskId(), ampeActionMap.get(ACTION_START_MICROPHONE).getBridgeCallback());


                } else if (ACTION_STOP_MICROPHONE.equals(ampeAppletRequestBean.getAction())) {
                    // 停止麦克风并返回数据——录完一整个返回
                    AmpeActionDataBean stopMicroBean = new AmpeActionDataBean();
                    stopMicroBean.setTaskId(ampeAppletRequestBean.getTaskId());
                    stopMicroBean.setBridgeCallback(bridgeCallback);
                    stopMicroBean.setEvent(ampeAppletRequestBean.getEvent());
                    ampeActionMap.put(ACTION_STOP_MICROPHONE, stopMicroBean);


                    //
                    if (zlwRecordManager == null) {
                        zlwRecordManager = ZlwRecordManager.getInstance(mContext);
                    }

                    zlwRecordManager.stopResultListener(new IMicroPhoneResultCallback() {
                        @Override
                        public void onSuccess(String result) {
                            stopMicroPhone(true, ampeAppletRequestBean.getEvent(), ampeAppletRequestBean.getTaskId(), ampeActionMap.get(ACTION_STOP_MICROPHONE).getBridgeCallback(), result);
                        }

                        @Override
                        public void onError(String resCode, String resMsg) {
                            stopMicroPhone(false, ampeAppletRequestBean.getEvent(), ampeAppletRequestBean.getTaskId(), ampeActionMap.get(ACTION_STOP_MICROPHONE).getBridgeCallback(), resMsg);
                        }
                    });


                } else if (ACTION_START_MICROPHONE_LISTENER.equals(ampeAppletRequestBean.getAction())) {
                    // 开启麦克风——持续返回
                    AppLogUtils.e("ACTION_START_MICROPHONE_LISTENER");
                    AmpeActionDataBean startMicroBean = new AmpeActionDataBean();
                    startMicroBean.setTaskId(ampeAppletRequestBean.getTaskId());
                    startMicroBean.setBridgeCallback(bridgeCallback);
                    startMicroBean.setEvent(ampeAppletRequestBean.getEvent());
                    ampeActionMap.put(ACTION_START_MICROPHONE_LISTENER, startMicroBean);

                    isCloseMicrophoneMessage = false;

                    if (zlwRecordManager == null) {
                        zlwRecordManager = ZlwRecordManager.getInstance(mContext);
                    }

                    AppLogUtils.e("ACTION_START_MICROPHONE_LISTENER---1");

                    AmpeAppletRequestBean.ParamsDTO paramsDTO = ampeAppletRequestBean.getParams();
                    Integer intervalTime = 1000;
                    if (paramsDTO != null) {
                        Integer intervalTime1 = paramsDTO.getIntervalTime();
                        if (intervalTime1 == null) {
                            intervalTime = 1000;
                        } else {
                            intervalTime = intervalTime1;
                        }
                    }

                    // 注意不要在startMircophoneListener方法后面，免得无法执行
                    returnListenerMessageToApplet(ACTION_START_MICROPHONE_LISTENER,
                            ampeAppletRequestBean.getEvent(),
                            ampeAppletRequestBean.getTaskId(),
                            ampeActionMap.get(ACTION_START_MICROPHONE_LISTENER).getBridgeCallback());

                    // 开始持续发送给小程序。
                    startMircophoneListener(intervalTime);

                    AppLogUtils.e("ACTION_START_MICROPHONE_LISTENER---2");


                } else if (ACTION_STOP_MICROPHONE_LISTENER.equals(ampeAppletRequestBean.getAction())) {
                    // 关闭麦克风——持续返回
                    AmpeActionDataBean startMicroBean = new AmpeActionDataBean();
                    startMicroBean.setTaskId(ampeAppletRequestBean.getTaskId());
                    startMicroBean.setBridgeCallback(bridgeCallback);
                    startMicroBean.setEvent(ampeAppletRequestBean.getEvent());
                    ampeActionMap.put(ACTION_STOP_MICROPHONE_LISTENER, startMicroBean);

                    isCloseMicrophoneMessage = true;

                    if (zlwRecordManager == null) {
                        zlwRecordManager = ZlwRecordManager.getInstance(mContext);
                    }

                    stopMicrophoneListener();

                    returnListenerMessageToApplet(ACTION_STOP_MICROPHONE_LISTENER,
                            ampeAppletRequestBean.getEvent(),
                            ampeAppletRequestBean.getTaskId(),
                            ampeActionMap.get(ACTION_STOP_MICROPHONE_LISTENER).getBridgeCallback());

                } else if (ACTION_MICROPHONE_STATE.equals(ampeAppletRequestBean.getAction())) {
                    // 获取麦克风录音状态
                    AppLogUtils.e("ACTION_MICROPHONE_STATE");


                    AmpeActionDataBean microStateBean = new AmpeActionDataBean();
                    microStateBean.setTaskId(ampeAppletRequestBean.getTaskId());
                    microStateBean.setBridgeCallback(bridgeCallback);
                    microStateBean.setEvent(ampeAppletRequestBean.getEvent());
                    ampeActionMap.put(ACTION_MICROPHONE_STATE, microStateBean);

                    if (zlwRecordManager == null) {
                        zlwRecordManager = ZlwRecordManager.getInstance(mContext);
                    }

                    zlwRecordManager.getState(new IMicroPhoneStateCallback() {
                        @Override
                        public void onState(int state) {
                            AppLogUtils.e("onState--state:" + state);
                            returnMicroState(true,
                                    state,
                                    "成功");
                        }

                        @Override
                        public void onError(int state, String msg) {
                            AppLogUtils.e("onState--onError:" + msg);
                            returnMicroState(false,
                                    state,
                                    msg);
                        }
                    });


                } else if (ACTION_START_INFRARED_INDUCTION_LISTENER.equals(ampeAppletRequestBean.getAction())) {
                    // 开启红外感应——持续返回
                    AppLogUtils.e(ACTION_START_INFRARED_INDUCTION_LISTENER);
                    AmpeActionDataBean startMicroBean = new AmpeActionDataBean();
                    startMicroBean.setTaskId(ampeAppletRequestBean.getTaskId());
                    startMicroBean.setBridgeCallback(bridgeCallback);
                    startMicroBean.setEvent(ampeAppletRequestBean.getEvent());
                    ampeActionMap.put(ACTION_START_INFRARED_INDUCTION_LISTENER, startMicroBean);

                    isCloseInfraredInductionMessage = false;


                    AmpeAppletRequestBean.ParamsDTO paramsDTO = ampeAppletRequestBean.getParams();

                    Integer infraredInductionIntervalTime = TIME_INDUCTION_INTERVAL;
                    if (paramsDTO != null) {
                        Integer intervalTime1 = paramsDTO.getIntervalTime();
                        if (intervalTime1 == null) {
                            infraredInductionIntervalTime = TIME_INDUCTION_INTERVAL;
                        } else {
                            infraredInductionIntervalTime = intervalTime1;
                        }
                    }

                    // 注意不要在sendInductionInstruct方法后面，免得无法执行
                    returnListenerMessageToApplet(ACTION_START_INFRARED_INDUCTION_LISTENER,
                            ampeAppletRequestBean.getEvent(),
                            ampeAppletRequestBean.getTaskId(),
                            ampeActionMap.get(ACTION_START_INFRARED_INDUCTION_LISTENER).getBridgeCallback());


                    // 发送指令
                    sendInductionInstruct(comPortInfraredInduction, infraredInductionIntervalTime);


                    AppLogUtils.e("ACTION_START_INFRARED_INDUCTION_LISTENER---2");


                } else if (ACTION_STOP_INFRARED_INDUCTION_LISTENER.equals(ampeAppletRequestBean.getAction())) {
                    // 关闭红外感应——持续返回
                    AmpeActionDataBean startMicroBean = new AmpeActionDataBean();
                    startMicroBean.setTaskId(ampeAppletRequestBean.getTaskId());
                    startMicroBean.setBridgeCallback(bridgeCallback);
                    startMicroBean.setEvent(ampeAppletRequestBean.getEvent());
                    ampeActionMap.put(ACTION_STOP_INFRARED_INDUCTION_LISTENER, startMicroBean);

                    isCloseInfraredInductionMessage = true;

                    returnListenerMessageToApplet(ACTION_STOP_INFRARED_INDUCTION_LISTENER,
                            ampeAppletRequestBean.getEvent(),
                            ampeAppletRequestBean.getTaskId(),
                            ampeActionMap.get(ACTION_STOP_INFRARED_INDUCTION_LISTENER).getBridgeCallback());

                }

            }
        });


    }

    // 发送读卡失败
    private void sendReadIDCardFail(String resMsg) {
        AmpeActionDataBean ampeActionDataBean = ampeActionMap.get(ACTION_IDCard);
        if (ampeActionDataBean == null) {
            AppLogUtils.e(ACTION_IDCard + "--ampeActionDataBean == null");
            return;
        }
        AromeServiceInvoker.BridgeCallback bridgeCallback = ampeActionDataBean.getBridgeCallback();

        AmpeAppletResultBean bean = new AmpeAppletResultBean();
        bean.setAction(ACTION_IDCard);
        bean.setEvent(ampeActionDataBean.getEvent());
        bean.setTaskId(ampeActionDataBean.getTaskId());
        bean.setSuccess(false);
        if (StringUtils.isNotNull(resMsg)) {
            bean.setMessage(resMsg);
        } else {
            bean.setMessage("未识别到，请重试");
        }

        AmpeAppletResultBean.Data dataBean = new AmpeAppletResultBean.Data();
        bean.setData(dataBean);


        // 回传处理结果给小程序
        try {
            JsonObject jsonObject = gson.toJsonTree(bean).getAsJsonObject();

            if (bridgeCallback != null) {
                bridgeCallback.callback(jsonObject.toString());
            } else {
                AppLogUtils.e("bridgeCallback--null");
            }

            // 日志开始----------------begin
            // 日志行数——对应web端"日志标签"
            String logLine = (new Throwable().getStackTrace())[0].toString();
            // 日志节点
            String logNode = "ACTION_IDCard--刷身份证失败--回传处理结果给小程序--";
            // 日志内容
            StringBuilder logContentSb = new StringBuilder();
            logContentSb.append(logNode).append(WARP)
                    .append("jsonObject = ").append(jsonObject);

            // 开始保存本地日志
            AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
                    .append(LINE)
                    .append(logLine).append(WARP)
                    .append(NODE)
                    .append(logContentSb)
                    .toString()
            );

            // 开始网络在线日志
            LogcatAddRequestBean logBean = new LogcatAddRequestBean();
            logBean.setLogType(NET_LOGCAT);
            // 对应web端"日志标签"
            logBean.setLogTag(logLine + WARP + LOG_NODE_APPLET + LOG_NODE_IDCARD);
            logBean.setLogContent(logContentSb.toString());
            requestLogcatAdd(logBean);
            // 日志开始----------------end

            // 打印编译器输出日志
            AppLogUtils.e(logContentSb);


        } catch (Throwable t) {
            AppLogUtils.e("onCalled--t" + t);
        }
    }

    private void stopMicroPhone(boolean isSuccess, String event, String taskId, AromeServiceInvoker.BridgeCallback bridgeCallback, String result) {

        AmpeAppletResultBean bean = new AmpeAppletResultBean();
        bean.setAction(ACTION_STOP_MICROPHONE);
        bean.setEvent(event);
        bean.setTaskId(taskId);
        if (isSuccess) {
            bean.setSuccess(true);
            bean.setMessage("成功");

            AmpeAppletResultBean.Data dataBean = new AmpeAppletResultBean.Data();
            dataBean.setVoiceContent(result);
            bean.setData(dataBean);

        } else {
            bean.setSuccess(false);
            bean.setMessage(result);
        }


        AppLogUtils.e("bean:" + bean.toString());

        // 回传处理结果给小程序
        try {
            JsonObject jsonObject = gson.toJsonTree(bean).getAsJsonObject();
            if (bridgeCallback != null) {
                bridgeCallback.callback(jsonObject.toString());
            }

            // 日志开始----------------begin
            // 日志行数——对应web端"日志标签"
            String logLine = (new Throwable().getStackTrace())[0].toString();
            // 日志节点
            String logNode = ACTION_STOP_MICROPHONE + "--回传处理结果给小程序--";
            // 日志内容
            StringBuilder logContentSb = new StringBuilder();
            logContentSb.append(logNode).append(WARP)
                    .append("jsonObject = ").append(jsonObject);

            // 开始保存本地日志
            AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
                    .append(LINE)
                    .append(logLine).append(WARP)
                    .append(NODE)
                    .append(logContentSb)
                    .toString()
            );

            // 开始网络在线日志
            LogcatAddRequestBean logBean = new LogcatAddRequestBean();
            logBean.setLogType(NET_LOGCAT);
            // 对应web端"日志标签"
            logBean.setLogTag(logLine + WARP + LOG_NODE_APPLET + LOG_NODE_MICROPHONE);
            logBean.setLogContent(logContentSb.toString());
            requestLogcatAdd(logBean);
            // 日志开始----------------end

            // 打印编译器输出日志
            AppLogUtils.e(logContentSb);

        } catch (Throwable t) {
            AppLogUtils.e("onCalled--t" + t);
        }

    }

    private void startMicroPhone(String event, String taskId, AromeServiceInvoker.BridgeCallback bridgeCallback) {

        if (zlwRecordManager == null) {
            zlwRecordManager = ZlwRecordManager.getInstance(mContext);
        }
        zlwRecordManager.start();

        AmpeAppletResultBean bean = new AmpeAppletResultBean();
        bean.setAction(ACTION_START_MICROPHONE);
        bean.setEvent(event);
        bean.setTaskId(taskId);
        bean.setSuccess(true);
        bean.setMessage("成功");

        AmpeAppletResultBean.Data dataBean = new AmpeAppletResultBean.Data();
        bean.setData(dataBean);

        AppLogUtils.e("bean:" + bean.toString());

        // 回传处理结果给小程序
        try {
            JsonObject jsonObject = gson.toJsonTree(bean).getAsJsonObject();
            if (bridgeCallback != null) {
                bridgeCallback.callback(jsonObject.toString());
            }

            // 日志开始----------------begin
            // 日志行数——对应web端"日志标签"
            String logLine = (new Throwable().getStackTrace())[0].toString();
            // 日志节点
            String logNode = ACTION_START_MICROPHONE + "--回传处理结果给小程序--";
            // 日志内容
            StringBuilder logContentSb = new StringBuilder();
            logContentSb.append(logNode).append(WARP)
                    .append("jsonObject = ").append(jsonObject);

            // 开始保存本地日志
            AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
                    .append(LINE)
                    .append(logLine).append(WARP)
                    .append(NODE)
                    .append(logContentSb)
                    .toString()
            );

            // 开始网络在线日志
            LogcatAddRequestBean logBean = new LogcatAddRequestBean();
            logBean.setLogType(NET_LOGCAT);
            // 对应web端"日志标签"
            logBean.setLogTag(logLine + WARP + LOG_NODE_APPLET + LOG_NODE_MICROPHONE);
            logBean.setLogContent(logContentSb.toString());
            requestLogcatAdd(logBean);
            // 日志开始----------------end

            // 打印编译器输出日志
            AppLogUtils.e(logContentSb);

        } catch (Throwable t) {
            AppLogUtils.e("onCalled--t" + t);
        }

    }


    private void returnListenerMessageToApplet(String action, String event, String taskId, AromeServiceInvoker.BridgeCallback bridgeCallback) {


        AmpeAppletResultBean bean = new AmpeAppletResultBean();
        bean.setAction(action);
        bean.setEvent(event);
        bean.setTaskId(taskId);
        bean.setSuccess(true);
        bean.setMessage("成功");

        AmpeAppletResultBean.Data dataBean = new AmpeAppletResultBean.Data();
        bean.setData(dataBean);

        AppLogUtils.e("bean:" + bean.toString());

        // 回传处理结果给小程序
        try {
            AppLogUtils.e("ACTION_START_MICROPHONE_LISTENER---4");
            JsonObject jsonObject = gson.toJsonTree(bean).getAsJsonObject();
            if (bridgeCallback != null) {
                bridgeCallback.callback(jsonObject.toString());
            }

            // 日志开始----------------begin
            // 日志行数——对应web端"日志标签"
            String logLine = (new Throwable().getStackTrace())[0].toString();
            // 日志节点
            String logNode = action + "--回传处理结果给小程序--";
            // 日志内容
            StringBuilder logContentSb = new StringBuilder();
            logContentSb.append(logNode).append(WARP)
                    .append("jsonObject = ").append(jsonObject);

            // 开始保存本地日志
            AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
                    .append(LINE)
                    .append(logLine).append(WARP)
                    .append(NODE)
                    .append(logContentSb)
                    .toString()
            );

            // 开始网络在线日志
            LogcatAddRequestBean logBean = new LogcatAddRequestBean();
            logBean.setLogType(NET_LOGCAT);
            // 对应web端"日志标签"
            String nodeName = "";
            if (action.contains("Microphone")) {
                nodeName = LOG_NODE_MICROPHONE;
            } else if (action.contains("Infrared") || action.contains("Induction")) {
                nodeName = LOG_NODE_INFRARED_INDUCTION;
            }
            logBean.setLogTag(logLine + WARP + LOG_NODE_APPLET + nodeName);
            logBean.setLogContent(logContentSb.toString());
            requestLogcatAdd(logBean);
            // 日志开始----------------end

            // 打印编译器输出日志
            AppLogUtils.e(logContentSb);

        } catch (Throwable t) {
            AppLogUtils.e("onCalled--t" + t);
        }

    }


    private void returnMicroState(boolean isSuccess, int state, String message) {


        AmpeActionDataBean ampeActionDataBean = ampeActionMap.get(ACTION_MICROPHONE_STATE);
        if (ampeActionDataBean == null) {
            AppLogUtils.e("ampeActionDataBean == null");
            return;
        }


        AmpeAppletResultBean bean = new AmpeAppletResultBean();
        bean.setAction(ACTION_MICROPHONE_STATE);
        bean.setEvent(ampeActionDataBean.getEvent());
        bean.setTaskId(ampeActionDataBean.getTaskId());
        bean.setSuccess(isSuccess);
        bean.setMessage(message);

        AmpeAppletResultBean.Data dataBean = new AmpeAppletResultBean.Data();
        dataBean.setMicrophoneState(state);
        dataBean.setMicrophoneListenerState(state);
//        if(isCloseMicrophoneMessage){
//            dataBean.setMicrophoneListenerState(0);
//        }else{
//            dataBean.setMicrophoneListenerState(1);
//        }
        bean.setData(dataBean);

        AppLogUtils.e("bean:" + bean.toString());

        // 回传处理结果给小程序
        try {
            JsonObject jsonObject = gson.toJsonTree(bean).getAsJsonObject();

            AromeServiceInvoker.BridgeCallback bridgeCallback = ampeActionMap.get(ACTION_MICROPHONE_STATE).getBridgeCallback();

            if (bridgeCallback != null) {
                bridgeCallback.callback(jsonObject.toString());
            }

            // 日志开始----------------begin
            // 日志行数——对应web端"日志标签"
            String logLine = (new Throwable().getStackTrace())[0].toString();
            // 日志节点
            String logNode = ACTION_MICROPHONE_STATE + "--回传处理结果给小程序--";
            // 日志内容
            StringBuilder logContentSb = new StringBuilder();
            logContentSb.append(logNode).append(WARP)
                    .append("jsonObject = ").append(jsonObject);

            // 开始保存本地日志
            AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
                    .append(LINE)
                    .append(logLine).append(WARP)
                    .append(NODE)
                    .append(logContentSb)
                    .toString()
            );

            // 开始网络在线日志
            LogcatAddRequestBean logBean = new LogcatAddRequestBean();
            logBean.setLogType(NET_LOGCAT);
            // 对应web端"日志标签"
            logBean.setLogTag(logLine + WARP + LOG_NODE_APPLET + LOG_NODE_MICROPHONE);
            logBean.setLogContent(logContentSb.toString());
            requestLogcatAdd(logBean);
            // 日志开始----------------end

            // 打印编译器输出日志
            AppLogUtils.e(logContentSb);

        } catch (Throwable t) {
            AppLogUtils.e("onCalled--t" + t);
        }

    }


    /**
     * 单次操作关闭给小程序
     *
     * @param ampeActionDataBean
     */
    private void sendSingleCloseMessageToApplet(String action, AmpeActionDataBean ampeActionDataBean) {

        if (ampeActionDataBean == null) {
            AppLogUtils.e("ampeActionDataBean == null");
            return;
        }
        AromeServiceInvoker.BridgeCallback bridgeCallback = ampeActionDataBean.getBridgeCallback();

        AmpeAppletResultBean bean = new AmpeAppletResultBean();
        bean.setAction(action);
        bean.setEvent(ampeActionDataBean.getEvent());
        bean.setTaskId(ampeActionDataBean.getTaskId());
        bean.setSuccess(true);
        bean.setMessage("关闭成功");

        AmpeAppletResultBean.Data dataBean = new AmpeAppletResultBean.Data();
        bean.setData(dataBean);


        // 回传处理结果给小程序
        try {
            JsonObject jsonObject = gson.toJsonTree(bean).getAsJsonObject();

            if (bridgeCallback != null) {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        bridgeCallback.callback(jsonObject.toString());
                    }
                }, 1000);

            } else {
                AppLogUtils.e("bridgeCallback--null");
            }

            // 日志开始----------------begin
            // 日志行数——对应web端"日志标签"
            String logLine = (new Throwable().getStackTrace())[0].toString();
            // 日志节点
            String logNode = action + "--回传处理结果给小程序--";
            // 日志内容
            StringBuilder logContentSb = new StringBuilder();
            logContentSb.append(logNode).append(WARP)
                    .append("jsonObject = ").append(jsonObject);

            // 开始保存本地日志
            AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
                    .append(LINE)
                    .append(logLine).append(WARP)
                    .append(NODE)
                    .append(logContentSb)
                    .toString()
            );

            // 开始网络在线日志
            LogcatAddRequestBean logBean = new LogcatAddRequestBean();
            logBean.setLogType(NET_LOGCAT);
            // 对应web端"日志标签"
            logBean.setLogTag(logLine + WARP + LOG_NODE_APPLET + LOG_NODE_IDCARD);
            logBean.setLogContent(logContentSb.toString());
            requestLogcatAdd(logBean);
            // 日志开始----------------end

            // 打印编译器输出日志
            AppLogUtils.e(logContentSb);


        } catch (Throwable t) {
            AppLogUtils.e("onCalled--t" + t);
        }


    }


    // 是否关闭麦克风数据，
    boolean isCloseMicrophoneMessage = true;

    // 是否关闭身份证信息
    boolean isCloseIdCardMessage;


    /**
     * 单次操作返回小程序
     * 成功或失败
     *
     * @param action
     * @param ampeActionDataBean
     * @param ampeAppletResultBean
     */
    private void returnMessageToApplet(String action, AmpeActionDataBean ampeActionDataBean, AmpeAppletResultBean ampeAppletResultBean) {

        AppLogUtils.e("ampeActionDataBean:" + ampeActionDataBean.toString());

        AppLogUtils.e("ampeAppletResultBean:" + ampeAppletResultBean.toString());


        if (ampeActionDataBean == null) {
            AppLogUtils.e("请求ampeActionDataBean == null");
            return;
        }

        if (ampeAppletResultBean == null) {
            AppLogUtils.e("返回ampeAppletResultBean == null");
            return;
        }


        try {
            JsonObject jsonObject = gson.toJsonTree(ampeAppletResultBean).getAsJsonObject();

            if (ampeActionDataBean.getBridgeCallback() != null) {
                // 回传处理结果给小程序
                ampeActionDataBean.getBridgeCallback().callback(jsonObject.toString());
            }


            // 日志打印和保存（本地和网络）
            logPrintSave(NET_LOGCAT,
                    (new Throwable().getStackTrace())[0].toString(),
                    action + "--回传处理结果给小程序--",
                    "jsonObject = " + jsonObject
            );


        } catch (Throwable t) {
            AppLogUtils.e("onCalled--t" + t);
        }

    }


    /**
     * 各类监听，主动给小程序
     *
     * @param eventName
     * @param eventData
     */
    public void sendMessageToApplet(String eventName, String eventData) {

        AppLogUtils.e("主动发消息给小程序eventName：" + eventName + "---发送内容eventData：" + eventData);


        AromeSendEventRequest request = new AromeSendEventRequest();
        request.eventName = eventName;

        JSONObject object = new JSONObject();
        try {
            // 勿动key，对外的文档key
            object.put("data", eventData);
        } catch (Throwable t) {

        }
        request.eventData = object.toString();

        AppLogUtils.e("主动发消息给小程序object：" + object.toString());


        AromeServiceInvoker.invoke(request, new AromeServiceTask.Callback<AromeResponse>() {
            @Override
            public void onCallback(AromeResponse response) {
                //自行处理事件发送成功后的回调
                AppLogUtils.e(eventName + "---" + response.toString());

                String type = "";

                if (eventName.equals(EVENT_IDCard_LISTENER)) {
                    // 身份证持续监听
                    type = LOG_NODE_IDCARD;
                } else if (eventName.equals(EVENT_QR_LISTENER)) {
                    // 二维码持续监听
                    type = LOG_NODE_QR;
                } else if (eventName.equals(EVENT_MICROPHONE_LISTENER)) {
                    // 麦克风持续监听
                    type = EVENT_MICROPHONE_LISTENER;
                } else if (eventName.equals(EVENT_INFRARED_INDUCTION_LISTENER)) {
                    // 开启红外感应持续监听
                    type = EVENT_INFRARED_INDUCTION_LISTENER;
                }

                // 日志行数——对应web端"日志标签"
                String logLine = (new Throwable().getStackTrace())[0].toString();
                // 日志节点
                String logNode = "主动推送给小程序结果---";
                // 日志内容
                StringBuilder logContentSb = new StringBuilder();
                logContentSb.append(logNode)
                        .append(WARP)
                        .append(type)
                        .append(WARP)
                        .append(eventName)
                        .append(WARP)
                        .append(eventData)
                        .append(WARP)
                        .append("aromeResponse = ")
                        .append(response);

                // 保存到本地及网络
                saveLogcatLocalAndNet(logLine, logContentSb.toString(), LOG_NODE_APPLET + type, NET_LOGCAT);
                // 打印编译器输出日志
//                AppLogUtils.e(eventName+"---"+logContentSb);


                if (response.code == 1001) {
                    // 失效
                    initAndActive(deviceConfigBean);
                }

            }
        });


    }


    /**
     * 保存到本地及网络
     *
     * @param logLine      日志行数
     * @param logContentSb 日志内容
     * @param logNodeType  日志节点类型——小程序、身份证
     * @param logLevelType 日志级别类型——NET_LOGCAT、NET_ERROR
     */
    public void saveLogcatLocalAndNet(String logLine, String logContentSb, String logNodeType, String logLevelType) {
        // 日志开始----------------begin
        // 日志行数——对应web端"日志标签"
//        String logLine = (new Throwable().getStackTrace())[0].toString();
//        // 日志节点
//        String logNode = "启动小程序结果---invoke";
//        // 日志内容
//        StringBuilder logContentSb = new StringBuilder();
//        logContentSb.append(logNode).append(WARP)
//                .append("code = ").append(code).append(WARP)
//                .append("aromeResponse = ").append(aromeResponse);


        // 开始保存本地日志
        AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
                .append(LINE)
                .append(logLine).append(WARP)
                .append(NODE)
                .append(logContentSb)
                .toString()
        );

        // 开始网络在线日志
        LogcatAddRequestBean bean = new LogcatAddRequestBean();
        // 日志级别
        bean.setLogType(logLevelType);
        // 对应web端"日志标签"
        bean.setLogTag(logLine + WARP + logNodeType);
        bean.setLogContent(logContentSb);
        requestLogcatAdd(bean);
        // 日志开始----------------end
    }

    /**
     * 本地过渡页
     */
    private WindowManager EnterWindowManager;//本地过度页加载
    private View EnterView;
    private GridView EnterIDNumberActivity_GridView;
    private Gridadapter gridadapter;
    private List<String> list = new ArrayList<>();
    private EditText EnterIDNumberActivity_edit;
    private TextView tv_OperatingTime;
    private LinearLayout EnterIDNumberActivity_SureClick, EnterIDNumberActivity_CancelClick;
    private RelativeLayout EnterIDNumberActivity_RelativeLayout;
    private ThreeElementsContract.Presenter mThreeElementsPresenter;
    //时间
    Handler mHandler = new Handler();
    Runnable runnableTime = new Runnable() {
        @Override
        public void run() {
            // 设置最新时间
            tv_time.setText(DateUtil.getTime("yyyy.MM.dd HH:mm:ss") + " " + DateUtil.getWeekOfDate(new Date()));
            // 接着发送刷新任务
            mHandler.postDelayed(runnableTime, 1000);
        }
    };
    // 写入无网络日志次数
    int netLogcatNum;
    //倒计时
    private int OperatingTime = 30;
    //EnterIDNumber-手输证号超时  Loding-等待页 Results-等待页
    private String OperatingTimeType = "EnterIDNumber";
    Handler OperatingTimeHandler = new Handler();
    Runnable OperatingTimeRunnable = new Runnable() {
        @Override
        public void run() {
            if (OperatingTime > 0) {
                OperatingTime--;
                if (OperatingTimeType.equals("EnterIDNumber")) {
                    tv_OperatingTime.setText("操作时间 " + OperatingTime + " 秒");
                } else if (OperatingTimeType.equals("Loding")) {
                    tv_OperatingTime.setText(OperatingTime + " 秒");
                }
                OperatingTimeHandler.postDelayed(OperatingTimeRunnable, 1000);
            } else {
                if (OperatingTimeType.equals("Loding")) {
                    OperatingTimeType = "Results";
                    OperatingTime = 3;
                    OperatingTimeHandler.postDelayed(OperatingTimeRunnable, 1000);
                } else {
                    sendMessage("手输证件号超时");
                    try {
                        if (EnterWindowManager != null) {
                            EnterWindowManager.removeView(EnterView);
                            EnterWindowManager = null;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    };
    private long lastClickTime; // 上次点击的时间
    private RelativeLayout enterIDCard_RelativeLayout;
    private LinearLayout enterIDCard_Loding;
    private TextView enterIDCard_LodingText;
    private ImageView enterIDCard_LodingImageView;

    public void EnterIDNumberWindowManager(Context context) {
        if ((EnterWindowManager != null && EnterView.isAttachedToWindow())) {
            return;
        }
        if (EnterWindowManager != null) {
            int CloseWhile = 2;
            while (true) {
                if (EnterView.isAttachedToWindow() || CloseWhile-- <= 0) {
                    WindowManagerInitView(context, EnterView);
                    return;
                }
                try {
                    Thread.sleep(20);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        EnterWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        if (Constants.DeviceModel.D2.equals(DeviceUtils.getDeviceModel())) {
            EnterView = LayoutInflater.from(context).inflate(R.layout.window_enter_idnumber_hp, null);
        } else if (Constants.DeviceModel.K8.equals(DeviceUtils.getDeviceModel())) {
            EnterView = LayoutInflater.from(context).inflate(R.layout.window_enter_idnumber_sp, null);
        }
        WindowManagerInitView(context, EnterView);
        // 创建一个FrameLayout，并将该View添加到FrameLayout中
        FrameLayout frameLayout = new FrameLayout(context);
        frameLayout.addView(EnterView);
        // 测量和布局FrameLayout，以确定View的大小
        frameLayout.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        frameLayout.layout(0, 0, frameLayout.getMeasuredWidth(), frameLayout.getMeasuredHeight());
        // 用来测量View的大小
        int measureSpec = View.MeasureSpec.makeMeasureSpec(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        EnterView.measure(measureSpec, measureSpec);
        int viewWidth = EnterView.getMeasuredWidth();
        int viewHeight = EnterView.getMeasuredHeight();
        frameLayout.removeView(EnterView);
        //WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
        int type;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;// 系统提示window
        }
        WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.MATCH_PARENT,
                type,
                WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                        | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN//将window放置在整个屏幕之内,无视其他的装饰(比如状态栏)
                        | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS//允许window扩展值屏幕之外
                        | WindowManager.LayoutParams.FLAG_FULLSCREEN//当这个window显示的时候,隐藏所有的装饰物(比如状态栏)这个flag允许window使用整个屏幕区域
                        | WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER,//标记在其它窗口的LayoutParams.flags中的存在情况而不断地被调整
                PixelFormat.RGBA_8888
        );
        //展示悬浮view
        EnterWindowManager.addView(EnterView, layoutParams);
    }

    private void WindowManagerInitView(Context context, View view) {
        EnterIDNumberActivity_GridView = view.findViewById(R.id.EnterIDNumberActivity_GridView);
        EnterIDNumberActivity_edit = view.findViewById(R.id.EnterIDNumberActivity_edit);
        tv_OperatingTime = view.findViewById(R.id.tv_OperatingTime);
        enterIDCard_RelativeLayout = view.findViewById(R.id.enterIDCard_RelativeLayout);
        //加载中
        enterIDCard_Loding = view.findViewById(R.id.enterIDCard_Loding);
        enterIDCard_LodingText = view.findViewById(R.id.enterIDCard_LodingText);
        enterIDCard_LodingImageView = view.findViewById(R.id.enterIDCard_LodingImageView);
        EnterIDNumberActivity_SureClick = view.findViewById(R.id.EnterIDNumberActivity_SureClick);
        EnterIDNumberActivity_CancelClick = view.findViewById(R.id.EnterIDNumberActivity_CancelClick);
        EnterIDNumberActivity_RelativeLayout = view.findViewById(R.id.EnterIDNumberActivity_RelativeLayout);
        EnterIDNumberActivity_SureClick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String edit = EnterIDNumberActivity_edit.getText().toString();
                if (!IdCardUtils.isValidatedAllIdcard(edit)) {//不符合
                    //重置悬浮框时间
                    OperatingTime = 30;
                    //添加输入框文字变红
                    EnterIDNumberActivity_edit.setTextColor(getResources().getColor(R.color.fFF3141));
                    //添加输入框抖动效果
                    IdCardUtils.ditheringAnimation(EnterIDNumberActivity_edit, context);
                } else {
                    EnterIDNumberActivity_edit.setTextColor(getResources().getColor(R.color.black));
                    long now = System.currentTimeMillis();
                    if (now - lastClickTime > 1000) {
                        lastClickTime = now;
                        sendEnterIDNumber(edit);
                    }
                }
            }
        });
        EnterIDNumberActivity_CancelClick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendMessage("取消手输证件号");
            }
        });
        mThreeElementsPresenter = new ThreeElementsPresenter(this);
        //关闭键盘弹出
        EnterIDNumberActivity_edit.setInputType(InputType.TYPE_NULL);
        EnterIDNumberActivity_edit.setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                EnterIDNumberActivity_edit.setInputType(InputType.TYPE_NULL); //关闭软键盘
                return false;
            }
        });
        if (Constants.DeviceModel.D2.equals(DeviceUtils.getDeviceModel())) {
            EnterIDNumberActivity_RelativeLayout.setBackgroundResource(R.mipmap.bg_enter_hp);
        } else {
            EnterIDNumberActivity_RelativeLayout.setBackgroundResource(R.mipmap.bg_enter_sp);
        }
        OperatingTimeHandler.postDelayed(OperatingTimeRunnable, 1000);
        list.clear();
        for (int i = 1; i < 13; i++) {
            if (i == 10) {
                list.add("X");
            } else if (i == 11) {
                list.add("0");
            } else {
                list.add(i + "");
            }
        }
        gridadapter = new Gridadapter(list, context);
        EnterIDNumberActivity_GridView.setAdapter(gridadapter);
        gridadapter.setListener(new Gridadapter.OnItemClickListener() {
            @Override
            public void onItemClick(String position) {
                OperatingTime = 30;
                if (position.equals("12")) {//删除
                    Editable editable = EnterIDNumberActivity_edit.getText();
                    EnterIDNumberActivity_edit.setSelection(EnterIDNumberActivity_edit.length());
                    int start = EnterIDNumberActivity_edit.getSelectionStart();
                    if (editable != null && editable.length() > 0 && start > 0) {
                        editable.delete(start - 1, start);
                    }
                } else {
                    String edit = EnterIDNumberActivity_edit.getText().toString();
                    EnterIDNumberActivity_edit.setText("");
                    EnterIDNumberActivity_edit.setText(edit + position);
                }
            }
        });
        //   initNet();
    }

    private void sendMessage(String Message) {
        AmpeActionDataBean ampeActionDataBean = ampeActionMap.get(ACTION_ENTERIDNUMBER);
        if (ampeActionDataBean == null) {
            AppLogUtils.e("ampeActionDataBean == null");
            return;
        }
        AmpeAppletResultBean bean = new AmpeAppletResultBean();
        bean.setAction(ACTION_ENTERIDNUMBER);
        bean.setEvent(ampeActionDataBean.getEvent());
        bean.setTaskId(ampeActionDataBean.getTaskId());
        bean.setSuccess(false);
        bean.setMessage(Message);
        AromeServiceInvoker.BridgeCallback bridgeCallback = ampeActionDataBean.getBridgeCallback();
        try {
            if (EnterWindowManager != null) {
                EnterWindowManager.removeView(EnterView);
                EnterWindowManager = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        OperatingTimeHandler.removeCallbacks(OperatingTimeRunnable);
        OperatingTimeHandler.removeCallbacksAndMessages(null);
        mHandler.removeCallbacks(runnableTime);
        mHandler.removeCallbacksAndMessages(null);
        // 回传处理结果给小程序
        try {
            JsonObject jsonObject = gson.toJsonTree(bean).getAsJsonObject();

            if (bridgeCallback != null) {
                bridgeCallback.callback(jsonObject.toString());
            }

            // 日志开始----------------begin
            // 日志行数——对应web端"日志标签"
            String logLine = (new Throwable().getStackTrace())[0].toString();
            // 日志节点
            String logNode = "ACTION_FACE--刷脸--用户三要素--回传处理结果给小程序--";
            // 日志内容
            StringBuilder logContentSb = new StringBuilder();
            logContentSb.append(logNode).append(WARP)
                    .append("jsonObject = ").append(jsonObject);

            // 开始保存本地日志
            AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
                    .append(LINE)
                    .append(logLine).append(WARP)
                    .append(NODE)
                    .append(logContentSb)
                    .toString()
            );

            // 开始网络在线日志
            LogcatAddRequestBean logBean = new LogcatAddRequestBean();
            logBean.setLogType(NET_LOGCAT);
            logBean.setLogTag(logLine + WARP + LOG_NODE_APPLET + LOG_NODE_FACE);
            logBean.setLogContent(logContentSb.toString());
            requestLogcatAdd(logBean);
            // 日志开始----------------end

            // 打印编译器输出日志
            AppLogUtils.e(logContentSb);


        } catch (Throwable t) {
            AppLogUtils.e("onCalled--t" + t);
        }
    }

    //点击确定进下网络请求
    private void sendEnterIDNumber(String IDNumber) {

        OperatingTimeType = "Loding";
        OperatingTime = 15;
        enterIDCard_Loding.setVisibility(View.VISIBLE);
        enterIDCard_RelativeLayout.setVisibility(View.GONE);
        enterIDCard_LodingText.setText("联网查询中……");
        enterIDCard_LodingText.setTextColor(getResources().getColor(R.color.f3D73FF));
        enterIDCard_LodingImageView.setBackgroundResource(R.mipmap.enter_idnumber_loding);
        //常口换取三要素
        long timecurrentTimeMillis = System.currentTimeMillis();
        Map<String, Object> params = new HashMap<>();
        params.put("sfzh", IDNumber);
        //公安网密钥
        DeviceConfigResultBean.ManualInIdCardAuthDTO manualInIdCardAuthDTO = new DeviceConfigResultBean.ManualInIdCardAuthDTO();
        deviceConfigBean.setManualInIdCardAuth(manualInIdCardAuthDTO);
        Map<String, Object> map = new HashMap<>();
        map.put("appId", deviceConfigBean.getManualInIdCardAuth().getAppId());
        map.put("bizContent", IdCardUtils.encrypt(
                deviceConfigBean.getManualInIdCardAuth().getPrivateKey(),
                JSON.toJSONString(params)
        ));
        map.put("reqTimestamp", timecurrentTimeMillis + "");
        map.put("sign", IdCardUtils.getSign(deviceConfigBean.getManualInIdCardAuth().getAppKey(),
                deviceConfigBean.getManualInIdCardAuth().getAppKey(),
                timecurrentTimeMillis + ""));
        AppLogUtils.i("常口输入请求入参 " + new Gson().toJson(map));
        mThreeElementsPresenter.ThreeElementsContract(map, "https://tx.hz-hanghui.com:8088/hanghui-server-platform/api/v1/open/user/sync/query");
    }
//判断activity是否在最上层
//    @Override
//    public void onWindowFocusChanged(boolean hasFocus) {
//        super.onWindowFocusChanged(hasFocus);
//        if (!hasFocus) {
//            Config.setFaceScenicUtile(faceScenicUtile, true);
//        } else {
//            Config.setFaceScenicUtile(faceScenicUtile, false);
//        }
//    }


    // BPaaSApi启动与否的标识
    private boolean isAPPStuter = true;

    /**
     * face——人脸1：N
     * personCard——人证1:1
     * Card——身份证
     * QrCard——二维码
     */
    private String CardOrCode = "face";


    private Handler timeHandler = new Handler();
    private Runnable heartBeatRunnable = new Runnable() {
        @Override
        public void run() {
            if (!ConfigData.taskStatus.equals("complete")) {
                CardOrCode = "face";
                ConfigData.taskStatus = "wait";
            }
            AppLogUtils.e("-----------------重启核点服务");
//            LocalremoveTouchView();
//            removeTouchView();

//            startBpaasService(ConfigData.getDeviceConfigResultBean().getTrade()trade, ConfigData.isNeed1V1, ConfigData.getDeviceConfigResultBean().getGroupId(), 0, ConfigData.mSessionId,
//                    ConfigData.machineAppId, "scanFace", false);
//            startBpaasService(ConfigData.getDeviceConfigResultBean().getTrade(), ConfigData.isNeed1V1, ConfigData.getDeviceConfigResultBean().getGroupId(), 0, ConfigData.mSessionId,
//                    ConfigData.getDeviceConfigResultBean().getAbcpAppId(), "scanFace", false);


            // 获取启动Bpaas刷脸的参数
            StartReadyBpaasServiceBean bpaasServiceBean = getStartReadyBpaasServiceBean();
            //启动核身服务
            startZfbBpaasService(bpaasServiceBean);

        }
    };


    RefreshPage resh = new RefreshPage();

    // 在线设备配置
    DeviceConfigResultBean deviceConfigBean;

    // 0000
    @Override
    public void showDeviceConfigData(DeviceConfigResultBean resultBean) {
        AppLogUtils.e("网络请求——在线配置返回结果");
        if (resultBean == null) {
            AppLogUtils.e("DeviceConfigResultBean--null，从本地中开始获取数据");
            DeviceConfigResultBean deviceConfigDataFromLocal = getDeviceConfigDataFromLocal();

            if (deviceConfigDataFromLocal == null) {
                AppLogUtils.e("从本地数据deviceConfigBean == null,return");
                return;
            } else {
                AppLogUtils.e("从本地数据deviceConfigBean有值");
                resultBean = deviceConfigDataFromLocal;
            }

        }

        // 日志开始----------------begin
        // 日志行数——对应web端"日志标签"
        String logLine = (new Throwable().getStackTrace())[0].toString();
        // 日志节点
        String logNode = "拉取在线配置结果---";
        // 日志内容
        StringBuilder logContentSb = new StringBuilder();
        logContentSb.append(logNode).append(WARP)
                .append("resultBean = ").append(resultBean.toString());

        // 开始保存本地日志
        AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
                .append(LINE)
                .append(logLine).append(WARP)
                .append(NODE)
                .append(logContentSb)
                .toString()
        );

        // 开始网络在线日志
        LogcatAddRequestBean bean = new LogcatAddRequestBean();
        bean.setLogType(NET_LOGCAT);
        // 对应web端"日志标签"
        bean.setLogTag(logLine + WARP + LOG_NODE_NET_CONFIG_QUERY);
        bean.setLogContent(logContentSb.toString());
        requestLogcatAdd(bean);
        // 日志开始----------------end


        setConfigStatusText("拉取在线配置成功");

        deviceConfigBean = resultBean;

        // 保存-内存
        ConfigData.setDeviceConfigResultBean(deviceConfigBean);
        // 保存-sp
        String deviceConfigBeanStr = gson.toJson(deviceConfigBean);
        localConfig.setDeviceConfigResultBeanStr(deviceConfigBeanStr);


        // 小程序通道
//        appletListen();


        // 刷脸配置
        boolean useAlipayFace = deviceConfigBean.isUseAlipayFace();
        AppLogUtils.e("useAlipayFace = " + useAlipayFace);
        if (useAlipayFace) {
            // 刷脸初始化——2.4.1放到ampe通道后建立
//            initAbcpFace();
        }

        // 二维码配置
        boolean useQrcode = deviceConfigBean.isUseQrcode();
        AppLogUtils.e("useQrcode = " + useQrcode);
        if (useQrcode) {
            /**
             * 刷二维码用
             * 开启串口
             */
            startQrCodeSeria();
        }


        startSeriaInductionLight();


        // 身份证配置
        boolean useIdcard = deviceConfigBean.isUseIdcard();
        AppLogUtils.e("useIdcard = " + useIdcard);

        idCardReaderBrand = deviceConfigBean.getIdCardReaderBrand();
        AppLogUtils.e("初始时idCardReaderBrand = " + idCardReaderBrand);
        if (idCardReaderBrand == null) {
            if (Constants.DeviceModel.D2.equals(deviceModel)) {
                // D2
                idCardReaderBrand = 2;
            } else if (Constants.DeviceModel.K8.equals(deviceModel)) {
                // K8
                idCardReaderBrand = 1;
            } else {
                idCardReaderBrand = 1;
            }
        }
        AppLogUtils.e("最终时idCardReaderBrand = " + idCardReaderBrand);

        if (useIdcard) {
            // 身份证
            initIDCard();
        }


        // 打印初始化
        if (iPrinter == null) {
            iPrinter = BasePrinter.getInstance().getPrinter(mContext);
        }

        iPrinter
                .initPrint(
                        new PrintInitResultCallback() {
                            @Override
                            public void onPrintInitSuccess() {
                                // 日志打印和保存（本地和网络）
                                logPrintSave(NET_LOGCAT,
                                        (new Throwable().getStackTrace())[0].toString(),
                                        "打印初始化---成功---",
                                        "model = " + deviceModel,
                                        "sn = " + localDeviceSN);


                                setConfigStatusText("打印初始化---成功---" + "model = " + deviceModel + " sn = " + localDeviceSN);

                            }

                            @Override
                            public void onPrintInitError(String errorCode, String errorMsg) {
                                // 日志打印和保存（本地和网络）
                                logPrintSave(NET_LOGCAT,
                                        (new Throwable().getStackTrace())[0].toString(),
                                        "打印初始化---失败---",
                                        "errorCode = " + errorCode,
                                        "errorMsg = " + errorMsg,
                                        "model = " + deviceModel,
                                        "sn = " + localDeviceSN
                                );

                                setConfigStatusText("打印初始化---失败---" + "errorCode = " + errorCode +
                                        " errorMsg = " + errorMsg +
                                        " model = " + deviceModel +
                                        " sn = " + localDeviceSN);

                            }
                        });


        // 禁止下拉通知栏 false-不启用(默认) true-启用
        forbidPullDown = deviceConfigBean.isForbidPullDown();
        AppLogUtils.e("下拉通知栏forbidPullDown--" + forbidPullDown);
        if (forbidPullDown) {
            iDeviceUI.hideNotification(mActivity);
        } else {
            iDeviceUI.showNotification(mActivity);
        }

        // 隐藏底部导航栏 false-不启用(默认) true-启用
        hideNavigationBar = deviceConfigBean.isHideNavigationBar();
        AppLogUtils.e("底部导航栏hideNavigationBar--" + hideNavigationBar);
        if (hideNavigationBar) {
            iDeviceUI.hideNavigationBar(mActivity);
        } else {
            iDeviceUI.showNavigationBar(mActivity);
        }


        boolean mirror = deviceConfigBean.isMirror();
        AppLogUtils.e("mirror--" + mirror);
        boolean displayMirror = deviceConfigBean.isDisplayMirror();
        AppLogUtils.e("displayMirror--" + displayMirror);

        // 主页图片
        try {
            if (StringUtils.isNotNull(deviceConfigBean.getHomePageUrl())) {
                GlideUtils.loadRelativeLayout(MainActivity.this, deviceConfigBean.getHomePageUrl(), item_root);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 启动页图片
        localConfig.setSplashImageUrl(deviceConfigBean.getStartPageUrl());


        // app自启动
        boolean autoLaunch = deviceConfigBean.isAutoLaunch();
        AppLogUtils.e("autoLaunch--" + autoLaunch);
        localConfig.setAutoApp(autoLaunch);


        // 设备心跳
        mHeartbeatPresenter = new HeartbeatPresenter(this);
        heartBeatRequestBean = new HeartBeatRequestBean();
        heartBeatRequestBean.setBizAppApkName(DeviceUtils.getAppPackageName(this));
        heartBeatRequestBean.setBizAppVersion(DeviceUtils.getAppVersionName(this));
        heartBeatRequestBean.setSn(localDeviceSN);
        heartBeatRequestBean.setHeartTrackingUrl(deviceConfigBean.getHeartTrackingUrl());
        mHeartbeatPresenter.requestHeartbeat(heartBeatRequestBean);

        // 设备在线心跳
        resh.mHandler.postDelayed(resh.runnableHeartbeat, TIME_HEARTBEAT);


        String appletName = deviceConfigBean.getAppName();
        // 小程序启动配置
        tv_enter_applet.setVisibility(View.GONE);
        tv_applet_name.setVisibility(View.GONE);
        boolean automaticEnterApplet = resultBean.isAutomaticEnterApplet();
        AppLogUtils.e("小程序启动automaticEnterApplet--" + automaticEnterApplet);


        if (automaticEnterApplet) {
            // 直接进入小程序
            // 初始化ampe   1111

//            initAndActive(resultBean);

            final DeviceConfigResultBean newResultBean = resultBean;

            // 为了身份证初始化成功
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    initAndActive(newResultBean);
                    // 如果未打开，那就是error1, no implement
                }
            }, 5 * 1000);


        } else {
            // 展示按钮
            tv_enter_applet.setVisibility(View.VISIBLE);
            tv_applet_name.setVisibility(View.VISIBLE);
            tv_applet_name.setText(appletName);
        }


        // 横屏D2的处理
        if (Constants.DeviceModel.D2.equals(deviceModel)) {
            tv_enter_applet.setText("点击进入" + appletName);
            tv_applet_name.setVisibility(View.GONE);
        }


    }

    private void startSeriaInductionLight() {

//        if(!deviceModel.equals(Constants.DeviceModel.T1YB01)){
//            // 非Y9
//            return;
//        }


        // 日志开始----------------begin
        // 日志行数——对应web端"日志标签"
        String logLine = (new Throwable().getStackTrace())[0].toString();
        // 日志节点
        String logNode = LOG_NODE_INFRARED_INDUCTION + "初始化---开始打开串口";
        // 日志内容
        StringBuilder logContentSb = new StringBuilder();
        logContentSb.append(logNode).append(WARP);

        // 开始保存本地日志
        AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
                .append(LINE)
                .append(logLine).append(WARP)
                .append(NODE)
                .append(logContentSb)
                .toString()
        );

        // 开始网络在线日志
        LogcatAddRequestBean logBean = new LogcatAddRequestBean();
        logBean.setLogType(NET_LOGCAT);
        logBean.setLogTag(logLine + WARP + LOG_NODE_INFRARED_INDUCTION);
        logBean.setLogContent(logContentSb.toString());
        requestLogcatAdd(logBean);
        // 日志开始----------------end


        isDisQrCodeQueue = true;
        InductionLightSerialControl sc = new InductionLightSerialControl();
        String pat = "";
        if (deviceModel.equals(Constants.DeviceModel.T1YB01)) {
            // 红外
            pat = "/dev/ttysWK2";
        } else if (deviceModel.equals(Constants.DeviceModel.F10)) {
            pat = "/dev/ttyHSL2";
        }
        AppLogUtils.e("--------------pat串口路径  " + pat);


        // 设置串口路径
        sc.setPort(pat);
        // 数据位，停止位，校验位
        sc.setN81("8", "1", "N");
        // 波特率
        sc.setBaudRate("9600");
        // 打开红外感应
        OpenInductionLightComPort(sc);

    }

    SerialHelper comPortInfraredInduction;

    public void OpenInductionLightComPort(SerialHelper comPort) {
        try {
            comPort.open();

            this.comPortInfraredInduction = comPort;
//            sendInductionInstruct(comPort);

            // 日志开始----------------begin
            // 日志行数——对应web端"日志标签"
            String logLine11 = (new Throwable().getStackTrace())[0].toString();
            // 日志节点
            String logNode11 = LOG_NODE_INFRARED_INDUCTION + "初始化---打开串口成功";
            // 日志内容
            StringBuilder logContentSb11 = new StringBuilder();
            logContentSb11.append(logNode11).append(WARP);

            // 开始保存本地日志
            AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
                    .append(LINE)
                    .append(logLine11).append(WARP)
                    .append(NODE)
                    .append(logContentSb11)
                    .toString()
            );

            // 开始网络在线日志
            LogcatAddRequestBean logBean11 = new LogcatAddRequestBean();
            logBean11.setLogType(NET_LOGCAT);
            logBean11.setLogTag(logLine11 + WARP + LOG_NODE_INFRARED_INDUCTION);
            logBean11.setLogContent(logContentSb11.toString());
            requestLogcatAdd(logBean11);
            // 日志开始----------------end

            AppLogUtils.e(logContentSb11);

        } catch (SecurityException e) {
            AppLogUtils.e("-----------打开串口失败:没有串口读/写权限");

            // 日志开始----------------begin
            // 日志行数——对应web端"日志标签"
            String logLine = (new Throwable().getStackTrace())[0].toString();
            // 日志节点
            String logNode = LOG_NODE_INFRARED_INDUCTION + "初始化---打开串口失败:没有串口读/写权限";
            // 日志内容
            StringBuilder logContentSb = new StringBuilder();
            logContentSb.append(logNode).append(WARP);

            // 开始保存本地日志
            AppLogUtils.saveLog(LogType.Error, new StringBuilder()
                    .append(LINE)
                    .append(logLine).append(WARP)
                    .append(NODE)
                    .append(logContentSb)
                    .toString()
            );

            // 开始网络在线日志
            LogcatAddRequestBean bean = new LogcatAddRequestBean();
            bean.setLogType(NET_ERROR);
            // 对应web端"日志标签"
            bean.setLogTag(logLine + WARP + LOG_NODE_INFRARED_INDUCTION);
            bean.setLogContent(logContentSb.toString());
            requestLogcatAdd(bean);
            // 日志开始----------------end


        } catch (IOException e) {
            AppLogUtils.e("-----------打开串口失败:未知错误");

            // 日志开始----------------begin
            // 日志行数——对应web端"日志标签"
            String logLine = (new Throwable().getStackTrace())[0].toString();
            // 日志节点
            String logNode = LOG_NODE_INFRARED_INDUCTION + "初始化---打开串口失败:未知错误";
            // 日志内容
            StringBuilder logContentSb = new StringBuilder();
            logContentSb.append(logNode).append(WARP);

            // 开始保存本地日志
            AppLogUtils.saveLog(LogType.Error, new StringBuilder()
                    .append(LINE)
                    .append(logLine).append(WARP)
                    .append(NODE)
                    .append(logContentSb)
                    .toString()
            );

            // 开始网络在线日志
            LogcatAddRequestBean bean = new LogcatAddRequestBean();
            bean.setLogType(NET_ERROR);
            // 对应web端"日志标签"
            bean.setLogTag(logLine + WARP + LOG_NODE_INFRARED_INDUCTION);
            bean.setLogContent(logContentSb.toString());
            requestLogcatAdd(bean);
            // 日志开始----------------end

        } catch (InvalidParameterException e) {
            AppLogUtils.e("-----------打开串口失败:参数错误");

            // 日志开始----------------begin
            // 日志行数——对应web端"日志标签"
            String logLine = (new Throwable().getStackTrace())[0].toString();
            // 日志节点
            String logNode = LOG_NODE_INFRARED_INDUCTION + "初始化---打开串口失败:参数错误";
            // 日志内容
            StringBuilder logContentSb = new StringBuilder();
            logContentSb.append(logNode).append(WARP);

            // 开始保存本地日志
            AppLogUtils.saveLog(LogType.Error, new StringBuilder()
                    .append(LINE)
                    .append(logLine).append(WARP)
                    .append(NODE)
                    .append(logContentSb)
                    .toString()
            );

            // 开始网络在线日志
            LogcatAddRequestBean bean = new LogcatAddRequestBean();
            bean.setLogType(NET_ERROR);
            // 对应web端"日志标签"
            bean.setLogTag(logLine + WARP + LOG_NODE_INFRARED_INDUCTION);
            bean.setLogContent(logContentSb.toString());
            requestLogcatAdd(bean);
            // 日志开始----------------end

        }
    }

    Timer timer;
    TimerTask inductionTimerTask;

    // 发送红外感应指令
    public void sendInductionInstruct(SerialHelper comPort, Integer infraredInductionIntervalTime) {

        comPort.startSend();

        timer = new Timer();
        inductionTimerTask = new TimerTask() {
            @Override
            public void run() {
                AppLogUtils.i("红外感应发送");
                // 转换数据后发送
                comPort.send(INDUCTION_INSTRUCT.getBytes());

            }
        };
        timer.schedule(inductionTimerTask, 1000, infraredInductionIntervalTime);


    }

    // 关闭红外感应消息发送
    boolean isCloseInfraredInductionMessage;


    private List<ComBean> inductionLightQueueList = new ArrayList();

    public class InductionLightSerialControl extends SerialHelper {
        public InductionLightSerialControl() {
        }

        @Override
        protected void onDataReceived(final ComBean ComRecData) {
            AppLogUtils.e("-----------原始数据 bRec  " + new Gson().toJson(ComRecData.bRec));
            inductionLightQueueList.add(ComRecData);
            AppLogUtils.e("-------数据处理后  " + MyFunc.ByteArrToHex(ComRecData.bRec));

//            String str = new String(ComRecData.bRec, java.nio.charset.StandardCharsets.UTF_8);
//            AppLogUtils.e("-------数据Str  " +str);


            String result = new String(ComRecData.bRec, java.nio.charset.StandardCharsets.UTF_8);
            AppLogUtils.e("----------inductionLightQueueList结果bRec  " + result);

            String handleResult = "";
            if (result.equals(INDUCTION_PEOPLE_YES)) {
                handleResult = "1";
            } else if (result.equals(INDUCTION_PEOPLE_NO)) {
                handleResult = "0";
            } else {
                //
                handleResult = "-1";
            }

            AppLogUtils.e("isCloseInfraredInductionMessage:" + isCloseInfraredInductionMessage);

            if (isCloseInfraredInductionMessage) {

            } else {
                // 准备数据发送
                JSONObject object = new JSONObject();
                try {
                    // 勿动key，对外的文档key
                    object.put(INDUCTION_CODE, handleResult);
                } catch (Throwable t) {

                }
                // 主动推送给小程序
                sendMessageToApplet(EVENT_INFRARED_INDUCTION_LISTENER, object.toString());
            }


            // 日志开始----------------begin
            // 日志行数——对应web端"日志标签"
            String logLine = (new Throwable().getStackTrace())[0].toString();
            // 日志节点
            String logNode = LOG_NODE_INFRARED_INDUCTION + "结果";
            // 日志内容
            StringBuilder logContentSb = new StringBuilder();
            logContentSb.append(logNode).append(WARP)
                    .append("原始数据 = ").append(new Gson().toJson(ComRecData.bRec)).append(WARP)
                    .append("原始数据MyFunc转换 = ").append(MyFunc.ByteArrToHex(ComRecData.bRec))
                    .append("原始数据转换result = ").append(result);


            // 开始保存本地日志
            AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
                    .append(LINE)
                    .append(logLine).append(WARP)
                    .append(NODE)
                    .append(logContentSb)
                    .toString()
            );

            // 开始网络在线日志
            LogcatAddRequestBean bean = new LogcatAddRequestBean();
            bean.setLogType(NET_LOGCAT);
            bean.setLogTag(logLine + WARP + LOG_NODE_INFRARED_INDUCTION);
            bean.setLogContent(logContentSb.toString());
            requestLogcatAdd(bean);
            // 日志开始----------------end


        }

        //尝试进行转换
        @Override
        protected void DoQueue() {
            if (inductionLightQueueList.size() > 0) {
//                for (int i = 0; i < qrCodeQueueList.size(); i++) {
//                    qrData = qrData + new String(qrCodeQueueList.get(i).bRec);
//                }
//                AppLogUtils.e("-----------QrCodeSerialControl二维码结果  " + qrData);
                String result = new String(inductionLightQueueList.get(0).bRec);
                AppLogUtils.e("----------inductionLightQueueList结果bRec  " + result);


                String handleResult = "";
                if (result.equals(INDUCTION_PEOPLE_YES)) {
                    handleResult = "1";
                } else if (result.equals(INDUCTION_PEOPLE_NO)) {
                    handleResult = "0";
                } else {
                    //
                    handleResult = "-1";
                }

                // 日志开始----------------begin
                // 日志行数——对应web端"日志标签"
                String logLine = (new Throwable().getStackTrace())[0].toString();
                // 日志节点
                String logNode = LOG_NODE_INFRARED_INDUCTION + "结果";
                // 日志内容
                StringBuilder logContentSb = new StringBuilder();
                logContentSb.append(logNode).append(WARP)
                        .append("转换后的数据 = ").append(result)
                        .append("最后处理后的数据 = ").append(handleResult);

                // 开始保存本地日志
                AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
                        .append(LINE)
                        .append(logLine).append(WARP)
                        .append(NODE)
                        .append(logContentSb)
                        .toString()
                );

                // 开始网络在线日志
                LogcatAddRequestBean bean = new LogcatAddRequestBean();
                bean.setLogType(NET_LOGCAT);
                // 对应web端"日志标签"
                bean.setLogTag(logLine + WARP + LOG_NODE_INFRARED_INDUCTION);
                bean.setLogContent(logContentSb.toString());
                requestLogcatAdd(bean);
                // 日志开始----------------end


                JSONObject object = new JSONObject();
                try {
                    // 勿动key，对外的文档key
                    object.put(INDUCTION_CODE, handleResult);
                } catch (Throwable t) {

                }
                // 主动推送给小程序
                sendMessageToApplet(EVENT_INFRARED_INDUCTION_LISTENER, object.toString());


                inductionLightQueueList.clear();
            }
        }
    }


    boolean forbidPullDown;
    boolean hideNavigationBar;


    private DeviceConfigResultBean getDeviceConfigDataFromLocal() {
        String deviceConfigResultBeanStr = localConfig.getDeviceConfigResultBeanStr("");
        if (StringUtils.isNotNull(deviceConfigResultBeanStr)) {
            deviceConfigBean = gson.fromJson(deviceConfigResultBeanStr, DeviceConfigResultBean.class);
            return deviceConfigBean;
        }
        return null;
    }


    @Override
    public void showLoading() {

    }

    @Override
    public void dismissLoading() {

    }

    @Override
    public void showError(String msg) {
//        ToastUtils.showLongToast(msg + "");

        // 日志开始----------------begin
        // 日志行数——对应web端"日志标签"
//        String logLine = (new Throwable().getStackTrace())[0].toString();
//        // 日志节点
//        String logNode = "网络请求结果异常---";
//        // 日志内容
//        StringBuilder logContentSb = new StringBuilder();
//        logContentSb.append(logNode).append(WARP)
//                .append("msg = ").append(msg);
//
//        // 开始保存本地日志
//        AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
//                .append(LINE)
//                .append(logLine).append(WARP)
//                .append(NODE)
//                .append(logContentSb)
//                .toString()
//        );
//
//        // 开始网络在线日志
//        LogcatAddRequestBean bean = new LogcatAddRequestBean();
//        bean.setLogType(NET_LOGCAT);
//        // 对应web端"日志标签"
//        bean.setLogTag(logLine + WARP + LOG_NODE_NET);
//        bean.setLogContent(logContentSb.toString());
//        requestLogcatAdd(bean);
        // 日志开始----------------end

    }

    @Override
    public void showError(String url, String msg) {
        AppLogUtils.e("showError--url:" + url + "   msg:" + msg);

//        setConfigStatusText(msg + "");

        netLogcatSave(url, msg);

        if (url.contains(API_CONFIG_QUERY)) {
            // 在线配置
            DeviceConfigResultBean deviceConfigDataFromLocal = getDeviceConfigDataFromLocal();
            if (deviceConfigDataFromLocal != null) {
                showDeviceConfigData(deviceConfigDataFromLocal);
            }
            setConfigStatusText(msg + "");
        }


        if (url.contains("faceAuth") || msg.contains("不相符")) {
            // 获取用户三要素

            AmpeActionDataBean ampeActionDataBean = null;
            String action = "";
            if (isInitFace && isFacePersonCard) {
                // 初始化成功，且是1:1
                AppLogUtils.e("BPaaSApi--startBpaasService--onEvent--isInitFace & isFacePersonCard");
                ampeActionDataBean = ampeActionMap.get(ACTION_FACE_PERSONCARD);
                action = ACTION_FACE_PERSONCARD;
            } else if (isInitFace) {
                AppLogUtils.e("BPaaSApi--startBpaasService--onEvent--isInitFace");
                ampeActionDataBean = ampeActionMap.get(ACTION_FACE);
                action = ACTION_FACE;
            } else if (isJxInitFace) {
                AppLogUtils.e("BPaaSApi--startBpaasService--onEvent--isJxInitFace");
                ampeActionDataBean = ampeActionMap.get(ACTION_SCAN_FACE);
                action = ACTION_SCAN_FACE;
            }

            if (ampeActionDataBean == null) {
                AppLogUtils.e("showAlipayUserInfoResult---ampeActionDataBean == null");
                return;
            }

            AmpeAppletResultBean bean = new AmpeAppletResultBean();
            bean.setAction(action);
            bean.setEvent(ampeActionDataBean.getEvent());
            bean.setTaskId(ampeActionDataBean.getTaskId());
            bean.setSuccess(false);
            bean.setMessage(msg);

            AromeServiceInvoker.BridgeCallback bridgeCallback = ampeActionDataBean.getBridgeCallback();

            // 回传处理结果给小程序
            try {
                JsonObject jsonObject = gson.toJsonTree(bean).getAsJsonObject();

                if (bridgeCallback != null) {
                    bridgeCallback.callback(jsonObject.toString());
                }

                // 日志开始----------------begin
                // 日志行数——对应web端"日志标签"
                String logLine = (new Throwable().getStackTrace())[0].toString();
                // 日志节点
                String logNode = "ACTION_FACE--刷脸--用户三要素--回传处理结果给小程序--";
                // 日志内容
                StringBuilder logContentSb = new StringBuilder();
                logContentSb.append(logNode).append(WARP)
                        .append("jsonObject = ").append(jsonObject);

                // 开始保存本地日志
                AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
                        .append(LINE)
                        .append(logLine).append(WARP)
                        .append(NODE)
                        .append(logContentSb)
                        .toString()
                );

                // 开始网络在线日志
                LogcatAddRequestBean logBean = new LogcatAddRequestBean();
                logBean.setLogType(NET_LOGCAT);
                logBean.setLogTag(logLine + WARP + LOG_NODE_APPLET + LOG_NODE_FACE);
                logBean.setLogContent(logContentSb.toString());
                requestLogcatAdd(logBean);
                // 日志开始----------------end

                // 打印编译器输出日志
                AppLogUtils.e(logContentSb);


            } catch (Throwable t) {
                AppLogUtils.e("onCalled--t" + t);
            }

            // 重置
            isFacePersonCard = false;

            // 重新唤起刷脸
            invokeResume();


        }


    }

    private void netLogcatSave(String url, String msg) {

        // 防止无网络时，一直写入日志和请求在线日志
        if (netLogcatNum > 3) {
            return;
        }

        netLogcatNum++;
        // 日志开始----------------begin
        // 日志行数——对应web端"日志标签"
        String logLine = (new Throwable().getStackTrace())[0].toString();
        // 日志节点
        String logNode = "网络请求结果异常---";
        // 日志内容
        StringBuilder logContentSb = new StringBuilder();
        logContentSb.append(logNode).append(WARP)
                .append("url = ").append(url).append(WARP)
                .append("msg = ").append(msg);

        // 开始保存本地日志
        AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
                .append(LINE)
                .append(logLine).append(WARP)
                .append(NODE)
                .append(logContentSb)
                .toString()
        );

        // 开始网络在线日志
        LogcatAddRequestBean bean = new LogcatAddRequestBean();
        bean.setLogType(NET_LOGCAT);
        // 对应web端"日志标签"
        bean.setLogTag(logLine + WARP + LOG_NODE_NET);
        bean.setLogContent(logContentSb.toString());
        requestLogcatAdd(bean);
        // 日志开始----------------end
    }

    @Override
    public void showHeartbeatResult(SimpleResultBean resultBean) {

        // 日志
//        String heartbeatUrl = "";
//        if (deviceConfigBean != null && deviceConfigBean.getHeartTrackingUrl() != null) {
//            heartbeatUrl = deviceConfigBean.getHeartTrackingUrl();
//        }
//
//        // 日志开始----------------begin
//        // 日志行数——对应web端"日志标签"
//        String logLine = (new Throwable().getStackTrace())[0].toString();
//        // 日志节点
//        String logNode = "设备心跳---";
//        // 日志内容
//        StringBuilder logContentSb = new StringBuilder();
//        logContentSb.append(logNode).append(WARP)
//                .append("url = ").append(heartbeatUrl).append(WARP)
//                .append("msg = ").append("成功");
//
//        // 开始保存本地日志
//        AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
//                .append(LINE)
//                .append(logLine).append(WARP)
//                .append(NODE)
//                .append(logContentSb)
//                .toString()
//        );
//
//        // 开始网络在线日志
//        LogcatAddRequestBean bean = new LogcatAddRequestBean();
//        bean.setLogType(NET_LOGCAT);
//        // 对应web端"日志标签"
//        bean.setLogTag(logLine + WARP + LOG_NODE_NET_HEARTBEAT);
//        bean.setLogContent(logContentSb.toString());
//        requestLogcatAdd(bean);
//        // 日志开始----------------end
    }

    // 在线日志
    public void requestLogcatAdd(LogcatAddRequestBean bean) {

        if (mLogcatAddPresenter == null) {
            mLogcatAddPresenter = new LogcatAddPresenter(this);
        }

        bean.setToken(TOKEN);
        bean.setSn(DeviceUtils.getDeviceSN());

        if (isNetAvailable) {
            mLogcatAddPresenter.requestLogcatAdd(bean);
        }

    }


    @Override
    public void showLogcatAddResult(SimpleResultBean resultBean) {

    }


    /**
     * 获取用户三要素
     * 刷脸1:1和1：N，只要后台开关开了，都会走这里
     *
     * @param alipayUserInfoBeanData
     */
    @Override
    public void showAlipayUserInfoResult(AlipayUserInfoResultBean alipayUserInfoBeanData) {
        AppLogUtils.e("showAlipayUserInfoResult--" + alipayUserInfoBeanData.toString());

        // 重新唤起刷脸
//        invokeResume();

//        AlipayUserInfoResultBean.DataDTO alipayUserInfoBeanData = resultBean.getData();
        String userName = alipayUserInfoBeanData.getUserName();
        String certNo = alipayUserInfoBeanData.getCertNo();
        AppLogUtils.e("showAlipayUserInfoResult---userName:" + userName);
        ConfigData.taskStatus = "wait";

        if (StringUtils.isNotNull(userName)) {
            this.certName = userName;
        }

        if (StringUtils.isNotNull(certNo)) {
            this.certNo = certNo;
        }

//                    ToastUtils.showLongToast("刷脸成功:" + userName + "  " + certNo);


        AmpeActionDataBean ampeActionDataBean = null;
        String action = "";
        if (CardOrCode.equals("personCard")) {
            // 初始化成功，且是1:1
            AppLogUtils.e("showAlipayUserInfoResult--personCard");
            ampeActionDataBean = ampeActionMap.get(ACTION_FACE_PERSONCARD);
            action = ACTION_FACE_PERSONCARD;
        } else if (CardOrCode.equals("face")) {
            // 初始化成功，且是1:N
            AppLogUtils.e("showAlipayUserInfoResult--face");
            ampeActionDataBean = ampeActionMap.get(ACTION_FACE);
            action = ACTION_FACE;
        }


        if (ampeActionDataBean == null) {
            // 一般都是
            AppLogUtils.e("showAlipayUserInfoResult---ampeActionDataBean == null");
            return;
        }
        AromeServiceInvoker.BridgeCallback bridgeCallback = ampeActionDataBean.getBridgeCallback();

        AmpeAppletResultBean bean = new AmpeAppletResultBean();
        bean.setAction(action);
        bean.setEvent(ampeActionDataBean.getEvent());
        bean.setTaskId(ampeActionDataBean.getTaskId());
        bean.setSuccess(true);
        bean.setMessage("成功");


        AmpeAppletResultBean.Data dataBean = new AmpeAppletResultBean.Data();
        dataBean.setIdNum(this.certNo);
        dataBean.setName(this.certName);
        dataBean.setUserId(alipayUserInfoBeanData.getUserId());
        dataBean.setMobile(alipayUserInfoBeanData.getMobile());
        dataBean.setAvatar(alipayUserInfoBeanData.getAvatar());
        dataBean.setPhotoBase64(alipayUserInfoBeanData.getPhotoBase64());

        bean.setData(dataBean);

        // 回传处理结果给小程序
        try {
            JsonObject jsonObject = gson.toJsonTree(bean).getAsJsonObject();

            if (bridgeCallback != null) {
                bridgeCallback.callback(jsonObject.toString());
            }

            // 日志开始----------------begin
            // 日志行数——对应web端"日志标签"
            String logLine = (new Throwable().getStackTrace())[0].toString();
            // 日志节点
            String logNode = "ACTION_FACE--刷脸--用户三要素--回传处理结果给小程序--";
            // 日志内容
            StringBuilder logContentSb = new StringBuilder();
            logContentSb.append(logNode).append(WARP)
                    .append("jsonObject = ").append(jsonObject);

            // 开始保存本地日志
            AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
                    .append(LINE)
                    .append(logLine).append(WARP)
                    .append(NODE)
                    .append(logContentSb)
                    .toString()
            );

            // 开始网络在线日志
            LogcatAddRequestBean logBean = new LogcatAddRequestBean();
            logBean.setLogType(NET_LOGCAT);
            logBean.setLogTag(logLine + WARP + LOG_NODE_APPLET + LOG_NODE_FACE);
            logBean.setLogContent(logContentSb.toString());
            requestLogcatAdd(logBean);
            // 日志开始----------------end

            // 打印编译器输出日志
            AppLogUtils.e(logContentSb);


        } catch (Throwable t) {
            AppLogUtils.e("onCalled--t" + t);
        }


    }


    class RefreshPage {
        Handler mHandler = new Handler();
        Runnable runnableTime = new Runnable() {
            @Override
            public void run() {
                // 设置最新时间
                tv_time.setText(DateUtil.getTime("yyyy.MM.dd HH:mm:ss") + " " + DateUtil.getWeekOfDate(new Date()));
                // 接着发送刷新任务
                mHandler.postDelayed(runnableTime, 1000);
            }
        };


        Runnable runnableHeartbeat = new Runnable() {
            @Override
            public void run() {
                mHandler.postDelayed(runnableHeartbeat, TIME_HEARTBEAT);
                mHeartbeatPresenter.requestHeartbeat(heartBeatRequestBean);
            }
        };

    }


    private final IpcListener mIpcListener = new IpcListener() {
        @Override
        public void onConnected(IpcChannel ipcChannel) {
            //启动核身服务
//            startBpaasService(ConfigD.trade, true, Config.GroupID, 0, Config.mSessionId,
//                    Config.machineAppId, "scanFace", false);
//            startBpaasService(ConfigData.getDeviceConfigResultBean().getTrade(), true, ConfigData.getDeviceConfigResultBean().getGroupId(), 0, ConfigData.mSessionId,
//                    ConfigData.getDeviceConfigResultBean().getAbcpAppId(), "scanFace", false);


            // 获取启动Bpaas刷脸的参数
            StartReadyBpaasServiceBean bpaasServiceBean = getStartReadyBpaasServiceBean();
            //启动核身服务
            startZfbBpaasService(bpaasServiceBean);


        }

        @Override
        public void onDisconnected(IpcChannel ipcChannel) {
        }

        @Override
        public void onConnectionFailed(IpcChannel ipcChannel) {
        }
    };


    String bPassErrorMessage = "";

    private void initAbcpFace() {
        Bundle extInfo = new Bundle();
        extInfo.putLong(BPaaSApi.KEY_EXT_TIME_OUT, 2 * 60 * 600);

        // test1
//        extInfo.putString("scopes", "auth_user,order_service");

        // MachineAppId 对应 abcpAppId

        // 日志开始----------------begin
        // 日志行数——对应web端"日志标签"
        String logLine = (new Throwable().getStackTrace())[0].toString();
        // 日志节点
        String logNode = "abcp--BPaaSApi--刷脸初始化入参---";
        // 日志内容
        StringBuilder logContentSb = new StringBuilder();
        logContentSb.append(logNode).append(WARP)
                .append("APP_ID = ").append(ConfigData.getDeviceConfigResultBean().getAbcpAppId()).append(WARP)
                .append("APP_VERION = ").append(ConfigData.appVersionBPaaS).append(WARP)
                .append("extInfo = ").append(new Gson().toJson(extInfo));

        // 开始保存本地日志
        AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
                .append(LINE)
                .append(logLine).append(WARP)
                .append(NODE)
                .append(logContentSb)
                .toString()
        );

        // 开始网络在线日志
        LogcatAddRequestBean bean = new LogcatAddRequestBean();
        bean.setLogType(NET_LOGCAT);
        // 对应web端"日志标签"
        bean.setLogTag(logLine + WARP + LOG_NODE_FACE);
        bean.setLogContent(logContentSb.toString());
        requestLogcatAdd(bean);
        // 日志开始----------------end


        AppLogUtils.e(logContentSb);

        BPaaSApi.getInstance().init(MyApplication.getContext(), ConfigData.getDeviceConfigResultBean().getAbcpAppId(), ConfigData.appVersionBPaaS, extInfo,
                new BPaaSInitCallback() {
                    @Override
                    public void onSuccess() {

                        AppLogUtils.e("init--FACE--onSuccess");

                        setConfigStatusText("BPaaSApi--刷脸初始化成功");

                        //添加IpcListener,用于监听与刷脸smile的连接,便于业务自愈
                        InnerApi.addIpcListener(mIpcListener);
                        Handler handler = new Handler();
                        String finalMSessionId1 = ConfigData.mSessionId;
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
//                                Main_APPStuter.setText("SDK初始化成功");
                                isAPPStuter = true;
                                //启动核身服务
//                                startBpaasService(ConfigData.getDeviceConfigResultBean().getTrade(), ConfigData.isNeed1V1, ConfigData.getDeviceConfigResultBean().getGroupId(), 0, ConfigData.mSessionId,
//                                        ConfigData.getDeviceConfigResultBean().getAbcpAppId(), "scanFace", false);

                                // startBpaasService00
                                // 获取启动Bpaas刷脸的参数
                                StartReadyBpaasServiceBean bpaasServiceBean = getStartReadyBpaasServiceBean();
                                //启动核身服务
                                startZfbBpaasService(bpaasServiceBean);


                            }
                        }, 500); // 延时3s执行run内代码


                        // 日志开始----------------begin
                        // 日志行数——对应web端"日志标签"
                        String logLine = (new Throwable().getStackTrace())[0].toString();
                        // 日志节点
                        String logNode = "BPaaSApi--init---onSuccess--刷脸初始化成功---";
                        // 日志内容
                        StringBuilder logContentSb = new StringBuilder();
                        logContentSb.append(logNode).append(WARP);

                        // 开始保存本地日志
                        AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
                                .append(LINE)
                                .append(logLine).append(WARP)
                                .append(NODE)
                                .append(logContentSb)
                                .toString()
                        );

                        // 开始网络在线日志
                        LogcatAddRequestBean bean = new LogcatAddRequestBean();
                        bean.setLogType(NET_LOGCAT);
                        // 对应web端"日志标签"
                        bean.setLogTag(logLine + WARP + LOG_NODE_FACE);
                        bean.setLogContent(logContentSb.toString());
                        requestLogcatAdd(bean);
                        // 日志开始----------------end

                        AppLogUtils.e(logContentSb);


                        sendInitFaceMessage();


                    }

                    @Override
                    public void onFail(String errorMessage) {
                        // E69003
                        AppLogUtils.e("BPaaSApi--init--onFail--errorMessage = " + errorMessage);

                        bPassErrorMessage = errorMessage;


                        // 日志开始----------------begin
                        // 日志行数——对应web端"日志标签"
                        String logLine = (new Throwable().getStackTrace())[0].toString();
                        // 日志节点
                        String logNode = "BPaaSApi--刷脸初始化失败---";
                        // 日志内容
                        StringBuilder logContentSb = new StringBuilder();
                        logContentSb.append(logNode).append(WARP)
                                .append("onFail---").append(WARP)
                                .append("errorMessage = ").append(errorMessage);

                        // 开始保存本地日志
                        AppLogUtils.saveLog(LogType.Error, new StringBuilder()
                                .append(LINE)
                                .append(logLine).append(WARP)
                                .append(NODE)
                                .append(logContentSb)
                                .toString()
                        );

                        // 开始网络在线日志
                        LogcatAddRequestBean bean = new LogcatAddRequestBean();
                        bean.setLogType(NET_ERROR);
                        // 对应web端"日志标签"
                        bean.setLogTag(logLine + WARP + LOG_NODE_FACE);
                        bean.setLogContent(logContentSb.toString());
                        requestLogcatAdd(bean);
                        // 日志开始----------------end


                    }
                });

        // 超过2秒不报fail，就认为初始化成功
        mMainHandler.postDelayed(new Runnable() {
            @Override
            public void run() {

                AppLogUtils.e("sendInitFaceMessage = 0");

                if (isInitFace) {

                    // 注释，等真正初始化成功
//                    sendInitFaceMessage();

                } else if (isJxInitFace) {
                    AppLogUtils.e("isJxInitFace");
                    // 江西，初始化完后直接刷脸
                    StartReadyBpaasServiceBean bpaasServiceBean = getStartReadyBpaasServiceBean();
                    invokeScanFace(bpaasServiceBean);
                }


            }
        }, 2000);


    }

    private void sendInitFaceMessage() {


        AmpeActionDataBean ampeActionDataBean = ampeActionMap.get(ACTION_INIT_FACE);
        if (ampeActionDataBean == null) {
            AppLogUtils.e("ampeActionDataBean == null");
            return;
        }
        AromeServiceInvoker.BridgeCallback bridgeCallback = ampeActionDataBean.getBridgeCallback();

        AmpeAppletResultBean initFaceBean = new AmpeAppletResultBean();
        initFaceBean.setAction(ACTION_INIT_FACE);
        initFaceBean.setEvent(ampeActionDataBean.getEvent());
        initFaceBean.setTaskId(ampeActionDataBean.getTaskId());

        if (StringUtils.isNull(bPassErrorMessage)) {
            initFaceBean.setSuccess(true);
            initFaceBean.setMessage("成功");
        } else {
            initFaceBean.setSuccess(false);
            initFaceBean.setMessage(bPassErrorMessage);
        }


        AmpeAppletResultBean.Data dataBean = new AmpeAppletResultBean.Data();
        initFaceBean.setData(dataBean);

        // 回传处理结果给小程序
        try {
            JsonObject jsonObject = gson.toJsonTree(initFaceBean).getAsJsonObject();

            if (bridgeCallback != null) {
                bridgeCallback.callback(jsonObject.toString());
            }


            // 日志开始----------------begin
            // 日志行数——对应web端"日志标签"
            String logLineInitFace = (new Throwable().getStackTrace())[0].toString();
            // 日志节点
            String logNodeInitFace = "ACTION_INIT_FACE--刷脸--startBPaaSService--";
            // 日志内容
            StringBuilder logContentSbInitFace = new StringBuilder();
            logContentSbInitFace.append(logNodeInitFace).append(WARP)
                    .append("jsonObject = ").append(jsonObject);

            // 开始保存本地日志
            AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
                    .append(LINE)
                    .append(logLineInitFace).append(WARP)
                    .append(NODE)
                    .append(logContentSbInitFace)
                    .toString()
            );


            // 开始网络在线日志
            LogcatAddRequestBean logBeanInitFace = new LogcatAddRequestBean();
            logBeanInitFace.setLogType(NET_LOGCAT);
            logBeanInitFace.setLogTag(logLineInitFace + WARP + LOG_NODE_APPLET + LOG_NODE_FACE);
            logBeanInitFace.setLogContent(logContentSbInitFace.toString());
            requestLogcatAdd(logBeanInitFace);
            // 日志开始----------------end

            // 打印编译器输出日志
            AppLogUtils.e(logContentSbInitFace);


        } catch (Throwable t) {
            AppLogUtils.e("onCalled--t" + t);
        }


    }

    private StartReadyBpaasServiceBean getStartReadyBpaasServiceBean() {
        DeviceConfigResultBean deviceConfigResultBean = ConfigData.getDeviceConfigResultBean();
        if (deviceConfigResultBean == null) {
            deviceConfigResultBean = new DeviceConfigResultBean();
        }

        StartReadyBpaasServiceBean bpaasServiceBean = new StartReadyBpaasServiceBean();
        bpaasServiceBean.setTrade(deviceConfigResultBean.getTrade());
        bpaasServiceBean.setNeed1v1(ConfigData.isNeed1V1);
        bpaasServiceBean.setCheckWay(ConfigData.checkWay);

        bpaasServiceBean.setMerchantAppId(deviceConfigResultBean.getServiceAppId());
//        bpaasServiceBean.setMerchantAppId("2021004108612349");


        bpaasServiceBean.setmSessionId(ConfigData.mSessionId);

        bpaasServiceBean.setServiceId(ConfigData.serviceId);
        bpaasServiceBean.setQuery(ConfigData.query);
        bpaasServiceBean.setScope(ConfigData.scope);
        AppLogUtils.e("ConfigData.scopes = " + ConfigData.scope);


        return bpaasServiceBean;
    }

    String mSessionId;


    boolean startBPaaSServiceFlag;

//    public void startBpaasService(String trade, boolean need1v1, String groupId, int scanFaceCheckWay, String mSessionId
//            , String machineAppId, String checkWay, boolean OnlyBPaas) {

    public void startZfbBpaasService(StartReadyBpaasServiceBean bpaasServiceBean) {

        AppLogUtils.e("BPaaSApi--startBpaasService");
//        AppLogUtils.e("BPaaSApi--startBpaasService--machineAppId = " + ConfigData.getDeviceConfigResultBean().getAbcpAppId());
//        AppLogUtils.e("BPaaSApi--startBpaasService--trade = " + bpaasServiceBean.getTrade());
        AppLogUtils.e("BPaaSApi--startBpaasService--bpaasServiceBean = " + bpaasServiceBean.toString());

//        if (mSessionId != null || (!mSessionId.equals(""))) {
////            stopBpaasService(mSessionId, faceScenicUtile);
//            return;
//        }

        Bundle params = new Bundle();
        params.putString("trade", bpaasServiceBean.getTrade());
        params.putBoolean("need1v1", bpaasServiceBean.isNeed1v1());
        params.putString("checkWay", bpaasServiceBean.getCheckWay());

        //这里 xxxxx 需替换成 isv 自己的需要授权的 merchantAppId
        params.putString("merchantAppId", bpaasServiceBean.getMerchantAppId());


        try {
            JSONObject extInfo = new JSONObject();

            // 聚合授权-------begin
            String serviceId = bpaasServiceBean.getServiceId();
            AppLogUtils.e("serviceId = " + serviceId);
            if (StringUtils.isNotNull(serviceId)) {
                extInfo.put("serviceId", serviceId);
            }

            String query = bpaasServiceBean.getQuery();
            AppLogUtils.e("query = " + query);
            if (StringUtils.isNotNull(query)) {
                extInfo.put("query", query);
            }

            // 信息授权组件scope
            String scope = bpaasServiceBean.getScope();
            AppLogUtils.e("scope = " + scope);
            if (StringUtils.isNotNull(scope)) {
                extInfo.put("scope", scope);
                // 注意，如果字符串之间有空格，会导致invoke刷脸失败1001
//            extInfo.put("scope", "auth_user, order_service");
                // 正确示例
//            extInfo.put("scope", "auth_user,order_service");
            }


//            if(!extInfo.has("scope")){
//                AppLogUtils.e("不包含scope");
//                try {
//                    extInfo.put("scope", "auth_user,order_service");
////            extInfo.put("scope", "auth_user,yingpin");
////            extInfo.put("scope", bpaasServiceBean.getScope());
////                    params.putString("extInfo", extInfo.toString());
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//            }


            // 聚合授权-------end

            AppLogUtils.e("displayHeight:" + displayHeight);
            AppLogUtils.e("displayWidth:" + displayWidth);


            if (Constants.DeviceModel.D2.equals(deviceModel)) {

                AppLogUtils.e("displayHeight:" + displayHeight);
                AppLogUtils.e("displayWidth:" + displayHeight * 0.625);
                AppLogUtils.e("displayX:" + (displayWidth - (displayHeight * 0.625)) / 2);

                // D2访客机刷脸屏幕设置-----begin
                // 是否悬浮，默认false
                extInfo.put("isFloat", true);
                // 显示X偏移，默认0    （宽度-刷脸界面宽度）/2   越大越往右边偏移
                extInfo.put("displayX", (displayWidth - (displayHeight * 0.625)) / 2 + 41);
//            extInfo.put("displayX",0);
                // 显示Y偏移，默认0
                extInfo.put("displayY", -300);
//            extInfo.put("displayY",0);
                // 显示宽度，默认屏幕宽度
//            extInfo.put("displayWidth",675);
                extInfo.put("displayWidth", (displayHeight * 0.625));// 如果+1.5的话，就会是悬浮状态（其余黑色）
                // 显示宽度，默认屏幕⾼度
//            extInfo.put("displayHeight",1080);
                extInfo.put("displayHeight", displayHeight);
                // 主副屏，0主 1副
                extInfo.put("displayMode", 0);
                // D2访客机刷脸屏幕设置-----end
            }


            params.putString("extInfo", extInfo.toString());
            AppLogUtils.e("extInfo = " + extInfo.toString());

        } catch (JSONException e) {
            AppLogUtils.e("extInfo -- e = " + e.toString());
            e.printStackTrace();
        }


        String cameraBrand = ConfigData.getDeviceConfigResultBean().getCameraBrand();
        AppLogUtils.e("cameraBrand=" + cameraBrand);
        if (CAMERA_BRAND.equals(cameraBrand)) {
            AppLogUtils.e("是马里奥的，不配置zolozConfig");
        } else {
            AppLogUtils.e("非马里奥的，开始配置zolozConfig");
            //各设备 zolozConfig 参数，参考 zolozConfig
            try {
                params.putString("zolozConfig", getHardWareConfig());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }


        params.putLong(BPaaSApi.KEY_BPAAS_IPC_TIME_OUT, -1L);

        AppLogUtils.e("BPaaSApi--准备startBpaasService");
        AppLogUtils.e("BPaaSApi--准备startBpaasService--params：" + params.toString());

        // 日志开始----------------begin
        // 日志行数——对应web端"日志标签"
        String logLine = (new Throwable().getStackTrace())[0].toString();
        // 日志节点
        String logNode = "startBpaasService入参---";
        // 日志内容
        StringBuilder logContentSb = new StringBuilder();
        logContentSb.append(logNode).append(WARP)
                .append("params = ").append(params.toString()).append(WARP)
                .append("StartBpaasServiceBean = ").append(bpaasServiceBean.toString())
        ;

        // 开始保存本地日志
        AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
                .append(LINE)
                .append(logLine).append(WARP)
                .append(NODE)
                .append(logContentSb)
                .toString()
        );

        // 开始网络在线日志
        LogcatAddRequestBean bean = new LogcatAddRequestBean();
        bean.setLogType(NET_LOGCAT);
        // 对应web端"日志标签"
        bean.setLogTag(logLine + WARP + LOG_NODE_FACE);
        bean.setLogContent(logContentSb.toString());
        requestLogcatAdd(bean);
        // 日志开始----------------end

        //
        AppLogUtils.e(logContentSb);


        String finalMSessionId = ConfigData.mSessionId;
        mSessionId = BPaaSApi.getInstance().startBPaaSService(ConfigData.getDeviceConfigResultBean().getAbcpAppId(),
                "BPaasVerifyID", params, new BPaaSCallback() {
                    @Override
                    public void onResponse(BPaaSResponse bPaaSResponse) {

                        AppLogUtils.e("BPaaSApi--startBpaasService--onResponse = " + bPaaSResponse);
                        // {code=1000, subCode='E00000', subMsg='成功(E00000)', mResult='Bundle[mParcelledData.dataSize=124]', extInfo={}}
                        // code=1001, subCode='E69009', subMsg='未初始化成功，请先初始化(E69009)  注意检测getHardWareConfig
                        // {code=1001, subCode='E60001', subMsg='flow eval error', mResult='null', extInfo={}}
                        // {code=1001, subCode='E69013', subMsg='服务连接断开(E69013)', mResult='null', extInfo={}}

                        int code = bPaaSResponse.getCode();

                        AppLogUtils.e("BPaaSApi--startBpaasService--onResponse--Code = " + code);


                        AppLogUtils.e("补光灯关闭");
                        // 补光灯关闭
                        iDeviceUI.hideFillLight(mActivity);

                        // 重新唤起
                        invokeResume();


                        // 日志开始----------------begin
                        // 日志行数——对应web端"日志标签"
                        String logLine = (new Throwable().getStackTrace())[0].toString();
                        // 日志节点
                        String logNode = "startBpaasService结果onResponse---";
                        // 日志内容
                        StringBuilder logContentSb = new StringBuilder();
                        logContentSb.append(logNode).append(WARP)
                                .append("code = ").append(code).append(WARP)
                                .append("onResponse = ").append(bPaaSResponse);

                        // 开始保存本地日志
                        AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
                                .append(LINE)
                                .append(logLine).append(WARP)
                                .append(NODE)
                                .append(logContentSb)
                                .toString()
                        );

                        // 开始网络在线日志
                        LogcatAddRequestBean bean = new LogcatAddRequestBean();
                        bean.setLogType(NET_LOGCAT);
                        // 对应web端"日志标签"
                        bean.setLogTag(logLine + WARP + LOG_NODE_FACE);
                        bean.setLogContent(logContentSb.toString());
                        requestLogcatAdd(bean);
                        // 日志开始----------------end


                        // 1000表示超时（已经刷脸成功拿到其他信息，但是还没有做其他处理，导致20s超时）
                        // 1004smile异常
                        if (code == 1004) {
                            //重新启动核点服务
                            startZfbBpaasService(bpaasServiceBean);
                        } else if (code == 1001) {
                            // BPaaSResponse{code=1001, subCode='E60001', subMsg='flow eval error', mResult='null', extInfo={}}


                        }


                        AmpeActionDataBean ampeActionDataBean = null;
                        String action = "";
                        if (isInitFace && CardOrCode.equals("personCard")) {
                            // 初始化成功，且是1:1
                            AppLogUtils.e("BPaaSApi--startBpaasService--onEvent--isInitFace & isFacePersonCard");
                            ampeActionDataBean = ampeActionMap.get(ACTION_FACE_PERSONCARD);
                            action = ACTION_FACE_PERSONCARD;
                        } else if (isInitFace && CardOrCode.equals("enterIDNumber")) {
                            // 初始化成功，且是1:1
                            AppLogUtils.e("BPaaSApi--startBpaasService--onEvent--isInitFace & isFacePersonCard");
                            ampeActionDataBean = ampeActionMap.get(ACTION_ENTERIDNUMBER);
                            action = ACTION_ENTERIDNUMBER;
                        } else if (isInitFace && CardOrCode.equals("face")) {
                            // 初始化成功，且是1:N
                            AppLogUtils.e("BPaaSApi--startBpaasService--onEvent--isInitFace");
                            ampeActionDataBean = ampeActionMap.get(ACTION_FACE);
                            action = ACTION_FACE;
                        } else if (isJxInitFace) {
                            AppLogUtils.e("BPaaSApi--startBpaasService--onEvent--isJxInitFace");
                            ampeActionDataBean = ampeActionMap.get(ACTION_SCAN_FACE);
                            action = ACTION_SCAN_FACE;
                        }

                        if (ampeActionDataBean == null) {
                            AppLogUtils.e("ampeActionDataBean == null");
                            return;
                        }


                        AromeServiceInvoker.BridgeCallback bridgeCallback = ampeActionDataBean.getBridgeCallback();

                        AmpeAppletResultBean ampeAppletResultBean = new AmpeAppletResultBean();
                        ampeAppletResultBean.setAction(action);

                        ampeAppletResultBean.setSuccess(false);
                        ampeAppletResultBean.setMessage(bPaaSResponse.toString());

                        Map<String, Object> extInfo = bPaaSResponse.getExtInfo();


                        // AmpeAppletResultBean中的extInfo是String。但1001时返回是{}
//                        AmpeAppletResultBean.Data dataBean = gson.fromJson(bPaaSResponse.toString(), AmpeAppletResultBean.Data.class);
                        AmpeAppletResultBean.Data dataBean = new AmpeAppletResultBean.Data();
                        dataBean.setCode(bPaaSResponse.getCode());
                        dataBean.setSubCode(bPaaSResponse.getSubCode());
                        dataBean.setSubMessage(bPaaSResponse.getSubMsg());
                        dataBean.setExtInfoObj(bPaaSResponse.getExtInfo());
                        dataBean.setOriginFaceInfo(bPaaSResponse.toString());
                        ampeAppletResultBean.setData(dataBean);

                        // 回传处理结果给小程序
                        try {
                            JsonObject jsonObject = gson.toJsonTree(ampeAppletResultBean).getAsJsonObject();

                            if (bridgeCallback != null) {
                                bridgeCallback.callback(jsonObject.toString());
                            }

                            // 日志开始----------------begin
                            // 日志行数——对应web端"日志标签"
                            String logLine11 = (new Throwable().getStackTrace())[0].toString();
                            // 日志节点
                            String logNode11 = action + "--刷脸---支付宝结果--回传处理结果给小程序--";
                            // 日志内容
                            StringBuilder logContentSb11 = new StringBuilder();
                            logContentSb11.append(logNode11).append(WARP)
                                    .append("jsonObject = ").append(jsonObject).append(WARP);

                            // 开始保存本地日志
                            AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
                                    .append(LINE)
                                    .append(logLine11).append(WARP)
                                    .append(NODE)
                                    .append(logContentSb11)
                                    .toString()
                            );

                            // 开始网络在线日志
                            LogcatAddRequestBean bean11 = new LogcatAddRequestBean();
                            bean11.setLogType(NET_LOGCAT);
                            // 对应web端"日志标签"
                            bean11.setLogTag(logLine11 + WARP + LOG_NODE_APPLET + LOG_NODE_FACE);
                            bean11.setLogContent(logContentSb11.toString());
                            requestLogcatAdd(bean11);
                            // 日志开始----------------end

                            // 打印编译器输出日志
                            AppLogUtils.e(logContentSb11);


                        } catch (Throwable t) {
                            AppLogUtils.e("onCalled--t" + t);
                        }


                    }

                    @Override
                    public void onEvent(String bPaasVerifyID, String resultStr, Bundle bundle) {

                        // 刷脸成功返回的数据
                        AppLogUtils.e("BPaaSApi--startBpaasService--onEvent,bPaasVerifyID: " + bPaasVerifyID,
                                "bundle = " + new Gson().toJson(bundle),
                                "resultStr:" + resultStr,
                                "CardOrCode: " + CardOrCode);


                        AppLogUtils.e("补光灯关闭");
                        // 补光灯关闭
                        iDeviceUI.hideFillLight(mActivity);

                        if (tv_scan_result != null) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    tv_scan_result.setText(resultStr + "");
                                }
                            });
                        }


                        // 日志开始----------------begin
                        // 日志行数——对应web端"日志标签"
                        String logLine = (new Throwable().getStackTrace())[0].toString();
                        // 日志节点
                        String logNode = LOG_NODE_FACE + "startBpaasService结果onEvent--刷脸返回数据---";
                        // 日志内容
                        StringBuilder logContentSb = new StringBuilder();
                        logContentSb.append(logNode).append(WARP)
                                .append("onEvent = ").append(WARP)
                                .append("resultStr = ").append(resultStr).append(WARP)
                                .append("bPaasVerifyID = ").append(bPaasVerifyID).append(WARP)
                                .append("bundle = ").append(new Gson().toJson(bundle))
                                .append("CardOrCode = ").append(CardOrCode)
                        ;

                        // 开始保存本地日志
                        AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
                                .append(LINE)
                                .append(logLine).append(WARP)
                                .append(NODE)
                                .append(logContentSb)
                                .toString()
                        );

                        // 开始网络在线日志
                        LogcatAddRequestBean bean = new LogcatAddRequestBean();
                        bean.setLogType(NET_LOGCAT);
                        // 对应web端"日志标签"
                        bean.setLogTag(logLine + WARP + LOG_NODE_FACE);
                        bean.setLogContent(logContentSb.toString());
                        requestLogcatAdd(bean);
                        // 日志开始----------------end


                        // {"alipayUid":"","code":2006,"extInfo":"{\"authCode\":\"\"}","ftoken":"fp11d8fef76c02372e78fe3169cbde9ch72","isvResult":true,"subCode":"Z1208","subMessage":"抱歉，无法认出你(Z1208)","vid":""}

                        timeHandler.removeCallbacks(heartBeatRunnable);//结束核点超时的保底机制

                        // 判断扫脸是否已结束
//                        if (ConfigData.taskStatus.equals("complete")) {
//                            return;
//                        }

                        ConfigData.setFaceScenicUtile(faceScenicUtile, false);

                        // 将resultStr转成json
                        InvokeScanFaceBean invokeScanFaceBean = new Gson().fromJson(resultStr, InvokeScanFaceBean.class);

                        AppLogUtils.e("invokeScanFaceBean.getCode() = " + invokeScanFaceBean.getCode());


                        // 重新唤起
                        invokeResume();


                        AmpeActionDataBean ampeActionDataBean = null;
                        String action = "";
                        if (isInitFace && CardOrCode.equals("personCard")) {
                            // 初始化成功，且是1:1
                            AppLogUtils.e("BPaaSApi--startBpaasService--onEvent--isInitFace & isFacePersonCard");
                            ampeActionDataBean = ampeActionMap.get(ACTION_FACE_PERSONCARD);
                            action = ACTION_FACE_PERSONCARD;
                        } else if (isInitFace && CardOrCode.equals("enterIDNumber")) {
                            // 初始化成功，且是1:1
                            AppLogUtils.e("BPaaSApi--startBpaasService--onEvent--isInitFace & isFacePersonCard");
                            ampeActionDataBean = ampeActionMap.get(ACTION_ENTERIDNUMBER);
                            action = ACTION_ENTERIDNUMBER;
                        } else if (isInitFace && CardOrCode.equals("face")) {
                            // 初始化成功，且是1:N
                            AppLogUtils.e("BPaaSApi--startBpaasService--onEvent--isInitFace");
                            ampeActionDataBean = ampeActionMap.get(ACTION_FACE);
                            action = ACTION_FACE;
                        } else if (isJxInitFace) {
                            AppLogUtils.e("BPaaSApi--startBpaasService--onEvent--isJxInitFace");
                            ampeActionDataBean = ampeActionMap.get(ACTION_SCAN_FACE);
                            action = ACTION_SCAN_FACE;
                        }

                        if (ampeActionDataBean == null) {
                            AppLogUtils.e("ampeActionDataBean == null");
                            return;
                        }

                        AromeServiceInvoker.BridgeCallback bridgeCallback = ampeActionDataBean.getBridgeCallback();

                        AmpeAppletResultBean ampeAppletResultBean = new AmpeAppletResultBean();
                        ampeAppletResultBean.setAction(action);
                        ampeAppletResultBean.setEvent(ampeActionDataBean.getEvent());
                        ampeAppletResultBean.setTaskId(ampeActionDataBean.getTaskId());


                        if (invokeScanFaceBean.getCode() == 1000) {


                            // 人证还是刷脸，判断三要素，

                            // 刷脸
                            if (CardOrCode.equals("face") || CardOrCode.equals("personCard")) {

                                // String userInfoTestData = "{\"vid\":\"\",\"code\":1000,\"isvResult\":true,\"subCode\":\"\",\"ftoken\":\"fp174ad54ffa1d5e6a532583d5017e12h84\",\"sn\":\"224F010T01400827\",\"subMessage\":\"\",\"alipayUid\":\"2088612116677214\",\"extInfo\":\"{\\\"authCode\\\":\\\"87ac7d355f1b4eeba2d4080bb427FX21\\\"}\"}\n";

                                // 根据配置是否请求用户信息三要素
                                boolean appGetUserInfo = deviceConfigBean.isAppGetUserInfo();
                                AppLogUtils.e("appGetUserInfo = " + appGetUserInfo);
                                if (appGetUserInfo) {
                                    // 获取三要素
                                    AlipayUserInfoRequestBean alipayUserInfoRequestBean = gson.fromJson(resultStr, AlipayUserInfoRequestBean.class);
                                    alipayUserInfoRequestBean.setServiceAddress(deviceConfigBean.getServiceAddress());
                                    alipayUserInfoRequestBean.setSn(DeviceUtils.getDeviceSN());
                                    alipayUserInfoRequestBean.setAppId(deviceConfigBean.getServiceAppId());
                                    if (mAlipayUserInfoPresenter == null) {
                                        mAlipayUserInfoPresenter = new AlipayUserInfoPresenter(MainActivity.this);
                                    }
                                    mAlipayUserInfoPresenter.requestAlipayUserInfo(alipayUserInfoRequestBean);


                                    // 日志开始保存----------------begin
                                    // 日志行数——对应web端"日志标签"
                                    String logLineUserInfo = (new Throwable().getStackTrace())[0].toString();
                                    // 日志节点
                                    String logNodeUserInfo = "用户信息三要素---入参---";
                                    // 日志内容
                                    StringBuilder logContentSbUserInfo = new StringBuilder();
                                    logContentSbUserInfo.append(logNodeUserInfo).append(WARP)
                                            .append("alipayUserInfoRequestBean = ").append(alipayUserInfoRequestBean.toString());

                                    // 开始保存本地日志
                                    AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
                                            .append(LINE)
                                            .append(logLineUserInfo).append(WARP)
                                            .append(NODE)
                                            .append(logContentSbUserInfo)
                                            .toString()
                                    );

                                    // 开始网络在线日志
                                    LogcatAddRequestBean logBeanUserInfo = new LogcatAddRequestBean();
                                    logBeanUserInfo.setLogType(NET_LOGCAT);
                                    // 对应web端"日志标签"
                                    logBeanUserInfo.setLogTag(logLineUserInfo + WARP + LOG_NODE_FACE);
                                    logBeanUserInfo.setLogContent(logContentSbUserInfo.toString());
                                    requestLogcatAdd(logBeanUserInfo);
                                    // 日志开始保存----------------end

                                    // 打印编译器输出日志
                                    AppLogUtils.e(logContentSbUserInfo);

                                } else {
                                    // 不获取，直接返回支付宝刷脸结果

                                    ampeAppletResultBean.setSuccess(true);
                                    ampeAppletResultBean.setMessage("成功");


                                    AmpeAppletResultBean.Data dataBean = gson.fromJson(resultStr, AmpeAppletResultBean.Data.class);
                                    dataBean.setOriginFaceInfo(resultStr);

                                    if (CardOrCode.equals("enterIDNumber")) {
                                        dataBean.setIdNum(IDNumber);
                                    }
                                    ampeAppletResultBean.setData(dataBean);

                                    // 回传处理结果给小程序
                                    try {
                                        JsonObject jsonObject = gson.toJsonTree(ampeAppletResultBean).getAsJsonObject();
                                        AppLogUtils.e("人证比对数据返回  " + new Gson().toJson(jsonObject));
                                        if (bridgeCallback != null) {
                                            bridgeCallback.callback(jsonObject.toString());
                                        }


                                        // 日志开始----------------begin
                                        // 日志行数——对应web端"日志标签"
                                        String logLine11 = (new Throwable().getStackTrace())[0].toString();
                                        // 日志节点
                                        String logNode11 = action + "--刷脸--支付宝结果--回传处理结果给小程序--";
                                        // 日志内容
                                        StringBuilder logContentSb11 = new StringBuilder();
                                        logContentSb11.append(logNode11).append(WARP)
                                                .append("jsonObject = ").append(jsonObject).append(WARP)
                                                .append("appGetUserInfo = ").append(appGetUserInfo);

                                        // 开始保存本地日志
                                        AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
                                                .append(LINE)
                                                .append(logLine11).append(WARP)
                                                .append(NODE)
                                                .append(logContentSb11)
                                                .toString()
                                        );

                                        // 开始网络在线日志
                                        LogcatAddRequestBean bean11 = new LogcatAddRequestBean();
                                        bean11.setLogType(NET_LOGCAT);
                                        // 对应web端"日志标签"
                                        bean11.setLogTag(logLine11 + WARP + LOG_NODE_APPLET + LOG_NODE_FACE);
                                        bean11.setLogContent(logContentSb11.toString());
                                        requestLogcatAdd(bean11);
                                        // 日志开始----------------end

                                        // 打印编译器输出日志
                                        AppLogUtils.e(logContentSb11);


                                    } catch (Throwable t) {
                                        AppLogUtils.e("onCalled--t" + t);
                                    }

                                }


//                                bean.setSn("224F010T01400827");
////                                bean.setSn(DeviceUtils.getDeviceSN());
//
//                                String userInfoTestData = gson.toJson(bean);
//
//
//                                new Thread(new Runnable() {
//                                    @Override
//                                    public void run() {
//                                        requestUserThreeInfo(userInfoTestData);
//                                    }
//                                }).start();


                                //
                                ConfigData.taskStatus = "complete";

                            } else if (CardOrCode.equals("enterIDNumber")) {

                                ampeAppletResultBean.setSuccess(true);
                                ampeAppletResultBean.setMessage("成功");


                                AmpeAppletResultBean.Data dataBean = gson.fromJson(resultStr, AmpeAppletResultBean.Data.class);
                                if (CardOrCode.equals("enterIDNumber")) {
                                    dataBean.setIdNum(IDNumber);
                                }
                                ampeAppletResultBean.setData(dataBean);

                                // 回传处理结果给小程序
                                try {
                                    JsonObject jsonObject = gson.toJsonTree(ampeAppletResultBean).getAsJsonObject();
                                    AppLogUtils.e("人证比对数据返回  " + new Gson().toJson(jsonObject));
                                    if (bridgeCallback != null) {
                                        bridgeCallback.callback(jsonObject.toString());
                                    }


                                    // 日志开始----------------begin
                                    // 日志行数——对应web端"日志标签"
                                    String logLine11 = (new Throwable().getStackTrace())[0].toString();
                                    // 日志节点
                                    String logNode11 = "ACTION_FACE--手输证件号--支付宝结果--回传处理结果给小程序--";
                                    // 日志内容
                                    StringBuilder logContentSb11 = new StringBuilder();
                                    logContentSb11.append(logNode11).append(WARP)
                                            .append("jsonObject = ").append(jsonObject).append(WARP)
                                            .append("appGetUserInfo = ").append(deviceConfigBean.isAppGetUserInfo());

                                    // 开始保存本地日志
                                    AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
                                            .append(LINE)
                                            .append(logLine11).append(WARP)
                                            .append(NODE)
                                            .append(logContentSb11)
                                            .toString()
                                    );

                                    // 开始网络在线日志
                                    LogcatAddRequestBean bean11 = new LogcatAddRequestBean();
                                    bean11.setLogType(NET_LOGCAT);
                                    // 对应web端"日志标签"
                                    bean11.setLogTag(logLine11 + WARP + LOG_NODE_APPLET + LOG_NODE_FACE);
                                    bean11.setLogContent(logContentSb11.toString());
                                    requestLogcatAdd(bean11);
                                    // 日志开始----------------end

                                    // 打印编译器输出日志
                                    AppLogUtils.e(logContentSb11);


                                } catch (Throwable t) {
                                    AppLogUtils.e("onCalled--t" + t);
                                }
                            }


                        } else {

                            // onEvent非1000

                            AppLogUtils.e("onEvent非1000");

                            ampeAppletResultBean.setSuccess(false);
                            ampeAppletResultBean.setMessage(resultStr);

                            AmpeAppletResultBean.Data dataBean = gson.fromJson(resultStr, AmpeAppletResultBean.Data.class);
                            dataBean.setOriginFaceInfo(resultStr);
                            ampeAppletResultBean.setData(dataBean);

                            // 回传处理结果给小程序
                            try {
                                JsonObject jsonObject = gson.toJsonTree(ampeAppletResultBean).getAsJsonObject();

                                if (bridgeCallback != null) {
                                    bridgeCallback.callback(jsonObject.toString());
                                }

                                // 日志开始----------------begin
                                // 日志行数——对应web端"日志标签"
                                String logLine11 = (new Throwable().getStackTrace())[0].toString();
                                // 日志节点
                                String logNode11 = action + "--刷脸---支付宝结果--回传处理结果给小程序--";
                                // 日志内容
                                StringBuilder logContentSb11 = new StringBuilder();
                                logContentSb11.append(logNode11).append(WARP)
                                        .append("jsonObject = ").append(jsonObject).append(WARP);

                                // 开始保存本地日志
                                AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
                                        .append(LINE)
                                        .append(logLine11).append(WARP)
                                        .append(NODE)
                                        .append(logContentSb11)
                                        .toString()
                                );

                                // 开始网络在线日志
                                LogcatAddRequestBean bean11 = new LogcatAddRequestBean();
                                bean11.setLogType(NET_LOGCAT);
                                // 对应web端"日志标签"
                                bean11.setLogTag(logLine11 + WARP + LOG_NODE_APPLET + LOG_NODE_FACE);
                                bean11.setLogContent(logContentSb11.toString());
                                requestLogcatAdd(bean11);
                                // 日志开始----------------end

                                // 打印编译器输出日志
                                AppLogUtils.e(logContentSb11);


                            } catch (Throwable t) {
                                AppLogUtils.e("onCalled--t" + t);
                            }


                            if (invokeScanFaceBean.getCode() == 1001) {
                                //

                            } else if (invokeScanFaceBean.getCode() == 2006) {
                                // 无法认出

                            }

                        }

                        // 重置
                        isFacePersonCard = false;


                    }
                });

        ConfigData.mSessionId = mSessionId;
        AppLogUtils.e("startBpaasService--mSessionId = " + mSessionId);


    }


    public void stopBpaasService() {
        if (mSessionId == null) {
            return;
        }
        AppLogUtils.e("stopBpaasService--SessionId =" + mSessionId);
        BPaaSApi.getInstance().stopBPaaSService(ConfigData.getDeviceConfigResultBean().getAbcpAppId(), "BPaasVerifyID", new Bundle(), mSessionId, new BPaaSCallback() {
            @Override
            public void onResponse(BPaaSResponse bPaaSResponse) {
                AppLogUtils.e("停止回调onResponse");
                if (bPaaSResponse == null || bPaaSResponse.getCode() == BPaaSResponse.RESULT_CODE_FAIL) {
                    AppLogUtils.e("stopBPaaSService--onResponse--失败 stopBPaaSService bPaaSResponse=" + bPaaSResponse);
                    return;
                }
                String subCode = bPaaSResponse.getSubCode();
                int code = bPaaSResponse.getCode();
                AppLogUtils.e("stopBPaaSService--onResponse--成功 stopBPaaSService subCode=" + subCode + "code：" + code);
            }

            @Override
            public void onEvent(String s, String resultStr, Bundle bundle) {
                AppLogUtils.e("stopBPaaSService--onEvent--resultStr:" + resultStr);
            }
        });
        mSessionId = null;
    }


    //    OkHttpClient client = new OkHttpClient().newBuilder().build();
//    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
//
//
//    String alipayUserInfoUrl = "https://ldb-permit.hz-hanghui.com:8088/hanghui/outapi/alipayApi/faceAuth/getAlipayUserInfo";
//
//    private Handler nethandler = new NetHandler(Looper.myLooper(), this);
//
//
    public final static int USER_INFO_SUCCESS = 100;

    class NetHandler extends Handler {
        WeakReference<Activity> mainActivityWeakReference;

        //构造函数传入外部的this
        public NetHandler(@NonNull Looper looper, Activity mainActivity) {
            super(looper);
            //构建一个弱引用对象
            mainActivityWeakReference = new WeakReference<Activity>(mainActivity);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            //判断活动是否还存在，如果不存在则结束
            Activity activity = mainActivityWeakReference.get();
            if (activity == null) {
                return;
            }

            switch (msg.what) {
                case USER_INFO_SUCCESS:
                    String s = (String) msg.obj;

//                    AlipayUserInfoResultBean alipayUserInfoResultBean = gson.fromJson(s, AlipayUserInfoResultBean.class);


                    break;
            }
        }
    }


//    // 根据authcode获取用户三要素
//    private void requestUserThreeInfo(String userInfoTestData) {
//
//
//        RequestBody requestBody = RequestBody.create(JSON, userInfoTestData);
//
//        Request request = new Request.Builder().url(alipayUserInfoUrl).post(requestBody).build();
//        Response response = null;
//        client.newCall(request).enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                Gson json = new Gson();
//                String toJson = response.body().string();
//
//                try {
//                    AppLogUtils.e("三要素--toJson:" + toJson);
//                    /**
//                     * {
//                     * 	"errcode": "0",
//                     * 	"errmsg": "成功",
//                     * 	"data": {
//                     * 		"userId": "2088612116677214",
//                     * 		"certNo": "",
//                     * 		"mobile": "",
//                     * 		"userName": "",
//                     * 		"personPictures": null,
//                     * 		"avatar": "https://tfs.alipayobjects.com/images/partner/TB1HRIDcIRCDuNjm2EsXXadrFX",
//                     * 		"photoBase64": null
//                     *        }
//                     * }
//                     */
//                    org.json.JSONObject jsonObject1 = new org.json.JSONObject(toJson);
//                    if (jsonObject1.getString("errcode").equals("0")) {
//                        org.json.JSONObject responseOrder = jsonObject1.getJSONObject("data");
//                        Message msg = Message.obtain();
//                        msg.obj = toJson;
//                        msg.what = USER_INFO_SUCCESS;
//                        nethandler.sendMessage(msg);
//
//                    } else {
//                    }
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//
//            }
//        });
//
//
//    }


    //设备 zolozConfig 参数
//    private String getHardWareConfig() throws JSONException {
//        JSONObject zolozConfig = new JSONObject();
//        zolozConfig.put("cameraID", 0);
//        zolozConfig.put("supCameraID", 1);
//        zolozConfig.put("toygerPowerMode", 0);
//        zolozConfig.put("minIod", 0.02);
////        zolozConfig.put("algorithmAngle", ConfigData.algorithmAngle);
////        zolozConfig.put("supAlgorithmAngle", ConfigData.supAlgorithmAngle);
////        zolozConfig.put("isDisplayMirror", ConfigData.isDisplayMirror);   //false
//        zolozConfig.put("algorithmAngle", 270);
//        zolozConfig.put("supAlgorithmAngle",270);
//        zolozConfig.put("isDisplayMirror",true);   //false
//        zolozConfig.put("supIsDisplayMirror", false);  //false
//        zolozConfig.put("supIsMirror", false);      //false
////        zolozConfig.put("isMirror", ConfigData.isMirror);          //true
////        zolozConfig.put("displayAngle", ConfigData.displayAngle);
//        zolozConfig.put("isMirror", true);          //true
//        zolozConfig.put("displayAngle", 90);
//        zolozConfig.put("supDisplayAngle", 90);
//        return zolozConfig.toString();
//    }


    // K8
    public String getHardWareConfig() throws JSONException {

        org.json.JSONObject zolozConfig = new JSONObject();
        zolozConfig.put("cameraID", 0); // 相机camera id 一般为0为colorCamera, 1为IrCamera
        zolozConfig.put("supCameraID", 1);  // 用于ir相机camera id，不设置的话自动用colorCameraId加1
        zolozConfig.put("toygerPowerMode", 0);
        zolozConfig.put("minIod", 0.02);
        zolozConfig.put("supIsMirror", false);  // 用于ir摄像头帧数据是否镜像
        zolozConfig.put("supIsDisplayMirror", false);    // 用于ir摄像头预览是否镜像
        zolozConfig.put("supDisplayAngle", 0);  // 用于ir摄像头预览角度，不设置的话保持和color的一致

        if (deviceConfigBean == null) {
            // 日志开始----------------begin
            // 日志行数——对应web端"日志标签"
            String logLine = (new Throwable().getStackTrace())[0].toString();
            // 日志节点
            String logNode = "摄像头配置错误---zolozConfig---getHardWareConfig---";
            // 日志内容
            StringBuilder logContentSb = new StringBuilder();
            logContentSb.append(logNode).append(WARP)
                    .append("deviceConfigBean == null，开始用默认值");

            // 开始保存本地日志
            AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
                    .append(LINE)
                    .append(logLine).append(WARP)
                    .append(NODE)
                    .append(logContentSb)
                    .toString()
            );

            // 开始网络在线日志
            LogcatAddRequestBean bean = new LogcatAddRequestBean();
            bean.setLogType(NET_LOGCAT);
            // 对应web端"日志标签"
            bean.setLogTag(logLine + WARP + LOG_NODE_FACE);
            bean.setLogContent(logContentSb.toString());
            requestLogcatAdd(bean);
            // 日志开始----------------end

            // 打印编译器输出日志
            AppLogUtils.e(logContentSb);

            // 设置k8默认值
            zolozConfig.put("algorithmAngle", 90);  // 送算法的图像角度
            zolozConfig.put("supAlgorithmAngle", 90);   // 用于ir摄像头算法角度
            zolozConfig.put("displayAngle", 0);    // 预览角度
            zolozConfig.put("isDisplayMirror", true);   // 预览的图像是否需要镜像  后面的摄像头背景 false头像移动向左，摄像头里也是向左
            zolozConfig.put("isMirror", false);  // 送算法图像是否镜像   小圆圈里的

        } else {
            zolozConfig.put("algorithmAngle", deviceConfigBean.getAlgorithmAngle());  // 送算法的图像角度
            zolozConfig.put("supAlgorithmAngle", deviceConfigBean.getSupAlgorithmAngle());   // 用于ir摄像头算法角度
            zolozConfig.put("displayAngle", deviceConfigBean.getDisplayAngle());    // 预览角度
            zolozConfig.put("isDisplayMirror", deviceConfigBean.isDisplayMirror());   // 预览的图像是否需要镜像 后面的摄像头背景  false头像移动向左，摄像头里也是向左
            zolozConfig.put("isMirror", deviceConfigBean.isMirror());  // 送算法图像是否镜像  小圆圈里的
        }


        // 日志开始----------------begin
        // 日志行数——对应web端"日志标签"
        String logLine = (new Throwable().getStackTrace())[0].toString();
        // 日志节点
        String logNode = "摄像头配置---zolozConfig---getHardWareConfig---";
        // 日志内容
        StringBuilder logContentSb = new StringBuilder();
        logContentSb.append(logNode).append(WARP)
                .append("zolozConfig = ").append(zolozConfig.toString());

        // 开始保存本地日志
        AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
                .append(LINE)
                .append(logLine).append(WARP)
                .append(NODE)
                .append(logContentSb)
                .toString()
        );

        // 开始网络在线日志
        LogcatAddRequestBean bean = new LogcatAddRequestBean();
        bean.setLogType(NET_LOGCAT);
        // 对应web端"日志标签"
        bean.setLogTag(logLine + WARP + LOG_NODE_FACE);
        bean.setLogContent(logContentSb.toString());
        requestLogcatAdd(bean);
        // 日志开始----------------end

        // 打印编译器输出日志
        AppLogUtils.e(logContentSb);

        return zolozConfig.toString();
    }


    /**
     * NFC(1, "NFC在线阅读器"),
     * TB(2, "天波阅读器"),
     * DX(3, "东信阅读器"),
     * XZX(4, "新中新阅读器"),
     * DK(5, "德卡阅读器"),
     * JL(6, "精伦阅读器"),
     * HS(7, "华视阅读器"),
     * ZAWL(8, "中安未来离线护照机阅读器模块"),
     */
    Integer idCardReaderBrand = 1;


//    int idcardRetryCount = 0;
//    int idcardRetryMaxCount = 3;
//
//
//    /**
//     * 新中新身份证阅读器
//     */
//    class MyTimer extends Thread {
//        @Override
//        public void run() {
//            if (idCardReaderThread==null){
//                return;
//            }
//            while (idCardReaderThread.isReading()) {
//                newIdCardHandler.obtainMessage(UPDATE_READER_STATUS).sendToTarget();
//                try {
//                    Thread.sleep(500);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//    }
//
//    //新中新身份证阅读器
//    IDCardReaderThread idCardReaderThread;
//    final int UPDATE_READER_STATUS = 0x40;
//    Handler newIdCardHandler = new Handler() {
//        @Override
//        public void handleMessage(Message msg) {
//            String devName = DeviceConnectManager.getInstance().getDevName();
//            switch (msg.what) {
//                case DeviceConnectManager.MESSAGE_CONNECTED:
//                    AppLogUtils.i(true, "newIdCardHandler_新中新身份证阅读器",devName + "新版身份证阅读器连接成功");
//                    break;
//                case DeviceConnectManager.MESSAGE_CONNECTING_DEVICE:
//                    AppLogUtils.i(true, "newIdCardHandler_新中新身份证阅读器",devName + "新版身份证阅读器正在连接");
//                    break;
//                case DeviceConnectManager.MESSAGE_CONNECTFAILED:
//                    AppLogUtils.e(true, "newIdCardHandler_新中新身份证阅读器",devName + "新版身份证阅读器连接失败");
//                    if (idCardReaderThread!=null){
//                        idCardReaderThread.close();
//                    }
//                    new Handler().postDelayed(new Runnable() {
//                        @Override
//                        public void run() {
//                                idCardReaderThread.read();
//                        }
//                    },5*1000);
//                    break;
//                case DeviceConnectManager.MESSAGE_DISCONNECTED:
//                    AppLogUtils.i(true, "newIdCardHandler_新中新身份证阅读器",devName + "新版身份证阅读器连接断开");
//                    if (idCardReaderThread!=null){
//                        idCardReaderThread.close();
//                    }
//                    break;
//                case DeviceConnectManager.MESSAGE_RECONNECT_DEVICE:
//                    AppLogUtils.i(true, "newIdCardHandler_新中新身份证阅读器",devName + "新版身份证阅读器重新连接");
//                    break;
//                case DeviceConnectManager.MESSAGE_STOP_READCARD:
//                    break;
//                case IDCardReaderThread.MESSAGE_START_READ:
//                    new MyTimer().start();
//                    AppLogUtils.i(true, "newIdCardHandler_新中新身份证阅读器","新版身份证阅读器开始读卡");
//                    break;
//                case IDCardReaderThread.MESSAGE_DISPLAY_IDCARD:
//                    AppLogUtils.i(true, "newIdCardHandler_新中新身份证阅读器","新版身份证读卡信息  " + new Gson().toJson((IDCards) msg.obj));
//                    SendIdCard((IDCards) msg.obj);
//                    break;
//                case IDCardReaderThread.MESSAGE_STOP_READ:
//                    AppLogUtils.i(true, "newIdCardHandler_新中新身份证阅读器","新版身份证阅读器停止读卡");
//                    break;
//                case UPDATE_READER_STATUS:
//                    AppLogUtils.i(false, "newIdCardHandler_新中新身份证阅读器","身份证读卡耗时等信息  " + idCardReaderThread.getReadStatus());
//                    break;
//            }
//            super.handleMessage(msg);
//        }
//    };
//
//    //新版身份证信息返回
//    private void SendIdCard(IDCards idcard) {
//
//        String name = "";
//        String bmpPhotos = "";
//
//        name = idcard.getName() + "";
//
//        AppLogUtils.e(true, "newIdCardHandler_新中新身份证阅读器","新版身份证读卡人员" + name
//                + "新版身份证读卡时间 " + idcard.getReadTime());
//        try {
//            Bitmap bmp = idcard.getPhoto();
//            if (bmp == null) {
//                AppLogUtils.e(true, "newIdCardHandler_新中新身份证阅读器","新版身份证照片解码出错 ");
//            } else {
//                bmpPhotos = bitmapToString(bmp);
//                AppLogUtils.e(false,"",bmpPhotos);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            AppLogUtils.e(true, "newIdCardHandler_新中新身份证阅读器","新版身份证照片解码异常 "+e);
//        }
//    }


    // ------------------身份证
    private void initIDCard() {

        // 日志开始----------------begin
        // 日志行数——对应web端"日志标签"
        String logLine = (new Throwable().getStackTrace())[0].toString();
        // 日志节点
        String logNode = "身份证--开始初始化---";
        // 日志内容
        StringBuilder logContentSb = new StringBuilder();
        logContentSb.append(logNode).append(WARP);

        // 开始保存本地日志
        AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
                .append(LINE)
                .append(logLine).append(WARP)
                .append(NODE)
                .append(logContentSb)
                .toString()
        );

        // 开始网络在线日志
        LogcatAddRequestBean bean = new LogcatAddRequestBean();
        bean.setLogType(NET_LOGCAT);
        // 对应web端"日志标签"
        bean.setLogTag(logLine + WARP + LOG_NODE_IDCARD);
        bean.setLogContent(logContentSb.toString());
        requestLogcatAdd(bean);
        // 日志开始----------------end
        // 打印编译器输出日志
        AppLogUtils.e(logContentSb);


        //新中新
//        DeviceConnectManager.getInstance().resetReader(ReaderInterfaceFactory.READER_USB);
//        idCardReaderThread = new IDCardReaderThread();
//        idCardReaderThread.setActivityAndHandler(this, newIdCardHandler);
//        idCardReaderThread.open(null);
//        new Handler().postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                    idCardReaderThread.read();
//            }
//        },2000);
//
//
//        if(true){
//            return;
//        }


        /**
         * D2 没有存储权限，就不会有身份证相关的日志了。需要先授予该权限
         */
        IDCardScan.with(mActivity, idCardReaderBrand).initIDCard(new IDCardInitResultCallback() {
            @Override
            public void onIDCardInitSuccess() {
                // 日志开始----------------begin
                // 日志行数——对应web端"日志标签"
                String logLine = (new Throwable().getStackTrace())[0].toString();
                // 日志节点
                String logNode = "身份证---初始化成功---" + "  sn号：" + DeviceUtils.getDeviceSN() + "  连接品牌：" + deviceConfigBean.getIdCardReaderBrand();
                ;
                // 日志内容
                StringBuilder logContentSb = new StringBuilder();
                logContentSb.append(logNode).append(WARP);

                // 开始保存本地日志
                AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
                        .append(LINE)
                        .append(logLine).append(WARP)
                        .append(NODE)
                        .append(logContentSb)
                        .toString()
                );

                // 开始网络在线日志
                LogcatAddRequestBean logBean = new LogcatAddRequestBean();
                logBean.setLogType(NET_LOGCAT);
                // 对应web端"日志标签"
                logBean.setLogTag(logLine + WARP + LOG_NODE_IDCARD);
                logBean.setLogContent(logContentSb.toString());
                // 日志网络请求
                requestLogcatAdd(logBean);
                // 日志开始----------------end

                // 打印编译器输出日志
                AppLogUtils.e(logContentSb);


                setConfigStatusText(logContentSb.toString());


//                ThreadPoolManager.getInstance().executeIOTask(new Runnable() {
//                    @Override
//                    public void run() {
                startIDCardListener();
//                    }
//                });


            }

            @Override
            public void onIDCardInitError(String errorCode, String errorMsg) {

                // 日志开始----------------begin
                // 日志行数——对应web端"日志标签"
                String logLine11 = (new Throwable().getStackTrace())[0].toString();
                // 日志节点
                String logNode11 = "身份证---初始化失败---" + errorMsg + "  sn号：" + DeviceUtils.getDeviceSN() + "  连接品牌：" + deviceConfigBean.getIdCardReaderBrand();
                ;
                // 日志内容
                StringBuilder logContentSb11 = new StringBuilder();
                logContentSb11.append(logNode11).append(WARP);

                // 开始保存本地日志
                AppLogUtils.saveLog(LogType.Error, new StringBuilder()
                        .append(LINE)
                        .append(logLine11).append(WARP)
                        .append(NODE)
                        .append(logContentSb11)
                        .toString()
                );

                // 开始网络在线日志
                LogcatAddRequestBean logBean11 = new LogcatAddRequestBean();
                logBean11.setLogType(NET_ERROR);
                // 对应web端"日志标签"
                logBean11.setLogTag(logLine + WARP + LOG_NODE_IDCARD);
                logBean11.setLogContent(logContentSb11.toString());
                // 日志网络请求
                requestLogcatAdd(logBean11);
                // 日志开始----------------end

                // 打印编译器输出日志
                AppLogUtils.i(logContentSb11);


                setConfigStatusText(logContentSb11.toString());


            }
        });

    }

    private void startIDCardListener() {


        AppLogUtils.e("startIDCardListener");

        if (idCardReaderBrand == null || idCardReaderBrand == 1) {
            // nfc要跳页面，故终止
            return;
        }

        // 直接在当前页面
        // 根据不同的设备取值
        IDCardScan.with(mActivity, idCardReaderBrand).startScanIDCard(new IDCardScanResultCallback() {
            @Override
            public void onIDCardScanSuccess(IDCardInfoBean idCardInfoBean) {
//                AppLogUtils.e("初始数据："+idCardInfoBean.toString());

                handleIdCardResultListener(idCardInfoBean);


            }

            @Override
            public void onIDCardError(String resCode, String resMsg) {
                AppLogUtils.e("resCode:" + resCode + "---resMsg:" + resMsg);


            }
        });


    }

    private void handleIdCardResultListener(IDCardInfoBean idCardInfoBean) {
        isReadIDCardSuccess = true;

        JSONObject object = new JSONObject();
        try {
            // 勿动key，对外的文档key
            object.put("name", idCardInfoBean.getIdcardName());
            object.put("idNum", idCardInfoBean.getIdcardNumber());
            object.put("address", idCardInfoBean.getAddress());
            object.put("nation", idCardInfoBean.getNation());
            object.put("sex", idCardInfoBean.getSex());
            object.put("birthDate", idCardInfoBean.getBirth());
            if (StringUtils.isNotNull(idCardInfoBean.getPhotoBase64())) {
                String photoBase64 = idCardInfoBean.getPhotoBase64().replaceAll("\n", "");
                object.put("photoBase64", photoBase64);
            }
//                    object.put("photoBase64", idCardInfoBean.getPhotoBase64());
            object.put("beginTime", idCardInfoBean.getBeginTime());
            object.put("endTime", idCardInfoBean.getEndTime());
            object.put("signingOrganization", idCardInfoBean.getSigningOrganization());
        } catch (Throwable t) {

        }

        if (isCloseIdCardMessage) {

        } else {
            // 主动推送给小程序
            sendMessageToApplet(EVENT_IDCard_LISTENER, object.toString());
        }
    }


    @Override
    protected void onDestroy() {
        AppLogUtils.e(mTag + "onDestroy");

        onDestroyUnregister();

        super.onDestroy();


    }

    private void onDestroyUnregister() {


        AppLogUtils.e("补光灯关闭");
        // 补光灯关闭
        iDeviceUI.hideFillLight(mActivity);

        if (localConfig != null) {
            localConfig.setScanIdCardOverTime(false);
        }

        // 录音
        deleteRecordAllFile();
        if (zlwRecordManager != null) {
            zlwRecordManager.stopAll();
            zlwRecordManager = null;
        }

        deleteAllPicture();


        // 停止定时器和定时任务
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (inductionTimerTask != null) {
            inductionTimerTask.cancel();
            inductionTimerTask = null;
        }


        //解除注册
        if (null != iAidlInterface && iAidlInterface.asBinder().isBinderAlive()) {
            try {
                iAidlInterface.unregisterCallBack(iAidlCallBack);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        //解除绑定服务
        if (null != serviceConnection) {
            unbindService(serviceConnection);
        }

        EventBus.getDefault().unregister(this);


        if (resh.mHandler != null) {
            resh.mHandler.removeCallbacksAndMessages(null);
            resh.mHandler = null;
        }


        if (mDeviceConfigPresenter != null) {
            mDeviceConfigPresenter = null;
        }

        if (mHeartbeatPresenter != null) {
            mHeartbeatPresenter = null;
        }

        if (mAlipayUserInfoPresenter != null) {
            mAlipayUserInfoPresenter = null;
        }

        if (connectivityManager != null) {
            // 网络监听
            connectivityManager.unregisterNetworkCallback(networkCallback);
        }

        // 身份证识别
        stopBpaasService();
        startBPaaSServiceFlag = false;

        isAppletListen = false;

        // 语音播报
        MTTSDemo.getInstance(mContext).stopTTS();

        // 停止打印
//        if(iPrintBase!=null){
//            iPrintBase.stop();
//        }


//        exitApplet();


        // 身份证识别
        IDCardScan.with(mActivity, idCardReaderBrand).onDestroy();

        // 打印
        if (iPrinter != null) {
            iPrinter.disconnect();
            iPrinter = null;
        }

    }


    boolean isReadIDCardSuccess;


    boolean isReadIDCardComplete;
    int readIDCardTotalTime = 15 * 1000;
    CountDownTimer readIDCardCountDownTimer;


    // 接收IDCardScanActivity页面返回的结果
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void receiveIDCardResult(AmpeAppletResultBean resultBean) {
        AppLogUtils.e("receiveIDCardResult--bean" + resultBean.toString());
        // ACTION_IDCard--回传处理结果给小程序


//        if(1 == idCardReaderBrand){
//            // nfc在线
//            if(resultBean!=null&&resultBean.getData()!=null){
//                // 主动推送给小程序
//                sendMessageToApplet(EVENT_IDCard_LISTENER,resultBean.getData().toString());
//            }
//            return;
//        }


        AmpeActionDataBean ampeActionDataBean = ampeActionMap.get(ACTION_IDCard);
        if (ampeActionDataBean == null) {
            AppLogUtils.e("ampeActionDataBean == null");
            return;
        }
        AromeServiceInvoker.BridgeCallback bridgeCallback = ampeActionDataBean.getBridgeCallback();

        AmpeAppletResultBean bean = new AmpeAppletResultBean();
        bean.setAction(ACTION_IDCard);
        bean.setEvent(ampeActionDataBean.getEvent());
        bean.setTaskId(ampeActionDataBean.getTaskId());
        bean.setSuccess(true);
        bean.setMessage("成功");

        AmpeAppletResultBean.Data dataBean = new AmpeAppletResultBean.Data();
        AmpeAppletResultBean.Data identityBean = resultBean.getData();


        AppLogUtils.e("name:" + identityBean.getName());
        // 可能会有空格，去除
        String name = identityBean.getName().replace(" ", "");
        String address = identityBean.getAddress();


        // 根据传入的参数，按需返回
        String[] paramsArray = ampeActionDataBean.getParamsArray();
        if (paramsArray != null && paramsArray.length > 0) {
            for (int i = 0; i < paramsArray.length; i++) {

                String param = paramsArray[i];

                if (param.equals("base")) {
                    dataBean.setIdNum(identityBean.getIdNum());
                    dataBean.setName(name);
                } else if (param.equals("photo")) {
//                    dataBean.setPhotoBase64(identityBean.getPhotoBase64());

                    if (StringUtils.isNotNull(identityBean.getPhotoBase64())) {
                        String photoBase64 = identityBean.getPhotoBase64().replaceAll("\n", "");
                        dataBean.setPhotoBase64(photoBase64);
                    }

                } else if (param.equals("other")) {
                    dataBean.setSigningOrganization(identityBean.getSigningOrganization());
                    dataBean.setAddress(address);
                    dataBean.setNation(identityBean.getNation());
                    dataBean.setSex(identityBean.getSex());
                    dataBean.setBeginTime(identityBean.getBeginTime());
                    dataBean.setEndTime(identityBean.getEndTime());
                    dataBean.setBirthDate(identityBean.getBirthDate());
                }
            }

            bean.setData(dataBean);

        } else {
            dataBean.setIdNum(identityBean.getIdNum());
            dataBean.setName(name);

            dataBean.setSigningOrganization(identityBean.getSigningOrganization());
            dataBean.setAddress(address);
            dataBean.setNation(identityBean.getNation());
            dataBean.setSex(identityBean.getSex());
            dataBean.setBeginTime(identityBean.getBeginTime());
            dataBean.setEndTime(identityBean.getEndTime());
            dataBean.setBirthDate(identityBean.getBirthDate());
            dataBean.setPhotoBase64(identityBean.getPhotoBase64());

            bean.setData(dataBean);
        }


        // 回传处理结果给小程序
        try {
            JsonObject jsonObject = gson.toJsonTree(bean).getAsJsonObject();

            if (bridgeCallback != null) {
                bridgeCallback.callback(jsonObject.toString());
            } else {
                AppLogUtils.e("bridgeCallback--null");
            }

            // 日志开始----------------begin
            // 日志行数——对应web端"日志标签"
            String logLine = (new Throwable().getStackTrace())[0].toString();
            // 日志节点
            String logNode = "ACTION_IDCard--刷身份证--回传处理结果给小程序--";
            // 日志内容
            StringBuilder logContentSb = new StringBuilder();
            logContentSb.append(logNode).append(WARP)
                    .append("jsonObject = ").append(jsonObject);

            // 开始保存本地日志
            AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
                    .append(LINE)
                    .append(logLine).append(WARP)
                    .append(NODE)
                    .append(logContentSb)
                    .toString()
            );

            // 开始网络在线日志
            LogcatAddRequestBean logBean = new LogcatAddRequestBean();
            logBean.setLogType(NET_LOGCAT);
            // 对应web端"日志标签"
            logBean.setLogTag(logLine + WARP + LOG_NODE_APPLET + LOG_NODE_IDCARD);
            logBean.setLogContent(logContentSb.toString());
            requestLogcatAdd(logBean);
            // 日志开始----------------end

            // 打印编译器输出日志
            AppLogUtils.e(logContentSb);


        } catch (Throwable t) {
            AppLogUtils.e("onCalled--t" + t);
        }

        isReadIDCardSuccess = false;

    }


    // --------------------------------二维码

    boolean isDisQrCodeQueue = true;//设置标识，判断是否继续执行接收二维码返回数据线程

    private void startQrCodeSeria() {


        // 日志开始----------------begin
        // 日志行数——对应web端"日志标签"
        String logLine = (new Throwable().getStackTrace())[0].toString();
        // 日志节点
        String logNode = "二维码---初始化---开始打开串口";
        // 日志内容
        StringBuilder logContentSb = new StringBuilder();
        logContentSb.append(logNode).append(WARP);

        // 开始保存本地日志
        AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
                .append(LINE)
                .append(logLine).append(WARP)
                .append(NODE)
                .append(logContentSb)
                .toString()
        );

        // 开始网络在线日志
        LogcatAddRequestBean logBean = new LogcatAddRequestBean();
        logBean.setLogType(NET_LOGCAT);
        logBean.setLogTag(logLine + WARP + LOG_NODE_QR);
        logBean.setLogContent(logContentSb.toString());
        requestLogcatAdd(logBean);
        // 日志开始----------------end


        isDisQrCodeQueue = true;
        QrCodeSerialControl ComA = new QrCodeSerialControl();
        String pat = "";
        if (Build.MODEL.indexOf("F2") != -1) {
            pat = "/dev/ttyACM0";
        } else if (Build.MODEL.indexOf("TPS980") != -1) {
            pat = "/dev/ttyS0";
        } else if (Build.MODEL.indexOf("K8") != -1) {
            pat = "/dev/ttyACM0";
        } else if (deviceModel.equals(Constants.DeviceModel.D2)) {
            pat = "/dev/ttyHSL0";
        } else {
            String[] DevicesPath = new SerialPortFinder().getAllDevicesPath();
            AppLogUtils.e("-------startQrCodeSeria串口-----" + new Gson().toJson(DevicesPath));
            boolean isACM = false;
            for (int i = 0; i < DevicesPath.length; i++) {
                if (DevicesPath[i].indexOf("/dev/ttyACM") != -1) {
                    isACM = true;
                    continue;
                }
            }
            if (isACM) {
                for (int i = 0; i < DevicesPath.length; i++) {
                    if (DevicesPath[i].indexOf("ttyACM") != -1) {
                        pat = DevicesPath[i];
                        return;
                    }
                }
            } else {
                AppLogUtils.e("-----------未能找到对应串口，串口连接失败  ");

                // 日志开始----------------begin
                // 日志行数——对应web端"日志标签"
                String logLine22 = (new Throwable().getStackTrace())[0].toString();
                // 日志节点
                String logNode22 = "二维码---初始化---打开串口失败---未能找到对应串口";
                // 日志内容
                StringBuilder logContentSb22 = new StringBuilder();
                logContentSb22.append(logNode22).append(WARP);

                // 开始保存本地日志
                AppLogUtils.saveLog(LogType.Error, new StringBuilder()
                        .append(LINE)
                        .append(logLine22).append(WARP)
                        .append(NODE)
                        .append(logContentSb22)
                        .toString()
                );

                // 开始网络在线日志
                LogcatAddRequestBean bean22 = new LogcatAddRequestBean();
                bean22.setLogType(NET_ERROR);
                // // 对应web端"日志标签"
                bean22.setLogTag(logLine22 + WARP + LOG_NODE_QR);
                bean22.setLogContent(logContentSb22.toString());
                requestLogcatAdd(bean22);
                // 日志开始----------------end


                // 开始USB
                startUsbQr();


                return;
            }
        }
        AppLogUtils.e("--------------pat串口路径  " + pat);


        // 设置串口路径
        ComA.setPort(pat);
        // 数据位，停止位，校验位
        ComA.setN81("8", "1", "N");
        //setN81(String idataBits, String istopBits, String cparity) {
        // 波特率
        ComA.setBaudRate("9600");
        OpenQrCodeComPort(ComA);

        sPort = pat;
        dataBits = 8;
        stopBits = 1;
        parity = 'N';
        iBaudRate = 9600;
    }


    String sPort;
    int iBaudRate;
    int dataBits;
    int stopBits;
    char parity;

    public void OpenQrCodeComPort(SerialHelper comPort) {
        try {
            comPort.open();


//            String zl = "O(00,26,1)E";
//
//            byte[] bytes = zl.getBytes();
////            String s = toHexString(zl);
//            comPort.send(bytes);


            // 日志开始----------------begin
            // 日志行数——对应web端"日志标签"
            String logLine11 = (new Throwable().getStackTrace())[0].toString();
            // 日志节点
            String logNode11 = "二维码---初始化---打开串口成功";
            // 日志内容
            StringBuilder logContentSb11 = new StringBuilder();
            logContentSb11.append(logNode11).append(WARP);

            // 开始保存本地日志
            AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
                    .append(LINE)
                    .append(logLine11).append(WARP)
                    .append(NODE)
                    .append(logContentSb11)
                    .toString()
            );

            // 开始网络在线日志
            LogcatAddRequestBean logBean11 = new LogcatAddRequestBean();
            logBean11.setLogType(NET_LOGCAT);
            logBean11.setLogTag(logLine11 + WARP + LOG_NODE_QR);
            logBean11.setLogContent(logContentSb11.toString());
            requestLogcatAdd(logBean11);
            // 日志开始----------------end

            AppLogUtils.e(logContentSb11);

        } catch (SecurityException e) {
            AppLogUtils.e("-----------打开串口失败:没有串口读/写权限");

            // 日志开始----------------begin
            // 日志行数——对应web端"日志标签"
            String logLine = (new Throwable().getStackTrace())[0].toString();
            // 日志节点
            String logNode = "二维码---初始化---打开串口失败:没有串口读/写权限";
            // 日志内容
            StringBuilder logContentSb = new StringBuilder();
            logContentSb.append(logNode).append(WARP);

            // 开始保存本地日志
            AppLogUtils.saveLog(LogType.Error, new StringBuilder()
                    .append(LINE)
                    .append(logLine).append(WARP)
                    .append(NODE)
                    .append(logContentSb)
                    .toString()
            );

            // 开始网络在线日志
            LogcatAddRequestBean bean = new LogcatAddRequestBean();
            bean.setLogType(NET_ERROR);
            // 对应web端"日志标签"
            bean.setLogTag(logLine + WARP + LOG_NODE_QR);
            bean.setLogContent(logContentSb.toString());
            requestLogcatAdd(bean);
            // 日志开始----------------end


        } catch (IOException e) {
            AppLogUtils.e("-----------打开串口失败:未知错误");

            // 日志开始----------------begin
            // 日志行数——对应web端"日志标签"
            String logLine = (new Throwable().getStackTrace())[0].toString();
            // 日志节点
            String logNode = "二维码---初始化---打开串口失败:未知错误";
            // 日志内容
            StringBuilder logContentSb = new StringBuilder();
            logContentSb.append(logNode).append(WARP);

            // 开始保存本地日志
            AppLogUtils.saveLog(LogType.Error, new StringBuilder()
                    .append(LINE)
                    .append(logLine).append(WARP)
                    .append(NODE)
                    .append(logContentSb)
                    .toString()
            );

            // 开始网络在线日志
            LogcatAddRequestBean bean = new LogcatAddRequestBean();
            bean.setLogType(NET_ERROR);
            // 对应web端"日志标签"
            bean.setLogTag(logLine + WARP + LOG_NODE_QR);
            bean.setLogContent(logContentSb.toString());
            requestLogcatAdd(bean);
            // 日志开始----------------end

        } catch (InvalidParameterException e) {
            AppLogUtils.e("-----------打开串口失败:参数错误");

            // 日志开始----------------begin
            // 日志行数——对应web端"日志标签"
            String logLine = (new Throwable().getStackTrace())[0].toString();
            // 日志节点
            String logNode = "二维码---初始化---打开串口失败:参数错误";
            // 日志内容
            StringBuilder logContentSb = new StringBuilder();
            logContentSb.append(logNode).append(WARP);

            // 开始保存本地日志
            AppLogUtils.saveLog(LogType.Error, new StringBuilder()
                    .append(LINE)
                    .append(logLine).append(WARP)
                    .append(NODE)
                    .append(logContentSb)
                    .toString()
            );

            // 开始网络在线日志
            LogcatAddRequestBean bean = new LogcatAddRequestBean();
            bean.setLogType(NET_ERROR);
            // 对应web端"日志标签"
            bean.setLogTag(logLine + WARP + LOG_NODE_QR);
            bean.setLogContent(logContentSb.toString());
            requestLogcatAdd(bean);
            // 日志开始----------------end

        }
    }

    private List<ComBean> qrCodeQueueList = new ArrayList();

    public class QrCodeSerialControl extends SerialHelper {
        public QrCodeSerialControl() {
        }

        @Override
        protected void onDataReceived(final ComBean ComRecData) {
            AppLogUtils.e("-----------原始数据 bRec  " + new Gson().toJson(ComRecData.bRec));
//            qrCodeQueueList.clear();
//            qrCodeQueueList.add(ComRecData);
            AppLogUtils.e("-------数据处理后  " + MyFunc.ByteArrToHex(ComRecData.bRec));


            qrData = new String(ComRecData.bRec);
            AppLogUtils.e("-------qrData  " + qrData);
//            qrData = new String(MyFunc.ByteArrToHex(ComRecData.bRec));

            // 单次和监听都发
            sendQRtoApplet();

            // 日志开始----------------begin
            // 日志行数——对应web端"日志标签"
            String logLine = (new Throwable().getStackTrace())[0].toString();
            // 日志节点
            String logNode = LOG_NODE_QR + "结果";
            // 日志内容
            StringBuilder logContentSb = new StringBuilder();
            logContentSb.append(logNode).append(WARP)
                    .append("原始数据 = ").append(new Gson().toJson(ComRecData.bRec)).append(WARP)
                    .append("原始数据MyFunc转换 = ").append(MyFunc.ByteArrToHex(ComRecData.bRec)).append(WARP)
                    .append("qrData = ").append(qrData);

            // 开始保存本地日志
            AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
                    .append(LINE)
                    .append(logLine).append(WARP)
                    .append(NODE)
                    .append(logContentSb)
                    .toString()
            );

            // 开始网络在线日志
            LogcatAddRequestBean bean = new LogcatAddRequestBean();
            bean.setLogType(NET_LOGCAT);
            bean.setLogTag(logLine + WARP + LOG_NODE_QR);
            bean.setLogContent(logContentSb.toString());
            requestLogcatAdd(bean);
            // 日志开始----------------end


        }

        //尝试进行转换
        @Override
        protected void DoQueue() {
            if (qrCodeQueueList.size() > 0) {
//                for (int i = 0; i < qrCodeQueueList.size(); i++) {
//                    qrData = qrData + new String(qrCodeQueueList.get(i).bRec);
//                }
//                AppLogUtils.e("-----------QrCodeSerialControl二维码结果  " + qrData);
                qrData = new String(qrCodeQueueList.get(0).bRec);
                AppLogUtils.e("-----------QrCodeSerialControl二维码结果bRec  " + qrData);

                // 日志开始----------------begin
                // 日志行数——对应web端"日志标签"
                String logLine = (new Throwable().getStackTrace())[0].toString();
                // 日志节点
                String logNode = LOG_NODE_QR + "结果";
                // 日志内容
                StringBuilder logContentSb = new StringBuilder();
                logContentSb.append(logNode).append(WARP)
                        .append("转换后的数据qrData = ").append(qrData);

                // 开始保存本地日志
                AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
                        .append(LINE)
                        .append(logLine).append(WARP)
                        .append(NODE)
                        .append(logContentSb)
                        .toString()
                );

                // 开始网络在线日志
                LogcatAddRequestBean bean = new LogcatAddRequestBean();
                bean.setLogType(NET_LOGCAT);
                // 对应web端"日志标签"
                bean.setLogTag(logLine + WARP + LOG_NODE_QR);
                bean.setLogContent(logContentSb.toString());
                requestLogcatAdd(bean);
                // 日志开始----------------end


                // 单次和监听都发
                sendQRtoApplet();

//                startQrCodeSeria();


//                ToastUtils.showLongToast("QrCodeSerialControl二维码结果  " + qrData);

//                RecHandler.postDelayed(RecRunnable, 0);
                qrCodeQueueList.clear();
            }
        }
    }

    /**
     * 二维码
     * 单次和监听发送数据
     */
    private void sendQRtoApplet() {
        JSONObject object = new JSONObject();
        try {
            // 勿动key，对外的文档key
            object.put("qrCode", qrData);
        } catch (Throwable t) {

        }
        // 监听，主动推送给小程序
        sendMessageToApplet(EVENT_QR_LISTENER, object.toString());


        // 单次发送给小程序
        runOnUiThread(new Runnable() {
            @Override
            public void run() {

                AmpeActionDataBean ampeActionDataBean = ampeActionMap.get(ACTION_QR);
                if (ampeActionDataBean == null) {
                    AppLogUtils.e("ampeActionDataBean == null");
                    return;
                }

                AromeServiceInvoker.BridgeCallback bridgeCallback = null;
                try {
                    bridgeCallback = ampeActionDataBean.getBridgeCallback();
                } catch (NullPointerException e) {
                    e.printStackTrace();
                }

                AmpeAppletResultBean bean = new AmpeAppletResultBean();
                bean.setAction(ACTION_QR);
                bean.setEvent(ampeActionDataBean.getEvent());
                bean.setTaskId(ampeActionDataBean.getTaskId());
                bean.setSuccess(true);
                bean.setMessage("成功");

                AmpeAppletResultBean.Data dataBean = new AmpeAppletResultBean.Data();
                dataBean.setQrCode(qrData);
                bean.setData(dataBean);

                // 回传处理结果给小程序
                try {
                    JsonObject jsonObject = gson.toJsonTree(bean).getAsJsonObject();
                    if (bridgeCallback != null) {
                        bridgeCallback.callback(jsonObject.toString());
                    }

//                    // 日志开始----------------begin
//                    // 日志行数——对应web端"日志标签"
//                    String logLine = (new Throwable().getStackTrace())[0].toString();
//                    // 日志节点
//                    String logNode = "ACTION_QR--二维码--回传处理结果给小程序";
//                    // 日志内容
//                    StringBuilder logContentSb = new StringBuilder();
//                    logContentSb.append(logNode).append(WARP)
//                            .append("jsonObject = ").append(jsonObject);
//
//                    // 开始保存本地日志
//                    AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
//                            .append(LINE)
//                            .append(logLine).append(WARP)
//                            .append(NODE)
//                            .append(logContentSb)
//                            .toString()
//                    );
//
//                    // 开始网络在线日志
//                    LogcatAddRequestBean logBean = new LogcatAddRequestBean();
//                    logBean.setLogType(NET_LOGCAT);
//                    // 对应web端"日志标签"
//                    logBean.setLogTag(logLine + WARP + LOG_NODE_APPLET + LOG_NODE_QR);
//                    logBean.setLogContent(logContentSb.toString());
//                    requestLogcatAdd(logBean);
//                    // 日志开始----------------end
//
//                    // 打印编译器输出日志
//                    AppLogUtils.e(logContentSb);


                    // 日志打印和保存（本地和网络）
                    logPrintSave(NET_LOGCAT,
                            (new Throwable().getStackTrace())[0].toString(),
                            LOG_NODE_APPLET + LOG_NODE_QR+"--回传处理结果给小程序",
                            "qrData = " + qrData,
                            "jsonObject = " + jsonObject
                    );


                } catch (Throwable t) {
                    AppLogUtils.e("onCalled--t" + t);
                }

            }
        });
    }


    public String qrData = "";


    private void startUsbQr() {
        QrUsb qrUsb = new QrUsb();

        qrUsb.init(mContext, new QrUsb.QrResultCallback() {
            @Override
            public void onScanSuccess(String qrCode) {

                // 防抖处理
//                long currentTime = Calendar.getInstance().getTimeInMillis();
//
//                AppLogUtils.e("小程序通道入参--",
//                        "lastQrCode:"+lastQrCode,
//                        "qrCode:"+qrCode,
//                        "lastQrTime:"+ lastQrTime,
//                        "currentTime:"+currentTime
//                );
//
//
//                if (lastQrCode.equals(qrCode) &&
//                        currentTime - lastQrTime <= MIN_QR_TIME) {
//                    AppLogUtils.e("同一条数据，并且小于指定时间，忽略");
//                    return;
//                }else{
//                    AppLogUtils.e("数据正常执行");
//                }
//
//                lastQrTime = currentTime;
//                // 设置可执行的指令
//                lastQrCode = qrCode;


                qrData = qrCode;


                // 单次和监听都发
                sendQRtoApplet();


            }

            @Override
            public void onScanFail() {

            }

            @Override
            public void onInitSuccess() {

                AppLogUtils.e("USB——onInitSuccess");

                // 日志打印和保存（本地和网络）
                logPrintSave(NET_LOGCAT,
                        (new Throwable().getStackTrace())[0].toString(),
                        LOG_NODE_QR,
                        "USB-扫码头初始化成功"
                );

            }

            @Override
            public void onInitFail(String errMsg) {

                AppLogUtils.e("USB——onInitFail：" + errMsg);

                // 日志打印和保存（本地和网络）
                logPrintSave(NET_LOGCAT,
                        (new Throwable().getStackTrace())[0].toString(),
                        LOG_NODE_QR,
                        "USB-扫码头初始化失败:" + errMsg
                );

            }
        });

    }


    public void getDeviceInfo(String event, String taskId, AromeServiceInvoker.BridgeCallback bridgeCallback) {


        AmpeAppletResultBean bean = new AmpeAppletResultBean();
        bean.setAction(ACTION_DEVICE);
        bean.setEvent(event);
        bean.setTaskId(taskId);
        bean.setSuccess(true);
        bean.setMessage("成功");

        AmpeAppletResultBean.Data dataBean = new AmpeAppletResultBean.Data();
        // sn
        dataBean.setSn(DeviceUtils.getDeviceSN());
        // 设备型号
        dataBean.setDeviceModel(DeviceUtils.getDeviceModel());
        // IP
        dataBean.setDeviceIP(DeviceUtils.getDeviceIP());
        // 设备固件号
        dataBean.setdeviceDisplay(DeviceUtils.getDeviceDisplay());
        // app版本号
        dataBean.setAppVersion(DeviceUtils.getAppVersionCode(mActivity) + "");
        // android版本
        dataBean.setAndroidVersion(DeviceUtils.getAndroidVersion());
        // 设置data
        bean.setData(dataBean);
        AppLogUtils.e("bean:" + bean.toString());

        // 回传处理结果给小程序
        try {
            JsonObject jsonObject = gson.toJsonTree(bean).getAsJsonObject();
            if (bridgeCallback != null) {
                bridgeCallback.callback(jsonObject.toString());
            }

            // 日志开始----------------begin
            // 日志行数——对应web端"日志标签"
            String logLine = (new Throwable().getStackTrace())[0].toString();
            // 日志节点
            String logNode = "ACTION_DEVICE--设备信息--回传处理结果给小程序--";
            // 日志内容
            StringBuilder logContentSb = new StringBuilder();
            logContentSb.append(logNode).append(WARP)
                    .append("jsonObject = ").append(jsonObject);

            // 开始保存本地日志
            AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
                    .append(LINE)
                    .append(logLine).append(WARP)
                    .append(NODE)
                    .append(logContentSb)
                    .toString()
            );

            // 开始网络在线日志
            LogcatAddRequestBean logBean = new LogcatAddRequestBean();
            logBean.setLogType(NET_LOGCAT);
            // 对应web端"日志标签"
            logBean.setLogTag(logLine + WARP + LOG_NODE_APPLET + LOG_NODE_DEVICE);
            logBean.setLogContent(logContentSb.toString());
            requestLogcatAdd(logBean);
            // 日志开始----------------end

            // 打印编译器输出日志
            AppLogUtils.e(logContentSb);

        } catch (Throwable t) {
            AppLogUtils.e("onCalled--t" + t);
        }


    }


    public void speech(String event, String taskId, AromeServiceInvoker.BridgeCallback bridgeCallback, boolean isSuccess, String msg) {


        AmpeAppletResultBean bean = new AmpeAppletResultBean();
        bean.setAction(ACTION_SPEECH);
        bean.setEvent(event);
        bean.setTaskId(taskId);
        bean.setSuccess(isSuccess);
        bean.setMessage(msg);

        AmpeAppletResultBean.Data dataBean = new AmpeAppletResultBean.Data();
        // 设置data
        bean.setData(dataBean);
        AppLogUtils.e("bean:" + bean.toString());

        // 回传处理结果给小程序
        try {
            JsonObject jsonObject = gson.toJsonTree(bean).getAsJsonObject();
            if (bridgeCallback != null) {
                bridgeCallback.callback(jsonObject.toString());
            }

            // 日志开始----------------begin
            // 日志行数——对应web端"日志标签"
            String logLine = (new Throwable().getStackTrace())[0].toString();
            // 日志节点
            String logNode = "ACTION_DEVICE--语音播报--回传处理结果给小程序--";
            // 日志内容
            StringBuilder logContentSb = new StringBuilder();
            logContentSb.append(logNode).append(WARP)
                    .append("jsonObject = ").append(jsonObject);

            // 开始保存本地日志
            AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
                    .append(LINE)
                    .append(logLine).append(WARP)
                    .append(NODE)
                    .append(logContentSb)
                    .toString()
            );


            // 开始网络在线日志
            LogcatAddRequestBean logBean = new LogcatAddRequestBean();
            logBean.setLogType(NET_LOGCAT);
            // 对应web端"日志标签"
            logBean.setLogTag(logLine + WARP + LOG_NODE_APPLET + LOG_NODE_SPEECH);
            logBean.setLogContent(logContentSb.toString());
            requestLogcatAdd(logBean);
            // 日志开始----------------end

            // 打印编译器输出日志
            AppLogUtils.e(logContentSb);

        } catch (Throwable t) {
            AppLogUtils.e("onCalled--t" + t);
        }


    }


    // ------------------------OMC相关的操作
    // 关闭app
    private void closeApp() {
        AppLogUtils.e("closeApp");
        finish();
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(0);
    }


    // 调用刷脸服务 1:N
    public void invokeScanFace(StartReadyBpaasServiceBean bpaasServiceBean) {
        AppLogUtils.e("invokeScanFace");

        AppLogUtils.e("补光灯开启");
        // 补光灯开启
        iDeviceUI.showFillLight(mActivity);

//        invokeResume();

        CardOrCode = "face";

//        if (Config.taskStatus.equals("doing") || Config.taskStatus.equals("wait")) {
        ConfigData.setFaceScenicUtile(faceScenicUtile, true);
        Map<String, Object> params = new HashMap<>();
//        params.put("checkWay", ConfigData.checkWay);
        params.put("checkWay", "scanFace");

        invoke(params, ConfigData.mSessionId);
//        }
    }

    String certName;
    String certNo;

    // 调用 1: 1人证比对服务
    public void invokePersonCard(String certName, String certNo, String certPhotoBase64Str) {

        AppLogUtils.e("invokePersonCard---certName:" + certName + "---certNo:" + certNo + "---certPhotoBase64Str:" + certPhotoBase64Str);

        AppLogUtils.e("补光灯开启");
        // 补光灯开启
        iDeviceUI.showFillLight(mActivity);

//        invokeResume();

        this.certName = certName;
        this.certNo = certNo;
        if (!CardOrCode.equals("enterIDNumber")) {
            CardOrCode = "personCard";
        }
        Map<String, Object> params = new HashMap<>();
        params.put("checkWay", "personCard");
        params.put("certNo", certNo);
        params.put("certName", certName);
        params.put("certPhotoBase64Str", certPhotoBase64Str);
        //参见 3.2.5
        invoke(params, ConfigData.mSessionId);
    }

    public void invoke(Map<String, Object> params, String mSessionId) {
        AppLogUtils.e("invoke -- params = " + params.toString());
        AppLogUtils.e("invoke -- mSessionId = " + mSessionId);
        // 初始化Bpaas服务前先判断mSessionId
        if (mSessionId == null) {
            AppLogUtils.e("invoke, mSessionId is null");
            return;
        }
        if (params == null) {
            params = new HashMap<>();
        }


        params.put(BPaaSApi.KEY_BPAAS_IPC_TIME_OUT, -1L);

        AppLogUtils.e("invoke -- params = " + params.toString());

        // 打印用
        final Map<String, Object> paramsNew = params;

        BPaaSApi.getInstance().invoke(ConfigData.getDeviceConfigResultBean().getAbcpAppId(),
                "BPaasVerifyID", params, mSessionId, new BPaaSCallback() {
                    @Override
                    public void onResponse(BPaaSResponse bPaaSResponse) {
                        // 只要能刷脸就会在这里，但刷脸的authcode和ftoken要到onEvent中拿
                        // 非主线程
                        AppLogUtils.e("---调用刷脸invoke onResponse = " + new Gson().toJson(bPaaSResponse) + "-----CardOrCode = " + CardOrCode);

//                        AppLogUtils.e("补光灯关闭");
//                        // 补光灯关闭
//                        iDeviceUI.hideFillLight(mActivity);

                        // {"mCode":1001,"mExtInfo":{},"mSubCode":"E69010","mSubMsg":"服务未连接(E69010)"}

                        int code = bPaaSResponse.getCode();

                        // 日志开始----------------begin
                        // 日志行数——对应web端"日志标签"
                        String logLine = (new Throwable().getStackTrace())[0].toString();
                        // 日志节点
                        String logNode = "刷脸invoke---onResponse---";
                        // 日志内容
                        StringBuilder logContentSb = new StringBuilder();
                        logContentSb.append(logNode).append(WARP)
                                .append("params = ").append(paramsNew).append(WARP)
                                .append("code = ").append(code).append(WARP)
                                .append("bPaaSResponse = ").append(bPaaSResponse).append(WARP)
                                .append("bPaaSResponseJson = ").append(gson.toJson(bPaaSResponse)).append(WARP)
                        ;

                        // 开始保存本地日志
                        AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
                                .append(LINE)
                                .append(logLine).append(WARP)
                                .append(NODE)
                                .append(logContentSb)
                                .toString()
                        );

                        // 开始网络在线日志
                        LogcatAddRequestBean bean = new LogcatAddRequestBean();
                        bean.setLogType(NET_LOGCAT);
                        // 对应web端"日志标签"
                        bean.setLogTag(logLine + WARP + LOG_NODE_FACE);
                        bean.setLogContent(logContentSb.toString());
                        requestLogcatAdd(bean);
                        // 日志开始----------------end


                        if (code == 1000) {
                            if (ConfigData.taskStatus.equals("complete") || (!CardOrCode.equals("QrCard") &&
                                    !CardOrCode.equals("Card"))) {
                                return;
                            }

                            timeHandler.removeCallbacks(heartBeatRunnable);//结束核点超时的保底机制
                            ConfigData.taskStatus = "complete";

//                            SetFederatedPlatformsBean setFederatedPlatformsBean = Config.getSetFederatedPlatformsBean();
//                            setMyFederatedPlatforms(setFederatedPlatformsBean,
//                                    setFederatedPlatformsBean.getData().get(0).getName(),
//                                    setFederatedPlatformsBean.getData().get(0).getCardid(),
//                                    setFederatedPlatformsBean.getData().get(0).getPhone());
                        } else if (code == 1001) {
                            ToastUtils.showLongToast(bPaaSResponse.getSubMsg());
//                            LocalremoveTouchView();
                        }
                    }

                    @Override
                    public void onEvent(String id, String resultStr, Bundle bundle) {
                        AppLogUtils.e("---调用刷脸invoke--onEvent--id = " + id + "----resultStr = " + resultStr + "-- bundle = " + new Gson().toJson(bundle));
                        // {"alipayUid":"","code":1001,"extInfo":"{\"authCode\":\"\"}","isvResult":true,"subCode":"Z6136","subMessage":"没有认出你，请再试一次(Z6136)","vid":""}null
                        // {"alipayUid":"2088612116677214","code":1000,"extInfo":"{\"authCode\":\"b34a132e7650445eb9b254d5dd7dDD21\"}","ftoken":"fp103df6a4e88e2611591822c46101e3h91","isvResult":true,"subCode":"","subMessage":"","vid":""}-- bundle = null

                        AppLogUtils.e("--调用刷脸invoke--onEvent--CardOrCode:" + CardOrCode);

                        AppLogUtils.e("补光灯关闭");
                        // 补光灯关闭
                        iDeviceUI.hideFillLight(mActivity);

                        // 日志开始----------------begin
                        // 日志行数——对应web端"日志标签"
                        String logLine = (new Throwable().getStackTrace())[0].toString();
                        // 日志节点
                        String logNode = "刷脸invoke---onEvent---";
                        // 日志内容
                        StringBuilder logContentSb = new StringBuilder();
                        logContentSb.append(logNode).append(WARP)
                                .append("id = ").append(id).append(WARP)
                                .append("resultStr = ").append(resultStr).append(WARP)
                                .append("bundle = ").append(new Gson().toJson(bundle));

                        // 开始保存本地日志
                        AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
                                .append(LINE)
                                .append(logLine).append(WARP)
                                .append(NODE)
                                .append(logContentSb)
                                .toString()
                        );

                        // 开始网络在线日志
                        LogcatAddRequestBean bean = new LogcatAddRequestBean();
                        bean.setLogType(NET_LOGCAT);
                        // 对应web端"日志标签"
                        bean.setLogTag(logLine + WARP + LOG_NODE_FACE);
                        bean.setLogContent(logContentSb.toString());
                        requestLogcatAdd(bean);
                        // 日志开始----------------end

                        // 将resultStr转成json
                        InvokeScanFaceBean invokeScanFaceBean = new Gson().fromJson(resultStr, InvokeScanFaceBean.class);

                        // 重新唤起
                        invokeResume();


                        AmpeActionDataBean ampeActionDataBean = null;
                        String action = "";
                        if (isInitFace && CardOrCode.equals("personCard")) {
                            // 初始化成功，且是1:1
                            AppLogUtils.e("BPaaSApi--startBpaasService--onEvent--isInitFace & isFacePersonCard");
                            ampeActionDataBean = ampeActionMap.get(ACTION_FACE_PERSONCARD);
                            action = ACTION_FACE_PERSONCARD;
                        } else if (isInitFace && CardOrCode.equals("enterIDNumber")) {
                            // 初始化成功，且是1:1
                            AppLogUtils.e("BPaaSApi--startBpaasService--onEvent--isInitFace & isFacePersonCard");
                            ampeActionDataBean = ampeActionMap.get(ACTION_ENTERIDNUMBER);
                            action = ACTION_ENTERIDNUMBER;
                        } else if (isInitFace && CardOrCode.equals("face")) {
                            // 初始化成功，且是1:N
                            AppLogUtils.e("BPaaSApi--startBpaasService--onEvent--isInitFace");
                            ampeActionDataBean = ampeActionMap.get(ACTION_FACE);
                            action = ACTION_FACE;
                        } else if (isJxInitFace) {
                            AppLogUtils.e("BPaaSApi--startBpaasService--onEvent--isJxInitFace");
                            ampeActionDataBean = ampeActionMap.get(ACTION_SCAN_FACE);
                            action = ACTION_SCAN_FACE;
                        }

                        if (ampeActionDataBean == null) {
                            AppLogUtils.e("ampeActionDataBean == null");
                            return;
                        }

                        AromeServiceInvoker.BridgeCallback bridgeCallback = ampeActionDataBean.getBridgeCallback();

                        AmpeAppletResultBean ampeAppletResultBean = new AmpeAppletResultBean();
                        ampeAppletResultBean.setAction(action);
                        ampeAppletResultBean.setEvent(ampeActionDataBean.getEvent());
                        ampeAppletResultBean.setTaskId(ampeActionDataBean.getTaskId());


                        if (invokeScanFaceBean.getCode() == 1000) {

                            if (CardOrCode.equals("face") || CardOrCode.equals("personCard")) {
                                // 刷脸 1:N
                                // String userInfoTestData = "{\"vid\":\"\",\"code\":1000,\"isvResult\":true,\"subCode\":\"\",\"ftoken\":\"fp174ad54ffa1d5e6a532583d5017e12h84\",\"sn\":\"224F010T01400827\",\"subMessage\":\"\",\"alipayUid\":\"2088612116677214\",\"extInfo\":\"{\\\"authCode\\\":\\\"87ac7d355f1b4eeba2d4080bb427FX21\\\"}\"}\n";


                                // 根据配置是否请求用户信息三要素
                                boolean appGetUserInfo = deviceConfigBean.isAppGetUserInfo();
                                AppLogUtils.e("appGetUserInfo = " + appGetUserInfo);
                                if (appGetUserInfo) {
                                    // 获取三要素
                                    AlipayUserInfoRequestBean alipayUserInfoRequestBean = gson.fromJson(resultStr, AlipayUserInfoRequestBean.class);
                                    alipayUserInfoRequestBean.setSn(DeviceUtils.getDeviceSN());
                                    if (mAlipayUserInfoPresenter == null) {
                                        mAlipayUserInfoPresenter = new AlipayUserInfoPresenter(MainActivity.this);
                                    }
                                    mAlipayUserInfoPresenter.requestAlipayUserInfo(alipayUserInfoRequestBean);


                                    // 日志开始保存----------------begin
                                    // 日志行数——对应web端"日志标签"
                                    String logLineUserInfo = (new Throwable().getStackTrace())[0].toString();
                                    // 日志节点
                                    String logNodeUserInfo = "用户信息三要素---入参---";
                                    // 日志内容
                                    StringBuilder logContentSbUserInfo = new StringBuilder();
                                    logContentSbUserInfo.append(logNodeUserInfo).append(WARP)
                                            .append("alipayUserInfoRequestBean = ").append(alipayUserInfoRequestBean.toString());

                                    // 开始保存本地日志
                                    AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
                                            .append(LINE)
                                            .append(logLineUserInfo).append(WARP)
                                            .append(NODE)
                                            .append(logContentSbUserInfo)
                                            .toString()
                                    );

                                    // 开始网络在线日志
                                    LogcatAddRequestBean logBeanUserInfo = new LogcatAddRequestBean();
                                    logBeanUserInfo.setLogType(NET_LOGCAT);
                                    // 对应web端"日志标签"
                                    logBeanUserInfo.setLogTag(logLineUserInfo + WARP + LOG_NODE_FACE);
                                    logBeanUserInfo.setLogContent(logContentSbUserInfo.toString());
                                    requestLogcatAdd(logBeanUserInfo);
                                    // 日志开始保存----------------end

                                    // 打印编译器输出日志
                                    AppLogUtils.e(logContentSbUserInfo);

                                } else {
                                    // 不获取，直接返回支付宝刷脸结果
//                                    AmpeActionDataBean ampeActionDataBean = ampeActionMap.get(ACTION_FACE);

                                    if (ampeActionDataBean == null) {
                                        AppLogUtils.e("ampeActionDataBean == null");
                                        return;
                                    }

                                    AmpeAppletResultBean.Data dataBean = gson.fromJson(resultStr, AmpeAppletResultBean.Data.class);
                                    dataBean.setOriginFaceInfo(resultStr);
                                    ampeAppletResultBean.setData(dataBean);

                                    // 回传处理结果给小程序
                                    try {
                                        JsonObject jsonObject = gson.toJsonTree(ampeAppletResultBean).getAsJsonObject();

                                        if (bridgeCallback != null) {
                                            bridgeCallback.callback(jsonObject.toString());
                                        }


                                        // 日志开始----------------begin
                                        // 日志行数——对应web端"日志标签"
                                        String logLine11 = (new Throwable().getStackTrace())[0].toString();
                                        // 日志节点
                                        String logNode11 = action + "--刷脸--支付宝结果--回传处理结果给小程序--";
                                        // 日志内容
                                        StringBuilder logContentSb11 = new StringBuilder();
                                        logContentSb11.append(logNode11).append(WARP)
                                                .append("jsonObject = ").append(jsonObject).append(WARP)
                                                .append("appGetUserInfo = ").append(appGetUserInfo);

                                        // 开始保存本地日志
                                        AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
                                                .append(LINE)
                                                .append(logLine11).append(WARP)
                                                .append(NODE)
                                                .append(logContentSb11)
                                                .toString()
                                        );

                                        // 开始网络在线日志
                                        LogcatAddRequestBean bean11 = new LogcatAddRequestBean();
                                        bean11.setLogType(NET_LOGCAT);
                                        // 对应web端"日志标签"
                                        bean11.setLogTag(logLine11 + WARP + LOG_NODE_APPLET + LOG_NODE_FACE);
                                        bean11.setLogContent(logContentSb11.toString());
                                        requestLogcatAdd(bean11);
                                        // 日志开始----------------end

                                        // 打印编译器输出日志
                                        AppLogUtils.e(logContentSb11);


                                    } catch (Throwable t) {
                                        AppLogUtils.e("onCalled--t" + t);
                                    }


                                }


                            }


                            //
                            ConfigData.taskStatus = "complete";


                        } else {

                            // 非1000

                            if (CardOrCode.equals("face") || CardOrCode.equals("personCard")) {
//                                AmpeActionDataBean ampeActionDataBean = ampeActionMap.get(ACTION_FACE);

                                if (ampeActionDataBean == null) {
                                    AppLogUtils.e("ampeActionDataBean == null");
                                    return;
                                }

                                ampeAppletResultBean.setAction(action);
                                ampeAppletResultBean.setEvent(ampeActionDataBean.getEvent());
                                ampeAppletResultBean.setTaskId(ampeActionDataBean.getTaskId());
                                ampeAppletResultBean.setSuccess(false);
                                ampeAppletResultBean.setMessage(resultStr);

                                AmpeAppletResultBean.Data dataBean = gson.fromJson(resultStr, AmpeAppletResultBean.Data.class);
                                dataBean.setOriginFaceInfo(resultStr);
                                ampeAppletResultBean.setData(dataBean);

                                // 回传处理结果给小程序
                                try {
                                    JsonObject jsonObject = gson.toJsonTree(ampeAppletResultBean).getAsJsonObject();

                                    if (bridgeCallback != null) {
                                        bridgeCallback.callback(jsonObject.toString());
                                    }

                                    // 日志开始----------------begin
                                    // 日志行数——对应web端"日志标签"
                                    String logLine11 = (new Throwable().getStackTrace())[0].toString();
                                    // 日志节点
                                    String logNode11 = action + "--刷脸--异常--支付宝结果--回传处理结果给小程序--";
                                    // 日志内容
                                    StringBuilder logContentSb11 = new StringBuilder();
                                    logContentSb11.append(logNode11).append(WARP)
                                            .append("jsonObject = ").append(jsonObject).append(WARP);

                                    // 开始保存本地日志
                                    AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
                                            .append(LINE)
                                            .append(logLine11).append(WARP)
                                            .append(NODE)
                                            .append(logContentSb11)
                                            .toString()
                                    );

                                    // 开始网络在线日志
                                    LogcatAddRequestBean bean11 = new LogcatAddRequestBean();
                                    bean11.setLogType(NET_LOGCAT);
                                    // 对应web端"日志标签"
                                    bean11.setLogTag(logLine11 + WARP + LOG_NODE_APPLET + LOG_NODE_FACE);
                                    bean11.setLogContent(logContentSb11.toString());
                                    requestLogcatAdd(bean11);
                                    // 日志开始----------------end

                                    // 打印编译器输出日志
                                    AppLogUtils.e(logContentSb11);


                                } catch (Throwable t) {
                                    AppLogUtils.e("onCalled--t" + t);
                                }
                            }


                            if (invokeScanFaceBean.getCode() == 1001) {
                                //

                            } else if (invokeScanFaceBean.getCode() == 2006) {
                                // 无法认出

                            }

                        }


                    }
                });
    }


    // 重新唤起刷脸
    public void invokeResume() {
        Map<String, Object> params = new HashMap<>();
        params.put("action", "resume");

        // 日志开始----------------begin
        // 日志行数——对应web端"日志标签"
        String logLine = (new Throwable().getStackTrace())[0].toString();
        // 日志节点
        String logNode = LOG_NODE_FACE + "invokeResume---重新唤起刷脸---";
        // 日志内容
        StringBuilder logContentSb = new StringBuilder();
        logContentSb.append(logNode).append(WARP)
                .append("params = ").append(params.toString());

        // 开始保存本地日志
        AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
                .append(LINE)
                .append(logLine).append(WARP)
                .append(NODE)
                .append(logContentSb)
                .toString()
        );

        // 开始网络在线日志
        LogcatAddRequestBean bean = new LogcatAddRequestBean();
        bean.setLogType(NET_LOGCAT);
        // 对应web端"日志标签"
        bean.setLogTag(logLine + WARP + LOG_NODE_FACE);
        bean.setLogContent(logContentSb.toString());
        requestLogcatAdd(bean);
        // 日志开始----------------end


        //参见 3.2.5
        invoke(params, ConfigData.mSessionId);
    }


    boolean hasPermission;


    /**
     * 请求权限
     */
    private void requestPermissionsMethod() {
        int targetSdkVersion = this.getApplicationInfo().targetSdkVersion;
        if (targetSdkVersion < 30) {
            return;
        }
        XXPermissions.with(this)
                // 申请多个权限
                .permission(Permission.MANAGE_EXTERNAL_STORAGE)
                // 设置权限请求拦截器（局部设置）
                //.interceptor(new PermissionInterceptor())
                // 设置不触发错误检测机制（局部设置）
                //.unchecked()
                .request(new OnPermissionCallback() {

                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        hasPermission = true;
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                    }
                });
    }


    // ----------aidl 消息互通-----------
    private void bindService() {

        AppLogUtils.e("bindService");
        Intent intent = new Intent();
        // 对应服务端AndroidManifest.xml配置service action:name
        String ACTION = "com.hh.hhomc.services.AidlService";
        intent.setAction(ACTION);
        // 对应服务端AndroidManifest.xml package,可能会是测试包，注意打印对应服务端app包名，不然会连不上
        intent.setPackage(BuildConfig.AIDL_SERVER_APP_PACKAGE_NAME);
        bindService(intent, serviceConnection, BIND_AUTO_CREATE);

    }

    IAidlInterface iAidlInterface;

    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            AppLogUtils.e("onServiceConnected");
            iAidlInterface = IAidlInterface.Stub.asInterface(iBinder);
            AppLogUtils.e("onServiceConnected--iAidlInterface--" + iAidlInterface);
            try {
                iAidlInterface.asBinder().linkToDeath(mDeathRecipient, 0);
                iAidlInterface.registerCallBack(iAidlCallBack);


                // 日志开始----------------begin
                // 日志行数——对应web端"日志标签"
                String logLine = (new Throwable().getStackTrace())[0].toString();
                // 日志节点
                String logNode = "AIDL---消息通道成功---";
                // 日志内容
                StringBuilder logContentSb = new StringBuilder();
                logContentSb.append(logNode).append(WARP)
                        .append("sn = ").append(DeviceUtils.getDeviceSN()).append(WARP)
                        .append("arome包名 = ").append(DeviceUtils.getAppPackageName(mActivity)).append(WARP)
                        .append("arome版本号 = ").append(DeviceUtils.getAppVersionName(mActivity));

                // 开始保存本地日志
                AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
                        .append(LINE)
                        .append(logLine).append(WARP)
                        .append(NODE)
                        .append(logContentSb)
                        .toString()
                );

                // 开始网络在线日志
                LogcatAddRequestBean bean = new LogcatAddRequestBean();
                bean.setLogType(NET_LOGCAT);
                // 对应web端"日志标签"
                bean.setLogTag(logLine + WARP + LOG_NODE_DEVICE + LOG_NODE_AIDL);
                bean.setLogContent(logContentSb.toString());
                requestLogcatAdd(bean);
                // 日志开始----------------end


                // 发送消息
//                sendAppInfoMessage();

                // 发送消息
//                if (iAidlInterface != null) {
//                    AppMessageBean sendBean = new AppMessageBean();
//                    sendBean.setBusinessAppPackageName(DeviceUtils.getAppPackageName(mActivity));
//                    sendBean.setBusinessAppVersionName(DeviceUtils.getAppVersionName(mActivity));
//                    iAidlInterface.setAppMessageBean(sendBean);
//                    AppLogUtils.e("发送消息");
//                }


            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {

        }
    };

    private IBinder.DeathRecipient mDeathRecipient = new IBinder.DeathRecipient() {
        //当承载IBinder的进程消失时接收回调的接口
        @Override
        public void binderDied() {
            if (null == iAidlInterface) {
                return;
            }
            iAidlInterface.asBinder().unlinkToDeath(mDeathRecipient, 0);
            iAidlInterface = null;
            //断线重来逻辑
        }
    };

    private IAidlCallBack iAidlCallBack = new IAidlCallBack.Stub() {
        @Override
        public void onMessageSuccess(AppMessageBean appMessageBean) throws RemoteException {
            AppLogUtils.e("IAidlCallBack---getAppMessageBean" + appMessageBean.toString());


            // TODO 这里就是接收到hhomc发送的消息，开始处理对应业务逻辑

            // 接受消息
//            AppMessageBean getBean = iAidlInterface.getAppMessageBean();
            if (appMessageBean != null) {
                AppLogUtils.e("接受消息 = " + appMessageBean.toString());
                String op = appMessageBean.getOp();

                if (CLOSE_APP.equals(op)) {
                    AppLogUtils.e("接受消息CLOSE_APP");

                    String businessAppPackageName = appMessageBean.getBusinessAppPackageName();
                    AppLogUtils.e("接受消息CLOSE_APP---businessAppPackageName = " + businessAppPackageName);

                    // 日志开始----------------begin
                    // 日志行数——对应web端"日志标签"
                    String logLine = (new Throwable().getStackTrace())[0].toString();
                    // 日志节点
                    String logNode = "iAidlCallBack--接受消息--CLOSE_APP---";
                    // 日志内容
                    StringBuilder logContentSb = new StringBuilder();
                    logContentSb.append(logNode).append(WARP)
                            .append("sn = ").append(DeviceUtils.getDeviceSN()).append(WARP)
                            .append("arome包名 = ").append(DeviceUtils.getAppPackageName(mActivity)).append(WARP)
                            .append("arome版本号 = ").append(DeviceUtils.getAppVersionName(mActivity)).append(WARP)
                            .append("appMessageBean = ").append(appMessageBean.toString());
                    ;

                    // 开始保存本地日志
                    AppLogUtils.saveLog(LogType.Logcat, new StringBuilder()
                            .append(LINE)
                            .append(logLine).append(WARP)
                            .append(NODE)
                            .append(logContentSb)
                            .toString()
                    );

                    // 开始网络在线日志
                    LogcatAddRequestBean bean = new LogcatAddRequestBean();
                    bean.setLogType(NET_LOGCAT);
                    // 对应web端"日志标签"
                    bean.setLogTag(logLine + WARP + LOG_NODE_DEVICE + LOG_NODE_AIDL);
                    bean.setLogContent(logContentSb.toString());
                    requestLogcatAdd(bean);
                    // 日志开始----------------end


//                    onDestroyUnregister();

//                    AppMessageBean bean = new AppMessageBean();
//                    bean.setOp(CLOSE_APP);
//                    bean.setSender(aidlSender);
//                    iAidlInterface.setAppMessageBean(bean);

//                    new Handler().postDelayed(new Runnable() {
//                        @Override
//                        public void run() {
                    // 上面的代码放开任意一段，都会导致无法关闭app

                    if (StringUtils.isNull(businessAppPackageName)) {
                        return;
                    } else if (businessAppPackageName.equals(DeviceUtils.getAppPackageName(MyApplication.getContext()))) {
                        AppLogUtils.e("包名一致，开始关闭App");
                        if (isLaunchApplet) {
                            // 先退出小程序
                            exitApplet();

                            mHandler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    closeApp();
                                }
                            }, 1 * 1000);


                        } else {
                            closeApp();
                        }
                    }


//                        }
//                    }, 1500); //延时10s执行run内代码


                } else if (REBOOT.equals(op)) {

                    iDeviceUI.reboot();

                }


            }


        }


//        @Override
//        public void setAppMessageBean(AppMessageBean appMessageBean) throws RemoteException {
//            AppLogUtils.e("IAidlCallBack---setAppMessageBean");
//            // 接受消息
//            AppMessageBean getBean = iAidlInterface.getAppMessageBean();
//            if (getBean != null) {
//                AppLogUtils.e("接受消息");
//                String businessAppPackageName = getBean.getBusinessAppPackageName();
//                String businessAppVersionName = getBean.getBusinessAppVersionName();
//                String op = getBean.getOp();
//
//                AppLogUtils.e("接受消息----businessAppPackageName  " + businessAppPackageName);
//                AppLogUtils.e("接受消息----businessAppVersionName  " + businessAppVersionName);
//                AppLogUtils.e("接受消息----op  " + op);
//
//                closeApp();
//
//            }
//        }
//
//        @Override
//        public AppMessageBean getAppMessageBean() throws RemoteException {
//            AppLogUtils.e("IAidlCallBack---getAppMessageBean");
//            // 接受消息
//            AppMessageBean getBean = iAidlInterface.getAppMessageBean();
//            if (getBean != null) {
//                AppLogUtils.e("接受消息");
//                String businessAppPackageName = getBean.getBusinessAppPackageName();
//                String businessAppVersionName = getBean.getBusinessAppVersionName();
//
//                AppLogUtils.e("接受消息----businessAppPackageName  " + businessAppPackageName);
//                AppLogUtils.e("接受消息----businessAppVersionName  " + businessAppVersionName);
//            }
//
//
//            return getBean;
//        }

    };


    private void sendAppInfoMessage() {
        // 发送消息
        if (iAidlInterface != null) {
            try {


                String appPackageName = DeviceUtils.getAppPackageName(mActivity);
                String appVersionName = DeviceUtils.getAppVersionName(mActivity);

                AppLogUtils.e("appPackageName--" + appPackageName);
                AppLogUtils.e("appVersionName--" + appVersionName);

                AppMessageBean sendBean = new AppMessageBean();
                sendBean.setBusinessAppPackageName(appPackageName + "");
                sendBean.setBusinessAppVersionName(appVersionName + "");
                sendBean.setSender(aidlSender);
                sendBean.setSender(DeviceUtils.getDeviceSN());

                iAidlInterface.setAppMessageBean(sendBean);
            } catch (RemoteException e) {
                e.printStackTrace();
            } catch (NullPointerException e) {
                AppLogUtils.e("发送消息--NullPointerException");
                e.printStackTrace();
            }
            AppLogUtils.e("发送消息");
        } else {
            AppLogUtils.e("发送消息---iAidlInterface");
        }
    }


    // onDestroy注意aidl解绑


}