package com.printer.demo.utils;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.os.Build;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.Log;


import com.printer.demo.R;
import com.printer.sdk.BarcodeCreater;
import com.printer.sdk.CanvasDrawPrint;
import com.printer.sdk.CanvasPrint;
import com.printer.sdk.FontProperty;
import com.printer.sdk.PrinterConstants;
import com.printer.sdk.PrinterConstants.Command;
import com.printer.sdk.PrinterConstants.PAlign;
import com.printer.sdk.PrinterConstants.PrinterType;
import com.printer.sdk.PrinterInstance;
import com.printer.sdk.Table;
import com.printer.sdk.utils.XLog;
import com.printer.sdk.zxing.BarcodeFormat;
import com.printer.sdk.zxing.EncodeHintType;
import com.printer.sdk.zxing.MultiFormatWriter;
import com.printer.sdk.zxing.WriterException;
import com.printer.sdk.zxing.common.BitMatrix;
import com.printer.sdk.zxing.qrcode.decoder.ErrorCorrectionLevel;

import java.util.Hashtable;

public class CanvasUtils {
    private static String TAG = "com.printer.demo.utils";

    /**
     * 画布模版一 普通画布，画布的用法
     *
     * @param resources
     * @param mPrinter
     * @param isStylus
     * @param is58mm
     */
    public void printCustomImage(Resources resources, PrinterInstance mPrinter, boolean isStylus, boolean is58mm) {
        mPrinter.initPrinter();
        mPrinter.setFont(0, 0, 0, 0, 0);
        mPrinter.setPrinter(Command.ALIGN, Command.ALIGN_LEFT);
        mPrinter.printText(resources.getString(R.string.str_canvas));
        mPrinter.setPrinter(Command.PRINT_AND_WAKE_PAPER_BY_LINE, 2);
        CanvasPrint cp = new CanvasPrint();
        /**
         * 初始化画布，画布的宽度为变量，一般有两个选择：1.58mm型号打印机实际可用是48mm，48*8=384px 2.
         * 80mm型号打印机实际可用是72mm，72*8=576px，因为画布的高度是无限制的，但从内存分配方面考虑要小于4M比较合适。
         * 所有预置为宽度的5倍。初始化画笔，默认属性有：1.消除锯齿 2.设置画笔颜色为黑色。
         *
         * init 方法包含cp.initCanvas(550)和cp.initPaint（），T9打印宽度为72mm，其他为47mm
         */
        if (isStylus) {
            cp.init(PrinterType.TIII);
        } else {
            if (is58mm) {
                cp.init(PrinterType.TIII);
            } else {
                cp.init(PrinterType.T9);
            }
        }
        // 非中文使用空格分隔单词
        cp.setUseSplit(true);
        // 阿拉伯文靠右显示
        cp.setTextAlignRight(true);
        /*
         * 插入图片函数：drawImage(float x,float y, String path) 其中（x,y）是指插入图片的左上顶点坐标。
         */
        FontProperty fp = new FontProperty();
        fp.setFont(false, false, false, false, 25, null);
        // 通过初始化的字体属性设置画笔
        cp.setFontProperty(fp);
        cp.drawText("Show example of context contains English language is showed in right of parent:");
        fp.setFont(false, false, false, false, 30, null);
        cp.setFontProperty(fp);
        cp.setTextAlignRight(false);
        cp.drawText("打印汉字测试，测试打满一行内容后，是否自动换行，且向左对齐展示。");
        cp.drawText("\n\b\n\n");
        cp.drawImage(BitmapFactory.decodeResource(resources, R.drawable.my_picture));
        if (isStylus) {
            // 针打图形，第二个参数为0倍高倍宽，为1只倍高
            mPrinter.printImageStylus(cp.getCanvasImage(), 1);

        } else {
            mPrinter.printImage(cp.getCanvasImage(), PAlign.NONE, 0, false);
        }
    }

