package com.hh.arome.activity;

import android.content.Intent;
import android.net.Network;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import com.alipay.arome.aromecli.AromeServiceInvoker;
import com.hh.arome.activity.setting.PasswordActivity;
import com.hh.arome.secondaryscreen.SecondaryScreenPageInvoker;
import com.hh.arome.utils.AIDLUtils;
import com.hh.arome.utils.CommonUtils;
import com.hh.lib_asr.ASRInvoker;
import com.hh.lib_base.BaseApplication;
import com.hh.lib_base.bean.event.ConfigStatusTextEvent;
import com.hh.lib_base.bean.event.ExitAppEvent;
import com.hh.lib_device.DevicesInvoker;
import com.hh.arome.view.CurrentTimeView;
import com.hh.arome.R;
import com.hh.lib_ampe.bean.BaseAmpeRequestBean;
import com.hh.lib_base.bean.device.DeviceConfigResultBean;
import com.hh.arome.bean.HeartBeatRequestBean;
import com.hh.arome.bean.device.DeviceConfigRequestBean;
import com.hh.arome.presenter.MainPresenter;
import com.hh.lib_ampe.listenr.AmpeResultListener;
import com.hh.lib_ampe.listenr.MiniProgramResultListener;
import com.hh.lib_ampe.utils.AromeInvoker;
import com.hh.lib_base.Constants;
import com.hh.lib_base.activity.BaseMVPActivity;
import com.hh.lib_base.log.AppLogUtils;
import com.hh.lib_base.log.UploadLogUtils;
import com.hh.lib_base.log.bean.LogcatAddRequestBean;
import com.hh.lib_base.manager.ActivityManager;
import com.hh.lib_base.utils.DoubClickUtils;
import com.hh.lib_base.utils.GsonUtils;
import com.hh.lib_base.utils.ImageLoaderUtils;
import com.hh.lib_base.utils.StringUtils;
import com.hh.lib_common.connect.NetworkCallback;
import com.hh.lib_common.connect.NetworkCallbackUtils;
import com.hh.lib_common.connect.NetworkUtils;
import com.hh.lib_base.utils.device.DeviceUtils;
import com.hh.lib_common.event.FillLightEvent;
import com.hh.lib_common.local.AppLocalConfigHandler;
import com.hh.lib_common.local.IAppLocalConfig;
import com.hh.lib_device.deviceui.BaseDeviceUI;
import com.hh.lib_device.deviceui.IDeviceUI;
import com.hh.lib_dx_base_multi.DxCardReader;
import com.hh.lib_face.BPaaSApiResultStateListener;
import com.hh.lib_face.bean.AlipayUserInfoRequestBean;
import com.hh.lib_face.bean.AlipayUserInfoResultBean;
import com.hh.lib_base.ConfigData;
import com.hh.lib_face.event.AlipayUserInfoRequestEvent;
import com.hh.lib_face.BPaaSApiInvoker;
import com.hh.lib_face.event.RequestThreeElementsEvent;
import com.hh.lib_idcard.IDCardInvoler;
import com.hh.lib_infrared.InfraredInvoker;
import com.hh.lib_print.PrinterInvoker;
import com.hh.lib_qr.QRCodeInvoker;
import com.hh.lib_record.RecordInvoker;
import com.hh.lib_record.bean.MicrophoneTypeEnum;
import com.hh.lib_social_security_card.SSCardInvoker;
import com.hh.lib_tts.SpeechInvoler;
import com.hh.lib_tts.voice.MTTSDemo;
import com.hh.lib_idcard_base.event.NFCIDcardEvent;
import com.lib_nfc.cpu.CPUCardInvoker;
import com.lib_nfc.m1.M1CardInvoker;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * @author xwh
 * Time 2024/8/20
 * Description: HHarome 主页
 **/
