package com.lib_nfc.m1;


import static com.hh.lib_base.Constants.LogcatValue.NET_LOGCAT;

import android.content.Context;

import com.alipay.arome.aromecli.AromeServiceInvoker;
import com.google.gson.JsonObject;
import com.hh.lib_m1_card.DxM1CardReader;
import com.hh.lib_m1_card.bean.AmpeResultM1CardBean;
import com.hh.lib_m1_card.config.M1CardConfig;
import com.hh.lib_m1_card.config.M1CardInitvalConfig;
import com.hh.lib_m1_card.config.M1CardWriteConfig;
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_ampe.utils.MyTypeToken;
import com.hh.lib_base.Constants;
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 org.greenrobot.eventbus.EventBus;

/**
 * Description: $
 *
 * @author xwh
 * time 2024/11/5
 **/
public class M1CardInvoker {

    private volatile static M1CardInvoker invoker;
    private DxM1CardReader dxM1CardReader;

    /**
     *
     * @author xwh
     * Time 2024/11/13
     * Description: M1卡功能交互入口
     *
    **/
    public void onCalled(Context context, BaseAmpeRequestBean dataBean, AromeServiceInvoker.BridgeCallback bridgeCallback) {
        if (dataBean == null) {
            return;
        }
        switch (dataBean.getAction()){
            case Constants.Ampe.ACTION_DOM1LISTENER:
                doM1Listener(dataBean);
                break;
            case Constants.Ampe.ACTION_DOM1WRITE:
                writeM1Card(dataBean);
                break;
            case Constants.Ampe.ACTION_DOM1CLEAR:
                    m1CardInitval(dataBean);
                break;

        }

    }


    /**
     *
     * @author xwh
     * Time 2024/11/13
     * Description: 启动/停止M1读卡器
     *
    **/
    private void doM1Listener(BaseAmpeRequestBean requestBean){
        if(requestBean==null){
            return;
        }
        BaseAmpeRequestBean<M1CardConfig> newBean= MyTypeToken.
                toBaseAmpeRequestBean(requestBean, M1CardConfig.class);
        if(newBean==null){
            return;
        }

        initM1();
        boolean success = false;

        if(Constants.Ampe.EVENT_START.equals(newBean.getEvent())){
            if(newBean.getParams()!=null){
                dxM1CardReader.setM1CardLoopConfig(newBean.getParams());
                success = dxM1CardReader.startRead();
            }

        } else if (Constants.Ampe.EVENT_STOP.equals(newBean.getEvent())) {
            success = dxM1CardReader.stopRead();
        }
        BaseAmpeAppletResultBean ssConfigBean = new BaseAmpeAppletResultBean();
        ssConfigBean.setAction(Constants.Ampe.ACTION_DOM1LISTENER);
        ssConfigBean.setEvent(requestBean.getEvent());
        ssConfigBean.setTaskId(requestBean.getTaskId());
        ssConfigBean.setSuccess(success);
        ssConfigBean.setMessage(success?"成功":"失败");


        try {
            JsonObject jsonObject = GsonUtils.getGson().toJsonTree(ssConfigBean).getAsJsonObject();
            if (requestBean.getBridgeCallback() != null) {
                requestBean.getBridgeCallback().callback(jsonObject.toString());
            }
            String logLine=(new Throwable().getStackTrace())[0].toString();
            UploadLogUtils.sendLogs(Constants.LogcatValue.LOG_M1CARD,
                    Constants.Ampe.ACTION_DOM1LISTENER,logLine,
                    jsonObject.toString());
        }catch (Exception e){
            AppLogUtils.e(e.toString());
        }
    }

    /**
     *
     * @author xwh
     * Time 2024/11/13
     * Description: M1写功能
     *
    **/
    private void writeM1Card(BaseAmpeRequestBean requestBean){
        if(requestBean==null){
            return;
        }
        BaseAmpeRequestBean<M1CardWriteConfig> newBean= MyTypeToken.
                toBaseAmpeRequestBean(requestBean, M1CardWriteConfig.class);
        if(newBean==null){
            return;
        }
        if(newBean.getParams()==null){
            return;
        }
        initM1();
        BaseAmpeAppletResultBean<AmpeResultM1CardBean> resultBean=dxM1CardReader.writeM1Card(newBean.getParams());
        if(resultBean==null){
            resultBean =new BaseAmpeAppletResultBean<>();
            resultBean.setSuccess(false);
            resultBean.setMessage("失败");
        }
        resultBean.setAction(requestBean.getAction());
        resultBean.setEvent(requestBean.getEvent());
        resultBean.setTaskId(requestBean.getTaskId());
        try {
            JsonObject jsonObject = GsonUtils.getGson().toJsonTree(resultBean).getAsJsonObject();
            if (newBean.getBridgeCallback() != null) {
                newBean.getBridgeCallback().callback(jsonObject.toString());
            }
            String logLine=(new Throwable().getStackTrace())[0].toString();
            UploadLogUtils.sendLogs(Constants.LogcatValue.LOG_M1CARD,
                    Constants.Ampe.ACTION_DOM1WRITE,logLine,
                    jsonObject.toString());
        }catch (Exception e){
            AppLogUtils.e(e.toString());
        }
    }

