package com.hh.lib_tb_print;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
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.ThreadPoolManager;
import com.hh.lib_base_print.bean.AmpeRequestPrintBean;
import com.hh.lib_base_print.bean.PrintBean;
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.hh.lib_base_print.utils.CodeUtils;
import com.telpo.tps550.api.TelpoException;
import com.telpo.tps550.api.printer.ThermalPrinter;
import com.telpo.tps550.api.printer.UsbThermalPrinter;
import com.telpo.tps550.api.util.SystemUtil;

import java.util.List;

/**
 *
 * @author xwh
 * time 2024/9/18
 *  Description: $天波打印机
 **/
public class TbPrinter extends BasePrinter {
    // 当前类名
    public String mTag = "HHArome--"+getClass().getSimpleName() + "--";
    private static volatile TbPrinter instance = null;
    private PrintInitResultCallback printInitResultCallback;
    private volatile boolean isInitSuccess=false;
    private static UsbThermalPrinter tps508Printer;
   private Handler mHandler ;
    int retryCount = 0;
    int allRetryCount = 6;

    private  final String ALGIN_LEFT = "left";
    private  final String ALGIN_RIGHT = "right";
    private  final String ALGIN_CENTER = "center";

    @Override
    public void initPrint(PrintInitResultCallback printInitResultCallback) {
        this.printInitResultCallback = printInitResultCallback;
        init();
    }

    private void init() {
        isPowerOn();
        try {
            getTps508Printer().setGray(5);//设置打印灰度值 level:0-7,默认为1
        } catch (TelpoException e) {
            e.printStackTrace();

            Log.e(mTag, "e:"+e.toString());

//            printInitResultCallback.onPrintInitError("-1","天波打印机，reset出错");

        }


    }

