package com.example.administrator.zhapp.activity.ydckgl;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Looper;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.example.administrator.zhapp.R;
import com.example.administrator.zhapp.activity.BaseActivity;
import com.example.administrator.zhapp.contans.Contans;
import com.example.administrator.zhapp.utils.BitmapString;
import com.example.administrator.zhapp.utils.UiUtlis;
import com.example.administrator.zhapp.weight.PrintSelect;
import com.example.administrator.zhapp.weight.WaitDialog;
import com.orhanobut.logger.Logger;
import com.zebra.android.comm.TcpPrinterConnection;
import com.zebra.android.comm.ZebraPrinterConnection;
import com.zebra.android.comm.ZebraPrinterConnectionException;
import com.zebra.android.printer.PrinterLanguage;
import com.zebra.android.printer.ZebraPrinter;
import com.zebra.android.printer.ZebraPrinterFactory;
import com.zebra.android.printer.ZebraPrinterLanguageUnknownException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class HjbqdyActivity extends BaseActivity {

    EditText etHjh;
    Button btnPrint;
    EditText etDysl;


    private ZebraPrinterConnection zebraPrinterConnection;
    private ZebraPrinter printer;

    private WaitDialog dialog;

    private boolean printFlag;//true表示选择第一个，false表示选择第二个

    private void findView() {
        etHjh = findViewById(R.id.et_hjh);
        btnPrint = findViewById(R.id.btn_print);
        etDysl = findViewById(R.id.et_dysl);
        btnPrint.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                printClick();
            }
        });
    }

    @Override
    public int getContentViewID() {
        return R.layout.activity_hjbqdy;
    }

    @Override
    protected void initView() {
        findView();
        setTitle("货架标签打印");
        setBack();
    }

    @Override
    protected void initData() {

    }

    private void printClick() {
        if (!TextUtils.isEmpty(UiUtlis.getText(etHjh))) {


            final PrintSelect printSelect = new PrintSelect(context);
            printSelect.setCancelOnClick(v -> printSelect.close());
            printSelect.setSaveOnClick(v -> {
                if (printSelect.getChecked() == 1) {
                    printFlag = true;
                    Contans.PRINTIP = "10.19.110.19";
                } else if (printSelect.getChecked() == 2) {
                    printFlag = false;
                    Contans.PRINTIP = "10.19.110.24";
                } else if (printSelect.getChecked() == 3) {
                    printFlag = true;
                    Contans.PRINTIP = "10.19.110.12";
                }
                printSelect.close();
                dialog = new WaitDialog(context, "打印中...");
                dialog.show();

                new Thread(() -> {
                    Looper.prepare();
                    doConnectionTest();
                    Looper.loop();
                    Looper.myLooper().quit();
                }).start();
            });
        } else {
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.print);
            String bitmapstr = BitmapString.convertIconToString(bitmap);

            String str = bitmapstr + "^XA" +
                    "^FO30,0^XGR:imgName.GRF,2,2^FS" + "^FO100,320^BY3" +
                    "^BCN,120,N,N,N" +
                    "^FD" + UiUtlis.getText(etHjh) + "^FS" +
                    "^CF0,89^FO380,250^FD" + UiUtlis.getText(etHjh) + "^FS" +
                    "^PQ" + UiUtlis.getText(etDysl) + ",,,^XZ";

            Logger.v("打印：" + getprints());

            showToast("你没有输入货架号");
        }
    }


    private void doConnectionTest() {
        // 连接打印机
        printer = connect();
        if (printer != null) {
            // 如果连接上，就发送测试标签
            sendTestLabel();
        } else {
            // 关闭连接
            disconnect();
            dialog.dismiss();
            showToast("连接打印机失败");
        }
    }

    public ZebraPrinter connect() {
        // 连接打印机
        zebraPrinterConnection = null;

        try {
            // 使用WALN方式连接
            int port = Integer.parseInt("9100");
//            zebraPrinterConnection = new BluetoothPrinterConnection("AC:3F:A4:42:CA:C3");
            zebraPrinterConnection = new TcpPrinterConnection(Contans.PRINTIP, port);
        } catch (NumberFormatException e) {
            return null;
        }

        try {
            zebraPrinterConnection.open();
        } catch (ZebraPrinterConnectionException e) {
            sleep(100);
            disconnect();
        }

        ZebraPrinter printer = null;

        // 如果已经连接
        if (zebraPrinterConnection.isConnected()) {
            try {
                // 获取打印工厂
                printer = ZebraPrinterFactory.getInstance(zebraPrinterConnection);
                // 打印语言
                PrinterLanguage pl = printer.getPrinterControlLanguage();
            } catch (ZebraPrinterConnectionException e) {
                printer = null;
                sleep(100);
                disconnect();
            } catch (ZebraPrinterLanguageUnknownException e) {
                printer = null;
                disconnect();
                sleep(100);
            }
        }
        return printer;
    }

    public void disconnect() {
        if (dialog != null) {
            dialog.dismiss();
            playSound();
            showToast("打印成功");
        }
        try {
            if (zebraPrinterConnection != null) {
                zebraPrinterConnection.close();
            }
            System.out.println("没有连接");
        } catch (ZebraPrinterConnectionException e) {
            System.out.println("连接错误，无连接");
        } finally {
        }
    }


    private void sendTestLabel() {
        try {
            byte[] configLabel = getConfigLabel();
            zebraPrinterConnection.write(configLabel);
            sleep(100);
        } catch (ZebraPrinterConnectionException e) {
        } finally {
            disconnect();
        }
    }

    /*
    */
    private byte[] getConfigLabel() {
        PrinterLanguage printerLanguage = printer.getPrinterControlLanguage();

        byte[] configLabel = null;
        if (printerLanguage == PrinterLanguage.ZPL) {
//
//            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.print);
//            String bitmapstr = BitmapString.convertIconToString(bitmap);

            String str = "";
            if (printFlag) {
                str = getprints() + "^XA" +
                        "^FO60,0^XGR:imgName.GRF,1,1^FS" +
                        "^A0,60,50^FO360,110^^FD" + UiUtlis.getText(etHjh) + "^FS" +
                        "^FO160,200BY3" + "^BCN,110,N,N,N" + "^FD" + UiUtlis.getText(etHjh) + "^FS" +
                        "^PQ" + (UiUtlis.getText(etDysl).equals("") ? "1" : UiUtlis.getText(etDysl)) + ",,,^XZ";
            } else {
                str = getprints() + "^XA" +
                        "^PW950^LL330^FO0,25^XGR:imgName.GRF,1,1^FS" +
                        "^A0,60,50^FO230,110^^FD" + UiUtlis.getText(etHjh) + "^FS" +
                        "^FO160,180BY3" + "^BCN,110,N,N,N" + "^FD" + UiUtlis.getText(etHjh) + "^FS" +
                        "^PQ" + (UiUtlis.getText(etDysl).equals("") ? "1" : UiUtlis.getText(etDysl)) + ",,,^XZ";
            }

//            String str1 = "^XA" + "^FO160,300BY3" + "^BCN,100,N,N,N" + "^FD" + UiUtlis.getText(etHjh) + "^FS" + "^PQ" + (UiUtlis.getText(etDysl).equals("") ? "1" : UiUtlis.getText(etDysl)) + ",,,^XZ";
//            Logger.v("打印数据" + str);
            configLabel = str.getBytes();

        } else if (printerLanguage == PrinterLanguage.CPCL) {
            String cpclConfigLabel = "! 0 200 200 406 1\r\n" + "ON-FEED IGNORE\r\n" + "BOX 20 20 380 380 8\r\n" + "T 0 6 137 177 TEST\r\n" + "PRINT\r\n";
            configLabel = cpclConfigLabel.getBytes();
        }
        return configLabel;
    }


    private String getprints() {
        try {
            String file;
            if (printFlag) {
                file = "print.txt";
            } else {
                file = "printsc.txt";
            }

            InputStream is = getResources().getAssets().open(file);
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader bfr = new BufferedReader(isr);
            StringBuffer sb = new StringBuffer();
            String in = "";
            while ((in = bfr.readLine()) != null) {
                sb.append(in);
            }
            return sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (zebraPrinterConnection != null && zebraPrinterConnection.isConnected()) {
            disconnect();
        }
    }

    private void sleep(long time) {
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void playSound() {
        Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        Ringtone r = RingtoneManager.getRingtone(this, sound);
        r.play();
    }
}