package com.common.print.many;

import static com.jx800r09.sdk_800r09_library.enumdata.PrintingStateEnum.State_Initializing;

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

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.BasePrinter;
import com.common.print.R;
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.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.UsbPrintPdfThreadTask;
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.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 是福创达(富芯)科技的打印机-型号FCD-D215
 * 适用于以下设备
 * 马里奥-y9-A4热敏
 */
public class MlaFCDD215Printer implements IPrinter {


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

    BasePrinter.OnPrintBaseListener listener;

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

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

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

    private MlaFCDD215Printer(Context context) {
        this.mContext = context;

       // init(context);
    }


    Context mContext;


    int retryCount = 0;
    boolean isInitSuccess;

    Handler mHandler = new Handler();

    public void init(Context context) {


        CommonLogUtils.e("A4-init");

        UsbDeviceManager.getInstance().init(context);
        UsbDeviceManager.getInstance().setUsbDeviceCallBack(new UsbDeviceListener());


        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                CommonLogUtils.e("执行getDevice");
                getDevice(UsbDeviceManager.getInstance().getAllUseDeviceHp());
            }
        },2000);




        // printInitResultCallback.onPrintInitSuccess();
        // printInitResultCallback.onPrintInitError("-1","找不到USB打印机，请检查USB线连接");


    }


    PrintInitResultCallback printInitResultCallback;

    @Override
    public void initPrint(PrintInitResultCallback printInitResultCallback) {

        this.printInitResultCallback = printInitResultCallback;

        init(mContext);

    }


    List<PrintDataBean> picturePrintTask = new ArrayList();

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


        CommonLogUtils.e("text--" + text);

        PrintDataBean printDataBean = new PrintDataBean();


        // 文字转Bitmap
