package com.printer.demo.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;

import com.printer.demo.R;
import com.printer.demo.bean.AlignedTable;
import com.printer.sdk.PrinterConstants;
import com.printer.sdk.PrinterConstants.Command;
import com.printer.sdk.PrinterInstance;
import com.printer.sdk.Table;


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Arrays;
import java.util.Enumeration;

@SuppressLint("DefaultLocale")
public class XTUtils {

    private static final String TAG = "XUtils";

    public static byte[] string2bytes(String content) {

        Log.i(TAG, "" + content);
        try {
            content = new String(content.getBytes("gbk"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        char[] charArray = content.toCharArray();
        byte[] tempByte = new byte[512];
        tempByte[0] = 0x34;
        int count = 0;
        for (int i = 0; i < charArray.length; i++) {

            if (charArray[i] == 'x' || charArray[i] == 'X') {

                tempByte[count++] = (byte) (char2Int(charArray[i + 1]) * 16 + char2Int(charArray[i + 2]));
            }

        }
        Log.i(TAG, "---------------");
        byte[] retByte = new byte[count];
        System.arraycopy(tempByte, 0, retByte, 0, count);
        for (int i = 0; i < retByte.length; i++) {
            Log.i(TAG, retByte[i] + "");
        }

        return tempByte;
    }

    private static int char2Int(char data) {
        if (data >= 48 && data <= 57)// 0~9
            data -= 48;
        else if (data >= 65 && data <= 70)// A~F
            data -= 55;
        else if (data >= 97 && data <= 102)// a~f
            data -= 87;
        return Integer.valueOf(data);
    }

    /**
     * @param
     * @return String
     * @Description: TODO
     */
    public static String bytesToHexString(byte[] src, int datalength) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < datalength; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append("0x").append(hv).append(" ");
        }
        stringBuilder.append("0x0a 0x0d");
        return stringBuilder.toString();
    }

    /**
     * 字符串转换为16进制字符串
     *
     * @param s
     * @return
     */

    public static String stringToHexString(String s) {
        String str = "";
        for (int i = 0; i < s.length(); i++) {
            int ch = (int) s.charAt(i);
            String s4 = Integer.toHexString(ch);
            str = str + s4;
        }
        return str;
    }

    /**
     * 16进制字符串转换为字符串
     *
     * @param s
     * @return
     */

    public static String hexStringToString(String s) {
        if (s == null || s.equals("")) {
            return null;
        }
        s = s.replace(" ", "");
        byte[] baKeyword = new byte[s.length() / 4];
        for (int i = 0; i < baKeyword.length; i++) {
            try {
                baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 4, i * 4 + 4).substring(2, 4), 16));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            s = new String(baKeyword, "gbk");
            new String();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return s;
    }

