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

import android.os.Looper;
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.entity.PrintInfos;
import com.example.administrator.zhapp.utils.GsonUtils;
import com.example.administrator.zhapp.utils.HttpListener;
import com.example.administrator.zhapp.utils.NohttpUtils;
import com.example.administrator.zhapp.utils.UiUtlis;
import com.example.administrator.zhapp.weight.WaitDialog;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.Response;
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;


public class TestPrintActivity extends BaseActivity {

    EditText etPic;
    EditText etGd;
    EditText etKd;
    EditText etTzgd;
    Button print;

    private String printstr = "";

    private ZebraPrinterConnection zebraPrinterConnection;
    private ZebraPrinter printer;

    private WaitDialog dialog;

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

    @Override
    protected void initView() {
        etPic = findViewById(R.id.et_pic);
        etGd = findViewById(R.id.et_gd);
        etKd = findViewById(R.id.et_kd);
        etTzgd = findViewById(R.id.et_tzgd);
        print = findViewById(R.id.print);

        print.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.show();
                requestPrint();
            }
        });

        dialog = new WaitDialog(context, "打印中...");

        setBack();
        setTitle("测试打印");
    }

    @Override
    protected void initData() {

    }

    private void requestPrint() {
        Request<String> request = NoHttp.createStringRequest(Contans.IP + Contans.PRINT);
        request.set("ponum", "P1602009");
        request.set("itemnum", "IT54274");
        request.set("gd", UiUtlis.getText(etGd));
        request.set("pictype", UiUtlis.getText(etPic));
        request.set("tzgd", UiUtlis.getText(etTzgd));
        request.set("kd", UiUtlis.getText(etKd));
        NohttpUtils.getInstance().add(this, 1, request, callback, false, false, " ");
    }

    /**
     * 结果回调
     */
    private HttpListener<String> callback = new HttpListener<String>() {
        @Override
        public void onSucceed(int what, Response<String> response) {

            try {
                PrintInfos infos = GsonUtils.GsonToBean(response.get(), PrintInfos.class);

                if (infos != null) {
                    if (infos.getTotal() == 1) {

                        printstr = infos.getRows().get(0).getStr();

                        new Thread(new Runnable() {
                            public void run() {
                                Looper.prepare();
                                doConnectionTest();
                                Looper.loop();
                                Looper.myLooper().quit();
                            }
                        }).start();
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        @Override
        public void onFailed(int what, Response<String> response) {
        }
    };


    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 TcpPrinterConnection("10.19.110.19", port);
        } catch (NumberFormatException e) {
            return null;
        }

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

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

    private void sendTestLabel() {
        try {
            //使用for循环打印所要打印的数量
            byte[] configLabel = getConfigLabel();
            // 打印。
            zebraPrinterConnection.write(configLabel);
        } catch (ZebraPrinterConnectionException e) {
        } finally {
            disconnect();
        }
    }

    /*
    */
    private byte[] getConfigLabel() {
        PrinterLanguage printerLanguage = printer.getPrinterControlLanguage();
        byte[] configLabel = null;
        if (printerLanguage == PrinterLanguage.ZPL) {
            String str = printstr + "^XA" +
                    "^FO30,20^XGR:imgName.GRF,2,2^FS"+"^FO380,230^BY3" +
                    "^BCN,130,N,N,N" +
                    "^FD123456^FS" +
                    "^PQ" + "1" + ",,,^XZ";
            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;
    }
}