    /**
     * 画布模版二 图片跟文字并行
     *
     * @param resources
     * @param mPrinter
     * @param isStylus
     * @param is58mm
     */
    public void printCustomImage2(Resources resources, PrinterInstance mPrinter) {
        // 创建画布
        CanvasPrint cp = new CanvasPrint();
        if (PrinterConstants.paperWidth == 576) {
            // 初始化画布，POS88系列用T9参数即可
            cp.init(PrinterType.T9);
            // 调用下面的方法生成二维码
            Bitmap bitmapCODE39 = createBitmapQR_CODE("123456789", 270, 270);
            // 将二维码画到画布上（0,0）处坐标
            cp.drawImage(0, 0, bitmapCODE39);
            /**
             * 默认字体
             */
            // 创建字体
            FontProperty fp = new FontProperty();
            // 字体属性赋值 此处参数个数根据SDK版本不同，有略微差别，酌情增减。
            fp.setFont(true, false, false, false, 40, null);
            // 设置字体
            cp.setFontProperty(fp);
            // 将文字画到画布上指定坐标处
            cp.drawText(250, 80, "默认字体");
            cp.drawLine(0, 240, 576, 240);

        } else if (PrinterConstants.paperWidth == 724) {
            // 100mm纸宽
            cp.init(PrinterType.T7);
            // 调用下面的方法生成二维码
            Bitmap bitmapCODE39 = createBitmapQR_CODE("123456789", 300, 300);
            // 将二维码画到画布上（0,0）处坐标
            cp.drawImage(0, 0, bitmapCODE39);
            /**
             * 默认字体
             */
            // 创建字体
            FontProperty fp = new FontProperty();
            // 字体属性赋值 此处参数个数根据SDK版本不同，有略微差别，酌情增减。
            fp.setFont(true, false, false, false, 50, null);
            // 设置字体
            cp.setFontProperty(fp);
            // 将文字画到画布上指定坐标处
            cp.drawText(320, 80, "默认字体");
            /**
             * 楷体
             */
            Typeface kaiti = Typeface.createFromAsset(resources.getAssets(), "kaiti.ttf");
            fp.setFont(true, false, false, false, 50, kaiti);
            // 设置字体
            cp.setFontProperty(fp);
            cp.drawText(320, 140, "楷体展示");
            /**
             * 宋体
             */
            Typeface songti = Typeface.createFromAsset(resources.getAssets(), "songti.ttf");
            fp.setFont(true, false, false, false, 50, songti);
            // 设置字体
            cp.setFontProperty(fp);
            cp.drawText(320, 200, "宋体展示");
            /**
             * 黑体
             */
            Typeface heiti = Typeface.createFromAsset(resources.getAssets(), "heiti.ttf");
            fp.setFont(true, false, false, false, 50, heiti);
            // 设置字体
            cp.setFontProperty(fp);
            cp.drawText(320, 260, "黑体展示");
            cp.drawLine(0, 265, 724, 265);

        } else if (PrinterConstants.paperWidth == 384) {
            // 58mm
            cp.init(PrinterType.TIII);
            // 调用下面的方法生成二维码
            Bitmap bitmapCODE39 = createBitmapQR_CODE("123456789", 150, 150);
            // 将二维码画到画布上（0,0）处坐标
            cp.drawImage(0, 0, bitmapCODE39);
            // 创建字体
            FontProperty fp = new FontProperty();
            /**
             * 楷体
             */
            Typeface kaiti = Typeface.createFromAsset(resources.getAssets(), "kaiti.ttf");
            fp.setFont(true, false, false, false, 30, kaiti);
            // 设置字体
            cp.setFontProperty(fp);
            cp.drawText(160, 40, "楷体展示");
            /**
             * 宋体
             */
            Typeface songti = Typeface.createFromAsset(resources.getAssets(), "songti.ttf");
            fp.setFont(true, false, false, false, 30, songti);
            // 设置字体
            cp.setFontProperty(fp);
            cp.drawText(160, 80, "宋体展示");
            /**
             * 黑体
             */
            Typeface heiti = Typeface.createFromAsset(resources.getAssets(), "heiti.ttf");
            fp.setFont(true, false, false, false, 30, heiti);
            // 设置字体
            cp.setFontProperty(fp);
            cp.drawText(160, 120, "黑体展示");
            cp.drawLine(0, 160, 384, 160);
        }

        // 将画布保存成图片并进行打印
        mPrinter.printImage(cp.getCanvasImage(), PAlign.NONE, 0, false);
        byte[] data = new byte[]{0x0d, 0x0a, 0x0d, 0x0a, 0x0d, 0x0a};
        mPrinter.sendBytesData(data);
        mPrinter.sendBytesData(data);
    }