    /**
     *
     * @author xwh
     * Time 2024/11/13
     * Description: M1卡设备初始值
     *
    **/
    private void m1CardInitval(BaseAmpeRequestBean requestBean){
        if(requestBean==null){
            return;
        }
        BaseAmpeRequestBean<M1CardInitvalConfig> newBean= MyTypeToken.
                toBaseAmpeRequestBean(requestBean, M1CardInitvalConfig.class);
        if(newBean==null){
            return;
        }
        if(newBean.getParams()==null){
            return;
        }
        initM1();
        BaseAmpeAppletResultBean<AmpeResultM1CardBean> resultBean=dxM1CardReader.m1CardInitval(newBean.getParams());
        if(resultBean==null){
            resultBean =new BaseAmpeAppletResultBean<>();
            resultBean.setSuccess(false);
            resultBean.setMessage("失败");
        }
        resultBean.setAction(requestBean.getAction());
        resultBean.setEvent(requestBean.getEvent());
        resultBean.setTaskId(requestBean.getTaskId());
        try {
            JsonObject jsonObject = GsonUtils.getGson().toJsonTree(resultBean).getAsJsonObject();
            if (newBean.getBridgeCallback() != null) {
                newBean.getBridgeCallback().callback(jsonObject.toString());
            }
            String logLine=(new Throwable().getStackTrace())[0].toString();
            UploadLogUtils.sendLogs(Constants.LogcatValue.LOG_M1CARD,
                    Constants.Ampe.ACTION_DOM1CLEAR,logLine,
                    jsonObject.toString());
        }catch (Exception e){
            AppLogUtils.e(e.toString());
        }
    }


    /**
     *
     * @author xwh
     * Time 2024/11/13
     * Description: 推送东信M1读取到的信息
     *
    **/
    private void sendM1toApplet(String info) {
        // 监听，主动推送给小程序
        if (AromeInvoker.getAromeInvoker() != null) {
            AromeInvoker.getAromeInvoker().sendMessageToApplet(Constants.
                    Ampe.ACTION_INITM1LISTENER,info);
        }

    }

    DxM1CardReader.M1CardReaderResultListener readerResultListener=new DxM1CardReader.M1CardReaderResultListener() {
        @Override
        public void onInitSuccessState(boolean isSuccess) {
            //TODO 子线程
            EventBus.getDefault().post(new ConfigStatusTextEvent(
                    isSuccess?"M1卡  初始化成功！":"M1卡  初始化失败！"));
        }

        @Override
        public void onJsonInfo(String info) {
            sendM1toApplet(info);
        }

        @Override
        public void onCardSearchFailed() {

        }

        @Override
        public void onLogInfo(String errMsg) {
            String logLine = (new Throwable().getStackTrace())[0].toString();
            UploadLogUtils.sendLogs(false,Constants.LogcatValue.LOG_M1CARD,
                    "",logLine,errMsg);
        }
    };
    private void initM1(){
        if(dxM1CardReader==null){
            synchronized (M1CardInvoker.class){
                if(dxM1CardReader==null){
                    dxM1CardReader=new DxM1CardReader();
                    dxM1CardReader.setM1CardReaderResultListener(readerResultListener);
                }
            }
        }
    }

    public static M1CardInvoker getInstance() {
        if (invoker == null) {
            synchronized (M1CardInvoker.class) {
                if (invoker == null) {
                    invoker = new M1CardInvoker();

                }
            }
        }
        return invoker;
    }

    public void onRelease() {
        if (dxM1CardReader != null) {
            dxM1CardReader.setM1CardReaderResultListener(null);
            dxM1CardReader.release();
            dxM1CardReader = null;
        }
        invoker = null;

    }
}
