package com.lib_nfc.cpu;

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_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 com.hh.lib_cpu_card.DXCPUCardReader;
import com.hh.lib_cpu_card.NFCCardConfig;
import com.hh.lib_cpu_card.bean.DxApduResultBean;
import com.lib_nfc.cpu.bean.AmpeRequestCPUCardBean;
import com.lib_nfc.cpu.bean.AmpeResultCPUCardBean;

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

import java.util.ArrayList;

/**
 *
 * @author xwh
 * time 2024/9/13
 * Description: CPU卡调用器
 **/
public class CPUCardInvoker {

    private volatile static CPUCardInvoker invoker;
    private DXCPUCardReader dxcpuCardReader;

    /**
     *
     * @author xwh
     * Time 2024/9/12
     * Description: CPU卡功能交互入口
     *
     **/
    public void onCalled(Context context, BaseAmpeRequestBean dataBean, AromeServiceInvoker.BridgeCallback bridgeCallback) {
        if (dataBean == null) {
            return;
        }
        switch (dataBean.getAction()){

            case Constants.Ampe.ACTION_NFC_STARTCPUCARDLOOPREAD:
                startLoopDX_Nfc(dataBean);
                break;
            case Constants.Ampe.ACTION_NFC_STOPCPUCARDLOOPREAD:
                stopLoopDX_NFC(dataBean);
                break;
            case Constants.Ampe.ACTION_NFC_READONCECPUCARDINFO:
                readOnceNfcCardInfo(dataBean);
                break;
            case Constants.Ampe.ACTION_NFC_PSAMCARDCOLDRESET:
                dx_NfcColdReset(dataBean);
                break;
            case Constants.Ampe.ACTION_NFC_SENDCPUCARDCOMMAND:
                sendDX_NfcCommand(dataBean);
                break;
            case Constants.Ampe.ACTION_NFC_SENDCPUCARDAPDUCOMMANDS:
                sendDX_NfcCommands(dataBean);
                break;
            case Constants.Ampe.ACTION_DX_NFC_BUZZER:
                sendDX_NfcBuzzer(dataBean);
                break;

        }


    }


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

        @Override
        public void onPollingInfo(String info) {
            sendDX_NFCtoApplet(info,true);
        }

        @Override
        public void onCardSearchFailed() {
            sendDX_NFCtoApplet("",false);
        }

