package com.hh.lib_print;

import static com.hh.lib_base.Constants.Ampe.ACTION_PRINT;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;

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.ConfigData;
import com.hh.lib_base.Constants;
import com.hh.lib_base.bean.device.DeviceConfigResultBean;
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_base.utils.device.DeviceUtils;
import com.hh.lib_base_print.BasePrinter;
import com.hh.lib_base_print.ThreadPoolManager;
import com.hh.lib_base_print.bean.AmpeRequestPrintBean;
import com.hh.lib_base_print.bean.PrintContentBean;
import com.hh.lib_base_print.callback.OnPrintBaseListener;
import com.hh.lib_base_print.callback.PrintInitResultCallback;
import com.hh.lib_tb_print.TbPrinter;

/**
 * Description: 打印机调用器
 * @author xwh
 * time 2024/9/19
 **/
public class PrinterInvoker {
    private volatile static PrinterInvoker invoker;
    private BasePrinter basePrinter;
    private Handler mHandler ;


    /**
     * @author xwh
     * Time 2024/9/6
     * Description: 红外线功能交互入口
     **/
    public void onCalled(Context context, BaseAmpeRequestBean dataBean, AromeServiceInvoker.BridgeCallback bridgeCallback) {
        if (dataBean == null) {
            return;
        }
        if(isUnEnabledHardware(dataBean,bridgeCallback)){
            return;
        }
        switch (dataBean.getAction()){
            case ACTION_PRINT:
                sendPrint(dataBean);
                break;
        }
    }

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

        return false;
    }

    /**
     *
     * @author xwh
     * Time 2024/9/20
     * Description: 发送打印机回调
     *
    **/
    public void sendPrint(BaseAmpeRequestBean requestBean){
        if(requestBean==null){
            return;
        }
        BaseAmpeRequestBean<AmpeRequestPrintBean> newRequestBean= MyTypeToken
                .toBaseAmpeRequestBean(requestBean,AmpeRequestPrintBean.class);
        if(newRequestBean==null){
            return;
        }
        if(newRequestBean.getParams()==null){
            return;
        }
        ThreadPoolManager.getInstance().executeIOTask(new Runnable() {
            @Override
            public void run() {
                basePrinter.startPrint(newRequestBean.getParams(), new OnPrintBaseListener() {
                    @Override
                    public void PrintingComplete() {
                        getmHandler().post(() ->
                                sendPrint(newRequestBean,true,""));

                    }

                    @Override
                    public void PrintingFail(String msg) {
                        getmHandler().post(() ->
                                sendPrint(newRequestBean,false,msg));

                    }
                });
            }
        });

    }


    /**
     *
     * Description: A4热敏添加失败监听，提取打印返回小程序结果代码
     * @author xwh
     * Time 2024/7/9
     *
     **/
    private void sendPrint(BaseAmpeRequestBean requestBean,boolean isSuccess,String msg){
        if (requestBean == null) {
            AppLogUtils.e("ampeActionDataBean == null");
            return;
        }
        AromeServiceInvoker.BridgeCallback bridgeCallback = null;
        try {
            bridgeCallback = requestBean.getBridgeCallback();
        } catch (NullPointerException e) {
            e.printStackTrace();
        }

        BaseAmpeAppletResultBean bean = new BaseAmpeAppletResultBean();
        bean.setAction(ACTION_PRINT);
        bean.setEvent(requestBean.getEvent());
        bean.setTaskId(requestBean.getTaskId());
        if(isSuccess) {
            bean.setSuccess(true);
            bean.setMessage("小票打印完成");
        }else{
            bean.setSuccess(false);
            bean.setMessage(msg);
        }
        // 回传处理结果给小程序
        try {
            JsonObject jsonObject = GsonUtils.getGson().toJsonTree(bean).getAsJsonObject();
            if (bridgeCallback != null) {
                bridgeCallback.callback(jsonObject.toString());
            }
            String logLine = (new Throwable().getStackTrace())[0].toString();
            UploadLogUtils.sendLogs(Constants.LogcatValue.LOG_PRINT,ACTION_PRINT,logLine,
                     "--小票--回传处理结果给小程序"+ "jsonObject = " + jsonObject);
        } catch (Throwable t) {
            AppLogUtils.e("onCalled--t" + t);
        }
    }




    /**
     *
     * @author xwh
     * Time 2024/9/20
     * Description: 初始化打印机
     *
    **/
    public void initPrint(int  printerBrand){
        if(basePrinter==null) {
            basePrinter = PrinterFactory.createPrinter(printerBrand);
            basePrinter.initPrint(new PrintInitResultCallback() {
                @Override
                public void onPrintInitSuccess() {
                    String deviceModel = DeviceUtils.getDeviceModel();
                    String  localDeviceSN = DeviceUtils.getDeviceSN();
                    String logLine = (new Throwable().getStackTrace())[0].toString();
                    UploadLogUtils.sendLogs(Constants.LogcatValue.LOG_PRINT,"",logLine,
                            "打印初始化---成功---" + "model = " + deviceModel + " sn = " + localDeviceSN);

                }

                @Override
                public void onPrintInitError(String errorCode, String errorMsg) {
                    String deviceModel = DeviceUtils.getDeviceModel();
                    String  localDeviceSN = DeviceUtils.getDeviceSN();
                    String logLine = (new Throwable().getStackTrace())[0].toString();
                    UploadLogUtils.sendLogs(Constants.LogcatValue.LOG_PRINT,"",logLine,
                            "打印初始化---失败---" + "errorCode = " + errorCode +
                                    " errorMsg = " + errorMsg +
                                    " model = " + deviceModel +
                                    " sn = " + localDeviceSN);
                }
            });
        }
    }

    public void onRelease() {

        if (basePrinter != null) {
            basePrinter.disconnect();
            basePrinter = null;
        }
        ThreadPoolManager.getInstance().shutdownExecutor();
        if(mHandler!=null){
            mHandler.removeCallbacksAndMessages(null);
        }
        invoker = null;
    }

    public Handler getmHandler() {
        if(mHandler==null){
            synchronized (TbPrinter.class){
                if(mHandler==null){
                    mHandler=new Handler(Looper.getMainLooper());
                }
            }
        }
        return mHandler;
    }

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