    public synchronized static void PrintTable(Resources resources,PrinterInstance mPrinter) {
        printTable1(resources, mPrinter); // 打印表格
    }
    public synchronized static void printNote(Resources resources, PrinterInstance mPrinter) {
        mPrinter.initPrinter();
        mPrinter.setFont(0, 0, 0, 0, 0);
        mPrinter.setPrinter(Command.ALIGN, Command.ALIGN_LEFT);
        mPrinter.printText(resources.getString(R.string.str_note));
        mPrinter.setPrinter(Command.PRINT_AND_WAKE_PAPER_BY_LINE, 2);
        StringBuffer sb = new StringBuffer();
        mPrinter.setPrinter(Command.ALIGN, Command.ALIGN_CENTER);
        mPrinter.setFont(0, 1, 1, 0, 0);
        mPrinter.printText(resources.getString(R.string.shop_company_title) + "\n");
        mPrinter.setPrinter(Command.ALIGN, Command.ALIGN_LEFT);
        // 字号使用默认
        mPrinter.setFont(0, 0, 0, 0, 0);
        sb.append(resources.getString(R.string.shop_num) + "574001\n");
        sb.append(resources.getString(R.string.shop_receipt_num) + "S00003169\n");
        sb.append(resources.getString(R.string.shop_cashier_num) + "s004_s004\n");
        sb.append(resources.getString(R.string.shop_receipt_date) + "2012-06-17\n");
        sb.append(resources.getString(R.string.shop_print_time) + "2012-06-17 13:37:24\n");
        mPrinter.printText(sb.toString()); // 打印

//        printTable1(resources, mPrinter); // 打印表格

        sb = new StringBuffer();

        if (PrinterConstants.paperWidth == 384) {
            sb.append(resources.getString(R.string.shop_goods_number) + "                    6.00\n");
            sb.append(resources.getString(R.string.shop_goods_total_price) + "                    35.00\n");
            sb.append(resources.getString(R.string.shop_payment) + "                    100.00\n");
            sb.append(resources.getString(R.string.shop_change) + "                    65.00\n");
        } else if (PrinterConstants.paperWidth == 576) {
            sb.append(resources.getString(R.string.shop_goods_number) + "                                6.00\n");
            sb.append(resources.getString(R.string.shop_goods_total_price) + "                                35.00\n");
            sb.append(resources.getString(R.string.shop_payment) + "                                100.00\n");
            sb.append(resources.getString(R.string.shop_change) + "                                65.00\n");
        } else if (PrinterConstants.paperWidth == 724) {
            sb.append(resources.getString(R.string.shop_goods_number)
                    + "                                            6.00\n");
            sb.append(resources.getString(R.string.shop_goods_total_price)
                    + "                                            35.00\n");
            sb.append(resources.getString(R.string.shop_payment)
                    + "                                            100.00\n");
            sb.append(
                    resources.getString(R.string.shop_change) + "                                            65.00\n");
        }

        sb.append(resources.getString(R.string.shop_company_name) + "\n");
        sb.append(resources.getString(R.string.shop_company_site) + "www.jiangsuxxxx.com\n");
        sb.append(resources.getString(R.string.shop_company_address) + "\n");
        sb.append(resources.getString(R.string.shop_company_tel) + "0574-12345678\n");
        sb.append(resources.getString(R.string.shop_Service_Line) + "4008-123-456 \n");

        if (PrinterConstants.paperWidth == 384) {
            sb.append("==============================\n");
        } else if (PrinterConstants.paperWidth == 576) {
            sb.append("==============================================\n");
        } else if (PrinterConstants.paperWidth == 724) {
            sb.append("================================================================\n");
        }

        mPrinter.printText(sb.toString());

        mPrinter.setPrinter(Command.ALIGN, Command.ALIGN_CENTER);
        mPrinter.setFont(0, 0, 1, 0, 0);
        mPrinter.printText(resources.getString(R.string.shop_thanks) + "\n");
        mPrinter.printText(resources.getString(R.string.shop_demo) + "\n\n\n");

        mPrinter.setFont(0, 0, 0, 0, 0);
        mPrinter.setPrinter(Command.ALIGN, Command.ALIGN_LEFT);
        mPrinter.setPrinter(Command.PRINT_AND_WAKE_PAPER_BY_LINE, 3);

    }
    public static void testLaoTable(PrinterInstance mPrinter) {

        mPrinter.setCharsetName("UTF-8");
        mPrinter.setPaperWidth(PrinterConstants.paperWidth);
//        mPrinter.setPrinter(PrinterConstants.Command.ALIGN_LEFT,);
        mPrinter.setPrinter(Command.ALIGN, Command.ALIGN_LEFT);
        // 使用匿名内部类或者 Lambda 对接你的 mPrinter
        LaoPrinterTestSuite.runAllTests(new LaoPrinterTestSuite.PrinterInterface() {
            @Override
            public void printText(String text) {
                mPrinter.printText(text);
            }
        });
        mPrinter.cutPaper(66, 50);

    }

