package com.hh.lib_mla80_print;

import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.hh.lib_base.BaseApplication;
import com.hh.lib_base.utils.StringUtils;
import com.hh.lib_base_print.BasePrinter;
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_base_print.utils.BitmapUtils;
import com.tx.printlib.Const;
import com.tx.printlib.UsbPrinter;

import java.util.Map;

/**
 *
 * @author xwh
 * time 2024/9/20
 * Description: 马里奥80打印机
 **/
public class MlaPrinter extends BasePrinter {
    // 当前类名
    public String mTag = "HHArome--"+getClass().getSimpleName() + "--";
    private static volatile MlaPrinter instance = null;
    private PrintInitResultCallback printInitResultCallback;
    private PendingIntent mPendingIntent;
    private Handler mHandler;
    private static UsbPrinter mUsbPrinter;
    private int vidpid[] = new int[]{0, 0};
    private  final String ALGIN_LEFT = "left";
    private  final String ALGIN_RIGHT = "right";
    private  final String ALGIN_CENTER = "center";

    private int retryCount = 0;
    private volatile boolean isInitSuccess;

    @Override
    public void initPrint(PrintInitResultCallback printInitResultCallback) {

        init();
    }
    private void init(){
        if (mUsbPrinter != null) {
            mUsbPrinter.close();
            mUsbPrinter=null;
        }

        final UsbManager mUsbManager = (UsbManager) BaseApplication.getContext()
                .getSystemService(Context.USB_SERVICE);
        if (Build.VERSION.SDK_INT >= 31) {
            mPendingIntent = PendingIntent.getBroadcast(BaseApplication.getContext(),
                    0, new Intent(BaseApplication.getContext().getApplicationInfo().packageName),
                    PendingIntent.FLAG_IMMUTABLE);
        } else {
            mPendingIntent = PendingIntent.getBroadcast(BaseApplication.getContext(),
                    0, new Intent(BaseApplication.getContext().getApplicationInfo().packageName),
                    0);
        }
        final UsbDevice dev = getCorrectDevice();
        if (dev!=null&&!mUsbManager.hasPermission(dev)) {
            mUsbManager.requestPermission(dev, mPendingIntent);
        }
        if (dev != null && getmUsbPrinter().open(dev)) {

            getmUsbPrinter().init();

            final long stat1 = getmUsbPrinter().getStatus();
            final long stat2 = getmUsbPrinter().getStatus2();
          //  Log.e(mTag, "stat1:" + stat1);
         //   Log.e(mTag, "stat2:" + stat2);
            // open()和close（）要配对使用
            getmUsbPrinter().close();

            isInitSuccess = true;
            if(printInitResultCallback!=null) {
                printInitResultCallback.onPrintInitSuccess();
            }

        } else {
          //  Log.e(mTag, "找不到USB打印机");
          //  Log.e(mTag, "retryCount:"+retryCount);

            getmUsbPrinter().close();

            if(retryCount <= 5){
                retryCount++;
                getmHandler().removeCallbacksAndMessages(null);
                getmHandler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        init();
                    }
                },2000);

            }else{
                isInitSuccess = false;
                if(printInitResultCallback!=null) {
                    printInitResultCallback.onPrintInitError("-1", "找不到USB打印机，请检查USB线连接");
                }
            }


        }
    }


    @Override
    public void printText(String text, int align, int textSize, boolean isBold) {
        // 恢复字体效果（大小、粗体等）为原始状态
        getmUsbPrinter().resetFont();
        // 文字位置，左中右
        getmUsbPrinter().doFunction(Const.TX_ALIGN, align, 0);
        // 文字加粗
        getmUsbPrinter().doFunction(Const.TX_FONT_BOLD, isBold ? Const.TX_ON : Const.TX_OFF, 0);
        // 文字大小
        if (textSize > 26) {
            getmUsbPrinter().doFunction(Const.TX_FONT_SIZE, Const.TX_SIZE_2X, Const.TX_SIZE_2X);
        } else {
            getmUsbPrinter().doFunction(Const.TX_FONT_SIZE, Const.TX_SIZE_1X, Const.TX_SIZE_1X);
        }
        // 打印文字
        getmUsbPrinter().outputStringLn(text);
        // 间隔
        feed(15);
        // 恢复字体效果（大小、粗体等）为原始状态
        getmUsbPrinter().resetFont();
    }

    @Override
    public void printBarCode(String text, int width, int height) {
        getmUsbPrinter().doFunction(Const.TX_BARCODE_HEIGHT, 15, 0);
        getmUsbPrinter().printBarcode(Const.TX_BAR_UPCA, text);
    }

    @Override
    public void printQrCode(String text, int width, int height) {
        // 点大小
        getmUsbPrinter().doFunction(Const.TX_QR_DOTSIZE, 6, 0);
        // 纠错等级
        getmUsbPrinter().doFunction(Const.TX_QR_ERRLEVEL, Const.TX_QR_ERRLEVEL_M, 0); //27 for TX_QR_ERRLEVEL,0x32

        getmUsbPrinter().printQRcode(text);
    }

    @Override
    public void printBitmap(String base64, int width, int height) {
        feed(10);

        String picturePath = null;
        try {
            picturePath = BitmapUtils.createPictureDirAndFile();
          //  Log.e(mTag,"picturePath:"+picturePath);
            Bitmap bitmap = BitmapUtils.stringToBitmap(base64);
            BitmapUtils.saveImage(picturePath,bitmap);
            Thread.sleep(500);
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(mTag,"e:"+e.toString());
        }
//        String picturePath = "/storage/emulated/0/T1YB01_2024-05-16.png";
        try {
        //    Log.e(mTag,"开始打印的picturePath:"+picturePath);
            getmUsbPrinter().doFunction(Const.TX_ALIGN, 1, 0);
            getmUsbPrinter().printImage(picturePath);
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(mTag,"e:"+e.toString());
        }

        feed(30);
    }

    @Override
    public void feed(int line) {
        // 走纸
        getmUsbPrinter().doFunction(Const.TX_FEED, line, 0);
    }

    @Override
    public void cutPaper() {

        feed(30);
        getmUsbPrinter().doFunction(Const.TX_FEED, 140, 0);
        getmUsbPrinter().doFunction(Const.TX_CUT, Const.TX_PURECUT_PARTIAL, 0);
        getmUsbPrinter().close();
    }

    @Override
    public void disconnect() {
        if(mUsbPrinter!=null){
            mUsbPrinter.close();
            mUsbPrinter=null;
        }
        if(mHandler!=null){
            mHandler.removeCallbacksAndMessages(null);
        }
        instance = null;
    }

    @Override
    public void startPrint(AmpeRequestPrintBean printBean, OnPrintBaseListener listener) {
        if (printBean == null) {
            return;
        }
        if (printBean.getPrintList() == null) {
            return;
        }
        if (!isInitSuccess) {
            if(listener!=null){
                listener.PrintingFail("未初始化");
            }
            return;
        }
        printerPrepare();
        // 打印时间
        int printTotalTime = 0;
        // 循环打印，并累计打印时间
        for (int i = 0; i < printBean.getPrintList().size(); i++) {
            PrintContentBean printContentBean = printBean.getPrintList().get(i);

            String text = printContentBean.getText();
            String qrCodeText = printContentBean.getQrCodeText();
            String imageBase64 = printContentBean.getImageBase64();

            int width = printContentBean.getWidth();
            int height = printContentBean.getHeight();

            if(StringUtils.isNotNull(text)){
                // 普通文字

                // 设置对齐位置
                int algin=0;
                String alginParam = printContentBean.getAlgin();
                if(ALGIN_LEFT.equalsIgnoreCase(alginParam)){
                    algin = 0;
                }else if(ALGIN_CENTER.equalsIgnoreCase(alginParam)){
                    algin = 1;
                }else if(ALGIN_RIGHT.equalsIgnoreCase(alginParam)){
                    algin = 2;
                }

                // 打印文字
                printText(text,
                        algin,
                        printContentBean.getTextSize(),
                        printContentBean.isBold());
                // 打印时间累计
                printTotalTime+=1000;

            }else if(StringUtils.isNotNull(qrCodeText)){
                // 二维码
                printQrCode(qrCodeText,width,height);
                // 打印时间累计
                printTotalTime+=2000;

            }else if(StringUtils.isNotNull(imageBase64)){
                // 图片

                printBitmap(imageBase64,width,height);
                // 打印时间累计
                printTotalTime+=2000;
            }

        }
        cutPaper();


        // 通知打印完成
        getmHandler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if(listener!=null){
                    listener.PrintingComplete();
                }
            }
        },printTotalTime);
    }

    /**
     *
     * @author xwh
     * Time 2024/9/20
     * Description: 打印机开始打印准备工作
     *
    **/
    private void printerPrepare(){
        // 每一次打印，都需要open下。等切纸时再close
        final UsbDevice dev = getCorrectDevice();
        if (dev != null && getmUsbPrinter().open(dev)) {

            getmUsbPrinter().init();

            final long stat1 = getmUsbPrinter().getStatus();
            final long stat2 = getmUsbPrinter().getStatus2();
          //  Log.e(mTag, "startPrint--stat1:" + stat1);
          //  Log.e(mTag, "startPrint--stat2:" + stat2);
            // 不再close,等打印完再close
        } else {
        //    Log.e(mTag, "startPrint--找不到USB打印机");
            getmUsbPrinter().close();

            // 再试下
            final UsbDevice dev2 = getCorrectDevice();

            if (dev2 != null && getmUsbPrinter().open(dev2)) {

                getmUsbPrinter().init();
                final long stat1 = getmUsbPrinter().getStatus();
                final long stat2 = getmUsbPrinter().getStatus2();
             //   Log.e(mTag, "startPrint--stat1:" + stat1);
             //   Log.e(mTag, "startPrint--stat2:" + stat2);
            }


        }
    }


    private synchronized UsbDevice getCorrectDevice() {
        synchronized (MlaPrinter.class) {
            final UsbManager usbMgr = (UsbManager) (BaseApplication.getContext().getSystemService(Context.USB_SERVICE));
            final Map<String, UsbDevice> devMap = usbMgr.getDeviceList();
        //    Log.e(mTag, "devMap: " + devMap.size());
            for (String name : devMap.keySet()) {
             //   Log.e(mTag, "check device: " + name);
                if (UsbPrinter.checkPrinter(devMap.get(name)))
                    return devMap.get(name);
            }
            return null;
        }
    }


    public UsbPrinter getmUsbPrinter() {
        if(mUsbPrinter==null){
            synchronized (MlaPrinter.class){
                if(mUsbPrinter==null){
                    mUsbPrinter = new UsbPrinter(BaseApplication.getContext());
                }
            }
        }
        return mUsbPrinter;
    }

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

    public static MlaPrinter getInstance() {
        //如果instance为空，就进行实例化
        if (instance == null) {
            //保证多线程下只有一个线程进行实例化
            synchronized (MlaPrinter.class) {
                //第二次判断，避免多线程下创建多个实例
                if (instance == null) {
                    instance = new MlaPrinter();
                }
            }
        }
        return instance;
    }
}
