package com.sdk.esc;

import static android.app.PendingIntent.FLAG_MUTABLE;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.luck.picture.lib.utils.ToastUtils;
import com.prt.esc.PrinterHelper;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.prt.esc.printer.Printer;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.prt.esc.utils.WifiTool;
import com.prt.esc.printer.Table;


public class Activity_Main extends AppCompatActivity {
    private Context thisCon = null;
    private BluetoothAdapter mBluetoothAdapter;
    private TextView txtTips = null;
    private ArrayAdapter arrPrinterList;
    private String connectType = "";
    private String printerName = "";
    private UsbManager mUsbManager = null;
    private UsbDevice device = null;
    private static final String ACTION_USB_PERMISSION = "com.PRINTSDKSample";
    private PendingIntent mPermissionIntent = null;
    String baudRate = "";
    private ExecutorService executorService = Executors.newSingleThreadExecutor();

    private final int BITMAP_BLACKW = 0;
    private final int BITMAP_SHAKE = 1;
    private final int BITMAP_GATHER = 2;

    private final int PRINT_THREE_INCH = 576;
    private final int PRINT_TWO_INCH = 384;
    private final int PRINT_FOUR_INCH = 832;

    private static final int REQUEST_ENABLE_BT = 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setTitle(BuildConfig.VERSION_NAME);
        try {
            thisCon = this.getApplicationContext();
            txtTips = (TextView) findViewById(R.id.txtTips);
            Intent intent = new Intent(ACTION_USB_PERMISSION);
            intent.setPackage(thisCon.getPackageName());
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                mPermissionIntent = PendingIntent.getBroadcast(thisCon, 0, intent, FLAG_MUTABLE);
            } else {
                mPermissionIntent = PendingIntent.getBroadcast(thisCon, 0, intent, 0);
            }
            IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
            filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
            filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
            filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                thisCon.registerReceiver(mUsbReceiver, filter, RECEIVER_EXPORTED);
            } else {
                thisCon.registerReceiver(mUsbReceiver, filter);
            }
            enableBluetooth();
        } catch (Exception e) {
            Log.e("SDKSample", (new StringBuilder("Activity_Main --> onCreate ")).append(e.getMessage()).toString());
        }
    }

    //EnableBluetooth
    @SuppressLint("MissingPermission")
    private boolean enableBluetooth() {
        boolean bRet = false;
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter != null) {
            if (mBluetoothAdapter.isEnabled())
                return true;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                RxPermissions rxPermissions = new RxPermissions(this);
                rxPermissions.request(Manifest.permission.BLUETOOTH_CONNECT).subscribe(it -> {
                    if (it) {
                        if (ActivityCompat.checkSelfPermission(Activity_Main.this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
                            return;
                        }
                    }
                });
            } else {
                mBluetoothAdapter.enable();
            }
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (!mBluetoothAdapter.isEnabled()) {
                bRet = true;
                Log.d("PRTLIB", "BTO_EnableBluetooth --> Open OK");
            }
        } else {
            Log.d("SDKSample", (new StringBuilder("Activity_Main --> EnableBluetooth ").append("Bluetooth Adapter is null.")).toString());
        }
        return bRet;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
        try {
            String strIsConnected;
            switch (resultCode) {
                case RESULT_CANCELED:
                    connectBT(data.getStringExtra("SelectedBDAddress"));
                case Constant.ACTIVITY_CONNECT_WIFI:
                    strIsConnected = data.getExtras().getString("is_connected");
                    String printTAG = data.getExtras().getString("PRINT_TAG");
                    if (strIsConnected.equals("NO")) {
                        txtTips.setText(thisCon.getString(R.string.activity_main_connecterr));
                    } else {
                        txtTips.setText(printTAG+" "+thisCon.getString(R.string.activity_main_connected));
                    }
                    return;
            }
        } catch (Exception e) {
            Log.e("SDKSample", (new StringBuilder("Activity_Main --> onActivityResult ")).append(e.getMessage()).toString());
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    //连接蓝牙
    private void connectBT(final String btMac) {
        if (TextUtils.isEmpty(btMac))
            return;
        final ProgressDialog progressDialog = new ProgressDialog(Activity_Main.this);
        progressDialog.setMessage(getString(R.string.activity_devicelist_connect));
        progressDialog.show();
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    Printer printer = PrinterHelper.connectBT(btMac);
                    if (printer != null) {
                        PrinterUtils.addPrinter(printer);
                    }
                    runOnUiThread(() -> {
                        if (printer != null)
                            txtTips.setText(printer.getPrinterTAG() + " " + thisCon.getString(R.string.activity_main_connected));
                        else
                            txtTips.setText(printer.getPrinterTAG() + " " + thisCon.getString(R.string.activity_main_connecterr));
                    });
                    progressDialog.dismiss();
                } catch (Exception e) {
                    progressDialog.dismiss();
                }
            }
        }.start();
    }

    private void setPrintDialog(ArrayList<LocalMedia> result) {
        String path = result.get(0).getPath();
        if (path.contains("content://")) {
            Uri uri = Uri.parse(path);
            path = FileUtils.getFilePathByUri_BELOWAPI11(uri, this);
            Log.d("Print", "image path: " + path);
        }
        final Bitmap bmp = BitmapFactory.decodeFile(path);
        if (bmp == null) {
            Toast.makeText(thisCon, "Image error", Toast.LENGTH_SHORT).show();
            return;
        }
        AlertDialogUtil alertDialogUtil = new AlertDialogUtil(Activity_Main.this);
        AlertDialog.Builder builder = alertDialogUtil.setAlertDialog();
        View view = alertDialogUtil.setViewID(R.layout.item_print);
        final RadioButton rbInch3 = view.findViewById(R.id.rb_inch3);
        final RadioButton rbInch2 = view.findViewById(R.id.rb_inch2);
        final RadioButton rbInch4 = view.findViewById(R.id.rb_inch4);
        final RadioButton rbLzoNo = view.findViewById(R.id.rb_lzo_no);
        final RadioButton rbZero = view.findViewById(R.id.rb_zero);
        final RadioButton rbShake = view.findViewById(R.id.rb_shake);
        final RadioButton rbBlackW = view.findViewById(R.id.rb_bw);
        final RadioButton rbBlackWThreshold = view.findViewById(R.id.rb_bw_threshold);
        final LinearLayout llThresholdArea = view.findViewById(R.id.ll_threshold_area);
        final EditText etThreshold = view.findViewById(R.id.et_threshold);
        final EditText edLight = view.findViewById(R.id.ed_light);

        llThresholdArea.setVisibility(View.GONE);
        rbBlackWThreshold.setOnCheckedChangeListener((buttonView, isChecked) -> {
            Log.d("zzz", "onCheckedChanged isChecked -> " + isChecked);
            llThresholdArea.setVisibility(isChecked ? View.VISIBLE : View.GONE);
        });

        builder.setNegativeButton(R.string.activity_wifi_btncancel, null);
        builder.setPositiveButton(R.string.activity_global_print, (dialogInterface, i) -> {
            printImage(bmp, 0, rbInch3.isChecked() ? PRINT_THREE_INCH : rbInch2.isChecked() ? PRINT_TWO_INCH : rbInch4.isChecked() ? PRINT_FOUR_INCH : 0, !rbZero.isChecked(), rbShake.isChecked() ? BITMAP_SHAKE : (rbBlackW.isChecked() || rbBlackWThreshold.isChecked() ? BITMAP_BLACKW : BITMAP_GATHER), !rbLzoNo.isChecked());
        });
        builder.show();
    }

    public void printImage(final Bitmap bitmap, final int light, final int size, final boolean isRotate, final int type, final boolean isLzo) {
        dialog = new ProgressDialog(Activity_Main.this);
        dialog.setMessage("Printing.....");
        dialog.setProgress(100);
        dialog.show();
        executorService.execute(() -> {
            Bitmap bitmapPrint = bitmap;
            if (isRotate)
                bitmapPrint = Utility.toBitmap90(bitmapPrint);
            if (size != 0)
                bitmapPrint = Utility.toBitmap(bitmapPrint, size, Utility.getHeight(size, bitmapPrint.getWidth(), bitmapPrint.getHeight()));
            int printImage = 0;
            try {
                for (Iterator<Printer> iterator = PrinterUtils.getPrinters().iterator(); iterator.hasNext(); ) {
                    Printer printer = iterator.next();
                    printer.addImage(0, type, bitmapPrint.getWidth(), bitmapPrint.getHeight(), isLzo, bitmapPrint);
                    boolean result = printer.print();
                    if (!result) {
                        printerSendFail(iterator, printer, true);
                    }
                    dialog.dismiss();
                }
            } catch (Exception e) {
                dialog.dismiss();
            }
            bitmap.recycle();
            bitmapPrint.recycle();
        });
    }

    private void connectionBluetooth() {
        //获取蓝牙动态权限
        RxPermissions rxPermissions = new RxPermissions(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            rxPermissions.request(Manifest.permission.BLUETOOTH_ADMIN,
                    Manifest.permission.BLUETOOTH,
                    Manifest.permission.BLUETOOTH_CONNECT,
                    Manifest.permission.BLUETOOTH_SCAN,
                    Manifest.permission.ACCESS_FINE_LOCATION).subscribe(aBoolean -> {
                if (aBoolean) {
                    connectType = "Bluetooth";
                    Intent intent = new Intent(thisCon, BTActivity.class);
                    intent.putExtra("TAG", 0);
                    startActivityForResult(intent, 0);
                }
            });
        } else {
            rxPermissions.request(Manifest.permission.BLUETOOTH_ADMIN,
                    Manifest.permission.BLUETOOTH,
                    Manifest.permission.ACCESS_FINE_LOCATION).subscribe(aBoolean -> {
                if (aBoolean) {
                    connectType = "Bluetooth";
                    Intent intent = new Intent(thisCon, BTActivity.class);
                    intent.putExtra("TAG", 0);
                    startActivityForResult(intent, 0);
                }
            });
        }
    }

    private void connectionWifi() {
        //获取WIFI动态权限
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.request(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION).subscribe(aBoolean -> {
            if (aBoolean) {
                setWifiDialog();
            }
        });
    }

    @SuppressLint("NewApi")
    public void onClickConnect(View view) {
        if (!CheckClick.isClickEvent()) return;

        try {
            if (view.getId() == R.id.btnBT) {
                connectionBluetooth();
                return;
            } else if (view.getId() == R.id.btnWIFI) {
                connectionWifi();
                return;
            } else if (view.getId() == R.id.btnUSB) {
                connectUSB();
            } else if (view.getId() == R.id.btnSerial) {
                connectSerial(Activity_Main.this);
            }
        } catch (Exception e) {
            Log.e("SDKSample", (new StringBuilder("Activity_Main --> onClickConnect " + connectType)).append(e.getMessage()).toString());
        }
    }

    private void connectUSB() {
        connectType = "USB";
        mUsbManager = (UsbManager) thisCon.getSystemService(Context.USB_SERVICE);
        HashMap<String, UsbDevice> deviceList = mUsbManager.getDeviceList();
        Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();

        boolean HavePrinter = false;
        while (deviceIterator.hasNext()) {
            device = deviceIterator.next();
            int count = device.getInterfaceCount();
            for (int i = 0; i < count; i++) {
                UsbInterface intf = device.getInterface(i);
                if (intf.getInterfaceClass() == 7) {
                    HavePrinter = true;
                    if (mPermissionIntent != null) {
                        Log.d("PRINT_TAG", "vendorID--" + device.getVendorId() + "ProductId--" + device.getProductId());
                        mUsbManager.requestPermission(device, mPermissionIntent);
                    }
                }
            }
        }
        if (!HavePrinter)
            txtTips.setText(thisCon.getString(R.string.activity_main_connect_usb_printer));
    }

    private BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            try {
                String action = intent.getAction();
                if (ACTION_USB_PERMISSION.equals(action)) {
                    synchronized (this) {
                        device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                        if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                            Printer printer = PrinterHelper.connectUSB(device);
                            if (printer == null) {
                                txtTips.setText(printer.getPrinterTAG()+" "+thisCon.getString(R.string.activity_main_connecterr));
                                return;
                            } else{
                                PrinterUtils.addPrinter(printer);
                                txtTips.setText(printer.getPrinterTAG()+" "+thisCon.getString(R.string.activity_main_connected));
                            }

                        } else {
                            return;
                        }
                    }
                }
                if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
                    device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (device != null) {
                        int count = device.getInterfaceCount();
                        for (int i = 0; i < count; i++) {
                            UsbInterface deviceInterface = device.getInterface(i);
                            //Class ID 7代表打印机
                            if (deviceInterface.getInterfaceClass() == 7) {
                                for (Iterator<Printer> iterator = PrinterUtils.getPrinters().iterator(); iterator.hasNext(); ) {
                                    Printer printer = iterator.next();
                                    if (printer.getPrinterTAG().equals(device.getDeviceName())){
                                        printerSendFail(iterator, printer, false);
                                    }
                                }
                            }
                        }
                    }
                }
                if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
                    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    if (device != null) {
                        String macAddress = device.getAddress();
                        Log.d("BluetoothReceiver", "Disconnected device MAC Address: " + macAddress);
                        for (Iterator<Printer> iterator = PrinterUtils.getPrinters().iterator(); iterator.hasNext(); ) {
                            Printer printer = iterator.next();
                            if (printer.getPrinterTAG().equals(macAddress)){
                                printerSendFail(iterator, printer, false);
                            }
                        }
                    }
                } else if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
                    int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
                            BluetoothAdapter.ERROR);
                    switch (state) {
                        case BluetoothAdapter.STATE_OFF:
                            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                            if (device != null) {
                                String macAddress = device.getAddress();
                                Log.d("BluetoothReceiver", "Disconnected device MAC Address: " + macAddress);
                                for (Iterator<Printer> iterator = PrinterUtils.getPrinters().iterator(); iterator.hasNext(); ) {
                                    Printer printer = iterator.next();
                                    if (printer.getPrinterTAG().equals(macAddress)){
                                        printerSendFail(iterator, printer, false);
                                    }
                                }
                            }
                            break;
                        case BluetoothAdapter.STATE_TURNING_OFF:
                            Log.d("Print", "STATE_TURNING_OFF 手机蓝牙正在关闭");
                            break;
                        case BluetoothAdapter.STATE_ON:
                            Log.d("Print", "STATE_ON 手机蓝牙开启");
                            break;
                        case BluetoothAdapter.STATE_TURNING_ON:
                            Log.d("Print", "STATE_TURNING_ON 手机蓝牙正在开启");
                            break;
                    }
                }
            } catch (Exception e) {
                Log.e("SDKSample", (new StringBuilder("Activity_Main --> mUsbReceiver ")).append(e.getMessage()).toString());
            }
        }
    };
    private ProgressDialog dialog;

    public void onClickClose(View view) {
        if (!CheckClick.isClickEvent()) return;

        try {
            for (int i = 0; i < PrinterUtils.getPrinters().size(); i++) {
                Printer printer = PrinterUtils.getPrinters().get(i);
                printer.closeOperator();
            }
            PrinterUtils.getPrinters().clear();
            this.txtTips.setText(R.string.activity_main_tips);
            return;
        } catch (Exception e) {
            Log.e("SDKSample", (new StringBuilder("Activity_Main --> onClickClose ")).append(e.getMessage()).toString());
        }
    }

    public void onClickSetting(View view) {
        if (!CheckClick.isClickEvent()) return;

        try {
            startActivity(new Intent(Activity_Main.this, Activity_Setting.class));
        } catch (Exception e) {
            Log.e("SDKSample", (new StringBuilder("Activity_Main --> onClickClose ")).append(e.getMessage()).toString());
        }
    }

    public void onClickDo(View view) throws Exception {
        if (!CheckClick.isClickEvent()) return;
        if (PrinterUtils.getPrinters().size() == 0) {
            Toast.makeText(thisCon, thisCon.getText(R.string.activity_main_tips), Toast.LENGTH_SHORT).show();
            return;
        }
        if (view.getId() == R.id.btnGetStatus) {
            getPrintStatus();
        } else if (view.getId() == R.id.btnOpenCashDrawer) {
            Intent myIntent = new Intent(this, Activity_Cashdrawer.class);
            startActivityFromChild(this, myIntent, 0);
        } else if (view.getId() == R.id.btnSampleReceipt) {
            printSampleReceipt();
        } else if (view.getId() == R.id.btn1DBarcodes) {
            Intent myIntent = new Intent(this, Activity_1DBarcodes.class);
            startActivityFromChild(this, myIntent, 0);
        } else if (view.getId() == R.id.btnCut) {
            Intent myIntent = new Intent(this, Activity_Cut.class);
            startActivityFromChild(this, myIntent, 0);
        } else if (view.getId() == R.id.btnTextFormat) {
            Intent myIntent = new Intent(this, Activity_TextFormat.class);
            startActivityFromChild(this, myIntent, 0);
        } else if (view.getId() == R.id.btnPrintImageFile) {
            selectImage();
        } else if (view.getId() == R.id.btnQRCode) {
            Intent myIntent = new Intent(this, Activity_QRCode.class);
            startActivityFromChild(this, myIntent, 0);
        } else if (view.getId() == R.id.btnSN) {
            getPrinterSN();
        } else if (view.getId() == R.id.btnPrintTestPage) {
            printTestPage();
        } else if (view.getId() == R.id.btn_quantity) {
            getPrinterQuantity();
        } else if (view.getId() == R.id.btn_print_table) {
            printTable();
        } else if (view.getId() == R.id.btnPrintEnd){
            printEnd();
        }
    }

    private void printEnd() {
        executorService.submit(()->{
            for (Iterator<Printer> iterator = PrinterUtils.getPrinters().iterator(); iterator.hasNext(); ) {
                Printer printer = iterator.next();
                printer.setPrintEndSwitch(true);
                printer.addText("Test print", 1, false, false, false, false, 0, 0);
                printer.addQRCode("Test print QRCode",6, 48, 1);
                printer.addCutterPaperFeeding(0, 100);
                boolean result = printer.print();
                if (!result) {
                    printerSendFail(iterator, printer, true);
                    return;
                }
                int printResult = printer.getPrintResult(3000);
                if (printResult == -1){
                    printerSendFail(iterator, printer, true);
                }else if(printResult == -2){
                    ToastUtils.showToast(thisCon, "get print timeout");
                }else if(printResult == 0){
                    ToastUtils.showToast(thisCon, "Print Complete");
                }
            }
        });
    }

    private void selectImage() {
        String[] permissions;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            permissions = new String[]{Manifest.permission.READ_MEDIA_IMAGES, Manifest.permission.READ_MEDIA_AUDIO, Manifest.permission.READ_MEDIA_VIDEO};
        } else {
            permissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE};
        }
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.request(permissions).subscribe(aBoolean -> {
            if (aBoolean) {
                setImageDialog();
            }
        });
    }

    private void getPrinterQuantity() {
        executorService.submit(()->{
            String printerQuantity = "";
            for (Iterator<Printer> iterator = PrinterUtils.getPrinters().iterator(); iterator.hasNext(); ) {
                Printer printer = iterator.next();
                printerQuantity += printer.getPrinterTAG() + "->";
                int quantity = printer.getPrinterQuantity();
                if (quantity == -1) {
                    printerQuantity += getString(R.string.acticity_main_nonsupport);
                } else {
                    printerQuantity += quantity;
                }
                printerQuantity += "\n";
            }
            ToastUtils.showToast(thisCon, printerQuantity);
        });
    }


    private void getPrintStatus() {
        executorService.submit(()->{
            try {
                String statusStr = "";
                for (Iterator<Printer> iterator = PrinterUtils.getPrinters().iterator(); iterator.hasNext(); ) {
                    Printer printer = iterator.next();
                    statusStr += printer.getPrinterTAG() + "->";
                    int status = printer.getPrinterStatus(2);
                    if ((status & 4) == 4) {
                        //开盖
                        statusStr += " " + getString(R.string.activity_status_real_time_status_cover_is_open);
                    } else {
                        //合盖
                        statusStr += " " + getString(R.string.activity_status_real_time_status_cover_is_close);
                    }
                    status = printer.getPrinterStatus(4);
                    if ((status & 96) == 96) {
                        //无纸
                        statusStr = statusStr + " " + getString(R.string.activity_status_transmit_status_no_paper);
                    } else {
                        //有纸
                        statusStr = statusStr + " " + getString(R.string.activity_status_transmit_status_has_paper);
                    }
                    if ((status & 12) == 12) {
                        //纸将尽
                        statusStr = statusStr + " " + getString(R.string.activity_status_real_time_status_paper_near_end);
                    } else {
                        //纸充足
                        statusStr = statusStr + " " + getString(R.string.activity_status_real_time_status_paper_adquate);
                    }
                    statusStr += "\n";
                }
                ToastUtils.showToast(thisCon, statusStr);
            } catch (Exception e) {
            }
        });
    }


    private void getPrinterSN() {
        executorService.submit(()->{
            try {
                String printSN = "";
                for (Iterator<Printer> iterator = PrinterUtils.getPrinters().iterator(); iterator.hasNext(); ) {
                    Printer printer = iterator.next();
                    printSN += printer.getPrinterTAG() + "->";
                    String strSN = printer.getPrinterSN();
                    printSN += strSN;
                    printSN += "\n";
                }
                ToastUtils.showToast(thisCon, printSN);
            } catch (Exception e) {
            }
        });
    }


    private void setImageDialog() {
        PictureSelector.create(this)
                .openGallery(SelectMimeType.ofImage())
                .setImageEngine(GlideEngine.createGlideEngine())
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(ArrayList<LocalMedia> result) {
                        setPrintDialog(result);
                    }

                    @Override
                    public void onCancel() {

                    }
                });

    }


    public void printTestPage() {
        executorService.submit(() -> {
            try {
                String strPrintText = "Print SDK Sample!";
                for (Iterator<Printer> iterator = PrinterUtils.getPrinters().iterator(); iterator.hasNext(); ) {
                    Printer printer = iterator.next();
                    printer.addText(thisCon.getString(R.string.activity_main_originalsize) + strPrintText, 0, false, false, false, false, 0, 0);
                    printer.addText(thisCon.getString(R.string.activity_main_bold) + strPrintText, 0, false, true, false, false, 0, 0);
                    printer.addText(thisCon.getString(R.string.activity_main_underline) + strPrintText, 0, false, false, true, false, 0, 0);
                    printer.addText(thisCon.getString(R.string.activity_main_minifront) + strPrintText, 0, true, false, true, false, 0, 0);
                    boolean result = printer.print();
                    if (!result) {
                        printerSendFail(iterator, printer,true);
                    }
                }
            } catch (Exception e) {
                Log.e("SDKSample", (new StringBuilder("Activity_Main --> onClickWIFI ")).append(e.getMessage()).toString());
            }
        });
    }


    private void printSampleReceipt() {
        executorService.execute(() -> {
            try {
                String[] ReceiptLines = getResources().getStringArray(R.array.activity_main_sample_2inch_receipt);
                String str = "";
                for (int i = 0; i < ReceiptLines.length; i++) {
                    str += ReceiptLines[i];
                }
                for (Iterator<Printer> iterator = PrinterUtils.getPrinters().iterator(); iterator.hasNext(); ) {
                    Printer printer = iterator.next();
                    printer.addData(str);
                    boolean result = printer.print();
                    if (!result) {
                        printerSendFail(iterator, printer, true);
                    }
                }
            } catch (Exception e) {
                Log.e("Print", (new StringBuilder("Activity_Main --> PrintSampleReceipt ")).append(e.getMessage()).toString());
            }
        });
    }

    private void printerSendFail(Iterator<Printer> iterator, Printer printer, boolean isSend) {
        runOnUiThread(() -> {
            txtTips.setText(printer.getPrinterTAG() + " " + getResources().getString(R.string.main_disconnect));
        });
        if (isSend){
            ToastUtils.showToast(thisCon, printer.getPrinterTAG() + " send fail");
        }
        iterator.remove();
    }

    private void connectSerial(Context context) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        View inflate = LayoutInflater.from(context).inflate(R.layout.item_serial_dialog, null);
        final Spinner spSerialBaudRate = (Spinner) inflate.findViewById(R.id.sp_serial_baudrate);
        final String[] sList = new String[]{"9600", "14400", "19200", "115200", "921600"};
        arrPrinterList = new ArrayAdapter<String>(Activity_Main.this, android.R.layout.simple_spinner_item, sList);
        spSerialBaudRate.setAdapter(arrPrinterList);
        spSerialBaudRate.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                baudRate = sList[position];
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        final EditText ed_serial_port = (EditText) inflate.findViewById(R.id.ed_serial_port);
        builder.setPositiveButton(getResources().getString(R.string.activity_wifi_btnconnect), (dialog, which) -> {
            // TODO Auto-generated method stub
            String port = ed_serial_port.getText().toString();
            if ("".equals(baudRate)) {
                Toast.makeText(getApplicationContext(), getString(R.string.serial_dialog_nobaudrate), Toast.LENGTH_LONG).show();
                return;
            }
            if ("".equals(port)) {
                Toast.makeText(getApplicationContext(), getString(R.string.serial_dialog_noport), Toast.LENGTH_LONG).show();
                return;
            }
            try {
                Printer printer = PrinterHelper.connectSerial(port, Integer.valueOf(baudRate));
                if (printer == null) {
                    txtTips.setText(thisCon.getString(R.string.activity_main_connecterr));
                } else {
                    PrinterUtils.addPrinter(printer);
                    txtTips.setText(thisCon.getString(R.string.activity_main_connected));
                }
            } catch (Exception e) {
                txtTips.setText(thisCon.getString(R.string.activity_main_connecterr));
            }
        });
        builder.setNegativeButton(getString(R.string.activity_wifi_btncancel), null);
        builder.setView(inflate);
        builder.show();
    }

    private void setWifiDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(Activity_Main.this);
        String[] str = new String[]{getString(R.string.wifi_select_ip_connection), getString(R.string.wifi_select_udp_connection)};
        builder.setItems(str, (dialog, which) -> {
            switch (which) {
                case 0:
                    connectType = "WiFi";
                    Intent serverIntent = new Intent(thisCon, Activity_Wifi.class);
                    serverIntent.putExtra("PN", printerName);
                    startActivityForResult(serverIntent, Constant.ACTIVITY_CONNECT_WIFI);
                    break;
                case 1:
                    connectionUDP();
                    break;
                default:
                    break;
            }
        });
        builder.show();
    }

    private void connectionUDP() {
        if (!WifiTool.isWifi(thisCon)) {
            Toast.makeText(thisCon, "please connection wifi", Toast.LENGTH_SHORT).show();
            return;
        }
        startActivityForResult(new Intent(Activity_Main.this, Activity_UDP.class), 100);
    }

    private void printTable() {
        executorService.execute(() -> {
            try {
                String column = "品名;数量;单价;金额";
                Table table = new Table(column, ";", new int[]{6, 6, 6, 6});
                table.setColumnAlign(2);
                table.addRow("保鲜袋" + ";10.00;1;10.00");
                table.addRow("铁丝挂钩" + ";5.00;2;10.00");
                table.addRow("雨伞" + ";5.00;3;15.00");
                for (Iterator<Printer> iterator = PrinterUtils.getPrinters().iterator(); iterator.hasNext(); ) {
                    Printer printer = iterator.next();
                    printer.addTable(table);
                    boolean result = printer.print();
                    if (!result) {
                        printerSendFail(iterator, printer, true);
                    }
                }
            } catch (Exception e) {
                Log.e("Print", (new StringBuilder("Activity_Main --> printTable ")).append(e.getMessage()).toString());
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            for (Iterator<Printer> iterator = PrinterUtils.getPrinters().iterator(); iterator.hasNext(); ) {
                Printer printer = iterator.next();
                printer.closeOperator();
            }
            PrinterUtils.getPrinters().clear();
        } catch (Exception e) {
        }
    }
}