    public static void testLaoImageTable(PrinterInstance printer) {
        // 1. 构造带老文的表格
        String header = "ລາຍການ|ຈໍານວນ|ລາຄານ້ຳດື່ນ້ຳດື່ນ້ຳດື່|ລວມນ້ຳດື່ນ້ຳດື່ນ້ຳດື່";  // 老文标题
        int[] widths = {10, 4, 4, 4};
        AlignedTable table = new AlignedTable(header, "\\|", widths, 0, 1);

        table.setColumnAlign(0, AlignedTable.Align.LEFT);
        table.setColumnAlign(1, AlignedTable.Align.CENTER);
        table.setColumnAlign(2, AlignedTable.Align.RIGHT);
        table.setColumnAlign(3, AlignedTable.Align.RIGHT);

        table.addRow("ນ້ຳດື່ນ້ຳດື່ນ້ຳດື່ນ້ຳດື່ນ້ຳດື່ມ|2|5,000|10,000ນ້ຳດື່ນ້ຳດື່ນ້ຳດື່ນ້ຳດື່");
        table.addRow("ເຂົ້ານ້ຳດື່ນ້ຳດື່ນ້ຳດື່|1|15,000|15,000");
        table.addRow("ໝີ່ນ້ຳດື່|3|6,000ນ້ຳດື່ນ້ຳດື່ນ້ຳດື່ນ້ຳດື່ນ້ຳດື່ນ້ຳດື່ນ້ຳດື່|18,000");

        // 2. 画成 Bitmap
        Bitmap bmp = Table2Bitmap.get().draw(table);

        // 3. 打印
        Bitmap otsu = ImageBinarizationUtils.binarizeImage(bmp, "otsu", 0);
        printer.printImage(otsu, PrinterConstants.PAlign.NONE, 0, false);
        printer.setPrinter(Command.PRINT_AND_WAKE_PAPER_BY_LINE, 3);
    }
    public static void printTable1(Resources resources, PrinterInstance mPrinter) {
        String column = resources.getString(R.string.note_title);
        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});
        }
        if (table != null) {
            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");
            mPrinter.printTable(table);
        }


        // 定义列标题、分隔符和每列的宽度
        String columnTitle = "Name|Age|City";
        String regularExpression = "\\|"; // 使用竖线分割列
        int[] columnWidth = {15, 5, 10}; // 每列的宽度

        // 创建 AlignedTable 对象
        AlignedTable table2 = new AlignedTable(columnTitle, regularExpression, columnWidth,0,0);

        // 设置各列的对齐方式
        table2.setColumnAlign(0, AlignedTable.Align.LEFT);   // 第 1 列左对齐
        table2.setColumnAlign(1, AlignedTable.Align.CENTER); // 第 2 列中对齐
        table2.setColumnAlign(2, AlignedTable.Align.RIGHT);  // 第 3 列右对齐

        // 添加数据行
        table2.addRow("Alice|30|New York");
        table2.addRow("Bob|25|San Francisco");
        table2.addRow("Charlie|35|Los Angeles");

        mPrinter.printText(table2.getTableText());

        // 定义列标题、分隔符和每列的宽度
        String columnTitle2 = "left:| right";
        String regularExpression2 = "\\|"; // 使用竖线分割列
        int[] columnWidth2 = {22, 22}; // 每列的宽度

        // 创建 AlignedTable 对象
        AlignedTable table3 = new AlignedTable(columnTitle2, regularExpression2, columnWidth2,1,1);
        // 设置各列的对齐方式
        table3.setColumnAlign(0, AlignedTable.Align.RIGHT);   // 第 1 列左对齐
        table3.setColumnAlign(1, AlignedTable.Align.LEFT); // 第 2 列中对齐

        // 添加数据行
        table3.addRow(resources.getString(R.string.test_align_row1));
        table3.addRow(resources.getString(R.string.test_align_row2));
        table3.addRow(resources.getString(R.string.test_align_row3));
        table3.addRow(resources.getString(R.string.test_align_row4));

        mPrinter.printText(table3.getTableText());
    }


    public static void printTableToBitmapTest(Resources resources, PrinterInstance printer) {
        // 初始化纸宽
        PrinterConstants.paperWidth = 576; // 80 mm

        // 初始化打印机
        printer.initPrinter();

        // 打印标题
        printer.setPrinter(PrinterConstants.Command.ALIGN, PrinterConstants.Command.ALIGN_CENTER);
        printer.setFont(0, 1, 1, 0, 0);
        // 替换为
        printer.printText(resources.getString(R.string.test_ticket_table_title));
        printer.setFont(0, 0, 0, 0, 0);

        // 4 列测试
//        print4ColumnsTest(printer);
        // 替换为
        print4ColumnsTest(resources, printer);

        // 3 列测试
        print3ColumnsTest(resources,printer);

        // 2 列测试
        print2ColumnsTest(resources,printer);

        // 结束
        printer.setPrinter(PrinterConstants.Command.ALIGN, PrinterConstants.Command.ALIGN_CENTER);
        // 替换为
        printer.printText(resources.getString(R.string.test_thanks));
        printer.setPrinter(PrinterConstants.Command.PRINT_AND_WAKE_PAPER_BY_LINE, 3);
    }

    private static void print4ColumnsTest(Resources resources, PrinterInstance printer) {
        printer.setPrinter(PrinterConstants.Command.ALIGN, PrinterConstants.Command.ALIGN_LEFT);
        // 替换为
        printer.printText(resources.getString(R.string.test_4_columns));

        // 普通方式设置列宽
        int[] widthsNormal = {10, 4, 4, 4};
        // 替换为
        printTable(resources, printer, resources.getString(R.string.test_normal_mode), widthsNormal, false);

        // 权重方式设置列宽
        int[] widthsWeight = ColWidthUtil.weight(PrinterConstants.paperWidth, 16, 5, 2, 2, 2);
        Log.d("TEST", "4 列权重宽度: " + Arrays.toString(widthsWeight));
        // 替换为
        printTable(resources, printer, resources.getString(R.string.test_weight_mode), widthsWeight, true);
    }

    private static void print3ColumnsTest(Resources resources, PrinterInstance printer) {
        printer.setPrinter(PrinterConstants.Command.ALIGN, PrinterConstants.Command.ALIGN_LEFT);
        // 替换为
        printer.printText(resources.getString(R.string.test_3_columns));



        // 普通方式设置列宽
        int[] widthsNormal = {10, 6, 6};
        // 替换为
        printTable(resources, printer, resources.getString(R.string.test_normal_mode), widthsNormal, false);

        // 权重方式设置列宽
        int[] widthsWeight = ColWidthUtil.weight(PrinterConstants.paperWidth, 8, 5, 2, 3);
        Log.d("TEST", "3 列权重宽度: " + Arrays.toString(widthsWeight));
        // 替换为
        printTable(resources, printer, resources.getString(R.string.test_weight_mode), widthsWeight, true);
    }

    private static void print2ColumnsTest(Resources resources, PrinterInstance printer) {
        printer.setPrinter(PrinterConstants.Command.ALIGN, PrinterConstants.Command.ALIGN_LEFT);
        // 替换为
        printer.printText(resources.getString(R.string.test_2_columns));

        // 普通方式设置列宽
        int[] widthsNormal = {16, 8};
        // 替换为
        printTable(resources, printer, resources.getString(R.string.test_normal_mode), widthsNormal, false);

        // 权重方式设置列宽
        int[] widthsWeight = ColWidthUtil.weight(PrinterConstants.paperWidth, 8, 5, 1);
        Log.d("TEST", "2 列权重宽度: " + Arrays.toString(widthsWeight));
        // 替换为
        printTable(resources, printer, resources.getString(R.string.test_weight_mode), widthsWeight, true);
    }

    private static void printTable(Resources resources, PrinterInstance printer, String type, int[] widths, boolean isWeight) {
        // 替换为
        String header = resources.getString(R.string.test_header_4col);
        AlignedTable table = new AlignedTable(header, "\\|", widths, 0, 1, isWeight);

        table.setColumnAlign(0, AlignedTable.Align.LEFT);
        table.setColumnAlign(1, AlignedTable.Align.CENTER);
        table.setColumnAlign(2, AlignedTable.Align.RIGHT);
        table.setColumnAlign(3, AlignedTable.Align.RIGHT);

        /* ---------- 超长老挝文（必换行） ---------- */
        table.addRow(resources.getString(R.string.test_row_4col_1));
        table.addRow(resources.getString(R.string.test_row_4col_2));
        table.addRow(resources.getString(R.string.test_row_4col_3));
        table.addRow(resources.getString(R.string.test_row_4col_4));

        /* ---------- 正常老挝文（不超宽） ---------- */
        table.addRow(resources.getString(R.string.test_row_4col_1));
        table.addRow(resources.getString(R.string.test_row_4col_2));
        table.addRow(resources.getString(R.string.test_row_4col_3));
        table.addRow(resources.getString(R.string.test_row_4col_4));

        /* ---------- 中老混合 ---------- */
        table.addRow(resources.getString(R.string.test_row_4col_9));
        table.addRow(resources.getString(R.string.test_row_4col_10));

        Bitmap bmp = Table2Bitmap.get().draw(table);
        Bitmap bin = ImageBinarizationUtils.binarizeImage(bmp, "otsu", 0);
        printer.printImage(bin, PrinterConstants.PAlign.NONE, 0, false);
        // 替换为
        printer.printText("-------" + type + "---- " + resources.getString(R.string.test_col_width_done));
    }
    /**
     * 老文+中文 超长混合换行测试
     * 先二值化再打印
     */
