package com.common.print;


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

import com.common.arome.Constants;
import com.common.arome.DeviceUtils;
import com.common.lib_base.common.async.ThreadPoolManager;
import com.common.lib_base.utils.StringUtils;
import com.common.lib_base.utils.log.CommonLogUtils;
import com.common.lib_base.utils.ui.ToastUtils;
import com.common.print.bean.PrintBean;
import com.common.print.callback.PrintInitResultCallback;
//import com.common.print.many.KMlaA4Printer;
//import com.common.print.many.MlaA4Printer;
import com.common.print.many.MlaFCDD215Printer;
import com.common.print.many.NullPrinter;
import com.common.print.many.TbPrinter;
import com.common.print.bean.PrintContentBean;
import com.common.print.many.base.IPrinter;
//import com.telpo.tps550.api.printer.UsbThermalPrinter;

import java.util.ArrayList;
import java.util.List;

public class BasePrinter {

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


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

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

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

    IPrinter iPrinter;


    public IPrinter getPrinter(Context context) {
        String model = DeviceUtils.getDeviceModel();
        CommonLogUtils.e("model:"+model);

        if (Constants.DeviceModel.T1YB01.equals(model)) {
            // y9
//            iPrinter = MlaPrinter.getInstance(context);
            iPrinter = MlaFCDD215Printer.getInstance(context);
//            iPrinter = KMlaA4Printer.Companion.getInstance(context);
        } else if(Constants.DeviceModel.D2.equals(model)) {
            // 天波
            iPrinter = TbPrinter.getInstance(context);
        }else {
            //其余设备
            iPrinter = NullPrinter.getInstance();
        }
        return iPrinter;
    }



    // 初始化
    PrintInitResultCallback printInitResultCallback;

    public void initPrint(PrintInitResultCallback printInitResultCallback) {

        this.printInitResultCallback = printInitResultCallback;

        iPrinter.initPrint(printInitResultCallback);
    }



    OnPrintBaseListener listener;

    public void setListener(OnPrintBaseListener lister) {
        listener = lister;
    }
    public interface OnPrintBaseListener {
        void PrintingComplete();
        void PrintingFail(String msg);
    }


    Handler mHandler = new Handler();

    List<PrintContentBean> printContentList = new ArrayList<>();

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


    PrintBean.PrintConfigDTO printConfigDTO;

    // 传入要打印的数据，开始打印
    public void handleDataAndPrint(List<PrintContentBean> printContentData, PrintBean.PrintConfigDTO printConfigDTO) {

        if(printContentData == null || printContentData.size() == 0){

            CommonLogUtils.e("printContentData == null");
            ToastUtils.showLongToast("打印数据为空");
            return;
        }

        this.printConfigDTO = printConfigDTO;


        if(iPrinter == null){
            CommonLogUtils.e("iPrinter == null");
            return;
        }

        printContentList.clear();
        printContentList.addAll(printContentData);


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

                startPrint();

            }
        });

    }

    private void startPrint() {


        CommonLogUtils.e("startPrint");

        iPrinter.startPrint();


        int printPageType = printConfigDTO.getPrintPageType();


        switch (printPageType){
            case -1:
                // 未设置
                commonPrint();
                CommonLogUtils.e("cutPaper");
                // 打印完并切纸
                iPrinter.cutPaper();
                break;
            case 1:
                CommonLogUtils.e("_______________123"+"startPrint  打印图片");
                a4PrintBitmap(); //内部监听方法调用cutpager
                break;
            case 2:
                a4PrintPdf();//内部监听方法调用cutpager
                break;
        }





    }

    /**
     * A4热敏打印
     */
    private void A4Print() {
        iPrinter.printTextBitmap(printContentList,printConfigDTO);
    }

    private void a4PrintBitmap(){
        if(printContentList.size()>0){
            PrintContentBean printContentBean = printContentList.get(0);
            String imageBase64 = printContentBean.getImageBase64();

            int width = printContentBean.getWidth();
            int height = printContentBean.getHeight();
            iPrinter.printBitmap(printConfigDTO,imageBase64,width,height);
        }

    }

    private void a4PrintPdf(){
        if(printContentList.size()>0){
            PrintContentBean printContentBean = printContentList.get(0);
            String pdfPath = printContentBean.getLocalPdfPath();
            iPrinter.printPDF(printConfigDTO,pdfPath);
        }

    }


    /**
     * 普通小票打印
     */
    private void commonPrint() {
        // 打印时间
        int printTotalTime = 0;
        // 循环打印，并累计打印时间
        for (int i = 0; i < printContentList.size(); i++) {
            PrintContentBean printContentBean = printContentList.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;
                }

                // 打印文字
                iPrinter.printText(text,
                        algin,
                        printContentBean.getTextSize(),
                        printContentBean.isBold());

                // 打印时间累计
                printTotalTime+=1000;

            }else if(StringUtils.isNotNull(qrCodeText)){
                // 二维码

                iPrinter.printQrCode(qrCodeText,width,height);

                // 打印时间累计
                printTotalTime+=2000;

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

                iPrinter.printBitmap(imageBase64,width,height);

                // 打印时间累计
                printTotalTime+=2000;
            }

        }



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


    }


    public void destory(){

        if(mHandler!=null){
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }

        if(iPrinter!=null){
            iPrinter.disconnect();
            iPrinter = null;
        }

        instance = null;

    }




}
