package com.hh.hardware.lib_mla_a4_print;

import android.content.Context;
import android.graphics.Bitmap;
import android.hardware.usb.UsbDevice;
import android.os.Handler;
import android.os.Looper;

import com.hh.lib_base.BaseApplication;
import com.hh.lib_base.log.AppLogUtils;
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.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.jx800r09.sdk_800r09_library.bean.PrintDataBean;
import com.jx800r09.sdk_800r09_library.enumdata.PageTypeEnum;
import com.jx800r09.sdk_800r09_library.enumdata.PrintingStateEnum;
import com.jx800r09.sdk_800r09_library.listener.UsbDeviceListener;
import com.jx800r09.sdk_800r09_library.task.UsbPrintPictureThreadTask;
import com.jx800r09.sdk_800r09_library.usb.UsbDeviceManager;
import com.jx800r09.sdk_800r09_library.utils.PrinterNameUtil;
import com.jx800r09.sdk_800r09_library.utils.ThreadUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 *
 * @author xwh
 * time 2024/9/20
 * Description: MlaFCDD215Printer（A4热敏打印机）
 **/
public class MlaFCDD215Printer extends BasePrinter {
    // 当前类名
    private String mTag = "HHArome--" + getClass().getSimpleName() + "--";
    //用volatile关键字确保 instance 在多线程下的可见性
    private static volatile MlaFCDD215Printer instance = null;
    private int retryCount = 0;
    private boolean isInitSuccess;

    private Handler mHandler ;
    private PrintInitResultCallback printInitResultCallback;
    private OnPrintBaseListener listener;
    private UsbPrintPictureThreadTask pictureThreadTask;

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

    public void init() {
        UsbDeviceManager.getInstance().init(BaseApplication.getContext());
        UsbDeviceManager.getInstance().setUsbDeviceCallBack(new UsbDeviceListener());
        getmHandler().postDelayed(new Runnable() {
            @Override
            public void run() {
                AppLogUtils.e("执行getDevice");
                getDevice(UsbDeviceManager.getInstance().getAllUseDeviceHp());
            }
        },2000);
    }
    private void getDevice(HashMap<String, UsbDevice> allUseDevice) {
        AppLogUtils.e("allUseDevice.size = " + allUseDevice.size());
        boolean isContain09 = false;
        Iterator<Map.Entry<String, UsbDevice>> iterator = allUseDevice.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            String key = (String) entry.getKey();
            UsbDevice value = (UsbDevice) entry.getValue();
            AppLogUtils.e("key = " + key,
                    "key = " + value);
            if (PrinterNameUtil.startWithName(value.getProductName())) {
                isContain09 = true;
                UsbDeviceManager.getInstance().reqPermission(value);
                AppLogUtils.e(
                        "deviceName=" + value.getDeviceName(),
                        "productName =" + value.getProductName());
            }
        }
        if (UsbDeviceManager.getInstance().isConnect()) {
            AppLogUtils.e("A4-已连接");
            //练习纸，因不知原因会走纸，沟通厂商后可以调用一次连续纸
            //打印机有断电保护，现状就是调用后确实能恢复使用
            UsbDeviceManager.getInstance().sendPieceToPiece();
            isInitSuccess = true;
            if(printInitResultCallback!=null){
                printInitResultCallback.onPrintInitSuccess();
            }
        } else {
            AppLogUtils.e("A4-未连接");
            getmHandler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    init();
                }
            },5000);
            isInitSuccess = false;
            if(printInitResultCallback!=null){
                printInitResultCallback.onPrintInitError("-1","A4热敏打印机未连接");
            }
        }
    }
    private void printProcessState(PrintingStateEnum printingStateEnum){
        switch (printingStateEnum){
            //初始化中
            case State_Initializing:

                break;
            //打印头过热
            case State_Head_Over_Hot:
                sendListener(false,"打印头过热");
                break;
            //打印机未合盖
            case State_Cover_Up:
                sendListener(false,"打印机未合盖");
                break;
            //打印机缺纸
            case State_Without_Page:
                sendListener(false,"打印机缺纸");
                break;
            //打印机正常即开始打印
            case State_Thermal_Mode_Normal:
                AppLogUtils.e("打印机正常即开始打印");
                break;
            //打印错误
            case State_Error:
                sendListener(false,"打印错误");
                break;
            //取消打印
            case State_Cancel_Print:
                sendListener(false,"取消打印");
                break;
            //打印完成
            case State_Done_Print:
                sendListener(true,"打印完成");
                AppLogUtils.e("打印完成");
                break;

        }
    }

    private void sendListener(boolean isComplete,String msg){
        if(listener!=null){
            if(isComplete){
                listener.PrintingComplete();
            }else{
                listener.PrintingFail(msg);
            }
        }
    }

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

    }

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

    }

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

    }

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

    }

    @Override
    public void feed(int line) {
        // 走纸
        if(0 == line){
            line = 1;
        }

        for (int i = 0; i < line; i++) {
            UsbDeviceManager.getInstance().sendPrinterStep();
        }
    }

    @Override
    public void cutPaper() {
        feed(1);
        AppLogUtils.e("printBitmap  cutPaper");

        getmHandler().postDelayed(new Runnable() {
            @Override
            public void run() {
                UsbDeviceManager.getInstance().sendCutter();
            }
        },1000);
    }

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

        if(StringUtils.isNull(base64)){
            AppLogUtils.e("printBitmap  图片参数为空");
            //  ToastUtils.showLongToast("图片参数为空");
            sendListener(false,"图片参数为空");
            return;
        }
        if(printConfigDTO==null){
            AppLogUtils.e("printBitmap  未配置打印浓度和速度");
            // ToastUtils.showLongToast("未配置打印浓度和速度");
            sendListener(false,"未配置打印浓度和速度");
            return;
        }
        List<PrintDataBean> picturePrintTask = new ArrayList();
        final Bitmap bitmap;


        // 横屏图片
