package com.hh.lib_qr;



import android.content.Context;
import com.alipay.arome.aromecli.AromeServiceInvoker;

import com.google.gson.JsonObject;
import com.hh.ib_base_qr.BaseQRScan;
import com.hh.ib_base_qr.QRInitListener;
import com.hh.ib_base_qr.QRResultCallback;
import com.hh.lib_ampe.bean.BaseAmpeAppletResultBean;
import com.hh.lib_ampe.bean.BaseAmpeRequestBean;
import com.hh.lib_ampe.utils.AromeInvoker;
import com.hh.lib_base.ConfigData;
import com.hh.lib_base.Constants;
import com.hh.lib_base.bean.device.DeviceConfigResultBean;

import com.hh.lib_base.bean.event.ConfigStatusTextEvent;
import com.hh.lib_base.log.AppLogUtils;
import com.hh.lib_base.log.UploadLogUtils;
import com.hh.lib_base.utils.GsonUtils;

import com.hh.lib_qr.bean.AmpeResultQRDataBean;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.util.HashMap;

/**
 * Description: $
 *
 * @author xwh
 * time 2024/9/9
 **/
public class QRCodeInvoker {

    private volatile static QRCodeInvoker invoker;
    private  BaseQRScan baseQRScan;
    private HashMap<String, BaseAmpeRequestBean> ampeActionMap = new HashMap<>();

    /**
     *
     * @author xwh
     * Time 2024/9/10
     * Description: 二维码功能交互入口
     *
    **/
    public void onCalled(Context context, BaseAmpeRequestBean dataBean, AromeServiceInvoker.BridgeCallback bridgeCallback) {
        if (dataBean == null) {
            return;
        }
        if(isUnEnabledHardware(dataBean,bridgeCallback)){
            return;
        }
        switch (dataBean.getAction()) {
            case Constants.Ampe.ACTION_QR:
                getAmpeActionMap().put(dataBean.getAction(),dataBean);
                break;
        }
    }

    /**
     *
     * @author xwh
     * Time 2024/9/26
     * Description: 是否未开启该模块
     * @return true:是该模块的消息并且未启用该模块
     **/
    private boolean isUnEnabledHardware(BaseAmpeRequestBean dataBean, AromeServiceInvoker.BridgeCallback bridgeCallback) {
        DeviceConfigResultBean configResultBean = ConfigData.getDeviceConfigResultBean();
        boolean isUseQrcode = true;
        if (configResultBean != null) {
            isUseQrcode = configResultBean.isUseQrcode();
        }
        String action = dataBean.getAction();
        if (!isUseQrcode &&
                action != null &&
                (Constants.Ampe.ACTION_QR.equals(action) )) {
            AromeInvoker.getAromeInvoker().hardwareNotEnabled(dataBean, bridgeCallback);
            return true;
        }

        return false;
    }

    /**
     *
     * @author xwh
     * Time 2024/10/11
     * Description: 初始化二维码
     *
    **/
    public void init(){
        DeviceConfigResultBean deviceConfigBean=ConfigData.getDeviceConfigResultBean();
        if(deviceConfigBean ==null){
            return;
        }
        int idCardReaderBrand = deviceConfigBean.getIdCardReaderBrand();
        baseQRScan=QRScanFactory.createQRScan(idCardReaderBrand);
        baseQRScan.onInit(new QRInitListener() {
            @Override
            public void onInitSuccess() {
                EventBus.getDefault().post(new ConfigStatusTextEvent("二维码-" + "-初始化成功"));
            }

            @Override
            public void onInitFail(int code, String errMsg) {
                EventBus.getDefault().post(new ConfigStatusTextEvent("二维码-" + "-初始化失败"));
            }
        });
        baseQRScan.setQrResultCallback(new QRResultCallback() {
            @Override
            public void onScanSuccess(String qrCode) {
                sendOnceQrData(qrCode);
                activeSendQRMessage(qrCode);
            }

            @Override
            public void onScanFail() {

            }
        });
    }

    /**
     *
     * @author xwh
     * Time 2024/10/11
     * Description: 发送单次二维码
     *
    **/
    private void sendOnceQrData(String qrData){
        BaseAmpeRequestBean requestBean= getAmpeActionMap().get(Constants.Ampe.ACTION_QR);
        if(requestBean==null){
            return;
        }

        BaseAmpeAppletResultBean bean = new BaseAmpeAppletResultBean();
        bean.setAction(Constants.Ampe.ACTION_QR);
        bean.setEvent(requestBean.getEvent());
        bean.setTaskId(requestBean.getTaskId());
        bean.setSuccess(true);
        bean.setMessage("成功");

        AmpeResultQRDataBean dataBean = new AmpeResultQRDataBean();
        dataBean.setQrCode(qrData);
        bean.setData(dataBean);

        // 回传处理结果给小程序
        try {
            JsonObject jsonObject = GsonUtils.getGson().toJsonTree(bean).getAsJsonObject();
            if (requestBean.getBridgeCallback() != null) {
                requestBean.getBridgeCallback().callback(jsonObject.toString());
            }
            getAmpeActionMap().remove(Constants.Ampe.ACTION_QR);
            String logLine = (new Throwable().getStackTrace())[0].toString();
            UploadLogUtils.sendLogs(Constants.LogcatValue.LOG_NODE_QR,"",
                    logLine,"--回传处理结果给小程序"+
                    "qrData = " + qrData+
                    "jsonObject = " + jsonObject);
        } catch (Exception e) {
            AppLogUtils.e("onCalled--t" + e.toString());
        }

    }

    /**
     *
     * @author xwh
     * Time 2024/10/11
     * Description: 主动发送二维码信息
     *
    **/
    private void activeSendQRMessage(String qrCode){
        JSONObject object = new JSONObject();
        try {
            // 勿动key，对外的文档key
            object.put("qrCode", qrCode);
            if (AromeInvoker.getAromeInvoker() != null) {
                AromeInvoker.getAromeInvoker().sendMessageToApplet(Constants.Ampe.EVENT_QR_LISTENER,
                        object.toString());
            }
        } catch (Throwable t) {

        }
    }






    public void  onRelease() {
        invoker = null;
    }

    public HashMap<String, BaseAmpeRequestBean> getAmpeActionMap() {
        if(ampeActionMap==null){
            synchronized (QRCodeInvoker.class){
                if(ampeActionMap==null){
                    ampeActionMap=new HashMap<>();
                }
            }
        }
        return ampeActionMap;
    }

    public static QRCodeInvoker getInstance() {
        if (invoker == null) {
            synchronized (QRCodeInvoker.class) {
                if (invoker == null) {
                    invoker = new QRCodeInvoker();
                }
            }
        }
        return invoker;
    }
}