//        Bitmap textToBimtap = BitmapUtils.createTextToBimtap(text, 2397, 1678);



        if(0 == textSize){
            textSize = 18;
        }else if(textSize > 20){
            textSize = textSize-20;
        }

        Bitmap textToBimtap = BitmapUtils.textPositionToBitmap(mContext,text,80,100,200);

        // 设定打印浓度，不设置默认为5
        printDataBean.setPotency(5);
        // 设定打印速度，不设置默认为5
        printDataBean.setSpeed(3);

        printDataBean.setBitmap(textToBimtap);
        // 给定想打印的纸张规格
        printDataBean.setPageTypeEnum(PageTypeEnum.Page_Type_A5_Normal);
        // 设定打印居中位置 0左边 1居中 2居右 不设置默认1
        printDataBean.setHorAlignment(align);
        //当出现打印过程中缺纸，是否重新打印上一页 默认为false ，不会重新打印该页
        printDataBean.setReprintLastPage(true);

        picturePrintTask.clear();
        picturePrintTask.add(printDataBean);


        UsbPrintPictureThreadTask pictureThreadTask = new UsbPrintPictureThreadTask(picturePrintTask, new UsbPrintPictureThreadTask.IPrinterListener() {
            @Override
            public void onPage(int i, int i1) {

            }

            @Override
            public void onPrintCopies(int i, int i1) {

            }

            @Override
            public void onStep(int i, int i1) {

            }

            @Override
            public void onDeviceStatus(String s) {

            }

            @Override
            public void onPrintProcessState(PrintingStateEnum printingStateEnum) {

            }


            @Override
            public void onCompleted() {

            }
        });

        // 应该是打印次数
        pictureThreadTask.setPrintCopies(1);


        ThreadUtils.executeByCpu(pictureThreadTask);


    }

    @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 zoomImg = BitmapUtils.zoomImg(bitmap,
                width,
                height);


        PrintDataBean printDataBean = new PrintDataBean();


        // 设定打印浓度，不设置默认为5
        printDataBean.setPotency(5);
        // 设定打印速度，不设置默认为5
        printDataBean.setSpeed(3);

        printDataBean.setBitmap(zoomImg);
        // 给定想打印的纸张规格
        printDataBean.setPageTypeEnum(PageTypeEnum.Page_Type_A4_Normal);
        // 设定打印居中位置 0左边 1居中 2居右 不设置默认1
        printDataBean.setHorAlignment(1);
        //当出现打印过程中缺纸，是否重新打印上一页 默认为false ，不会重新打印该页
        printDataBean.setReprintLastPage(true);

        picturePrintTask.clear();
        picturePrintTask.add(printDataBean);


        UsbPrintPictureThreadTask pictureThreadTask = new UsbPrintPictureThreadTask(picturePrintTask, new UsbPrintPictureThreadTask.IPrinterListener() {
            @Override
            public void onPage(int i, int i1) {

            }

            @Override
            public void onPrintCopies(int i, int i1) {

            }

            @Override
            public void onStep(int i, int i1) {

            }

            @Override
            public void onDeviceStatus(String s) {

            }

            @Override
            public void onPrintProcessState(PrintingStateEnum printingStateEnum) {

            }


            @Override
            public void onCompleted() {

            }
        });

        // 应该是打印次数
        pictureThreadTask.setPrintCopies(1);


        ThreadUtils.executeByCpu(pictureThreadTask);


    }

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


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


        CommonLogUtils.e("printContentList--"+printContentList.toString(),
                "printConfigDTO--"+printConfigDTO.toString());


        int printContent = printConfigDTO.getPrintContent();


        // 得到图片
        Bitmap textToBimtap = BitmapUtils.createTextBitmap(mContext,printContentList,printContent);

        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);

        printDataBean.setBitmap(textToBimtap);
        // 给定想打印的纸张规格

        /**
         * Page_Type_A4_Normal(0),
         * Page_Type_A4_Roll(1),
         * Page_Type_A4_ANSI_A(2),
         * Page_Type_A5_Normal(3),
         * Page_Type_200mm(4),
         * Page_Type_150mm(5),
         * Page_Type_100mm(6),
         * Page_Type_Customize(7);
         */
        if(0 == printContent){
            // A4
            printDataBean.setPageTypeEnum(PageTypeEnum.Page_Type_A4_Normal);
        }else if(3 == printContent){
            // A5
            printDataBean.setPageTypeEnum(PageTypeEnum.Page_Type_A5_Normal);
        }else{
            // 默认
            printDataBean.setPageTypeEnum(PageTypeEnum.Page_Type_A4_Normal);
        }

        // 设定打印居中位置 0左边 1居中 2居右 不设置默认1
        printDataBean.setHorAlignment(1);
        //当出现打印过程中缺纸，是否重新打印上一页 默认为false ，不会重新打印该页
        printDataBean.setReprintLastPage(true);

        picturePrintTask.clear();
        picturePrintTask.add(printDataBean);


        UsbPrintPictureThreadTask pictureThreadTask = new UsbPrintPictureThreadTask(picturePrintTask, new UsbPrintPictureThreadTask.IPrinterListener() {
            @Override
            public void onPage(int i, int i1) {

            }

            @Override
            public void onPrintCopies(int i, int i1) {

            }

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

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

            @Override
            public void onPrintProcessState(PrintingStateEnum printingStateEnum) {
                CommonLogUtils.e("printingStateEnum:"+printingStateEnum.toString());
            }


            @Override
            public void onCompleted() {
                CommonLogUtils.e("onCompleted");

                cutPaper();
            }
        });

        // 应该是打印次数
        pictureThreadTask.setPrintCopies(1);



        ThreadUtils.executeByCpu(pictureThreadTask);





    }

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

        if(StringUtils.isNull(base64)){
            CommonLogUtils.e("_______________123"+"printBitmap  图片参数为空");
            ToastUtils.showLongToast("图片参数为空");
            sendListener(false,"图片参数为空");
            return;
        }
        if(printConfigDTO==null){
            CommonLogUtils.e("_______________123"+"printBitmap  未配置打印浓度和速度");
            ToastUtils.showLongToast("未配置打印浓度和速度");
            sendListener(false,"未配置打印浓度和速度");
            return;
        }

        picturePrintTask.clear();

        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);


       final UsbPrintPictureThreadTask 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) {
                CommonLogUtils.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() {
                CommonLogUtils.e("_______________123"+"printBitmap  onCompleted");

                cutPaper();
                if(bitmap!=null&&!bitmap.isRecycled()){
                    bitmap.recycle();
                }
            }
        });


        // 应该是打印次数
        pictureThreadTask.setPrintCopies(1);
        getMainHandler().post(new Runnable() {
            @Override
            public void run() {
                ThreadUtils.executeByCpu(pictureThreadTask);
            }
        });



    }
    Handler mainHandler;
    private Handler getMainHandler(){
        if(mainHandler==null){
            synchronized (MlaFCDD215Printer.class){
                if(mainHandler==null){
                    mainHandler = new Handler(Looper.getMainLooper());
                }
            }
        }
        return mainHandler;
    }
    @Override
    public void printPDF(PrintBean.PrintConfigDTO printConfigDTO, String localPath) {
        printPdf(printConfigDTO,localPath);
    }


    public void printPdf(PrintBean.PrintConfigDTO printConfigDTO, String localPath){

        CommonLogUtils.e("printPdf");
        if(StringUtils.isNull(localPath)){
            ToastUtils.showLongToast("PDF文件地址为空");
            sendListener(false,"PDF文件地址为空");
            return;
        }
        if(printConfigDTO==null){
            ToastUtils.showLongToast("未配置打印浓度和速度");
            sendListener(false,"未配置打印浓度和速度");
            return;
        }

        picturePrintTask.clear();
//        Bitmap bitmap = BitmapUtils.stringToBitmap(base64);


        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);
        }
        // 设定打印居中位置 0左边 1居中 2居右 不设置默认1   设置该行，会导致右边的一部分内容会移动到左边