    // 上电
    public void isPowerOn() {
        ThreadPoolManager.getInstance().executeIOTask(new Runnable() {
            @Override
            public void run() {
                try {

                    getTps508Printer().start(0);
                    Thread.sleep(500);
                    getTps508Printer().reset();
                    getmHandler().postDelayed(new Runnable() {
                        @Override
                        public void run() {

                            int checkStatus = 0;
                            try {
                                checkStatus = ThermalPrinter.checkStatus();
                            } catch (TelpoException e) {
                                e.printStackTrace();
                            }

                         //   Log.e(mTag, "checkStatus：" + checkStatus);
                            if (checkStatus == ThermalPrinter.STATUS_OK) {
                                // 打印机就绪
                                isInitSuccess=true;
                                if(printInitResultCallback!=null) {
                                    printInitResultCallback.onPrintInitSuccess();
                                }
                            } else if (checkStatus == ThermalPrinter.STATUS_NO_PAPER) {
                                // 打印机缺纸
                                isInitSuccess=false;
                                if(printInitResultCallback!=null) {
                                    printInitResultCallback.onPrintInitError(checkStatus + "", "打印机——打印机缺纸");
                                }
                            } else if (checkStatus == ThermalPrinter.STATUS_OVER_HEAT) {
                                // 打印机机芯过热
                                isInitSuccess=false;
                                if(printInitResultCallback!=null) {
                                    printInitResultCallback.onPrintInitError(checkStatus + "", "打印机——机芯过热");
                                }
                            } else if (checkStatus == ThermalPrinter.STATUS_OVER_FLOW) {
                                // 打印机缓存已满
                                isInitSuccess=false;
                                if(printInitResultCallback!=null) {
                                    printInitResultCallback.onPrintInitError(checkStatus + "", "打印机——缓存已满");
                                }
                            } else if (checkStatus == ThermalPrinter.STATUS_UNKNOWN) {
                                // 打印机状态未知
                                isInitSuccess=false;
                                if(printInitResultCallback!=null) {
                                    printInitResultCallback.onPrintInitError(checkStatus + "", "打印机——状态未知");
                                }
                            }

                        }
                    }, 1000);
                } catch (TelpoException | InterruptedException e) {
                    e.printStackTrace();
                    Log.e(mTag, "e：" + e.toString());
                    if (e.toString().contains("DeviceNotOpenException")) {
                        try {
                            tps508Printer.start(0);
                            tps508Printer.reset();
                        } catch (TelpoException telpoException) {
                            telpoException.printStackTrace();
                            Log.e(mTag, "e：" + e.toString());
                        }
                    } else if (e.toString().contains("DeviceAlreadyOpenException")) {
                        isInitSuccess=true;
                        if(printInitResultCallback!=null) {
                            printInitResultCallback.onPrintInitSuccess();
                        }

                    } else if (retryCount <= allRetryCount) {
                        retryCount++;
                       // Log.e(mTag, "retryCount:" + retryCount);
                        getmHandler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                isPowerOn();
                            }
                        }, 1000);

                    }
//                    else{
//                        printInitResultCallback.onPrintInitError("-1","天波打印机start、reset出错");
//                    }


                }catch ( Exception e){

                }

            }
        });

    }



    @Override
    public void printText(String text, int align, int textSize, boolean isBold) {
        try {

            getTps508Printer().setAlgin(align);//设置打印对齐方式
            getTps508Printer().setTextSize(textSize);
            getTps508Printer().addString(text);
            getTps508Printer().setBold(isBold);

        } catch (TelpoException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void printBarCode(String text, int width, int height) {

    }

    @Override
    public void printQrCode(String text, int width, int height) {
        Bitmap bitmap = CodeUtils.createQRCodeBitmap(text,
                800,
                800,
                "UTF-8",
                "M",
                "1",
                Color.BLACK, Color
                        .WHITE
                , null,
                0.2F,
                null);

        if (width == 0) {
            width = 376;
        }
        if (height == 0) {
            height = 376;
        }
        Bitmap bitmap1 = BitmapUtils.zoomImg(bitmap,
                width,
                height);
        if (bitmap != null && !bitmap.isRecycled()) {
            bitmap.recycle();
            bitmap = null;
        }
        try {
            getTps508Printer().printLogo(bitmap1, true);
            if (bitmap1 != null && !bitmap1.isRecycled()) {
                bitmap1.recycle();
                bitmap1 = null;
            }
        } catch (TelpoException e) {
            e.printStackTrace();
        }


    }

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

        Bitmap bitmap = BitmapUtils.stringToBitmap(base64);

        if (width == 0) {
            width = 376;
        }
        if (height == 0) {
            height = 376;
        }

        Bitmap bitmap1 = BitmapUtils.zoomImg(bitmap,
                width,
                height);
        if (bitmap != null && !bitmap.isRecycled()) {
            bitmap.recycle();
            bitmap = null;
        }

        try {
            getTps508Printer().printLogo(bitmap1, true);
            if (bitmap1 != null && !bitmap1.isRecycled()) {
                bitmap1.recycle();
                bitmap1 = null;
            }
        } catch (TelpoException e) {
            e.printStackTrace();
        }catch (Exception e){

        }
    }



    @Override
    public void feed(int line) {
        try {
            getTps508Printer().walkPaper(line);
        } catch (TelpoException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void cutPaper() {
        // D2这个没有切纸的，要手动撕它。所以不要调用切纸的接口，会报错崩溃
        feed(15);
        try {
            getTps508Printer().printString();//启动打印，打印完不走纸
        } catch (TelpoException e) {
            e.printStackTrace();
        }
        feed(15);
    }

    @Override
    public void disconnect() {
        if(tps508Printer!=null) {
            try {
                tps508Printer.stop();
            }catch (Exception e){

            }finally {
                tps508Printer=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;
        }
        // 打印时间
        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);
    }

    public static UsbThermalPrinter getTps508Printer() {
        if(tps508Printer==null){
            synchronized (TbPrinter.class){
                if(tps508Printer==null){
                    tps508Printer=new UsbThermalPrinter(BaseApplication.getContext());
                }
            }
        }
        return tps508Printer;
    }

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