        @Override
        public void onLogInfo(String errMsg) {
            String logLine = (new Throwable().getStackTrace())[0].toString();
            UploadLogUtils.sendLogs(false,Constants.LogcatValue.LOG_NFC_CPU,
                    "",logLine,errMsg);
        }
    };

    /**
     *
     * @author xwh
     * Time 2024/11/5
     * Description: 初始化东信NFC串口读卡器
     *
    **/
    private void initDX_Nfc() {
        if (dxcpuCardReader == null) {
            synchronized (CPUCardInvoker.this) {
                if (dxcpuCardReader == null) {
                    dxcpuCardReader = DXCPUCardReader.getInstance(null);
                }
            }
        }
    }

    /**
     *
     * desc:启动东信NFC轮询
     * @author xia weihao
     * @date 2024/6/27
     *
     */
    private void startLoopDX_Nfc(BaseAmpeRequestBean requestBean){
        if(requestBean==null){
            return;
        }
        BaseAmpeRequestBean<AmpeRequestCPUCardBean> newBean= MyTypeToken.
                toBaseAmpeRequestBean(requestBean, AmpeRequestCPUCardBean.class);
        if(newBean==null){
            return;
        }
        NFCCardConfig config=new NFCCardConfig();
        config.setSameCardIntervalTime(newBean.getParams().getIntervalTime());
        boolean isComeBackFailed=false;
        if(newBean.getParams().isComeBackFailed()){
            isComeBackFailed=true;
        }
        config.setComeBackFailed(isComeBackFailed);
        initDX_Nfc();
        dxcpuCardReader.setConfig(config);
        dxcpuCardReader.setNfcCardResultListener(cpuCardListener);
        boolean success = dxcpuCardReader.startRead();

        BaseAmpeAppletResultBean ssConfigBean = new BaseAmpeAppletResultBean();
        ssConfigBean.setAction(Constants.Ampe.ACTION_NFC_STARTCPUCARDLOOPREAD);
        ssConfigBean.setEvent(newBean.getEvent());
        ssConfigBean.setTaskId(newBean.getTaskId());
        ssConfigBean.setSuccess(success);
        ssConfigBean.setMessage(success?"成功":"失败");
        try {
            JsonObject jsonObject = GsonUtils.getGson().toJsonTree(ssConfigBean).getAsJsonObject();
            if (newBean.getBridgeCallback() != null) {
                newBean.getBridgeCallback().callback(jsonObject.toString());
            }
            String logLine=(new Throwable().getStackTrace())[0].toString();
            UploadLogUtils.sendLogs(Constants.LogcatValue.LOG_NFC_CPU,
                    Constants.Ampe.ACTION_NFC_STARTCPUCARDLOOPREAD,logLine,
                    jsonObject.toString());
        }catch (Exception e){
            AppLogUtils.e(e.toString());
        }
    }

    /**
     *
     * desc:停止东信NFC轮询
     * @author xia weihao
     * @date 2024/6/27
     *
     */
    private void stopLoopDX_NFC(BaseAmpeRequestBean requestBean){
        if(requestBean==null){
            return;
        }
        boolean success = false;
        if (dxcpuCardReader == null) {
            String logLine = (new Throwable().getStackTrace())[0].toString();
            UploadLogUtils.sendLogs(Constants.LogcatValue.LOG_NFC_CPU,
                    Constants.Ampe.ACTION_NFC_STOPCPUCARDLOOPREAD, logLine,
                    " dxcpuCardReader == null");
        } else {
            success = dxcpuCardReader.stopRead();
            dxcpuCardReader.setNfcCardResultListener(null);
        }
        BaseAmpeAppletResultBean ssConfigBean = new BaseAmpeAppletResultBean();
        ssConfigBean.setAction(Constants.Ampe.ACTION_NFC_STOPCPUCARDLOOPREAD);
        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_NFC_CPU,
                    Constants.Ampe.ACTION_NFC_STOPCPUCARDLOOPREAD,logLine,
                    jsonObject.toString());
        }catch (Exception e){
            AppLogUtils.e(e.toString());
        }
    }

    /**
     *
     * desc:东信 单次上电读取nfc卡信息
     * @author xia weihao
     * @date 2024/6/27
     *
     */
    private void readOnceNfcCardInfo(BaseAmpeRequestBean requestBean){
        if(requestBean==null){
            return;
        }
        String info="";
        initDX_Nfc();
        info=dxcpuCardReader.getOnceCardInfo();
        BaseAmpeAppletResultBean<AmpeResultCPUCardBean> ssConfigBean = new BaseAmpeAppletResultBean();
        ssConfigBean.setAction(Constants.Ampe.ACTION_NFC_READONCECPUCARDINFO);
        ssConfigBean.setEvent(requestBean.getEvent());
        ssConfigBean.setTaskId(requestBean.getTaskId());
        ssConfigBean.setSuccess(true);
        ssConfigBean.setMessage("成功");
        AmpeResultCPUCardBean dataBean=new AmpeResultCPUCardBean();
        dataBean.setNfc_cardInfo(info);
        ssConfigBean.setData(dataBean);

        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_NFC_CPU,
                    Constants.Ampe.ACTION_NFC_READONCECPUCARDINFO,logLine,
                    jsonObject.toString());
        }catch (Exception e){
            AppLogUtils.e(e.toString());
        }
    }

    /**
     *
     * @author xwh
     * Time 2024/11/5
     * Description: CPU卡冷复位
     *
    **/
    private void dx_NfcColdReset(BaseAmpeRequestBean requestBean){
        if(requestBean==null){
            return;
        }
        BaseAmpeRequestBean<AmpeRequestCPUCardBean> newBean= MyTypeToken.
                toBaseAmpeRequestBean(requestBean, AmpeRequestCPUCardBean.class);
        if(newBean==null){
            return;
        }
        String result="";
        initDX_Nfc();
        result=dxcpuCardReader.coldReset(newBean.getParams().getSlot());
        BaseAmpeAppletResultBean ssConfigBean = new BaseAmpeAppletResultBean();
        ssConfigBean.setAction(Constants.Ampe.ACTION_NFC_PSAMCARDCOLDRESET);
        ssConfigBean.setEvent(newBean.getEvent());
        ssConfigBean.setTaskId(newBean.getTaskId());
        ssConfigBean.setSuccess(true);
        ssConfigBean.setMessage("成功");
        AmpeResultCPUCardBean dataBean=new AmpeResultCPUCardBean();
        dataBean.setNfc_resultInfo(result);
        ssConfigBean.setData(dataBean);


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


    /**
     *
     * desc:东信NFC APdu命令
     * @author xia weihao
     * @date 2024/6/27
     *
     */
    private void sendDX_NfcCommand(BaseAmpeRequestBean requestBean){
        if(requestBean==null){
            return;
        }
        BaseAmpeRequestBean<AmpeRequestCPUCardBean> newBean= MyTypeToken.
                toBaseAmpeRequestBean(requestBean, AmpeRequestCPUCardBean.class);
        if(newBean==null){
            return;
        }
        String result="";
        initDX_Nfc();
        int type=newBean.getParams().getType();
        String command=new String(newBean.getParams().getCommandApdu());
        int slot=newBean.getParams().getSlot();
        result=dxcpuCardReader.sendAPDU(slot,command,type);

        BaseAmpeAppletResultBean<AmpeResultCPUCardBean> ssConfigBean = new BaseAmpeAppletResultBean();
        ssConfigBean.setAction(Constants.Ampe.ACTION_NFC_SENDCPUCARDCOMMAND);
        ssConfigBean.setEvent(newBean.getEvent());
        ssConfigBean.setTaskId(newBean.getTaskId());
        ssConfigBean.setSuccess(true);
        ssConfigBean.setMessage("成功");
        AmpeResultCPUCardBean dataBean = new  AmpeResultCPUCardBean();
        dataBean.setNfc_resultInfo(result);
        ssConfigBean.setData(dataBean);

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

    /**
     *
     * desc:东信NFC APdu指令集
     * @author xia weihao
     * @date 2024/6/27
     *
     */
    private void sendDX_NfcCommands(BaseAmpeRequestBean requestBean){
        DxApduResultBean result = null;
        if(requestBean==null){
            return;
        }
        BaseAmpeRequestBean<AmpeRequestCPUCardBean> newBean= MyTypeToken.
                toBaseAmpeRequestBean(requestBean, AmpeRequestCPUCardBean.class);
        if(newBean==null){
            return;
        }
        initDX_Nfc();
        int type=newBean.getParams().getType();
        ArrayList<String> commands=newBean.getParams().getCommandApdus();
        int slot=newBean.getParams().getSlot();
        result=dxcpuCardReader.sendAPDU(slot,commands,type);

        BaseAmpeAppletResultBean<AmpeResultCPUCardBean> ssConfigBean = new BaseAmpeAppletResultBean();
        ssConfigBean.setAction(Constants.Ampe.ACTION_NFC_SENDCPUCARDAPDUCOMMANDS);
        ssConfigBean.setEvent(newBean.getEvent());
        ssConfigBean.setTaskId(newBean.getTaskId());
        AmpeResultCPUCardBean dataBean = new  AmpeResultCPUCardBean();
        if (result != null) {
            if (result.isSuccess()) {
                ssConfigBean.setSuccess(true);
                ssConfigBean.setMessage("成功");
                dataBean.setNfc_commandResults(result.getResultInfo());
            } else {
                ssConfigBean.setSuccess(false);
                ssConfigBean.setMessage("失败:" + result.getCode());
                dataBean.setNfc_commandResults(result.getResultInfo());
            }

        } else {
            ssConfigBean.setSuccess(false);
            ssConfigBean.setMessage("失败");
        }
        ssConfigBean.setData(dataBean);


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

    /**
     *
     * desc：启动东信蜂鸣器
     * @author xia weihao
     * @date 2024/6/27
     *
     */
    private void sendDX_NfcBuzzer(BaseAmpeRequestBean requestBean){
        if(requestBean==null){
            return;
        }
        BaseAmpeRequestBean<AmpeRequestCPUCardBean> newBean= MyTypeToken.
                toBaseAmpeRequestBean(requestBean, AmpeRequestCPUCardBean.class);
        if(newBean==null){
            return;
        }
        initDX_Nfc();
        int beep=newBean.getParams().getBeep();
        dxcpuCardReader.startBeep(beep);

        BaseAmpeAppletResultBean ssConfigBean = new BaseAmpeAppletResultBean();
        ssConfigBean.setAction(Constants.Ampe.ACTION_DX_NFC_BUZZER);
        ssConfigBean.setEvent(newBean.getEvent());
        ssConfigBean.setTaskId(newBean.getTaskId());
        ssConfigBean.setSuccess(true);
        ssConfigBean.setMessage("成功");

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


    /**
     *
     * desc:推送东信NFC读取到的信息
     * @author xia weihao
     * @date 2024/6/25
     *
     */
    private void sendDX_NFCtoApplet(String info,boolean isCardSearcSucceeded) {
        JSONObject json = new JSONObject();
        try {
            // 勿动key，对外的文档key
            json.put("nfc_cardInfo", info);
            if(isCardSearcSucceeded){  //上电成功
                json.put("code",0);
            }else{
                json.put("code",-1); //上电失败，包括其他（寻卡、选卡等）
            }
        } catch (Throwable t) {

        }
        // 监听，主动推送给小程序
        if (AromeInvoker.getAromeInvoker() != null) {
            AromeInvoker.getAromeInvoker().sendMessageToApplet(Constants.
                    Ampe.EVENT_NFC_CPUCARDLISTENER, json.toString());
        }

    }


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

                }
            }
        }
        return invoker;
    }

    public void onRelease() {
        if (dxcpuCardReader != null) {
            dxcpuCardReader.setNfcCardResultListener(null);
            dxcpuCardReader.release();
            dxcpuCardReader = null;
        }
        invoker = null;

    }
}