    public static void pageModePrinting(CanvasDrawPrint mCanvasDrawPrint, PrinterInstance mPrinter, Context mContext) {

        // 初始化画布宽高
        mCanvasDrawPrint.SPRTSetPageMode(500, 800);
        mCanvasDrawPrint.setTextAlignRight(true);//设置对其方式
        mCanvasDrawPrint.setUseSplit(true); // 页面上文本超出后换行是否使用分隔字符串
        // 绘制字体
        mCanvasDrawPrint.SPRTPrintText(0, 0, null, 60, true, true, 0.5f, mContext.getString(R.string.canvas_text_demo), mContext);
        // mCanvasDrawPrint.SPRTPrintText(0, mCanvasDrawPrint.getLength(), "kaiti.ttf", 60, false, false, 0, "楷体文字", mContext);
        //绘制直线
        mCanvasDrawPrint.SPRTPrintLine(0, mCanvasDrawPrint.getLength(), 450, mCanvasDrawPrint.getLength(), 10);
        //设置画笔样式
        mCanvasDrawPrint.setPaintStyle(Paint.Style.STROKE);
        //绘制专业PDF417
        mCanvasDrawPrint.SPRTPrintPDFCode(0, mCanvasDrawPrint.getLength(), 500, 500, 23, 8, 3, "123456789");
        //绘制专业QRCode
        mCanvasDrawPrint.SPRTPrintQRCode(0, mCanvasDrawPrint.getLength(), 200, 200, 10, 10, 4, "123456");

        // 绘制一维码
        mCanvasDrawPrint.SPRTPrintCode(BarcodeCreater.CODE_128, 0, mCanvasDrawPrint.getLength(), 300, 200, true, "123456");

        //将画布保存成图片并进行打印
        mPrinter.printImage(mCanvasDrawPrint.getCanvasImage(), PAlign.NONE, 0, false);
        byte[] data = new byte[]{0x0d, 0x0a, 0x0d, 0x0a, 0x0d, 0x0a};
        mPrinter.sendBytesData(data);
        mPrinter.sendBytesData(data);
    }

    /**
     * 把文本直接画成图形并发送给打印机（基于 CanvasDrawPrint）
     * @param mPrinter   已初始化的 PrinterInstance
     * @param text       需要打印的文本（可包含 \n 换行）
     * @param scaleX     横向放大倍数 1.0=原始 2.0=两倍宽 …
     * @param scaleY     纵向放大倍数 1.0=原始 2.0=两倍高 …
     */
    public static void printTextAsImageDirect(PrinterInstance mPrinter,
                                              String text,
                                              float scaleX,
                                              float scaleY) {

        if (mPrinter == null || text == null || "".equals(text)) return;

        /* 1. 计算单行行高（后面用来累加总高） */
        Paint tmpPaint = new Paint();
        tmpPaint.setTextSize(24);          // 基础字号，可随意调
        tmpPaint.setAntiAlias(true);
        Paint.FontMetrics fm = tmpPaint.getFontMetrics();
        int lineH = (int) Math.ceil(fm.bottom - fm.top);
        int lineHeight = (int) (lineH * scaleY);

        /* 2. 把文本按 \n 拆成多行，计算最大宽度与总高 */
        String[] lines = text.split("\n");
        int maxW = 0;
        for (String line : lines) {
            maxW = Math.max(maxW, (int) tmpPaint.measureText(line));
        }
        int bmpW = (int) (maxW * scaleX) + 20;   // 左右各留 10 px
        int bmpH = lineHeight * lines.length + 20; // 上下各留 10 px

        /* 3. 用 CanvasDrawPrint 生成画布 */
        CanvasDrawPrint cd = new CanvasDrawPrint();
        cd.SPRTSetPageMode(bmpW, bmpH);   // 初始化画布

        /* 4. 设置画笔：字号 + 横向放大（TextScaleX） */
        Paint paint = new Paint();
        paint.setColor(0xFF000000);
        paint.setTextSize(24);
        paint.setAntiAlias(true);
        paint.setTextScaleX(scaleX);      // 横向放大
        float baseY = 10 - fm.top;        // 首行 baseline

        Canvas canvas = new Canvas(cd.getCanvasImage());
        for (String line : lines) {
            canvas.drawText(line, 10, baseY, paint);
            baseY += lineHeight;
        }

        /* 5. 把画布直接发给打印机 */
        mPrinter.printImage(cd.getCanvasImage(), PAlign.NONE, 0, false);

        /* 6. 走纸两行，避免下一张内容重叠 */
        byte[] feed = {0x0d, 0x0a, 0x0d, 0x0a};
        mPrinter.sendBytesData(feed);
    }

