package com.printer.demo;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.printer.demo.global.GlobalContants;
import com.printer.demo.utils.BitmapSaver;
import com.printer.demo.utils.CanvasUtils;
import com.printer.demo.utils.ImageBinarizationUtils;
import com.printer.demo.utils.PrefUtils;
import com.printer.demo.utils.PrinterBlockSender;
import com.printer.demo.utils.TimeTracker;
import com.printer.sdk.CanvasDrawPrint;
import com.printer.sdk.PrinterConstants;
import com.printer.sdk.PrinterConstants.Command;
import com.printer.sdk.PrinterConstants.PAlign;
import com.printer.sdk.PrinterInstance;
import com.printer.sdk.Table;
import com.printer.sdk.monochrome.BitmapConvertor;
import com.printer.sdk.utils.Utils;
import com.printer.sdk.utils.XLog;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import androidx.core.content.FileProvider;

/**
 *
 * @Description 处理图片打印相关
 */
public class PicturePrintActivity extends BaseActivity implements OnClickListener, OnItemSelectedListener {
    private Context mContext;
    private boolean is58mm = false;
    private boolean isStylus = false;
    private Button btn_photo_print, btn_select_photo, btn_canvas_print, btn_monochrome_print, btn_page_mode_printingt,
            btn_page_mode_printingt2, btn_text_to_bitmap_printingt, btn_print_bitmap_space;
    private ImageView iv_Original_picture;
    private ImageView iv_monochrome_picture;
    private LinearLayout header;
    private final static int IMAGE_CAPTURE_FROM_CAMERA = 1;
    private final static int IMAGE_CAPTURE_FROM_GALLERY = 2;
    private static final String TAG = "PicturePrintActivity";
    private BitmapConvertor convertor;
    private WindowManager wm;
    private ProgressDialog mPd;
    private String remp_dir = null;
    private static PrinterInstance mPrinter;
    private CanvasDrawPrint mCanvasDrawPrint;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(R.layout.activity_print_picture);
        init();
        Log.e(TAG, "onCreate");
        // if (savedInstanceState != null) {
        // remp_dir = savedInstanceState.getString("remp_dir");
        // // System.out.println("onCreate: temp = " + remp_dir);
        // Log.e(TAG, "remp_dir:"+remp_dir);
        // }
        mPrinter = PrinterInstance.mPrinter;
        remp_dir = getFilePath();
    }


    @Override
    protected void onResume() {
        super.onResume();
        Log.e(TAG, "onResume");
        // if (GlobalContants.ISCONNECTED) {
        // if ("".equals(GlobalContants.DEVICENAME)
        // || GlobalContants.DEVICENAME == null) {
        // headerConnecedState.setText(R.string.unknown_device);
        //
        // } else {
        //
        // headerConnecedState.setText(GlobalContants.DEVICENAME);
        // }
        //
        // }

    }

    private void init() {

        header = (LinearLayout) findViewById(R.id.ll_header_picture);
        btn_photo_print = (Button) findViewById(R.id.btn_photo_print);
        btn_photo_print.setOnClickListener(this);
        btn_print_bitmap_space = (Button) findViewById(R.id.btn_print_bitmap_space);
        btn_print_bitmap_space.setOnClickListener(this);
        btn_monochrome_print = (Button) findViewById(R.id.btn_monochrome_print);
        btn_text_to_bitmap_printingt = (Button) findViewById(R.id.btn_text_to_bitmap_printingt);
        btn_text_to_bitmap_printingt.setOnClickListener(this);
        btn_monochrome_print.setOnClickListener(this);
        btn_page_mode_printingt = (Button) findViewById(R.id.btn_page_mode_printingt);
        btn_page_mode_printingt2 = (Button) findViewById(R.id.btn_page_mode_printingt2);
        btn_page_mode_printingt.setOnClickListener(this);
        btn_page_mode_printingt2.setOnClickListener(this);
        btn_select_photo = (Button) findViewById(R.id.btn_select_photo);
        btn_select_photo.setOnClickListener(this);
        btn_canvas_print = (Button) findViewById(R.id.btn_canvas_print);
        btn_canvas_print.setOnClickListener(this);
        // iv_Original_picture = (ImageView)
        // findViewById(R.id.iv_Original_picture);
        iv_monochrome_picture = (ImageView) findViewById(R.id.iv_monochrome_picture);

        if (mCanvasDrawPrint == null) {
            mCanvasDrawPrint = new CanvasDrawPrint();
        }
        ;
        mCanvasDrawPrint.setCanvasDrawBack(mCanvasDrawBack);
        //自定义数据
//        iv_monochrome_picture.setImageBitmap(new CanvasUtils().pageModePrintingWW(mCanvasDrawPrint, PrinterInstance.mPrinter, mContext, getResources()));
        initHeader(header);
        convertor = new BitmapConvertor(this);
        wm = this.getWindowManager();
    }

    /**
     * 初始化标题上的信息
     */
    private void initHeader(LinearLayout header) {
        setHeaderLeftText(header, getString(R.string.back), new OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();

            }
        });
        headerConnecedState.setText(getTitleState());
        setHeaderLeftImage(header, new OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });
        setHeaderCenterText(header, getString(R.string.headview_PicturePrint));

    }

    @Override
    public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
        // TODO Auto-generated method stub

    }

    // 查询缓冲区是否可接收
    private static final byte[] CMD_QUERY_SPACE = {0x10, 0x04, 0x01};

    @Override
    public void onClick(View view) {

        if (mPrinter == null || !SettingActivity.isConnected) {
            Toast.makeText(mContext, getString(R.string.no_connected), 0).show();
            return;
        }
        if (view == btn_monochrome_print) {
            new Thread(new Runnable() {
                public void run() {

                    mPrinter.printText(getString(R.string.text_print_mono_bitmap));
                    mPrinter.setPrinter(Command.PRINT_AND_WAKE_PAPER_BY_LINE, 1);
                    Bitmap bitmap1 = BitmapFactory.decodeResource(getResources(), R.drawable.my_monochrome_image);
                    if (bitmap1.getWidth() > PrinterConstants.paperWidth) {
                        bitmap1 = Utils.zoomImage(bitmap1, PrinterConstants.paperWidth, PrefUtils.getInt(mContext, GlobalContants.PRINTERTYPE, 0));
                    }
                    mPrinter.printImage(bitmap1, PAlign.NONE, 0, 128);
                    byte[] data = new byte[]{0x0d, 0x0a, 0x0d, 0x0a, 0x0d, 0x0a};
                    mPrinter.sendBytesData(data);
                    mPrinter.sendBytesData(data);
                }
            }).start();

        } else if (view == btn_photo_print) {
            remp_dir = getFilePath();
            // 拍照我们用Action为MediaStroe.ACTION_IMAGE_CAPTURE,
            // 有些人使用其他的Action但我发现在有些机子中会出问题，所以优先选择这个
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                //设置7.0中共享文件，分享路径定义在xml/provider_pathsaths.xml
                intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                Uri contentUri = FileProvider.getUriForFile(this,
                        BuildConfig.APPLICATION_ID + ".fileProvider", new File(remp_dir));
                intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);
            } else {
                intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(remp_dir)));
            }

            startActivityForResult(intent, IMAGE_CAPTURE_FROM_CAMERA);

        } else if (view == btn_select_photo) {
            // 拍照我们用Action为Intent.ACTION_GET_CONTENT,
            // 有些人使用其他的Action但我发现在有些机子中会出问题，所以优先选择这个
            Intent intent2 = new Intent();
            intent2.setType("image/*");
            intent2.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(intent2, IMAGE_CAPTURE_FROM_GALLERY);

        } else if (view == btn_canvas_print) {
            if (mPrinter == null) {
                Log.i(TAG, "mPrinter为空");
            } else {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        new CanvasUtils().printCustomImage2(mContext.getResources(), PrinterInstance.mPrinter);
                    }
                }).start();

            }
        } else if (view == btn_text_to_bitmap_printingt) {
            if (mPrinter == null) {
                Log.i(TAG, "mPrinter为空");
            } else {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        CanvasUtils canvasUtils = new CanvasUtils();
                        Bitmap bitmap = canvasUtils.textToBitmap("问候与自我介绍\n" +
                                "老挝文：ສະບາຍດີ ຂ້ອຍເປັນຄົນຈີນ\n" +
                                "中文：你好，我是中国人。\n" +
                                "发音提示：萨百迪（你好），快奔昆金（我是中国人）\n" +
                                "。\n" +
                                "2. 日常询问\n" +
                                "老挝文：ເຈົ້າຊື່ຫຍັງ? ລາຄາເທົ່າໃດ?\n" +
                                "中文：你叫什么名字？多少钱？\n" +
                                "发音提示：娇斯娘（你叫什么名字）\n" +
                                "；拉卡涛贷（多少钱）\n" +
                                "。\n" +
                                "3. 表达感谢与道别\n" +
                                "老挝文：ຂອບໃຈ ແລ້ວເຈິກັນໃໝ່!\n" +
                                "中文：谢谢，再见！\n" +
                                "发音提示：阔仔（谢谢），了结根迈（再见）\n" +
                                "。\n" +
                                "4. 简单对话组合\n" +
                                "老挝文：ມື້ນີ້ ເຈົ້າສະບາຍດີບໍ? ຂ້ອຍດີຫລາຍ.\n" +
                                "中文：今天过得好吗？我很好。\n" +
                                "发音提示：暮利照萨百迪波（今天好吗）？快迪来（我很好）\n" +
                                "。\n" +
                                "5. 常用短句合集\n" +
                                "老挝文：ໂຊກດີ! ເຮັດໄດ້ດີຫລາຍ! ຂ້ອຍເຫັນນຳ.\n" +
                                "中文：祝你好运！干得漂亮！我同意。\n" +
                                "发音提示：索迪（好运），黑呆迪来（干得好），快恨南（我同意)", 1.5f, 1);
//                        mPrinter.printImage(bitmap, PAlign.NONE, 0, false);
                        Bitmap otsu = ImageBinarizationUtils.binarizeImage(bitmap, "otsu", 0);
//						BitmapSaver.saveBitmap(otsu, "otsu.png", mContext);
//                        Bitmap otsu = ImageBinarizationUtils.binarizeImage(bitmap, "otsu", 0);
//                        Bitmap floyd = ImageBinarizationUtils.binarizeImage(bitmap, "floyd", 0);
                        mPrinter.printImage(otsu, PAlign.START, 0, false);

                    }
                }).start();

            }
        } else if (view == btn_page_mode_printingt) {
            if (mPrinter == null) {
                Log.i(TAG, "mPrinter为空");
            } else {
                // 创建画布

                if (mCanvasDrawPrint == null) {
                    mCanvasDrawPrint = new CanvasDrawPrint();
                }
                ;
                mCanvasDrawPrint.setCanvasDrawBack(mCanvasDrawBack);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Bitmap bitmap = new CanvasUtils().pageModePrintingWW(mCanvasDrawPrint, PrinterInstance.mPrinter, mContext, getResources());
//                        Bitmap otsu = ImageBinarizationUtils.binarizeImage(bitmap, "otsu", 0);
//                        Bitmap otsu = ImageBinarizationUtils.binarizeImage(bitmap, "otsu", 0);
//                        Bitmap floyd = ImageBinarizationUtils.binarizeImage(bitmap, "floyd", 0);
//                        mPrinter.printImage(otsu, PAlign.START, 0,false);

                        mPrinter.printImage(bitmap, PAlign.NONE, 0, false);

//                        mPrinter.printImage(monoChromeBitmap, PAlign.NONE, 0, 128);

//                        new CanvasUtils().pageModePrinting(mCanvasDrawPrint, PrinterInstance.mPrinter, mContext);
                    }
                }).start();

            }
        } else if (view == btn_page_mode_printingt2) {
            if (mPrinter == null) {
                Log.i(TAG, "mPrinter为空");
            } else {
                // 创建画布

                if (mCanvasDrawPrint == null) {
                    mCanvasDrawPrint = new CanvasDrawPrint();
                }
                ;
                mCanvasDrawPrint.setCanvasDrawBack(mCanvasDrawBack);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
//                        new CanvasUtils().pageModePrinting(mCanvasDrawPrint, PrinterInstance.mPrinter, mContext);
                        Bitmap bitmap = new CanvasUtils().pageModePrintingWW(mCanvasDrawPrint, PrinterInstance.mPrinter, mContext, getResources());
                        //这里是测试用的 如果想尝试大津法二值化  用选择相册
                        Bitmap otsu = ImageBinarizationUtils.binarizeImage(bitmap, "otsu", 0);
//						BitmapSaver.saveBitmap(otsu, "otsu.png", mContext);
//                        Bitmap otsu = ImageBinarizationUtils.binarizeImage(bitmap, "otsu", 0);
//                        Bitmap floyd = ImageBinarizationUtils.binarizeImage(bitmap, "floyd", 0);
                        mPrinter.printImage(otsu, PAlign.START, 0, false);

//                        mPrinter.printImage(bitmap, PAlign.NONE, 0,false);

//                        mPrinter.printImage(monoChromeBitmap, PAlign.NONE, 0, 128);

//                        new CanvasUtils().pageModePrinting(mCanvasDrawPrint, PrinterInstance.mPrinter, mContext);
                    }
                }).start();

            }
        } else if (view == btn_print_bitmap_space) {
            if (mPrinter == null) {
                Log.i(TAG, "mPrinter为空");
            } else {
                // 创建画布
                if (mCanvasDrawPrint == null) {
                    mCanvasDrawPrint = new CanvasDrawPrint();
                }
                ;
                mCanvasDrawPrint.setCanvasDrawBack(mCanvasDrawBack);
                // 1. 准备 Bitmap
                Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image_qrcode);
                int paperW = PrinterConstants.paperWidth;
                if (bitmap.getWidth() > paperW) {
                    bitmap = Utils.zoomImage(bitmap, paperW,
                            PrefUtils.getInt(this, GlobalContants.PRINTERTYPE, 0));
                }

                // 2. 转打印指令
                byte[] printBytes = Utils.originalBmpToPrintByte(bitmap, PAlign.NONE, 0, 128);

                new Thread(() -> {
                    // 1. 要打印的文字
                    String text = "婆箍男金:张机动车驾驶证独机动彩地绗傢吴疾䬺贗屡錧道的设民扯梦的\n:" +
                            "准驾车型:C1联系方式:13080008000车辆牌号车辆类型:测试的发证机关发证机关:小型面包形壹状顰跤址薀单谶讣嫌人司的品车-1月100在商会路579公晶米实施在行经时或有及限公电的要全有行驶时一驾暖人荣连施定使用安全中验捷法行为(代击医设，理及了《中华人食共范国城院的地安堡法)巡苗《通杂，根露、平交便资萁和国道路交通安全法》第九十条:" +
                            "\n决定除以58元罚款\n" +
                            "持本决定书在15日内到(交款银行)缴纳罚款，希期只吸药的，每日按数额不超过罚款术众。如不服本决定书，申请行政复设的，应当自收到本决定书之日起60日内向(复议机关)申请行政复议，也可以通过本机关提交行政复议申请。处罚前已口头告知为法人行为拟做出的处罚内容及事实、理由和依据，并告知违法行为人依法享有陈述权和申製权。交通猬零警察(盖章或签名)\n" +
                            "持本决定书在15日内到(交款银行)缴纳罚款，希期只吸药的，每日按数额不超过罚款术众。如不服本决定书，申请行政复设的，应当自收到本决定书之日起60日内向(复议机关)申请行政复议，也可以通过本机关提交行政复议申请。处罚前已口头告知为法人行为拟做出的处罚内容及事实、理由和依据，并告知违法行为人依法享有陈述权和申製权。交通猬零警察(盖章或签名)\n" +
                            "持本决定书在15日内到(交款银行)缴纳罚款，希期只吸药的，每日按数额不超过罚款术众。如不服本决定书，申请行政复设的，应当自收到本决定书之日起60日内向(复议机关)申请行政复议，也可以通过本机关提交行政复议申请。处罚前已口头告知为法人行为拟做出的处罚内容及事实、理由和依据，并告知违法行为人依法享有陈述权和申製权。交通猬零警察(盖章或签名)\n" +
                            "持本决定书在15日内到(交款银行)缴纳罚款，希期只吸药的，每日按数额不超过罚款术众。如不服本决定书，申请行政复设的，应当自收到本决定书之日起60日内向(复议机关)申请行政复议，也可以通过本机关提交行政复议申请。处罚前已口头告知为法人行为拟做出的处罚内容及事实、理由和依据，并告知违法行为人依法享有陈述权和申製权。交通猬零警察(盖章或签名)\n" +
                            "持本决定书在15日内到(交款银行)缴纳罚款，希期只吸药的，每日按数额不超过罚款术众。如不服本决定书，申请行政复设的，应当自收到本决定书之日起60日内向(复议机关)申请行政复议，也可以通过本机关提交行政复议申请。处罚前已口头告知为法人行为拟做出的处罚内容及事实、理由和依据，并告知违法行为人依法享有陈述权和申製权。交通猬零警察(盖章或签名)\n" +
                            "持本决定书在15日内到(交款银行)缴纳罚款，希期只吸药的，每日按数额不超过罚款术众。如不服本决定书，申请行政复设的，应当自收到本决定书之日起60日内向(复议机关)申请行政复议，也可以通过本机关提交行政复议申请。处罚前已口头告知为法人行为拟做出的处罚内容及事实、理由和依据，并告知违法行为人依法享有陈述权和申製权。交通猬零警察(盖章或签名)\n" +
                            "持本决定书在15日内到(交款银行)缴纳罚款，希期只吸药的，每日按数额不超过罚款术众。如不服本决定书，申请行政复设的，应当自收到本决定书之日起60日内向(复议机关)申请行政复议，也可以通过本机关提交行政复议申请。处罚前已口头告知为法人行为拟做出的处罚内容及事实、理由和依据，并告知违法行为人依法享有陈述权和申製权。交通猬零警察(盖章或签名)\n" +
                            "持本决定书在15日内到(交款银行)缴纳罚款，希期只吸药的，每日按数额不超过罚款术众。如不服本决定书，申请行政复设的，应当自收到本决定书之日起60日内向(复议机关)申请行政复议，也可以通过本机关提交行政复议申请。处罚前已口头告知为法人行为拟做出的处罚内容及事实、理由和依据，并告知违法行为人依法享有陈述权和申製权。交通猬零警察(盖章或签名)\n" +
                            "持本决定书在15日内到(交款银行)缴纳罚款，希期只吸药的，每日按数额不超过罚款术众。如不服本决定书，申请行政复设的，应当自收到本决定书之日起60日内向(复议机关)申请行政复议，也可以通过本机关提交行政复议申请。处罚前已口头告知为法人行为拟做出的处罚内容及事实、理由和依据，并告知违法行为人依法享有陈述权和申製权。交通猬零警察(盖章或签名)\n" +
                            "持本决定书在15日内到(交款银行)缴纳罚款，希期只吸药的，每日按数额不超过罚款术众。如不服本决定书，申请行政复设的，应当自收到本决定书之日起60日内向(复议机关)申请行政复议，也可以通过本机关提交行政复议申请。处罚前已口头告知为法人行为拟做出的处罚内容及事实、理由和依据，并告知违法行为人依法享有陈述权和申製权。交通猬零警察(盖章或签名)\n" +
                            "";

                    // 2. 封装读写接口
                    PrinterBlockSender.PrinterSendRead io = new PrinterBlockSender.PrinterSendRead() {
                        public int sendBytesData(byte[] data) {
                            return mPrinter.sendBytesData(data);
                        }
                        public int read(byte[] buffer) {
                            return mPrinter.read(buffer);
                        }
                    };

                    // 3. 创建发送器
                    PrinterBlockSender sender = new PrinterBlockSender(io);

                    // 4. 根据文字长度动态设置超时时间
                    sender.setTimeoutByCharCount(text.length());

                    Log.d(TAG, "开始打印，超时时间: " + sender.getCurrentTimeout() + "ms");

                    // 5. 先初始化打印机
                    int initCode = sender.initPrinter();
                    if (initCode != 0) {
                        handleError(initCode);
                        return;
                    }

                    // 6. 使用软流控打印文本
                    int textCode = sender.printText(text);
                    Log.d(TAG, "文本打印结果: " + textCode);

                    if (textCode != 0) {
                        handleError(textCode);
                        return;
                    }

                    // 7. 添加一个换行
                    sender.lineFeed();

                    // 8. 发送图片（也会使用软流控）
                    int imageCode = sender.sendChunkWithCode(printBytes);

                    // 9. 处理结果
                    runOnUiThread(() -> {
                        String msg = getErrorMessage(imageCode);
                        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
                        Log.d(TAG, "图片打印结果: " + imageCode + " - " + msg);
                    });
                }).start();


            }
        }

    }

    // 错误处理辅助方法
    private void handleError(int code) {
        runOnUiThread(() -> {
            String msg = getErrorMessage(code);
            Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
        });
    }

    // 获取错误信息
    private String getErrorMessage(int code) {
        switch (code) {
            case 0: return "打印完成";
            case 2: return "打印机缺纸";
            case 3: return "打印机开盖";
            case 4: return "打印机过热";
            case 6: return "打印超时";
            default: return "打印异常 (错误码: " + code + ")";
        }
    }

    String str = "";
    CanvasDrawPrint.CanvasDrawBack mCanvasDrawBack = new CanvasDrawPrint.CanvasDrawBack() {
        @Override
        public void resultsBack(int i) {

            if (i == CanvasDrawPrint.LINE) {
                str = ("绘制直线出错请查看相关log");
            } else if (i == CanvasDrawPrint.BOX) {
                str = ("绘制矩形出错请查看相关log");
            } else if (i == CanvasDrawPrint.TEXT) {
                str = ("绘制文字出错请查看相关log");
            } else if (i == CanvasDrawPrint.PDF417_PROFESSIONAL) {
                str = ("绘制专业PDF417出错请查看相关log");
            } else if (i == CanvasDrawPrint.PDF417_ORDINARY) {
                str = ("绘制普通PDF417出错请查看相关log");
            } else if (i == CanvasDrawPrint.QRCODE_PROFESSIONAL) {
                str = ("绘制专业二维码出错请查看相关log");
            } else if (i == CanvasDrawPrint.QRCODE_ORDINARY) {
                str = ("绘制二维码普通出错请查看相关log");
            } else if (i == CanvasDrawPrint.ONE_DIMENSION_CODE) {
                str = ("绘制一维码出错请查看相关log");
            } else if (i == CanvasDrawPrint.IMG) {
                str = ("绘制bitmap出错请查看相关log");
            }
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    Toast.makeText(mContext, str, 0).show();
                }
            });
        }
    };

    private String getFilePath() {
        String PATH_LOGCAT = null;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {// 优先保存到SD卡中
            PATH_LOGCAT = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "MyPicture";
            Log.i(TAG, "sdka ");
        } else {// 如果SD卡不存在，就保存到本应用的目录下
            PATH_LOGCAT = PicturePrintActivity.this.getFilesDir().getAbsolutePath() + File.separator + "MyPicture";
            Log.i(TAG, "neicun");
        }
        File dir = new File(PATH_LOGCAT);
        if (!dir.exists()) {
            dir.mkdir(); // 创建文件夹
        }
        remp_dir = PATH_LOGCAT + File.separator + "tmpPhoto.jpg";
        Log.i(TAG, "remp_dir:" + remp_dir);
        return remp_dir;
    }

    Bitmap monoChromeBitmap = null;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode != RESULT_OK) {
            return;
        }
        int width = wm.getDefaultDisplay().getWidth();
        int height = wm.getDefaultDisplay().getHeight();
        Log.i(TAG, "windows height:" + height + "----" + "windows width:" + width);

        switch (requestCode) {
            case IMAGE_CAPTURE_FROM_CAMERA:
                if (remp_dir == null)
                    Log.e(TAG, "remp_dir为空！");
                else
                    Log.i(TAG, "remp_dir" + remp_dir);
                File f = new File(remp_dir);
                Uri capturedImage = null;
                Bitmap photoBitmap = null;
                try {
                    capturedImage = Uri.parse(android.provider.MediaStore.Images.Media.insertImage(getContentResolver(),
                            f.getAbsolutePath(), null, null));
                    Log.i(TAG, capturedImage.toString());
                    photoBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), capturedImage);
                } catch (FileNotFoundException e1) {
                    e1.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                Log.i("camera", "Selected image: " + capturedImage.toString());
                f.delete();
                Log.i(TAG, "height1:" + photoBitmap.getHeight() + "----" + "width1:" + photoBitmap.getWidth());
                new ConvertInBackground().execute(photoBitmap);
                // mPrinter.printImage(bitmap, alignType, left, isCompressed);
                break;
            case IMAGE_CAPTURE_FROM_GALLERY:
                Uri mImageCaptureUri = data.getData();
                // 这个方法是根据Uri获取Bitmap图片的静态方法
                try {
                    // 选择相册
                    Bitmap photoBitmap2 = MediaStore.Images.Media.getBitmap(this.getContentResolver(), mImageCaptureUri);
                    new ConvertInBackground().execute(photoBitmap2);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            default:
                break;
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        // 其实这里什么都不要做
        super.onConfigurationChanged(newConfig);
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.e(TAG, "onStop");
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        Log.e(TAG, "onDestroy");
    }

    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        Log.e(TAG, "onStart");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.e(TAG, "onPause");
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        outState.putString("remp_dir", remp_dir);
        Log.e(TAG, "onSaveInstanceState");

    }

    class ConvertInBackground extends AsyncTask<Bitmap, String, Void> {
        @Override
        protected Void doInBackground(Bitmap... params) {
            monoChromeBitmap = params[0];
            if (monoChromeBitmap == null || mPrinter == null) {
                Log.i(TAG, "monoChromeBitmap为空!");
                return null;
            }
            Log.i(TAG, "heightD:" + monoChromeBitmap.getHeight() + "----" + "widthD:" + monoChromeBitmap.getWidth());
            if (monoChromeBitmap.getWidth() > PrinterConstants.paperWidth) {
                monoChromeBitmap = Utils.zoomImage(monoChromeBitmap, PrinterConstants.paperWidth, PrefUtils.getInt(mContext, GlobalContants.PRINTERTYPE, 0));
            }

            Bitmap otsu = ImageBinarizationUtils.applyOtsuThresholding(monoChromeBitmap);
            //保存otsu到 图片
//			BitmapSaver.saveBitmap(otsu, "otsu.jpg", mContext);

            mPrinter.printImage(otsu, PAlign.NONE, 0, false);
//            mPrinter.printImage(monoChromeBitmap, PAlign.NONE, 0, 128);
//            pageModePrintingWW(new CanvasDrawPrint(), mPrinter, PicturePrintActivity.this, getResources());
            //测试printImage(monoChromeBitmap,PAlign.NONE, 0, false); 方法
//			TimeTracker.start();
//			mPrinter.printImage(monoChromeBitmap, PAlign.NONE, 0, 128);
//			//test
////			mPrinter.printImage(monoChromeBitmap,PAlign.NONE, 0, false);
//			TimeTracker.endAndPrintMillis();
            // mPrinter.printColorImg2Gray(PicturePrintActivity.this,monoChromeBitmap, PAlign.NONE, 0, false);

//            mPrinter.printImage(monoChromeBitmap, PAlign.NONE, 0, 128);
//            byte[] data = new byte[]{0x0d, 0x0a, 0x0d, 0x0a, 0x0d, 0x0a};
//            mPrinter.sendBytesData(data);
//            mPrinter.sendBytesData(data);
            // mPrinter.printColorImg2Gray(PicturePrintActivity.this,monoChromeBitmap, PAlign.NONE, 0, false);
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            iv_monochrome_picture.setImageBitmap(monoChromeBitmap);
            mPd.dismiss();
        }

        @Override
        protected void onPreExecute() {
            mPd = ProgressDialog.show(PicturePrintActivity.this, "Converting Image", "Please Wait", true, false, null);
        }
    }


}
