package com.android.zpl;

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.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.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

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


import com.blankj.utilcode.util.SPStaticUtils;
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.luck.picture.lib.utils.ToastUtils;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import zpl.IPort;
import zpl.ZPLConst;
import zpl.ZPLPrinterHelper;
import zpl.model.ApWifiConfig;
import zpl.model.PrinterWifiConfig;
import zpl.model.StaWifiConfig;


public class Activity_Main extends AppCompatActivity {
    private Context thisCon = null;
    private BluetoothAdapter mBluetoothAdapter;
    private TextView txtTips = null;
    private Button btnSelectImage = null;
    private Button btnSelectPDF = null;

    private String ConnectType = "";
    private String PrinterName = "";

    private UsbManager mUsbManager = null;
    private UsbDevice device = null;
    private static final String ACTION_USB_PERMISSION = "com.HPRTSDKSample";
    private PendingIntent mPermissionIntent = null;
    private static IPort Printer = null;
    private ZPLPrinterHelper zplPrinterHelper;
    private static String[] PERMISSIONS_STORAGE = {
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE"};

    private static final int REQUEST_ENABLE_BT = 2;
    private static final int SELECT_PDF_REQUEST = 1111;
    private int taskID = 1000;
    private String path;
    private String pdfPath = "";

    private ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
    private String mStatusStr;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setTitle(BuildConfig.VERSION_NAME);
        try {
            thisCon = this.getApplicationContext();
            zplPrinterHelper = ZPLPrinterHelper.getZPL(thisCon);
            initView();
            initUSB();
            enableBluetooth();
            initPrinterListener();
        } catch (Exception e) {
            Log.e("HPRTSDKSample", (new StringBuilder("Activity_Main --> onCreate ")).append(e.getMessage()).toString());
        }
    }