//        printDataBean.setHorAlignment(1);
        //当出现打印过程中缺纸，是否重新打印上一页 默认为false ，不会重新打印该页
        printDataBean.setReprintLastPage(true);
        // 设置打印的pdf
//        printDataBean.setFilePath(copyAssetGetFilePath("a4_p.pdf"));
        printDataBean.setFilePath(localPath);


       final UsbPrintPdfThreadTask pdfThreadTask = new UsbPrintPdfThreadTask(printDataBean, new UsbPrintPdfThreadTask.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) {
                CommonLogUtils.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() {
                CommonLogUtils.e("onCompleted = ");
                cutPaper();
            }
        });

        // 应该是打印次数
        pdfThreadTask.setPrintCopies(1);

        getMainHandler().post(new Runnable() {
            @Override
            public void run() {
                ThreadUtils.executeByCpu(pdfThreadTask);
            }
        });


    }



    @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);

        CommonLogUtils.e("_______________123"+"printBitmap  cutPaper");

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


    }

    @Override
    public void disconnect() {


    }

    @Override
    public void startPrint() {

        // 有可能上次打印没有切掉
//        cutPaper();
    }


    private void getDevice(HashMap<String, UsbDevice> allUseDevice) {

        CommonLogUtils.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();

            CommonLogUtils.e("key = " + key,
                    "key = " + value);

            if (PrinterNameUtil.startWithName(value.getProductName())) {
                isContain09 = true;

                UsbDeviceManager.getInstance().reqPermission(value);

                CommonLogUtils.e(
                        "deviceName=" + value.getDeviceName(),
                        "productName =" + value.getProductName());
            }
        }


//        for (String key : allUseDevice.keySet()) {
//            CommonLogUtils.e("for-map-key:" + key);
//            UsbDevice usbDevice = allUseDevice.get(key);
//            if (PrinterNameUtil.startWithName(usbDevice.getProductName())){
//                CommonLogUtils.e(
//                        "for-deviceName=" + usbDevice.getDeviceName(),
//                        "for-productName =" + usbDevice.getProductName());
//            }
//
//        }


        if (UsbDeviceManager.getInstance().isConnect()) {
            CommonLogUtils.e("A4-已连接");
            //练习纸，因不知原因会走纸，沟通厂商后可以调用一次连续纸
            //打印机有断电保护，现状就是调用后确实能恢复使用
            UsbDeviceManager.getInstance().sendPieceToPiece();
            if(printInitResultCallback!=null){
                printInitResultCallback.onPrintInitSuccess();
            }
        } else {
            CommonLogUtils.e("A4-未连接");
            if(printInitResultCallback!=null){
                printInitResultCallback.onPrintInitError("-1","A4热敏打印机未连接");
            }
        }


    }


    public String copyAssetGetFilePath(String fileName){

        try {
            File cacheDir = mContext.getCacheDir();
            if (!cacheDir.exists()) {
                cacheDir.mkdirs();
            }

            File outFile = new File(cacheDir, fileName);
            if (!outFile.exists()) {
                    boolean res = outFile.createNewFile();
                if (!res) {
                    return null;
                }
            } else {
                if (outFile.length() > 10) { //表示已经写入一次
                    return outFile.getPath();
                }
            }

            InputStream is = mContext.getAssets().open(fileName);
            FileOutputStream fos = new FileOutputStream(outFile);

            byte[] buffer = new byte[1024]; // 一个字节数组

            int byteCount=0;
            while (( byteCount=is.read(buffer) ) != -1 ){
                fos.write(buffer,0,byteCount);
            }

            fos.flush();
            is.close();
            fos.close();
            return outFile.getPath();
        }catch (IOException e) {
            e.printStackTrace();
        }
        return null;



    }


    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:
                CommonLogUtils.e("_______________123"+"打印机正常即开始打印");
                break;
            //打印错误
            case State_Error:
                sendListener(false,"打印错误");
                break;
            //取消打印
            case State_Cancel_Print:
                sendListener(false,"取消打印");
                break;
            //打印完成
            case State_Done_Print:
                sendListener(true,"打印完成");
                CommonLogUtils.e("_______________123"+"打印完成");
                break;

        }

    }

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

    public void setListener(BasePrinter.OnPrintBaseListener listener) {
        this.listener = listener;
    }
}