//    public static void printLaoLongNameTest(PrinterInstance printer) {
//        printer.initPrinter();
//        printer.setPrinter(Command.ALIGN, Command.ALIGN_CENTER);
//        printer.setFont(0, 1, 1, 0, 0);
//        printer.printText("老文超长换行测试\n");
//        printer.setFont(0, 0, 0, 0, 0);
//
//        /* ======== 1. 商品区（4 列） ======== */
//        String header4 = "品名|Qty|单价|小计";
//        int[] w4 = PrinterConstants.paperWidth == 384
//                ? new int[]{8, 3, 3, 3}   // 58 mm
//                : new int[]{10, 4, 4, 4}; // 80 mm
//        AlignedTable t4 = new AlignedTable(header4, "\\|", w4, 0, 1);
//        t4.setColumnAlign(0, AlignedTable.Align.LEFT);
//        t4.setColumnAlign(1, AlignedTable.Align.CENTER);
//        t4.setColumnAlign(2, AlignedTable.Align.RIGHT);
//        t4.setColumnAlign(3, AlignedTable.Align.RIGHT);
//
//        // ① 超长老文（必换行）
//        t4.addRow("ນ້ຳດື່ມປິດຝາສີຟ້າຂະໜາດ 500 ມລ ລາຍການທີ່ຍາວໆໆໆ|2|5,000|10,000");
//        // ② 超长中文
//        t4.addRow("冰鲜铁观音超大瓶矿泉水500毫升装买一瓶送一瓶活动价|1|3,500|3,500");
//        // ③ 老文+中文+数字+符号混合
//        t4.addRow("ສະບູ່ເຫຼື້ງຈີน中华皂125g【限时】|3|2,800|8,400");
//        // ④ 短的老文
//        t4.addRow("ເຂົ້າ|5|1,200|6,000");
//        // ⑤ 带空格、括号、星号
//        t4.addRow("青岛啤酒 330ml * 6罐装（易拉罐）|1|19,900|19,900");
//
//        Bitmap bmp = Table2Bitmap.get().draw(t4);
//        // 关键：先二值化再打印
//        Bitmap bin = ImageBinarizationUtils.binarizeImage(bmp, "otsu", 0);
//        printer.printImage(bin, PrinterConstants.PAlign.NONE, 0, false);
//
//        /* ======== 2. 结算区（2 列，无老文） ======== */
//        String header2 = "项目|金额";
//        int[] w2 =  new int[]{14, 8};
//        AlignedTable t2 = new AlignedTable(header2, "\\|", w2, 0, 0);
//        t2.setColumnAlign(0, AlignedTable.Align.LEFT);
//        t2.setColumnAlign(1, AlignedTable.Align.RIGHT);
//        t2.addRow("------------------------|");
//        t2.addRow("应收合计|48,800");
//        t2.addRow("会员优惠|-1,000");
//        t2.addRow("实收|50,000");
//        t2.addRow("找零|1,200");
//
//        Bitmap bmp2 = Table2Bitmap.get().draw(t2);
//        Bitmap bin2 = ImageBinarizationUtils.binarizeImage(bmp2, "otsu", 0);
//        printer.printImage(bin2, PrinterConstants.PAlign.NONE, 0, false);
//
//        /* ======== 3. 尾部（无老文） ======== */
//        printer.setPrinter(Command.ALIGN, Command.ALIGN_CENTER);
//        printer.printText("谢谢光临\n");
//        printer.printText("2025-11-18 16:00\n\n\n");
//        printer.setPrinter(Command.PRINT_AND_WAKE_PAPER_BY_LINE, 3);
//    }
    public static synchronized void printTest(Resources resources, PrinterInstance mPrinter) {

        mPrinter.initPrinter();

        mPrinter.printText(resources.getString(R.string.str_text));
        mPrinter.setPrinter(Command.PRINT_AND_WAKE_PAPER_BY_LINE, 2);

        mPrinter.setFont(0, 0, 0, 0, 0);
        mPrinter.setPrinter(Command.ALIGN, 0);
        mPrinter.printText(resources.getString(R.string.str_text_left));
        mPrinter.setPrinter(Command.PRINT_AND_WAKE_PAPER_BY_LINE, 2);// ��2��

        mPrinter.setPrinter(Command.ALIGN, 1);
        mPrinter.printText(resources.getString(R.string.str_text_center));
        mPrinter.setPrinter(Command.PRINT_AND_WAKE_PAPER_BY_LINE, 2);// ��2��

        mPrinter.setPrinter(Command.ALIGN, 2);
        mPrinter.printText(resources.getString(R.string.str_text_right));
        mPrinter.setPrinter(Command.PRINT_AND_WAKE_PAPER_BY_LINE, 3); // ��3��

        mPrinter.setPrinter(Command.ALIGN, 0);
        mPrinter.setFont(0, 0, 0, 1, 0);
        mPrinter.printText(resources.getString(R.string.str_text_strong));
        mPrinter.setPrinter(Command.PRINT_AND_WAKE_PAPER_BY_LINE, 2); // ��2��

        mPrinter.setFont(0, 0, 0, 0, 1);
        mPrinter.sendBytesData(new byte[]{(byte) 0x1C, (byte) 0x21, (byte) 0x80});
        mPrinter.printText(resources.getString(R.string.str_text_underline));
        mPrinter.sendBytesData(new byte[]{(byte) 0x1C, (byte) 0x21, (byte) 0x00});
        mPrinter.setPrinter(Command.PRINT_AND_WAKE_PAPER_BY_LINE, 2); // ��2��

        mPrinter.setFont(0, 0, 0, 0, 0);
        mPrinter.printText(resources.getString(R.string.str_text_height));
        for (int i = 0; i < 4; i++) {
            mPrinter.setFont(0, i, i, 0, 0);
            mPrinter.printText((i + 1) + resources.getString(R.string.times));

        }
        mPrinter.setPrinter(Command.PRINT_AND_WAKE_PAPER_BY_LINE, 1);
        mPrinter.setPrinter(Command.PRINT_AND_WAKE_PAPER_BY_LINE, 3);

        for (int i = 0; i < 4; i++) {

            mPrinter.setFont(0, i, i, 0, 0);
            mPrinter.printText(resources.getString(R.string.bigger) + (i + 1) + resources.getString(R.string.bigger1));
            mPrinter.setPrinter(Command.PRINT_AND_WAKE_PAPER_BY_LINE, 3);

        }

        mPrinter.setFont(0, 0, 0, 0, 0);
        mPrinter.setPrinter(Command.ALIGN, 0);
        mPrinter.setPrinter(Command.PRINT_AND_WAKE_PAPER_BY_LINE, 3);
    }

    /**
     * @param is 输入流
     * @return String 返回的字符串
     * @throws IOException
     */
    public static String readFromStream(InputStream is) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = is.read(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }
        is.close();
        String result = baos.toString();
        baos.close();
        return result;
    }

	/**
	 * 将一个字符串中的所有字母均转换为大写
	 *
	 * @param devicesAddress
	 * @return
	 */
	/**
	 * 将一个字符串中的所有字母均转换为大写
	 *
	 * @param devicesAddress
	 * @return
	 */
	public static String formatTheString(String devicesAddress) {
		StringBuffer newDevicesAddress = new StringBuffer("");
		for (int i = 0; i < devicesAddress.length(); i++) {
			String childString = "";
			char chars = devicesAddress.charAt(i);
			if(i==0||i%2!=0){
				childString+= chars;
			}else{
				childString=":"+chars;
			}
			childString = childString.toUpperCase();
			newDevicesAddress.append(childString);
		}
		String result=newDevicesAddress.toString();
		if(result.length()>17){
			return newDevicesAddress.toString().substring(0, 17);
		}
		return result;
	}
	public static boolean isLetter(String str) {
		java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("[a-zA-Z]+");
		java.util.regex.Matcher m = pattern.matcher(str);
		return m.matches();
	}

    /**
     * Android获取当前手机IP地址的两种方式
     */
    // 1
    public static String getIPAddress(Context context) {
        NetworkInfo info = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE))
                .getActiveNetworkInfo();
        if (info != null && info.isConnected()) {
            if (info.getType() == ConnectivityManager.TYPE_MOBILE) {// 当前使用2G/3G/4G网络
                try {
                    // Enumeration<NetworkInterface>
                    // en=NetworkInterface.getNetworkInterfaces();
                    for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                            .hasMoreElements(); ) {
                        NetworkInterface intf = en.nextElement();
                        for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr
                                .hasMoreElements(); ) {
                            InetAddress inetAddress = enumIpAddr.nextElement();
                            if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                                return inetAddress.getHostAddress();
                            }
                        }
                    }
                } catch (SocketException e) {
                    e.printStackTrace();
                }

            } else if (info.getType() == ConnectivityManager.TYPE_WIFI) {// 当前使用无线网络
                WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                String ipAddress = intIP2StringIP(wifiInfo.getIpAddress());// 得到IPV4地址
                return ipAddress;
            }
        } else {
            // 当前无网络连接,请在设置中打开网络
            WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            wifiManager.setWifiEnabled(true);
        }
        return null;
    }

    /**
     * 将得到的int类型的IP转换为String类型
     *
     * @param ip
     * @return
     */
    public static String intIP2StringIP(int ip) {
        return (ip & 0xFF) + "." + ((ip >> 8) & 0xFF) + "." + ((ip >> 16) & 0xFF) + "." + (ip >> 24 & 0xFF);
    }

    // 2
    public String getLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
            Log.e("WifiPreference IpAddress", ex.toString());
        }
        return null;
    }

    /**
     * @param
     * @return String
     * @Description: TODO
     */
    public static String bytesToHexString2(byte[] src, int datalength) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < datalength; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        if (!stringBuilder.toString().endsWith("0a0d")) {
            stringBuilder.append("0a0d");
        }
        return stringBuilder.toString();
    }

    /**
     * 16进制字符串转换为字符串
     *
     * @param s
     * @return
     */

    public static String hexStringToString2(String s) {
        if (s == null || s.equals("")) {
            return null;
        }
        s = s.replace(" ", "");
        byte[] baKeyword = new byte[s.length() / 2];
        for (int i = 0; i < baKeyword.length; i++) {
            try {
                baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2).substring(0, 2), 16));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            s = new String(baKeyword, "gbk");
            new String();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return s;
    }

    public static byte[] string2bytes2(String content) {

        Log.i(TAG, "" + content);
        try {
            content = new String(content.getBytes("gbk")).trim();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        char[] charArray = content.toCharArray();
        byte[] tempByte = new byte[512];
        tempByte[0] = 0x34;
        int count = 0;
        for (int i = 0; i < charArray.length; i = i + 2) {
            tempByte[count++] = (byte) (char2Int(charArray[i]) * 16 + char2Int(charArray[i + 1]));
        }
        Log.i(TAG, "---------------");

		byte[] retByte = new byte[count];
		System.arraycopy(tempByte, 0, retByte, 0, count);
		for (int i = 0; i < retByte.length; i++) {
			Log.i(TAG, retByte[i] + "");
		}
		return tempByte;
	}

    public static byte[] readFile(File file) {
        if (!file.isFile()) return null;

        FileInputStream fis = null;
        ByteArrayOutputStream os = null;
        try {
            fis = new FileInputStream(file);
            os = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
            // 关键一句：用 GBK 解码再编码
            String gbkStr = new String(os.toByteArray(), "GBK");
            return gbkStr.getBytes("GBK");
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (os != null) os.close();
                if (fis != null) fis.close();
            } catch (IOException ignore) {}
        }
    }

	public static String readStringFromFile(File file) {
		// 需要读取的文件，参数是文件的路径名加文件名
		if (file.isFile()) {
			// 以字节流方法读取文件

			FileInputStream fis = null;
			ByteArrayOutputStream outputStream=null;
			String str = null;

			try {
				fis = new FileInputStream(file);
				// 设置一个，每次 装载信息的容器
				byte[] buffer = new byte[1024];
				outputStream = new ByteArrayOutputStream();
				// 开始读取数据
				int len = 0;// 每次读取到的数据的长度
				while ((len = fis.read(buffer)) != -1) {// len值为-1时，表示没有数据了
					// append方法往sb对象里面添加数据
					outputStream.write(buffer, 0, len);
				}
				str = new String(outputStream.toByteArray(), "gbk");
				// 输出字符串
				return str;
			} catch (IOException e) {
				e.printStackTrace();
			}finally {
				try {
					outputStream.close();
					outputStream=null;
					fis.close();
					fis=null;
				} catch (IOException e) {
					e.printStackTrace();
				}

			}
		} else {
			return null;
		}
		return null;
	}
}
