package com.common.print.many;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Handler;
import android.util.Log;

import com.common.lib_base.common.async.ThreadPoolManager;
import com.common.print.bean.PrintBean;
import com.common.print.bean.PrintContentBean;
import com.common.print.many.base.IPrinter;
import com.common.print.callback.PrintInitResultCallback;
import com.common.print.utils.BitmapUtils;
import com.common.print.utils.CodeUtils;
import com.telpo.tps550.api.TelpoException;
import com.telpo.tps550.api.printer.ThermalPrinter;
import com.telpo.tps550.api.printer.UsbThermalPrinter;

import java.util.List;

/**
 * 天波
 * D2
 */
public class TbPrinter implements IPrinter {

    // 当前类名
    public String mTag = "HHArome--"+getClass().getSimpleName() + "--";

    //用volatile关键字确保 instance 在多线程下的可见性
    private static volatile TbPrinter instance = null;

    //将构造方法私有化，禁止外部通过构造方法创建实例
    private TbPrinter() {
    }

    //提供一个公共的访问方法，用于获取该类的唯一实例
    public static TbPrinter getInstance(Context context) {
        //如果instance为空，就进行实例化
        if (instance == null) {
            //保证多线程下只有一个线程进行实例化
            synchronized (TbPrinter.class) {
                //第二次判断，避免多线程下创建多个实例
                if (instance == null) {
                    instance = new TbPrinter(context);
                }
            }
        }
        return instance;
    }

    Context mContext;

    private TbPrinter(Context context) {
        this.mContext = context;
//        init();
    }

    private static UsbThermalPrinter tps508Printer;

    private void init() {


        tps508Printer = new UsbThermalPrinter(mContext);

        isPowerOn();


        try {

            tps508Printer.setGray(5);//设置打印灰度值 level:0-7,默认为1


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

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

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

        }


    }

    Handler mHandler = new Handler();

    int retryCount = 0;
    int allRetryCount = 6;

    // 上电
    public void isPowerOn() {
        if (tps508Printer == null) {
            tps508Printer = new UsbThermalPrinter(mContext);
        }


        ThreadPoolManager.getInstance().executeIOTask(new Runnable() {
            @Override
            public void run() {
                try {

                    tps508Printer.start(0);
                    Thread.sleep(500);
                    tps508Printer.reset();


                    mHandler.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){
                                // 打印机就绪
                                printInitResultCallback.onPrintInitSuccess();
                            }else if(checkStatus == ThermalPrinter.STATUS_NO_PAPER){
                                // 打印机缺纸
                                printInitResultCallback.onPrintInitError(checkStatus+"","打印机——打印机缺纸");
                            }else if(checkStatus == ThermalPrinter.STATUS_OVER_HEAT){
                                // 打印机机芯过热
                                printInitResultCallback.onPrintInitError(checkStatus+"","打印机——机芯过热");
                            }else if(checkStatus == ThermalPrinter.STATUS_OVER_FLOW){
                                // 打印机缓存已满
                                printInitResultCallback.onPrintInitError(checkStatus+"","打印机——缓存已满");
                            }else if(checkStatus == ThermalPrinter.STATUS_UNKNOWN){
                                // 打印机状态未知
                                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")){

                        printInitResultCallback.onPrintInitSuccess();

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

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


                }

            }
        });

    }

    PrintInitResultCallback printInitResultCallback;


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

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

        try {

            tps508Printer.setAlgin(align);//设置打印对齐方式
            tps508Printer.setTextSize(textSize);
            tps508Printer.addString(text);
            tps508Printer.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);

        try {
            tps508Printer.printLogo(bitmap1, true);
        } 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);

        try {
            tps508Printer.printLogo(bitmap1, true);
        } catch (TelpoException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void printTextBitmap(List<PrintContentBean> printContentList, PrintBean.PrintConfigDTO printConfigDTO) {

    }

    @Override
    public void printBitmap(PrintBean.PrintConfigDTO printConfigDTO, String base64, int width, int height) {

    }

    @Override
    public void printPDF(PrintBean.PrintConfigDTO printConfigDTO, String localPath) {

    }

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

    @Override
    public void cutPaper() {

        // D2这个没有切纸的，要手动撕它。所以不要调用切纸的接口，会报错崩溃

        feed(15);

        try {
            tps508Printer.printString();//启动打印，打印完不走纸
        } catch (TelpoException e) {
            e.printStackTrace();
        }


        feed(15);

    }

    @Override
    public void disconnect() {
        tps508Printer.stop();
    }

    @Override
    public void startPrint() {

    }







}