//        base64 = "https://img-s-msn-com.akamaized.net/tenant/amp/entityid/BB1oTBz1.img?w=604&h=486&m=6&x=194&y=159&s=183&d=183";

        // 竖屏
        //   base64 = "https://tse4-mm.cn.bing.net/th/id/OIP-C.VC96IQ53w1EhF5yR442lGAHaNK?w=115&h=180&c=7&r=0&o=5&dpr=1.5&pid=1.7";

        bitmap = BitmapUtils.stringToBitmap(base64);

        // bitmap = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.a4_img);

        PrintDataBean printDataBean = new PrintDataBean();
        int potency=printConfigDTO.getPrintPotency();
        if(potency<1){
            potency=1;
        }
        if(potency>5){
            potency=5;
        }
        int speed=printConfigDTO.getPrintSpeed();
        if(speed<1){
            speed=1;
        }
        if(speed>5){
            speed=5;
        }
        // 设定打印浓度，不设置默认为5
        printDataBean.setPotency(potency);
        // 设定打印速度，不设置默认为5。打印速度越低，对电压要求越低
        printDataBean.setSpeed(speed);
        // 给定想打印的纸张规格
        if(0 == printConfigDTO.getPrintContent()){
            // A4
            printDataBean.setPageTypeEnum(PageTypeEnum.Page_Type_A4_Normal);
        }else if(3 == printConfigDTO.getPrintContent()){
            // A5
            printDataBean.setPageTypeEnum(PageTypeEnum.Page_Type_A5_Normal);
        }else{
            // 默认
            printDataBean.setPageTypeEnum(PageTypeEnum.Page_Type_A4_Normal);
        }
        printDataBean.setPageTypeEnum(PageTypeEnum.Page_Type_A4_Normal);
        // 设定打印居中位置 0左边 1居中 2居右 不设置默认1
        printDataBean.setHorAlignment(1);
        //当出现打印过程中缺纸，是否重新打印上一页 默认为false ，不会重新打印该页
        printDataBean.setReprintLastPage(true);
        // 设置打印的图片
        printDataBean.setBitmap(bitmap);
        picturePrintTask.add(printDataBean);

        if(picturePrintTask!=null){
            ThreadUtils.cancel(pictureThreadTask);
        }
        pictureThreadTask = new UsbPrintPictureThreadTask(picturePrintTask,
                new UsbPrintPictureThreadTask.IPrinterListener() {
            @Override
            public void onPage(int i, int i1) {
//                CommonLogUtils.e("i = "+i,
//                        "i1 = "+i1);
            }

            @Override
            public void onPrintCopies(int i, int i1) {
//                CommonLogUtils.e("i = "+i,
//                        "i1 = "+i1);
            }

            @Override
            public void onStep(int i, int i1) {
//                CommonLogUtils.e("i = "+i,
//                        "i1 = "+i1);
            }

            @Override
            public void onDeviceStatus(String s) {
                AppLogUtils.e("s = " + s);
            }

            @Override
            public void onPrintProcessState(PrintingStateEnum printingStateEnum) {
                printProcessState(printingStateEnum);
            }

//            @Override
//            public void onPrintProcessState(PrintingStateEnum printingStateEnum) {
//                CommonLogUtils.e("printingStateEnum = " + printingStateEnum.getMsg());
//            }

            @Override
            public void onCompleted() {
                AppLogUtils.e("printBitmap  onCompleted");
                cutPaper();
                if(bitmap!=null&&!bitmap.isRecycled()){
                    bitmap.recycle();
                }
                pictureThreadTask = null;
            }
        });


        // 应该是打印次数
        if(pictureThreadTask!=null){
            pictureThreadTask.setPrintCopies(1);
        }

        getmHandler().post(new Runnable() {
            @Override
            public void run() {
                if(pictureThreadTask!=null){
                    ThreadUtils.executeByCpu(pictureThreadTask);
                }
            }
        });



    }

    @Override
    public void disconnect() {
        if (pictureThreadTask != null) {
            ThreadUtils.cancel(pictureThreadTask);
            pictureThreadTask = null;
        }
        instance = null;

    }

    @Override
    public void startPrint(AmpeRequestPrintBean printBean, OnPrintBaseListener listener) {
        this.listener=listener;
        if (printBean == null) {
            return;
        }
        if (printBean.getPrintList() == null) {
            return;
        }
        if (!isInitSuccess) {
            if(listener!=null){
                listener.PrintingFail("未初始化");
            }
            return;
        }
        if(printBean.getPrintList() .size()>0){
            PrintContentBean printContentBean = printBean.getPrintList() .get(0);
            String imageBase64 = printContentBean.getImageBase64();
            int width = printContentBean.getWidth();
            int height = printContentBean.getHeight();
            PrintBean.PrintConfigDTO printConfigDTO=new PrintBean.PrintConfigDTO();
            printConfigDTO.setPrintContent(printBean.getPrintContent());
            printConfigDTO.setPrintPotency(printBean.getPrintPotency());
            printConfigDTO.setPrintSpeed(printBean.getPrintSpeed());
            printBitmap(printConfigDTO,imageBase64,width,height);
        }
    }


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

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