public class MainActivity extends BaseMVPActivity<MainPresenter> implements View.OnClickListener,CurrentTimeView.OnTimeListener
        , AIDLUtils.AIDLCallBack, AmpeResultListener, MiniProgramResultListener, BPaaSApiResultStateListener {

    private ImageView ivBg;//背景图
    //网络状态UI
    private TextView tvNetNo;
    private ImageView ivNetWifi, ivNetFlow, ivNetLine,ivSetting;

    //版本号、SN UI
    private TextView tvVersion, tvSn, tvConfigStatus;
    private CurrentTimeView timeView;

    private TextView tvEnterApplet, tvAppletName;

    private String deviceModel;  //设备型号
    private NetworkCallbackUtils networkCallbackUtils; //网络监听工具类
    private IAppLocalConfig localConfig;
    private String localDeviceSN;
    private DeviceConfigResultBean deviceConfigBean;
    private HeartBeatRequestBean heartBeatBean;
    private AIDLUtils aidlUtils; //AIDL 通信工具
    private AromeInvoker aromeInvoker; //AMPE 工具类
    private Handler mHandler ;
    private IDeviceUI iDeviceUI;   //各设备厂商提供的控制代码

    private volatile boolean isLaunchApplet = false;//是否已经启动小程序
    private volatile boolean isUseIDCard = true; //是否启用身份证
    private volatile boolean isUseQrcode=true;//是否启用扫二维码
    private volatile boolean isOpenPrinter=true;//是否启动打印机
    private volatile boolean  isUseAlipayFace=true; //是否启动刷脸能力
    private volatile boolean isRequestNetConfig = false; // 是否已经请求过在线配置

    private final int WHAT_INIT_APPLET=0x51; //初始化小程序
    private final int WHAT_LAUNCH_APPLET=0x52; //启动小程序后15秒显示手动进入按钮

    @Override
    protected int getLayoutId() {
        deviceModel = DeviceUtils.getDeviceModel();
        if (Constants.DeviceModel.D2.equals(deviceModel)) {
            return R.layout.activity_main_hp;
        } else {
            return R.layout.activity_main;
        }
    }

    @NonNull
    @Override
    public MainPresenter initPresenter() {
        return new MainPresenter();
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        ivBg = findViewById(R.id.iv_bg);
        tvNetNo = findViewById(R.id.tv_net_no);
        ivNetWifi = findViewById(R.id.iv_net_wifi);
        ivNetFlow = findViewById(R.id.iv_net_flow);
        ivNetLine = findViewById(R.id.iv_net_line);
        ivSetting = findViewById(R.id.iv_setting);
        tvVersion = findViewById(R.id.tv_version);
        tvSn = findViewById(R.id.tv_sn);
        tvConfigStatus = findViewById(R.id.tv_config_status);
        timeView = findViewById(R.id.current_time_view);

        tvEnterApplet = findViewById(R.id.tv_enter_applet);
        tvAppletName = findViewById(R.id.tv_applet_name);

        getLifecycle().addObserver(timeView);

    }

    @Override
    protected void initData() {
        initConfig();  //初始化配置
        initBusiness(); //业务配置初
        initNet();       //当前网络状态
        initShowUI();
    }

    /**
     * @author xwh
     * Time 2024/8/21
     * Description: 事件
     * TODO initEvent()在initData()方法后
     **/
    @Override
    protected void initEvent() {
        timeView.setOnTimeListener(this);
        if (aidlUtils != null) {
            aidlUtils.setAIDLCallBack(this);
        }
        tvEnterApplet.setOnClickListener(this);
        ivSetting.setOnClickListener(this);
        BPaaSApiInvoker.getInstance().setbPaaSApiResultStateListener(this);

    }

    /**
     * @author xwh
     * Time 2024/8/20
     * Description: 主要接口网络请求
     **/
    private void requestNetData() {
        requestDeviceConfig();
    }

    /**
     * @author xwh
     * Time 2024/8/20
     * Description: 请求设备信息
     **/
    private void requestDeviceConfig() {
        DeviceConfigRequestBean mDeviceConfigRequestBean = new DeviceConfigRequestBean();
        mDeviceConfigRequestBean.setSn(DeviceUtils.getDeviceSN());
        mDeviceConfigRequestBean.setToken(Constants.Value.TOKEN);
        mPresenter.requestDeviceConfig(mDeviceConfigRequestBean);
    }


    /**
     * @author xwh
     * Time 2024/8/21
     * Description: 获取此设备信息
     * 在线配置接口成功返回方法。
     **/
    public void showDeviceConfigData(DeviceConfigResultBean data) {
        deviceConfigBean = CommonUtils.getDeviceConfigData(data);
        if (deviceConfigBean == null) {
            return;
        }
        String logLine = (new Throwable().getStackTrace())[0].toString();
        UploadLogUtils.sendLogs(Constants.LogcatValue.LOG_NODE_NET_CONFIG_QUERY,
                "在线配置", logLine, deviceConfigBean.toString());
        // 保存-sp
        String deviceConfigBeanStr = GsonUtils.getGson().toJson(deviceConfigBean);
        ConfigData.setDeviceConfigResultBean(deviceConfigBean);
        localConfig.setDeviceConfigResultBeanStr(deviceConfigBeanStr);
        setConfigStatusText("拉取在线配置成功");
        CommonUtils.forbidPullDown(this,iDeviceUI,deviceConfigBean.isForbidPullDown());
        CommonUtils.navigationBar(this,iDeviceUI,deviceConfigBean.isHideNavigationBar());
        if (StringUtils.isNotNull(deviceConfigBean.getHomePageUrl())) {
            ImageLoaderUtils.Companion.loadImage(deviceConfigBean.getHomePageUrl(), ivBg);
        }
        // 启动页图片
        localConfig.setSplashImageUrl(deviceConfigBean.getStartPageUrl());
        // app自启动
        boolean autoLaunch = deviceConfigBean.isAutoLaunch();
        if(autoLaunch){ //TODO 保活自启动服务
            CommonUtils.startKeepliveService(BaseApplication.getContext());
        }else {
            CommonUtils.stopKeepliveService(BaseApplication.getContext());
        }
        localConfig.setAutoApp(autoLaunch);
        isUseIDCard =deviceConfigBean.isUseIdcard();
        if(isUseIDCard){
            IDCardInvoler.getInstance().initCard(deviceConfigBean);
        }
        initHeartBeat(); //心跳初始化数据包
        showDeviceConfigUI(deviceConfigBean);
        //红外线初始化
        InfraredInvoker.getInstance().initInfrared();
         isUseQrcode = deviceConfigBean.isUseQrcode();
        if (isUseQrcode) {
            QRCodeInvoker.getInstance().init();
        }
       // R.color.material_on_background_disabled
        boolean isOpenMicrophone = deviceConfigBean.isOpenMicrophone();
        int microphoneType = deviceConfigBean.getMicrophoneType();
        if (isOpenMicrophone &&
                microphoneType == MicrophoneTypeEnum.NATIVE_AUDI0.getValue()) {
            //初始化实时语音
            RecordInvoker.getInstance().initRecord();
        }
        isOpenPrinter=deviceConfigBean.isOpenPrinter();
        if(isOpenPrinter){
            PrinterInvoker.getInstance().initPrint(deviceConfigBean.getPrinterConfig());
        }
        // 刷脸配置
        isUseAlipayFace = deviceConfigBean.isUseAlipayFace();
        if (isUseAlipayFace) {
            //初始化刷脸服务
            BPaaSApiInvoker.getInstance().initAbcpFace(null);
        }
    }

    /**
     *
     * @author xwh
     * Time 2024/11/18
     * Description: 接口调用公共失败方法
     *
    **/
    public void showError(String url, String msg) {
        String logLine = (new Throwable().getStackTrace())[0].toString();
        UploadLogUtils.sendLogs(Constants.LogcatValue.LOG_NODE_NET, url, logLine, msg);
        if (url.contains(Constants.Url.API_CONFIG_QUERY)) {   // 在线配置
            DeviceConfigResultBean deviceConfigDataFromLocal = CommonUtils.getDeviceConfigDataFromLocal();
            if (deviceConfigDataFromLocal != null) {
                showDeviceConfigData(deviceConfigDataFromLocal);
            }
            setConfigStatusText(msg + "");
        }
        if (url.contains("faceAuth") || msg.contains("不相符")) {
            AlipayUserInfoResultBean resultBean = new AlipayUserInfoResultBean();
            resultBean.setFailed(true);
            resultBean.setFailedMsg(msg);
            BPaaSApiInvoker.getInstance().showAlipayUserInfoResult(resultBean);
        }
    }

    /**
     * @author xwh
     * Time 2024/8/20
     * Description:初始化UI
     **/
    private void initShowUI() {
        if (Constants.DeviceModel.D2.equals(deviceModel)) {
            ImageLoaderUtils.Companion.loadRes(this, R.mipmap.bg_main_hp, ivBg);
        } else {
            ImageLoaderUtils.Companion.loadRes(this, R.mipmap.bg_main, ivBg);
        }

        tvVersion.setText("版本号：" + DeviceUtils.getAppVersionName(this));
        tvSn.setText("SN号：" + localDeviceSN);
        AppLogUtils.e("SN号：" + localDeviceSN
                +"    版本号：" + DeviceUtils.getAppVersionName(this));
    }
    /**
     *
     * @author xwh
     * Time 2024/9/23
     * Description: 根据接口配置显示首页按钮
     *
    **/
    private void showDeviceConfigUI(final DeviceConfigResultBean configBean) {
        if (configBean == null) {
            return;
        }
        String appletName = deviceConfigBean.getAppName();
        // 小程序启动配置
        tvEnterApplet.setVisibility(View.GONE);
        tvAppletName.setVisibility(View.GONE);
        boolean automaticEnterApplet = deviceConfigBean.isAutomaticEnterApplet();
        if (automaticEnterApplet) {  //小程序启动automaticEnterApplet
            getmHandler().removeMessages(WHAT_INIT_APPLET);
            getmHandler().sendEmptyMessageDelayed(WHAT_INIT_APPLET,5000);
        } else {
            // 展示按钮
            tvEnterApplet.setVisibility(View.VISIBLE);
            tvAppletName.setVisibility(View.VISIBLE);
            tvAppletName.setText(appletName);
        }
    }


    /**
     * @author xwh
     * Time 2024/8/20
     * Description: 初始化配置
     **/
    private void initConfig() {
        localConfig = AppLocalConfigHandler.create(getApplicationContext(), IAppLocalConfig.class);
        localDeviceSN = DeviceUtils.getDeviceSN();

    }

    /**
     * @author xwh
     * Time 2024/8/21
     * Description: 初始化业务逻辑
     **/
    private void initBusiness() {
        iDeviceUI = BaseDeviceUI.getInstance().getDeviceUI();
        iDeviceUI.hideFillLight(this);
        aidlUtils = AIDLUtils.getInstance();
        aidlUtils.bindService(this);
        CommonUtils.delLocalLog();
        CommonUtils.deleteAllPicture();
        aromeInvoker = AromeInvoker.getInstance(this);
        aromeInvoker.setMiniProgramResultListener(this);
        getmHandler().postDelayed(() -> {
            // 先初始化下语音，防止首次没有声音
            MTTSDemo.getInstance(MainActivity.this);
        },5000);
    }

    /**
     * @author xwh
     * Time 2024/8/22
     * Description: 初始化心跳包数据
     **/
    private void initHeartBeat() {
        heartBeatBean = new HeartBeatRequestBean();
        heartBeatBean.setBizAppApkName(DeviceUtils.getAppPackageName(this));
        heartBeatBean.setBizAppVersion(DeviceUtils.getAppVersionName(this));
        heartBeatBean.setSn(localDeviceSN);
        heartBeatBean.setHeartTrackingUrl(deviceConfigBean.getHeartTrackingUrl());
    }

    /**
     * @author xwh
     * Time 2024/8/20
     * Description: 监听网络状态
     **/
    private void initNet() {
        initNetIcon();
        networkCallbackUtils = new NetworkCallbackUtils();
        networkCallbackUtils.registerNetworkCallback(this, new NetworkCallback() {
            @Override
            public void onAvailable(@NonNull Network network) {
                refreshNetState();
            }

            @Override
            public void onLost(@NonNull Network network) {
                refreshNetState();
            }
        });
    }

    /**
     * @author xwh
     * Time 2024/8/20
     * Description: 初始化网络状态图标
     **/
    private void initNetIcon() {
        tvNetNo.setVisibility(View.VISIBLE);
        ivNetWifi.setVisibility(View.GONE);
        ivNetFlow.setVisibility(View.GONE);
        ivNetLine.setVisibility(View.GONE);
    }

    /**
     *
     * @author xwh
     * Time 2024/9/23
     * Description: 初始化小城西
     *
    **/
    private void initApplet(final DeviceConfigResultBean configBean){
        if(!isLaunchApplet){
            int appletOperationTimeout = 30;
            if (localConfig != null) {
                appletOperationTimeout = localConfig.getAppletOperationTimeout();
            }
            if (configBean == null || aromeInvoker == null) {
                setConfigStatusText("初始化小程序失败！");
                return;
            }
            try {
                aromeInvoker.initAndActive(configBean,getPackageName(),appletOperationTimeout);
            }catch (Exception e){

            }

        }
    }

    /**
     * @author xwh
     * Time 2024/8/21
     * Description: 显示当前设备状态信息
     **/
    public void setConfigStatusText(String text) {
        runOnUiThread(() -> {
            if (tvConfigStatus != null && !TextUtils.isEmpty(text)) {
                tvConfigStatus.setText(text);String logLine = (new Throwable().getStackTrace())[0].toString();
                UploadLogUtils.sendLogs("硬件模块-初始化",
                        "",logLine,text);

            }
        });
    }

    /**
     * @author xwh
     * Time 2024/8/21
     * Description: 心跳
     **/
    @Override
    public void onHeartbeat() {
        if (mPresenter != null) {
            mPresenter.requestHeartbeat(heartBeatBean);
        }
    }

    /**
     * @author xwh
     * Time 2024/8/20
     * Description: 网络状态变更刷新
     **/
    private void refreshNetState() {
        runOnUiThread(() -> {
            initNetIcon();
            tvNetNo.setVisibility(View.GONE); //todo 隐藏无网络文字
            boolean isNetworkAvaiable = NetworkUtils.isNetworkAvaiable(getApplicationContext());
            if (isNetworkAvaiable) {
                String netType = NetworkUtils.getNetType(getApplicationContext());
                AppLogUtils.e("netType--" + netType);
                if (StringUtils.isNotNull(netType)) {
                    if (netType.contains("WIFI")) {
                        ivNetWifi.setVisibility(View.VISIBLE);
                    } else if (netType.contains("MOBILE")) {
                        ivNetFlow.setVisibility(View.VISIBLE);
                    }else if(netType.contains("ETHERNET")){
                        ivNetLine.setVisibility(View.VISIBLE);
                    }
                }
                if(isRequestNetConfig){
                    return; //TODO 已经请求过在线配置，不需要重复请求
                }
                setConfigStatusText(netType + " 请求在线配置...");
                isRequestNetConfig = true;
                // 网络请求
                requestNetData();
            } else {
                tvNetNo.setVisibility(View.VISIBLE);
            }
        });
    }

    /**
     *
     * @author xwh
     * Time 2024/9/5
     * Description: 日志
     *
    **/
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void sendLogcat(LogcatAddRequestBean logBean) {
        if (mPresenter != null && deviceConfigBean != null && logBean != null) {
            mPresenter.requestLogcatAdd(deviceConfigBean.getLogPushUrl(), logBean);
        }
    }
    /**
     *
     * @author xwh
     * Time 2024/9/5
     * Description: 控制补光灯
     *
    **/
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void hideFillLight(FillLightEvent fillLightEvent) {
        if (iDeviceUI != null) {
            if(fillLightEvent.isShow()){
                iDeviceUI.showFillLight(this);
            }else {
                iDeviceUI.hideFillLight(this);
            }
        }
    }
    /**
     *
     * @author xwh
     * Time 2024/9/5
     * Description: 获取三要素接口
     *
    **/
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void requestAlipayUserInfo(AlipayUserInfoRequestEvent event) {
        if(event==null){
            return;
        }
        AlipayUserInfoRequestBean requestBean=event.getRequestBean();
        if(mPresenter!=null&&requestBean!=null) {
            mPresenter.requestAlipayUserInfo(requestBean,event.getCertNo(),event.getCertName());
        }
    }
    /**
     *
     * @author xwh
     * Time 2024/9/5
     * Description: 请求国密接口
     *
    **/
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void requestThreeElements(RequestThreeElementsEvent event) {
        if (event == null) {
            return;
        }
        if (mPresenter != null) {
            mPresenter.requestThreeElements(event.getMap(), event.getUrl());
        }
    }
    /**
     *
     * @author xwh
     * Time 2024/9/5
     * Description: 显示硬件模块状态
     *
    **/
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void setConfigStatusText(ConfigStatusTextEvent event) {
        if (event == null) {
            return;
        }
        setConfigStatusText(event.getText());

    }
    
    /**
     *
     * @author xwh
     * Time 2024/9/5
     * Description: NFC在线刷身份证
     *
    **/
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void nfcIDCard(NFCIDcardEvent event) {
        if (event == null) {
            return;
        }
        IDCardInvoler.getInstance().NFCCardInfo(event);
    }
    /**
     *
     * @author xwh
     * Time 2024/9/23
     * Description: 退出应用
     *
    **/
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void closeApp(ExitAppEvent event) {
        closeApp();
    }



    @Override
    public void reboot() {
        runOnUiThread(() -> {
            if (iDeviceUI != null) {
                iDeviceUI.reboot();
            }
        });

    }

    @Override
    public void closeApp() {
        runOnUiThread(() -> {
            finish();
        });
    }


    @Override
    public  void onInitApplet(){
        setConfigStatusText("初始化小程序配置");
    }
    @Override
    public void onInitAppletFailed(String code, String msg){
        setConfigStatusText(msg);
    }
    @Override
    public void onStartApplet() {
        setConfigStatusText("启动小程序...");
    }
    @Override
    public void onStartAppletSuccess() {
        isLaunchApplet=true;
        setConfigStatusText("启动小程序成功");
        getmHandler().removeMessages(WHAT_LAUNCH_APPLET);
        getmHandler().sendEmptyMessageDelayed(WHAT_LAUNCH_APPLET,15000);

    }
    @Override
    public void onStartAppletFailed(String code, String msg) {
        isLaunchApplet=false;
        setConfigStatusText(msg); //启动小程序失败
    }

    @Override
    public void ampeChannelSuccrss() {
        setConfigStatusText("小程序通道建立成功");
    }

    @Override
    public void onInitBpaaSSuccess() {
        setConfigStatusText("BPaaSApi--刷脸初始化成功");
    }

    @Override
    public void onFaceResult(String resultStr) {
        //TODO 更新UI注意线程
    }
    /**
     *
     * @author xwh
     * Time 2024/8/23
     * Description: AMPE：HHArome与小程序交互方法
     *
    **/
    @Override
    public void onCalled(String action, BaseAmpeRequestBean dataBean, AromeServiceInvoker.BridgeCallback bridgeCallback) {
        if(dataBean==null){
            return;
        }
        dataBean.setBridgeCallback(bridgeCallback);
       // Log.i("____________123",dataBean.getAction()+"  "+dataBean.getParams());
        //设备能力
        DevicesInvoker.getInstance().onCalled(MainActivity.this,dataBean,bridgeCallback);
        //刷脸能力
        BPaaSApiInvoker.getInstance().onCalled(MainActivity.this,dataBean,bridgeCallback);
        //文字转语音
        SpeechInvoler.getInstance().onCalled(MainActivity.this,dataBean,bridgeCallback);
        //身份证
        IDCardInvoler.getInstance().onCalled(MainActivity.this,dataBean,bridgeCallback);
        //副屏
        SecondaryScreenPageInvoker.getInstance().onCalled(MainActivity.this,dataBean,bridgeCallback);
        //红外线
        InfraredInvoker.getInstance().onCalled(MainActivity.this,dataBean,bridgeCallback);
        //二维码
        QRCodeInvoker.getInstance().onCalled(MainActivity.this,dataBean,bridgeCallback);
        //实时语音
        RecordInvoker.getInstance().onCalled(MainActivity.this,dataBean,bridgeCallback);
        //社保卡
        SSCardInvoker.getInstance().onCalled(MainActivity.this,dataBean,bridgeCallback);
        //CPU卡
        CPUCardInvoker.getInstance().onCalled(MainActivity.this,dataBean,bridgeCallback);
        //打印机
        PrinterInvoker.getInstance().onCalled(MainActivity.this,dataBean,bridgeCallback);
        //M1卡
        M1CardInvoker.getInstance().onCalled(MainActivity.this,dataBean,bridgeCallback);
        //语音识别
        ASRInvoker.getInstance().onCalled(MainActivity.this,dataBean,bridgeCallback);

    }

    public Handler getmHandler() {
        if(mHandler==null){
            synchronized (MainActivity.class){
                if(mHandler==null){
                    mHandler=new Handler(Looper.getMainLooper()){
                        @Override
                        public void handleMessage(@NonNull Message msg) {
                            switch (msg.what){
                                case WHAT_INIT_APPLET:
                                    initApplet(deviceConfigBean);
                                    break;
                                case WHAT_LAUNCH_APPLET:
                                   tvEnterApplet.setVisibility(View.VISIBLE);
                                    break;
                            }
                            super.handleMessage(msg);

                        }
                    };
                }
            }
        }
        return mHandler;
    }

    private void onDestroyUnregister() {
        EventBus.getDefault().unregister(this);
        //关闭补光灯
        if (iDeviceUI != null) {
            iDeviceUI.hideFillLight(this); // 补光灯关闭
        }
        //解除网络绑定
        if (networkCallbackUtils != null) {
            networkCallbackUtils.unregisterNetworkCallback(this);
        }
        //解除AIDL绑定
        if (aidlUtils != null) {
            aidlUtils.unbindService(this);
            aidlUtils.onRelease();
            aidlUtils=null;

        }
        //设备控制
        BaseDeviceUI.getInstance().onRelease();
        //ampe
        aromeInvoker=null;
        AromeInvoker.onRelease();
        //刷脸功能释放
        BPaaSApiInvoker.getInstance().onRelease();
        //删除临时身份证临时照图片
        CommonUtils.deleteAllPicture();
        //重置常量
        ConfigData.reset();
        //身份证
        IDCardInvoler.getInstance().onRelease();
        //副屏
        SecondaryScreenPageInvoker.getInstance().onRelease();
        //红外感应
        InfraredInvoker.getInstance().onRelease();
        //二维码
        QRCodeInvoker.getInstance().onRelease();
        //文字转语音
        SpeechInvoler.getInstance().onRelease();
        //设备能力
        DevicesInvoker.getInstance().onRelease();
        //实时语音
        RecordInvoker.getInstance().onRelease();
        //社保卡
        SSCardInvoker.getInstance().onRelease();
        //CPU卡
        CPUCardInvoker.getInstance().onRelease();
        //M1卡
        M1CardInvoker.getInstance().onRelease();
        //打印机
        PrinterInvoker.getInstance().onRelease();
        //东信多合一（身份证、社保卡、二维码等等）
        DxCardReader.getInstance().release();
        //语音识别
        ASRInvoker.getInstance().onRelease();
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK){
            UploadLogUtils.sendLogs(false,"用户主动退出"," ","","");
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        onDestroyUnregister();
        ActivityManager.finishAll();
        getmHandler().removeCallbacksAndMessages(null);
        super.onDestroy();
        System.exit(0);
    }


    @Override
    public void onClick(View v) {
        if (DoubClickUtils.onDoubClick()) {
            return;
        }
        switch (v.getId()) {
            case R.id.tv_enter_applet:
                isLaunchApplet = false;
                initApplet(deviceConfigBean);
                break;
            case R.id.iv_setting:
                  startActivity(new Intent(this, PasswordActivity.class));
                break;
        }
    }


}