    /**
     * 仿 pageModePrintingWW 风格：文本 → StaticLayout → CanvasDrawPrint → Bitmap
     * 解决“字体过粗 / 右边截断 / 底部截断”问题
     *
     * @param text   待打印文本，可含 \n
     * @param scaleX 横向放大倍数（1.0 原始）
     * @param scaleY 纵向放大倍数（1.0 原始）
     * @return 白底黑字、不截断的 Bitmap
     */
    public static Bitmap textToBitmap(String text,
                                      float scaleX,
                                      float scaleY) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
            if (text == null || text.isEmpty()) return null;
        }

        /* ---------- 1. 基础 TextPaint（先算尺寸） ---------- */
        TextPaint basePaint = new TextPaint();
        basePaint.setColor(Color.BLACK);
        basePaint.setTextSize(24);          // 基础字号
        basePaint.setAntiAlias(true);
        basePaint.setTextScaleX(scaleX);    // 倍宽

        /* ---------- 2. 按 576 px 宽（80 mm 纸）算所需高度 ---------- */
        int pageWidth = PrinterConstants.paperWidth;                // 与 pageModePrintingWW 保持一致
        int padding = 10;
        int layoutWidth = pageWidth - padding * 2;

        StaticLayout layout = new StaticLayout(
                text, basePaint, layoutWidth,
                Layout.Alignment.ALIGN_NORMAL,
                1.0f, 0.0f, false);

        int needHeight = layout.getHeight() + padding * 2;   // 总高

        /* ---------- 3. CanvasDrawPrint 一次性建画布 ---------- */
        CanvasDrawPrint cd = new CanvasDrawPrint();
        cd.SPRTSetPageMode(pageWidth, needHeight);   // 刚好够用，不浪费

        /* ---------- 4. 真正画图的 TextPaint（倍高用 canvas.scale） ---------- */
        TextPaint drawPaint = new TextPaint(basePaint);
        drawPaint.setTextSize(24 * scaleY);   // 字号放大=倍高

        Canvas canvas = new Canvas(cd.getCanvasImage());
        canvas.drawColor(Color.WHITE);
        canvas.save();
        canvas.translate(padding, padding);   // 留边
        canvas.scale(1.0f, scaleY);         // 仅纵向放大
        layout.draw(canvas);                // StaticLayout 自动换行、不截断
        canvas.restore();

        /* ---------- 5. 只返回 Bitmap ---------- */
        return cd.getCanvasImage();
    }
    public static Bitmap pageModePrintingWW(CanvasDrawPrint mCanvasDrawPrint, PrinterInstance mPrinter, Context mContext, Resources resources) {
        // 初始化画布宽高
        mCanvasDrawPrint.SPRTSetPageMode(576, 800);

//        String[][] tableData = {
//                {"列1", "列2", "列3", "列4", "列5"},
//                {resources.getString(R.string.bags), "10.00", "1", "10.00", "10.00"},
//                {resources.getString(R.string.hook), "5.00", "2", "10.00"},
//                {resources.getString(R.string.umbrella), "5.00", "3", "15.00", "10.00"},
//                {"数阿打发斯蒂芬据1", "数去玩儿去玩儿清热据2", "数据00000000000234\n2323523532453245235432450000000003", "列4", "10.00"},
//                {"更多数据阿斯蒂芬撒旦法\n时代发生大发1", "更多数据29999999999", "更多数据3", "列4", "10.00"},
//                {"测试空数据实时换行\n时代发生大发1", "测试空数据"},
//                {"پۇل سوممىسى", "بىرلىك باھا", "سان", "مال", "列5"},
//                {"最后一行更多数据阿斯蒂芬撒旦法时代发生大发1", "更多数据29999999999", "更多数据3", "列4", "10.00"}
//        };
//        String[][] tableData = {
//                {"列1", "列2", "列3", "列4"},
//                {"数阿打发斯蒂芬据1", "数去玩儿去玩儿清热据2", "数据000000000002342323523532453245235432450000000003", "列4"},
//                {"更多数据阿斯蒂芬撒旦法时代发生大发1", "更多数据29999999999", "更多数据3", "列4"},
//                {" پۇل سوممىسى", "بىرلىك باھا", "سان", "مال"},
//                {"更多数据阿斯蒂芬撒旦法时代发生大发1", "更多数据29999999999", "更多数据3", "列4"}
//        };
        String[][] tableData = {
                {"中国工商银行" +
                        "INDUSTRIAL AND COMMERCIAL BANK OF CHINA" +
                        "生僻字繁体字测试:囡尒峣,繁體字，㧟㩳㧐，𫄸𬟁" +
                        "数字测试：1234567890dsss" +
                        "汉字测试：日目晶金鑫樊张刘王赵" +
                        "符号测试1：.,;:&\"'|~!@#$%^&*()[]{}<>?" +
                        "符号测试2：。，；：|~！@#￥%……&*（）-+=【】{}“”‘’《》？" +
                        "维文测试:：ئالاقە يولىدا كاشىلا كۆرۈلدى"}
        };
        // 初始化画布宽高
        mCanvasDrawPrint.SPRTSetPageMode(576, 800);

        // 表格数据

        int rowPadding = 10; // 行间距
        int columnPadding = 5; // 列间距

        // 列宽数组，确保总宽度适应页面宽度
        int[] columnWidths = {500};
//        int[] columnWidths = {100, 120, 200, 80};

        // 对齐方式
        Layout.Alignment[] alignments = {
                Layout.Alignment.ALIGN_NORMAL,  // 列1: 左对齐
                Layout.Alignment.ALIGN_CENTER,  // 列2: 居中对齐
                Layout.Alignment.ALIGN_NORMAL,  // 列3: 左对齐
                Layout.Alignment.ALIGN_OPPOSITE  // 列4: 右对齐
        };

        // 创建表格位图
        Bitmap tableBitmap = createDynamicTableContentBitmap(mCanvasDrawPrint, tableData,
                rowPadding, columnPadding, columnWidths, alignments, DOUBLE_WIDTH_PAINT);
//        Bitmap tableBitmap = createDynamicTableContentBitmap(mCanvasDrawPrint, tableData, DEFAULT_TEXT_SIZE,
//                rowPadding, columnPadding, columnWidths, alignments, DEFAULT_PAINT);
        return tableBitmap;
    }

    private static final int DEFAULT_TEXT_SIZE = 20;


    private static final TextPaint DEFAULT_PAINT;
    private static final TextPaint BOLD_PAINT;
    private static final TextPaint ITALIC_PAINT;
    private static final TextPaint DOUBLE_WIDTH_PAINT;
    private static final float DOUBLE_HEIGHT = 2.0f;//设置倍高
    private static final float DOUBLE_WIDTH = 1.0f;//设置倍宽

    static {
        // 初始化默认字体样式
        DEFAULT_PAINT = new TextPaint();
        DEFAULT_PAINT.setColor(Color.BLACK); // 设置文本颜色为黑色
        DEFAULT_PAINT.setTextSize(DEFAULT_TEXT_SIZE); // 设置文本大小
        DEFAULT_PAINT.setTypeface(Typeface.DEFAULT); // 设置默认字体

        // 初始化加粗字体样式
        BOLD_PAINT = new TextPaint(DEFAULT_PAINT);
        BOLD_PAINT.setTypeface(Typeface.DEFAULT_BOLD); // 设置字体为加粗

        // 初始化斜体字体样式
        ITALIC_PAINT = new TextPaint(DEFAULT_PAINT);
        ITALIC_PAINT.setTypeface(Typeface.create(DEFAULT_PAINT.getTypeface(), Typeface.ITALIC)); // 设置字体为斜体
        // 初始化倍宽字体样式
        DOUBLE_WIDTH_PAINT = new TextPaint(DEFAULT_PAINT);
        DOUBLE_WIDTH_PAINT.setTextScaleX(DOUBLE_WIDTH); // 设置字体宽度为默认的两倍
    }

    public static Bitmap createDynamicTableContentBitmap(CanvasDrawPrint mCanvasDrawPrint, String[][] tableData, int rowPadding,
                                                         int columnPadding, int[] columnWidths, Layout.Alignment[] alignments, TextPaint defaultPaint) {
        Bitmap bitmap = mCanvasDrawPrint.getCanvasImage();
        int bitmapWidth = bitmap.getWidth();
        int maxHeight = bitmap.getHeight();
        int numRows = tableData.length;
        int numCols = tableData[0].length;
        int countWidth = 0;

        // 计算总列宽
        for (int width : columnWidths) {
            countWidth += width;
        }

        // 检查并调整列宽数组的长度
        if (columnWidths.length < numCols) {
            int[] newColumnWidths = new int[numCols];
            System.arraycopy(columnWidths, 0, newColumnWidths, 0, columnWidths.length);
            int avgColWidth = bitmapWidth / numCols;
            for (int i = columnWidths.length; i < numCols; i++) {
                newColumnWidths[i] = avgColWidth;
            }
            columnWidths = newColumnWidths;
        } else if (columnWidths.length > numCols) {
            int[] newColumnWidths = new int[numCols];
            System.arraycopy(columnWidths, 0, newColumnWidths, 0, numCols);
            columnWidths = newColumnWidths;
        }

        // 检查并调整对齐方式数组的长度
        if (alignments.length < numCols) {
            Layout.Alignment[] newAlignments = new Layout.Alignment[numCols];
            System.arraycopy(alignments, 0, newAlignments, 0, alignments.length);
            for (int i = alignments.length; i < numCols; i++) {
                newAlignments[i] = Layout.Alignment.ALIGN_NORMAL;  // 默认左对齐
            }
            alignments = newAlignments;
        } else if (alignments.length > numCols) {
            Layout.Alignment[] newAlignments = new Layout.Alignment[numCols];
            System.arraycopy(alignments, 0, newAlignments, 0, numCols);
            alignments = newAlignments;
        }

        // 动态计算所需高度
        int totalHeight = rowPadding;  // 开始绘制的 Y 坐标
        for (int row = 0; row < numRows; row++) {
            int maxLineHeight = getMaxLineHeight(numCols, columnWidths, tableData[row], defaultPaint, columnPadding);
            totalHeight += maxLineHeight * DOUBLE_HEIGHT + rowPadding;
        }

        // 如果计算出的总高度超过最大高度，则使用计算出的高度
        int bitmapHeight = Math.max(totalHeight, maxHeight);
        if (bitmapHeight > maxHeight) {
            bitmap = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Bitmap.Config.ARGB_4444);
        }

        Canvas canvas = new Canvas(bitmap);
        canvas.drawColor(Color.WHITE);  // 设置背景颜色为白色

        // 绘制内容
        int y = rowPadding;  // 开始绘制的 Y 坐标
        for (int row = 0; row < numRows; row++) {
            int x = 0;  // 每行开始绘制的 X 坐标，不需要左边距
            for (int col = 0; col < numCols; col++) {
                String text = (col < tableData[row].length) ? tableData[row][col] : "";  // 检查是否超出列数

                int cellWidth = columnWidths[col] - columnPadding * 2;

                // 使用 StaticLayout 处理文本换行
                StaticLayout staticLayout = new StaticLayout(
                        text,
                        defaultPaint,
                        cellWidth,
                        alignments[col],
                        1.0f,
                        0.0f,
                        false
                );

                // 绘制文本
                canvas.save();
                canvas.scale(1, DOUBLE_HEIGHT, x + columnPadding, y); // 仅设置倍高
                canvas.translate(x + columnPadding, y);
                staticLayout.draw(canvas);
                canvas.restore();

                x += columnWidths[col];  // 移动到下一个列的起始位置
            }

            // 计算当前行的最大行高
            int maxLineHeight = getMaxLineHeight(numCols, columnWidths, tableData[row], defaultPaint, columnPadding);
            y += maxLineHeight * DOUBLE_HEIGHT + rowPadding;  // 移动到下一行的起始位置
        }
        return bitmap;
    }

    private static int getMaxLineHeight(int numCols, int[] colWidths, String[] rowData, TextPaint paint, int columnPadding) {
        int maxLineHeight = 0;
        for (int col = 0; col < numCols; col++) {
            String text = (col < rowData.length) ? rowData[col] : "";  // 检查是否超出列数
            int cellWidth = colWidths[col] - columnPadding * 2;
            StaticLayout staticLayout = new StaticLayout(
                    text,
                    paint,
                    cellWidth,
                    Layout.Alignment.ALIGN_NORMAL,
                    1.0f,
                    0.0f,
                    false
            );
            maxLineHeight = Math.max(maxLineHeight, staticLayout.getHeight());
        }
        return maxLineHeight;
    }

    public float calculateTotalTextHeight(String[] lines, int fontSize, Context mContext) {
        Paint paint = new Paint();
        paint.setTextSize(fontSize);
        Paint.FontMetrics fontMetrics = paint.getFontMetrics();
        float lineHeight = fontMetrics.bottom - fontMetrics.top; // 每行的高度

        // 计算总高度
        return lineHeight * lines.length;
    }

    public static void logMultilineText(String tag, String text) {
        // 使用 \n 分隔每行
        String[] lines = text.split("\n");

        for (String line : lines) {
            Log.d(tag, line); // 每行作为单独的日志条目
        }
    }


    public static Table getTableWW(Resources resources, PrinterInstance mPrinter) {

        String column = "مال; سان; بىرلىك باھا; پۇل سوممىسى";
        Table table = null;
        if (PrinterConstants.paperWidth == 384) {
            table = new Table(column, ";", new int[]{14, 6, 6, 6});
        } else if (PrinterConstants.paperWidth == 576) {
            table = new Table(column, ";", new int[]{18, 10, 10, 12});
        } else if (PrinterConstants.paperWidth == 724) {
            table = new Table(column, ";", new int[]{22, 14, 14, 18});
        }
        table.addRow("" + resources.getString(R.string.bags) + ";10.00;1;10.00");
        table.addRow("" + resources.getString(R.string.hook) + ";5.00;2;10.00");
        table.addRow("" + resources.getString(R.string.umbrella) + ";5.00;3;15.00");
        return table;
    }

    /**
     * 生成二维码图片
     *
     * @param str    内容
     * @param param1 宽度
     * @param param2 高度
     * @return
     */
    public static Bitmap createBitmap(String str, int param1, int param2, int type) {
        try {
            // BitMatrix matrix = new
            // MultiFormatWriter().encode(str,BarcodeFormat.PDF417, param1,
            // param2);
            // BitMatrix matrix = new
            // MultiFormatWriter().encode(str,BarcodeFormat.QR_CODE, param1,
            // param2);
            // new MultiFormatWriter().en
            Hashtable<EncodeHintType, Object> hint = new Hashtable<EncodeHintType, Object>();
            if (type == 0) {
                hint.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
            } else if (type == 1) {
                hint.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
            } else if (type == 2) {
                hint.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.Q);
            } else {
                hint.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            }
            BitMatrix matrix = new MultiFormatWriter().encode(str, BarcodeFormat.QR_CODE, param1, param1, hint);
            int width = param1;
            // int width = matrix.width;
            int height = param2;
            // int height = matrix.height;
            int[] pixels = new int[width * height];
            for (int y = 0; y < width; ++y) {
                for (int x = 0; x < height; ++x) {
                    if (matrix.get(x, y)) {
                        pixels[y * width + x] = 0xff000000; // black pixel
                    } else {
                        pixels[y * width + x] = 0xffffffff; // white pixel
                    }
                }
            }
            Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            bmp.setPixels(pixels, 0, width, 0, 0, width, height);
            Log.i(TAG, "createBitmap-width:" + bmp.getWidth());
            Log.i(TAG, "createBitmap-height:" + bmp.getHeight());
            return bmp;
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 生成QR_CODE类型二维码图片
     *
     * @param str    内容
     * @param param1 宽度
     * @param param2 高度
     * @return
     */
    public static Bitmap createBitmapQR_CODE(String str, int param1, int param2) {
        try {
            BitMatrix matrix = new MultiFormatWriter().encode(str, BarcodeFormat.QR_CODE, param1, param2);
            int width = matrix.getWidth();
            int height = matrix.getWidth();
            int[] pixels = new int[width * height];
            for (int y = 0; y < height; ++y) {
                for (int x = 0; x < width; ++x) {
                    if (matrix.get(x, y)) {
                        pixels[y * width + x] = 0xff000000; // black pixel
                    } else {
                        pixels[y * width + x] = 0xffffffff; // white pixel
                    }
                }
            }
            Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            bmp.setPixels(pixels, 0, width, 0, 0, width, height);
            Log.i(TAG, "createBitmapCODE39-width:" + bmp.getWidth());
            Log.i(TAG, "createBitmapCODE39-height:" + bmp.getHeight());
            return bmp;
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return null;
    }

}