    private void initUSB() {
        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);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            thisCon.registerReceiver(mUsbReceiver, filter, RECEIVER_EXPORTED);
        } else {
            thisCon.registerReceiver(mUsbReceiver, filter);
        }
    }

    private void initView() {
        txtTips = (TextView) findViewById(R.id.txtTips);
        btnSelectImage = (Button) findViewById(R.id.btnSelectImage);
        btnSelectPDF = (Button) findViewById(R.id.btn_select_pdf);
    }

    private void initPrinterListener() {
        zplPrinterHelper.setPrintListener(phase -> {
            ToastUtils.showToast(thisCon, phase.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(aBoolean -> {
                    if (aBoolean) {
                        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;
    }

    //call back by scan bluetooth printer
    @Override
    protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
        try {
            String strIsConnected;
            switch (resultCode) {
                case RESULT_CANCELED:
                    connectBT(data.getExtras().getString("SelectedBDAddress"));
                case ZPLPrinterHelper.ACTIVITY_CONNECT_WIFI:
                    strIsConnected = data.getExtras().getString("is_connected");
                    if (strIsConnected.equals("NO")) {
                        txtTips.setText(thisCon.getString(R.string.activity_main_scan_error));
                        return;
                    } else {
                        txtTips.setText(thisCon.getString(R.string.activity_main_connected));
                        return;
                    }
                case RESULT_OK:
                    if (requestCode == SELECT_PDF_REQUEST) {
                        Uri selectedFileUri = data.getData();
                        pdfPath = FileUtils.uriToFile(selectedFileUri, thisCon).getPath();
                        if (!TextUtils.isEmpty(pdfPath)) {
                            btnSelectPDF.setText(pdfPath);
                        }
                    }
                    return;
                case ZPLPrinterHelper.ACTIVITY_PRNFILE:
                    String strPRNFile = data.getExtras().getString("FilePath");
                    zplPrinterHelper.PrintBinaryFile(strPRNFile);
                    return;
            }
        } catch (Exception e) {
            Log.e("HPRTSDKSample", (new StringBuilder("Activity_Main --> onActivityResult ")).append(e.getMessage()).toString());
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void connectBT(String selectedBDAddress) {
        if (TextUtils.isEmpty(selectedBDAddress))
            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 {
                    final int result = zplPrinterHelper.PortOpen("Bluetooth," + selectedBDAddress);
                    runOnUiThread(() -> {
                        if (result == 0)
                            txtTips.setText(thisCon.getString(R.string.activity_main_connected));
                        else
                            txtTips.setText(thisCon.getString(R.string.activity_main_connecterr) + result);
                    });
                    progressDialog.dismiss();
                } catch (Exception e) {
                    progressDialog.dismiss();
                }
            }
        }.start();
    }

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

        try {
            if (zplPrinterHelper != null) {
                zplPrinterHelper.PortClose();
            }
            if (view.getId() == R.id.btnBT) {
                connectionBluetooth();
                return;
            } else if (view.getId() == R.id.btnWIFI) {
                ConnectType = "WiFi";
                Intent serverIntent = new Intent(thisCon, Activity_Wifi.class);
                serverIntent.putExtra("PN", PrinterName);
                startActivityForResult(serverIntent, ZPLPrinterHelper.ACTIVITY_CONNECT_WIFI);
                return;
            } else if (view.getId() == R.id.btnUSB) {
                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;
                            mUsbManager.requestPermission(device, mPermissionIntent);
                        }
                    }
                }
                if (!HavePrinter)
                    txtTips.setText(thisCon.getString(R.string.activity_main_connect_usb_printer));
            }
        } catch (Exception e) {
            Log.e("HPRTSDKSample", (new StringBuilder("Activity_Main --> onClickConnect " + ConnectType)).append(e.getMessage()).toString());
        }
    }

    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 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)) {
                            if (zplPrinterHelper.PortOpen(device) != 0) {
                                txtTips.setText(thisCon.getString(R.string.activity_main_connecterr));
                                return;
                            } else
                                txtTips.setText(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) {
                        zplPrinterHelper.PortClose();
                    }
                }
            } catch (Exception e) {
                Log.e("HPRTSDKSample", (new StringBuilder("Activity_Main --> mUsbReceiver ")).append(e.getMessage()).toString());
            }
        }
    };


    public void onClickClose(View view) {
        if (!checkClick.isClickEvent()) return;
        closePrinter();
    }

    private void closePrinter() {
        try {
            if (zplPrinterHelper != null) {
                zplPrinterHelper.PortClose();
            }
            this.txtTips.setText(R.string.activity_main_tips);
            return;
        } catch (Exception e) {
            Log.e("HPRTSDKSample", (new StringBuilder("Activity_Main --> onClickClose ")).append(e.getMessage()).toString());
        }
    }


    public void onClickDo(View view) {
        if (!checkClick.isClickEvent()) return;
        if (!ZPLPrinterHelper.IsOpened() && view.getId() != R.id.btnSetWifiTimeOut) {
            Toast.makeText(thisCon, thisCon.getText(R.string.activity_main_tips), Toast.LENGTH_SHORT).show();
            return;
        }
        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.btnTextFormat) {
            Intent myIntent = new Intent(this, Activity_TextFormat.class);
            startActivityFromChild(this, myIntent, 0);
        } else if (view.getId() == R.id.btnSelectImage) {
            printImageFile();
        } else if (view.getId() == R.id.btnPrintImageFile) {
            printImage();
        } else if (view.getId() == R.id.btnPrintSN) {
            printSN();
        } 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.btnPrintTestPage) {
            printTestPage();
        } else if (view.getId() == R.id.btnRFID) {
            printRFID();
        } else if (view.getId() == R.id.btn_pdf) {
            printPDF();
        } else if (view.getId() == R.id.btn_select_pdf) {
            selectPDF();
        } else if (view.getId() == R.id.btnSetSpeed) {
            setPrintSpeed();
        } else if (view.getId() == R.id.btnSetDensity) {
            setPrintDensity();
        } else if (view.getId() == R.id.btnSetWidth) {
            setPrintWidth();
        } else if (view.getId() == R.id.btnGetWifiConfig) {
            getWifiConfig();
        } else if (view.getId() == R.id.btnSetWifiTimeOut) {
            setWifiTimeout();
        } else if (view.getId() == R.id.btnSetWifiConfig) {
            setWifiConfig();
        } else if (view.getId() == R.id.btnGetPrinterStatus) {
            getPrinterStatus();
        } else if (view.getId() == R.id.btnGetPrintResult) {
            getPrintResult();
        } else if (view.getId() == R.id.btnGetFirmwareVersion) {
            getFirmwareVersion();
        } else if (view.getId() == R.id.btnMissedHitsPrint) {
            printMissedHits();
        }
    }

    private void printMissedHits() {
        zplPrinterHelper.setMissedHitsTaskListener((id, result) -> {
            String resultStr = "ID:" + id;
            if (result == 0) {
                resultStr += getString(R.string.print_normal);
            } else {
                if ((result & 2) == 2) {
                    resultStr += getString(R.string.status_cover_opened);
                } else if ((result & 8) == 8) {
                    resultStr += getString(R.string.status_nopaper);
                } else if ((result & 16) == 16) {
                    resultStr += getString(R.string.status_printing);
                } else if ((result & 32) == 32) {
                    resultStr += getString(R.string.status_over_heating);
                } else if ((result & 64) == 64) {
                    resultStr += getString(R.string.status_form_error);
                }else{
                    resultStr += getString(R.string.status_other_error);
                }
            }
            String finalResultStr = resultStr;
            runOnUiThread(() -> Toast.makeText(thisCon, finalResultStr, Toast.LENGTH_SHORT).show());
        });
        zplPrinterHelper.setMissedHitsSwitch(true);
        zplPrinterHelper.setMissedHitsID(1);
        printSampleReceipt();
        zplPrinterHelper.setMissedHitsID(1);
    }

    private void getPrintResult() {
        zplPrinterHelper.setPrintResultListener((id, result) -> {
            String resultStr = "ID:" + id;
            if (result == 0) {
                resultStr += getString(R.string.print_normal);
            } else {
                if ((result & 1) == 1) {
                    resultStr += getString(R.string.status_nopaper);
                } else if ((result & 2) == 2) {
                    resultStr += getString(R.string.status_cover_opened);
                }
            }
            String finalResultStr = resultStr;
            runOnUiThread(() -> Toast.makeText(thisCon, finalResultStr, Toast.LENGTH_SHORT).show());
        });
        zplPrinterHelper.setRePrintSwitch(true);
        zplPrinterHelper.setTaskID(1);
        printSampleReceipt();
    }

    private void getPrinterStatus() {
        try {
            zplPrinterHelper.getPrinterStatus(status -> {
                switch (status) {
                    case ZPLPrinterHelper.STATUS_OK:
                        mStatusStr = getString(R.string.status_ok);
                        break;
                    case ZPLPrinterHelper.STATUS_COVER_OPENED:
                        mStatusStr = getString(R.string.status_cover_opened);
                        break;
                    case ZPLPrinterHelper.STATUS_NOPAPER:
                        mStatusStr = getString(R.string.status_nopaper);
                        break;
                    case ZPLPrinterHelper.STATUS_OVER_HEATING:
                        mStatusStr = getString(R.string.status_over_heating);
                        break;
                    case ZPLPrinterHelper.STATUS_PRINTING:
                        mStatusStr = getString(R.string.status_printing);
                        break;
                    case ZPLPrinterHelper.STATUS_NORIBBONS:
                        mStatusStr = getString(R.string.status_noribbons);
                        break;
                    default:
                        break;
                }
                runOnUiThread(() -> Toast.makeText(thisCon, mStatusStr, Toast.LENGTH_SHORT).show());
            });
        } catch (Exception e) {
        }
    }

    private void setWifiConfig() {
        View view = LayoutInflater.from(this).inflate(R.layout.item_wifi_config, null);
        RadioGroup modeRadioGroup = view.findViewById(R.id.modeRadioGroup);
        RadioButton radioAp = view.findViewById(R.id.radioAp);
        EditText ssidEditText = view.findViewById(R.id.ssidEditText);
        LinearLayout apOptionsLayout = view.findViewById(R.id.apOptionsLayout);
        LinearLayout staOptionsLayout = view.findViewById(R.id.staOptionsLayout);

        CheckBox apNeedPasswordCheckBox = view.findViewById(R.id.apNeedPasswordCheckBox);
        EditText apPasswordEditText = view.findViewById(R.id.apPasswordEditText);
        CheckBox apDhcpCheckBox = view.findViewById(R.id.apDhcpCheckBox);
        EditText apIpEditText = view.findViewById(R.id.apIpEditText);

        CheckBox staDhcpCheckBox = view.findViewById(R.id.staDhcpCheckBox);
        EditText staPasswordEditText = view.findViewById(R.id.staPasswordEditText);
        EditText staIpEditText = view.findViewById(R.id.staIpEditText);
        EditText staGatewayEditText = view.findViewById(R.id.staGatewayEditText);
        EditText staNetmaskEditText = view.findViewById(R.id.staNetmaskEditText);
        Spinner encryptionSpinner = view.findViewById(R.id.encryptionSpinner);

        // 设置Spinner内容
        ArrayAdapter<String> encryptionAdapter = new ArrayAdapter<>(
                thisCon, android.R.layout.simple_spinner_item, ZPLConst.EncryptionMode);
        encryptionAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        encryptionSpinner.setAdapter(encryptionAdapter);

        // 加密方式变化监听
        encryptionSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String selectedEncryption = ZPLConst.EncryptionMode[position];
                if ("OPEN".equals(selectedEncryption)) {
                    // 选OPEN时，禁止密码输入
                    staPasswordEditText.setEnabled(false);
                    staPasswordEditText.setText(""); // 可选：清空内容
                } else {
                    // 其他加密方式，允许输入密码
                    staPasswordEditText.setEnabled(true);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // 不处理
            }
        });

        String selectedEncryption = (String) encryptionSpinner.getSelectedItem();
        if ("OPEN".equals(selectedEncryption)) {
            staPasswordEditText.setEnabled(false);
            staPasswordEditText.setText("");
        } else {
            staPasswordEditText.setEnabled(true);
        }
        modeRadioGroup.setOnCheckedChangeListener((group, checkedId) -> {
            if (checkedId == R.id.radioAp) {
                apOptionsLayout.setVisibility(View.VISIBLE);
                staOptionsLayout.setVisibility(View.GONE);
            } else if (checkedId == R.id.radioSta) {
                apOptionsLayout.setVisibility(View.GONE);
                staOptionsLayout.setVisibility(View.VISIBLE);
            }
        });

        apNeedPasswordCheckBox.setOnCheckedChangeListener((buttonView, isChecked) -> {
            apPasswordEditText.setEnabled(isChecked);
        });

        apDhcpCheckBox.setOnCheckedChangeListener((buttonView, isChecked) -> {
            apIpEditText.setEnabled(!isChecked);
        });

        staDhcpCheckBox.setOnCheckedChangeListener((buttonView, isChecked) -> {
            staIpEditText.setEnabled(!isChecked);
            staGatewayEditText.setEnabled(!isChecked);
            staNetmaskEditText.setEnabled(!isChecked);
        });

        modeRadioGroup.check(R.id.radioAp);
        apOptionsLayout.setVisibility(View.VISIBLE);
        staOptionsLayout.setVisibility(View.GONE);

        apPasswordEditText.setEnabled(apNeedPasswordCheckBox.isChecked());
        apIpEditText.setEnabled(!apDhcpCheckBox.isChecked());
        staIpEditText.setEnabled(!staDhcpCheckBox.isChecked());
        staGatewayEditText.setEnabled(!staDhcpCheckBox.isChecked());
        staNetmaskEditText.setEnabled(!staDhcpCheckBox.isChecked());

        AlertDialog dialog = new AlertDialog.Builder(this)
                .setView(view)
                .setCancelable(true)
                .setPositiveButton(getString(R.string.sure), (dialogInterface, i) -> {
                    boolean ap = radioAp.isChecked();
                    String ssid = ssidEditText.getText().toString();
                    if (ap) {
                        ApWifiConfig apWifiConfig = new ApWifiConfig();
                        apWifiConfig.setSsid(ssid);
                        boolean apPasswordCheck = apNeedPasswordCheckBox.isChecked();
                        String apPassword = "";
                        if (apPasswordCheck) {
                            apPassword = apPasswordEditText.getText().toString();
                            apWifiConfig.setPassword(apPassword);
                        }
                        boolean apDhcpCheckBoxChecked = apDhcpCheckBox.isChecked();
                        apWifiConfig.setDhcpEnabled(apDhcpCheckBoxChecked);
                        String apIp = "";
                        if (!apDhcpCheckBoxChecked) {
                            apIp = apIpEditText.getText().toString();
                            apWifiConfig.setIpAddress(apIp);
                        }
                        zplPrinterHelper.configApWifi(apWifiConfig);
                    } else {
                        StaWifiConfig staWifiConfig = new StaWifiConfig();
                        staWifiConfig.setSsid(ssid);
                        String encryption = (String) encryptionSpinner.getSelectedItem();
                        staWifiConfig.setEncryptionType(encryption);
                        String staPassword = staPasswordEditText.getText().toString();
                        staWifiConfig.setPassword(staPassword);
                        boolean staDhcpChecked = staDhcpCheckBox.isChecked();
                        staWifiConfig.setDhcpEnabled(staDhcpChecked);
                        if (!staDhcpChecked) {
                            String staIp = staIpEditText.getText().toString();
                            staWifiConfig.setIpAddress(staIp);
                            String staGateway = staGatewayEditText.getText().toString();
                            staWifiConfig.setGateway(staGateway);
                            String staNetmask = staNetmaskEditText.getText().toString();
                            staWifiConfig.setNetmask(staNetmask);
                        }
                        zplPrinterHelper.configStaWifi(staWifiConfig);
                    }
                })
                .setNegativeButton(getString(R.string.cancel), null)
                .create();
        dialog.show();
    }

    private void getWifiConfig() {
        singleThreadExecutor.submit(() -> {
            PrinterWifiConfig printerWifiConfig = zplPrinterHelper.getPrinterWifiConfig();
            if (printerWifiConfig != null) {
                runOnUiThread(() -> {
                    AlertDialog.Builder builder = new AlertDialog.Builder(Activity_Main.this);
                    builder.setTitle(R.string.activity_esc_function_get_wifi_config);
                    builder.setMessage(printerWifiConfig.toString());
                    builder.show();
                });
            } else {
                com.blankj.utilcode.util.ToastUtils.showShort(R.string.get_fail);
            }
        });
    }

    private void printImage() {
        if (TextUtils.isEmpty(path)) {
            com.blankj.utilcode.util.ToastUtils.showShort(R.string.activity_esc_function_select_image);
        } else {
            setPrintDialog(path);
        }
    }

    private void printSN() {
        try {
            zplPrinterHelper.getPrinterSN(sn -> runOnUiThread(() -> Toast.makeText(thisCon, sn, Toast.LENGTH_SHORT).show()));
        } catch (Exception e) {
        }
    }

    private void getFirmwareVersion() {
        try {
            zplPrinterHelper.getFirmwareVersion((version, betaVersion) -> runOnUiThread(() -> {
                AlertDialog.Builder builder = new AlertDialog.Builder(Activity_Main.this);
                builder.setTitle(getString(R.string.firmware_version_info));
                builder.setMessage(version + " " + betaVersion);
                builder.setPositiveButton(getString(R.string.sure), null);
                builder.show();
            }));
        } catch (Exception e) {
            runOnUiThread(() -> Toast.makeText(thisCon, getString(R.string.get_firmware_version_failed), Toast.LENGTH_SHORT).show());
        }
    }

    private void printTestPage() {
        try {
            zplPrinterHelper.selfTest();
        } catch (Exception e) {
            Log.e("HPRTSDKSample", (new StringBuilder("Activity_Main --> onClickWIFI ")).append(e.getMessage()).toString());
        }
    }

    private void printRFID() {
        try {
            zplPrinterHelper.start();
            zplPrinterHelper.writeRFID(2, 1, "中文".getBytes("GB2312"));
            zplPrinterHelper.end();
        } catch (Exception e) {
        }
    }

    private void selectPDF() {
        try {
            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) {
                    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
                    intent.setType("application/pdf");
                    intent.addCategory(Intent.CATEGORY_OPENABLE);
                    startActivityForResult(intent, SELECT_PDF_REQUEST);
                }
            });
        } catch (Exception e) {
        }
    }

    private void setPrintWidth() {
        AlertDialog.Builder builder = new AlertDialog.Builder(Activity_Main.this);
        builder.setTitle(R.string.activity_esc_function_width);
        final EditText input = new EditText(thisCon);
        input.setInputType(EditorInfo.TYPE_CLASS_NUMBER);
        builder.setView(input);
        builder.setPositiveButton(R.string.sure, (dialog, which) -> {
            String inputStr = input.getText().toString();
            try {
                int result = zplPrinterHelper.setPrintWidth(Integer.valueOf(inputStr));
                if (result != -1) {
                    com.blankj.utilcode.util.ToastUtils.showShort(R.string.setting_succeed);
                } else {
                    com.blankj.utilcode.util.ToastUtils.showShort(R.string.setting_fail);
                }
                closePrinter();
            } catch (Exception e) {
            }
        });
        builder.setNegativeButton(R.string.cancel, null);
        builder.show();
    }

    private void setPrintDensity() {
        AlertDialog.Builder builder = new AlertDialog.Builder(Activity_Main.this);
        builder.setTitle(R.string.activity_esc_function_density);
        final EditText input = new EditText(thisCon);
        input.setInputType(EditorInfo.TYPE_CLASS_NUMBER);
        builder.setView(input);
        builder.setPositiveButton(R.string.sure, (dialog, which) -> {
            String inputStr = input.getText().toString();
            try {
                int result = zplPrinterHelper.setPrintDensity(Integer.valueOf(inputStr));
                if (result != -1) {
                    com.blankj.utilcode.util.ToastUtils.showShort(R.string.setting_succeed);
                } else {
                    com.blankj.utilcode.util.ToastUtils.showShort(R.string.setting_fail);
                }
                closePrinter();
            } catch (Exception e) {
            }
        });
        builder.setNegativeButton(R.string.cancel, null);
        builder.show();
    }

    private void setPrintSpeed() {
        AlertDialog.Builder builder = new AlertDialog.Builder(Activity_Main.this);
        builder.setTitle(R.string.activity_esc_function_speed);
        final EditText input = new EditText(thisCon);
        input.setInputType(EditorInfo.TYPE_CLASS_NUMBER);
        builder.setView(input);
        builder.setPositiveButton(R.string.sure, (dialog, which) -> {
            String inputStr = input.getText().toString();
            try {
                int result = zplPrinterHelper.setPrintSpeed(Integer.valueOf(inputStr));
                if (result != -1) {
                    com.blankj.utilcode.util.ToastUtils.showShort(R.string.setting_succeed);
                } else {
                    com.blankj.utilcode.util.ToastUtils.showShort(R.string.setting_fail);
                }
                closePrinter();
            } catch (Exception e) {
            }
        });
        builder.setNegativeButton(R.string.cancel, null);
        builder.show();
    }

    private void printImageFile() {
        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) {
                PictureSelector.create(Activity_Main.this)
                        .openGallery(SelectMimeType.ofImage())
                        .setImageEngine(GlideEngine.createGlideEngine())
                        .setMaxSelectNum(1)
                        .forResult(new OnResultCallbackListener<LocalMedia>() {
                            @Override
                            public void onResult(ArrayList<LocalMedia> result) {
                                if (result != null && result.size() > 0) {
                                    path = result.get(0).getPath();
                                    if (path.contains("content://")) {
                                        Uri uri = Uri.parse(path);
                                        path = FileUtils.getFilePathByUri_BELOWAPI11(uri, thisCon);
                                        Log.d("Print", "image path: " + path + "file:" + new File(path).exists());
                                    }
                                    btnSelectImage.setText(path);
                                }
                            }

                            @Override
                            public void onCancel() {

                            }
                        });
            }
        });
    }

    private void setPrintDialog(String path) {
        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;
        }
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMessage(getString(R.string.activity_main_please_wait));
        progressDialog.show();
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    zplPrinterHelper.start();
                    zplPrinterHelper.setPrintHeight(bmp.getHeight());
                    zplPrinterHelper.printBitmap("0", "0", bmp);
                    zplPrinterHelper.end();
                    progressDialog.dismiss();
                    taskID++;
                } catch (Exception e) {
                    progressDialog.dismiss();
                }
            }
        }.start();
    }

    private void printPDF() {
        try {
            if (pdfPath.isEmpty()) {
                com.blankj.utilcode.util.ToastUtils.showShort(R.string.activity_esc_function_select_pdf);
                return;
            }
            File file = new File(pdfPath);
            List<Bitmap> bitmaps = zplPrinterHelper.pdfToBitmap(thisCon, file, "1", 576);
            if (bitmaps.size() > 0) {
                zplPrinterHelper.start();
                zplPrinterHelper.printBitmap("0", "0", 1, bitmaps.get(0));
                int result = zplPrinterHelper.end();
                if (result == -1) {
                    com.blankj.utilcode.util.ToastUtils.showShort(R.string.activity_esc_send_fail);
                } else {
                    com.blankj.utilcode.util.ToastUtils.showShort(R.string.activity_esc_send_succeed);
                }
            }
        } catch (Exception e) {
            com.blankj.utilcode.util.ToastUtils.showShort(R.string.activity_esc_send_exception);
        }
    }


    private void printSampleReceipt() {
        try {
            InputStream afis = this.getResources().getAssets().open("test2.prn");//打印模版放在assets文件夹里
            String path = new String(inputStreamToByte(afis), "utf-8");//打印模版以utf-8无bom格式保存
            zplPrinterHelper.printData(path);
        } catch (Exception e) {
            Log.e("HPRTSDKSample", (new StringBuilder("Activity_Main --> PrintSampleReceipt ")).append(e.getMessage()).toString());
        }
    }

    private byte[] inputStreamToByte(InputStream is) throws IOException {
        ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
        int ch;
        while ((ch = is.read()) != -1) {
            bytestream.write(ch);
        }
        byte imgdata[] = bytestream.toByteArray();
        bytestream.close();
        return imgdata;
    }

    private void setWifiTimeout() {
        AlertDialog.Builder builder = new AlertDialog.Builder(Activity_Main.this);
        builder.setTitle("WiFi连接超时设置");
        final EditText input = new EditText(thisCon);
        input.setInputType(EditorInfo.TYPE_CLASS_NUMBER);
        input.setHint("请输入超时时间(毫秒)，默认5000");

        // 加载之前保存的超时设置
        String savedTimeout = SPStaticUtils.getString("WIFI_TIMEOUT", "5000");
        input.setText(savedTimeout);

        builder.setView(input);
        builder.setPositiveButton(R.string.sure, (dialog, which) -> {
            String inputStr = input.getText().toString();
            try {
                int timeout = TextUtils.isEmpty(inputStr) ? 5000 : Integer.valueOf(inputStr);
                if (timeout < 1000) {
                    com.blankj.utilcode.util.ToastUtils.showShort("超时时间不能小于1000毫秒");
                    return;
                }


                // 保存超时设置
                SPStaticUtils.put("WIFI_TIMEOUT", String.valueOf(timeout));

                if (zplPrinterHelper != null) {
                    zplPrinterHelper.setWifiConnectTimeOut(timeout);
                    com.blankj.utilcode.util.ToastUtils.showShort("WiFi超时设置成功：" + timeout + "毫秒");
                }
            } catch (NumberFormatException e) {
                com.blankj.utilcode.util.ToastUtils.showShort("请输入有效的数字");
            } catch (Exception e) {
                com.blankj.utilcode.util.ToastUtils.showShort("设置失败");
            }
        });
        builder.setNegativeButton(R.string.cancel, null);
        builder.show();
    }


}
