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

import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Looper;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import com.example.administrator.zhapp.R;
import com.example.administrator.zhapp.entity.PrintInfos;
import com.example.administrator.zhapp.entity.PrintIns;
import com.example.administrator.zhapp.entity.PrintStringInfo;
import com.example.administrator.zhapp.fragment.BaseFragment;
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.activity.ydckgl.MateLablePrint;
import com.example.administrator.zhapp.adapter.PoInfoadapter;
import com.example.administrator.zhapp.contans.Contans;
import com.example.administrator.zhapp.entity.PrintInfo;
import com.example.administrator.zhapp.utils.UiUtlis;
import com.example.administrator.zhapp.weight.PrintSelect;
import com.example.administrator.zhapp.weight.WaitDialog;
import com.google.gson.Gson;
import com.orhanobut.logger.Logger;
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;
import java.util.ArrayList;
import java.util.List;

/**
 * 移动仓库管理-标签打印
 */
public class MateLablePrintFragment extends BaseFragment implements PoInfoadapter.CallBack {

    ListView lv;
    EditText et_cgd;
    Button btn_query;
    Button btn_print;


    @Override
    protected void initView() {

        dialog = new WaitDialog(context, "打印中...");
        mActivity = (MateLablePrint) getActivity();
        mActivity.getToolbar().setText("物料标签打印");
        headView = View.inflate(getContext(), R.layout.po_lv_item, null);
        headView.findViewById(R.id.head).setVisibility(View.VISIBLE);
        et = (EditText) headView.findViewById(R.id.et_dysl);
        et.setVisibility(View.GONE);
        headView.findViewById(R.id.tv_dysl).setVisibility(View.VISIBLE);
        checkBox = (CheckBox) headView.findViewById(R.id.cb_isprint);
        checkBox.setChecked(false);
        lv = (ListView) view.findViewById(R.id.lv);
        et_cgd = (EditText) view.findViewById(R.id.et_cgd);
        btn_query = view.findViewById(R.id.btn_query);
        btn_print = view.findViewById(R.id.btn_print);

        btn_query.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //隐藏软键盘
                UiUtlis.hideInput(et_cgd, context);

                String gdh = et_cgd.getText().toString().trim();
                if (TextUtils.isEmpty(gdh)) {
                    showToast("你没有输入采购单号");
                } else {
                    sendNohttpRequest(gdh);
                }
            }
        });
        btn_print.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //System.out.println("打印的数据" + getString());
                prints.clear();
                strs.clear();
                if (polist != null) {
                    for (int i = 0; i < polist.size(); i++) {
                        if (polist.get(i).isPrint()) {
                            prints.add(polist.get(i));
                        }
                    }
                    if (prints.size() != 0) {
                        final PrintSelect printSelect = new PrintSelect(context);
                        printSelect.setSaveOnClick(new View.OnClickListener() {
                            @Override
                            public void onClick(View 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.show();
                                //开启一个线程连接打印机打印条码

                                for (int i = 0; i < prints.size(); i++) {

                                    if (printFlag) {
                                        requestPrint(prints.get(i).getPonum(), prints.get(i).getItemnum(), "1");
                                    } else {
                                        requestPrint(prints.get(i).getPonum(), prints.get(i).getItemnum(), "2");
                                    }
                                }

//                                new Thread(new Runnable() {
//                                    public void run() {
//                                        Looper.prepare();
//                                        doConnectionTest();
//                                        Looper.loop();
//                                        Looper.myLooper().quit();
//                                    }
//                                }).start();
                            }
                        });
                        printSelect.setCancelOnClick(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                printSelect.close();
                            }
                        });

                    } else {
                        showToast("你没有选择要打印的项目");
                    }
                } else {
                    showToast("没有需要打印的项目");
                }
            }
        });
    }


    private WaitDialog dialog;

    private TextView tv;
    private MateLablePrint mActivity;
    private PoInfoadapter mAdapter;
    private View headView;
    private EditText et;
    private CheckBox checkBox;
    private List<PrintInfo.PrintBean> polist;
    private List<PrintInfo.PrintBean> prints;

    private ZebraPrinterConnection zebraPrinterConnection;
    private ZebraPrinter printer;

    private List<PrintStringInfo> printStrs;
    private List<PrintIns> strs;

    private boolean printFlag;


    public MateLablePrintFragment() {
    }

    public static MateLablePrintFragment newInstance() {
        MateLablePrintFragment fragment = new MateLablePrintFragment();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public int getContentViewId() {
        return R.layout.fragment_mate_lable_print;
    }




    public void initData() {
        polist = new ArrayList<>();
        prints = new ArrayList<>();
        printStrs = new ArrayList<>();
        strs = new ArrayList<>();
        checkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean b = checkBox.isChecked();
                for (int i = 0; i < polist.size(); i++) {
                    polist.get(i).setPrint(b);
                }
                mAdapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    /**
     * checkBox点击事件
     */
    @Override
    public void onChanged(View view) {
        CheckBox cb = (CheckBox) view;
        int checkitem = (int) cb.getTag();
        polist.get(checkitem).setPrint(cb.isChecked());
        int count = 0;
        for (int i = 0; i < polist.size(); i++) {
            if (polist.get(i).isPrint() == false) {
                count++;
            }
        }
        if (count == 0) {
            checkBox.setChecked(true);
        } else {
            checkBox.setChecked(false);
        }

        mAdapter.notifyDataSetChanged();
    }

    private void sendNohttpRequest(String gdh) {
        Request<String> request = NoHttp.createStringRequest(Contans.IP + Contans.WLBQDY);
        request.set("ponum", gdh);
        NohttpUtils.getInstance().add(getActivity(), 0, request, callback, true, true, UiUtlis.getString(getContext(), R.string.loading));
    }

    private void requestPrint(String ponum, String itemnum, String pirType) {
        Request<String> request = NoHttp.createStringRequest(Contans.IP + Contans.PRINT);
        request.set("ponum", ponum);
        request.set("itemnum", itemnum);
        request.set("gd", "250");
        request.set("pictype", "2");
        if (pirType.equals("1")) {
            request.set("tzgd", "250");
        } else {
            request.set("tzgd", "280");
        }

        request.set("kd", "520");
        request.set("priType", pirType);
        NohttpUtils.getInstance().add(getActivity(), 1, request, callback, false, false, " ");
    }

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

            try {

                switch (what) {

                    case 0:
                        PrintInfo info = new PrintInfo();
                        String json = response.get();
                        Gson gson = new Gson();
                        info = gson.fromJson(json, PrintInfo.class);
                        if (info != null) {
                            if (info.getTotal() == 0) {
                                showToast("没有查到该条数据");
                                if (mAdapter != null) {
                                    polist.clear();
                                    if (lv.getHeaderViewsCount() == 1) {
                                        lv.removeHeaderView(headView);
                                    }
                                    mAdapter.notifyDataSetChanged();
                                }
                            } else {
                                polist.clear();
                                polist.addAll(info.getRows());
                                if (mAdapter == null) {
                                    mAdapter = new PoInfoadapter(polist, getContext(), MateLablePrintFragment.this);
                                    lv.setAdapter(mAdapter);
                                } else {
                                    mAdapter.notifyDataSetChanged();
                                }

                                if (lv.getHeaderViewsCount() != 1) {
                                    lv.addHeaderView(headView, null, false);
                                }
                            }
                        } else {
                            showToast(UiUtlis.getString(context, R.string.data_error));
                        }
                        break;
                    case 1:

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

                            if (infos != null) {
                                if (infos.getTotal() == 1) {
                                    PrintIns ins = new PrintIns();
                                    ins.setStr(infos.getRows().get(0).getStr());
                                    ins.setItemnum(infos.getRows().get(0).getItemnum());
                                    strs.add(ins);
                                }
                            }

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

//                    strs.add(response.get());
//
//                    String str = response.get() + "^XA" +
//                            "^FO50,50^XGR:imgName.GRF,1,1^FS" +
//                            "^PQ" + 1 + ",,,^XZ";
////
//                    Logger.v("打印数据" + str);

                        if (strs.size() == prints.size()) {

                            for (int i = 0; i < strs.size(); i++) {
                                for (int j = 0; j < prints.size(); j++) {
                                    if (strs.get(i).getItemnum().equals(prints.get(j).getItemnum())) {
                                        prints.get(j).setStr(strs.get(i).getStr());
                                    }
                                }
                            }

                            //开始打印
                            new Thread(new Runnable() {
                                public void run() {
                                    Looper.prepare();
                                    doConnectionTest();
                                    Looper.loop();
                                    Looper.myLooper().quit();
                                }
                            }).start();
                        }
//                    Logger.v("打印数据" + response.get());
//                    showToast(response.get());
                        break;
                }
            } catch (Exception e) {
                showToast("数据出错");
                e.printStackTrace();
            }
        }

        @Override
        public void onFailed(int what, Response<String> response) {
            if (dialog != null && dialog.isShowing()) {
                dialog.dismiss();
            }
        }
    };


    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(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;
                sleep(100);
                disconnect();
            }
        }
        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 {
            //使用for循环打印所要打印的数量
            for (int i = 0; i < prints.size(); i++) {
                byte[] configLabel = getConfigLabel(prints.get(i).getStr(), prints.get(i).getPrintCount(), prints.get(i).getItemnum());
                // 打印。
                zebraPrinterConnection.write(configLabel);
                sleep(100);
            }
        } catch (ZebraPrinterConnectionException e) {
        } finally {
            disconnect();
        }
    }

    /*
    */
    private byte[] getConfigLabel(String itnum, String page, String itemnum) {
        PrinterLanguage printerLanguage = printer.getPrinterControlLanguage();
        byte[] configLabel = null;
        if (printerLanguage == PrinterLanguage.ZPL) {
            //configLabel = "^XA^FO17,16^GB379,371,8^FS^FT65,255^A0N,135,134^FDTEST^FS^XZ".getBytes();
            //String str = "^XA^LH60,60^FO200,160^AF^ABN,30,30^FD珠海发电厂^FS^FO120,120^B3,,80,,^FD" + itnum + "^FS" + "^PQ" + page + ",,,^XZ";
            //configLabel = str.getBytes();

            String str;
            if (printFlag) {
                str = itnum + "^XA" +
                        "^FO10,0^XGR:imgName.GRF,2,2^FS" + "^FO380,250^BY3" +
                        "^BCN,120,N,N,N" +
                        "^FD" + itemnum + "^FS" +
                        "^PQ" + page + ",,,^XZ";
            } else {
                str = itnum + "^XA" +
                        "^PW950^LL330^FO40,40^XGR:imgName.GRF,1,1^FS" + "^FO180,160BY3" +
                        "^BCN,60,N,N,N" +
                        "^FD" + itemnum + "^FS" +
                        "^PQ" + page + ",,,^XZ";
            }

            Logger.v("打印数据" + str);


            configLabel = str.getBytes();
            //configLabel = getString().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;
    }

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

    //    /**
//     * 3
//     *
//     * @return
//     */
//    private String getString() {
//
//        String str = "^XA" +
//                "^CI14" +
//                "^SEE:GB.DAT" +
//                "^CW1,E:MSUNG24.FNT" +
//                "^CI14" +
//                "^FO30,20" + BitmapString.convertIconToString(BitmapFactory.decodeResource(context.getResources(), R.mipmap.logo)) +
//                "^FO80,20" + BitmapString.convertStringToIcon("广东省粤电集团有限公司珠海发电厂", "dc") +
//                "^FO80,60^AF^ABN,10,10^FD ZHUHAI POWER STATION OF GUANGDONG YUDEANGROUPCO,LTD ^FS" +
//                "^FO40,80" + BitmapString.convertStringToIcon("脱硫循环" + "", "tlxh") +
//                "^FO40,120" + BitmapString.convertStringToIcon("风机型号:" + "", "fjxh") +
//                "^FO400,80^AF^ABN,30,30^FD PO:p1602009 ^FS" +
//                "^FO200,160^BY2,3,50^BCN,90,N,N,N,A^FD" + "IT51242" + "^FS" +//条码
//                "^FO40,300" + BitmapString.convertStringToIcon("专业:" + "码头专业", "zy") +
//                "^FO240,300" + BitmapString.convertStringToIcon("申请:" + "码头专业", "sq") +
//                "^FO400,280^AF^ABN,30,30^FD 接收 ^FS" +
//                "^FO400,315^AF^ABN,30,30^FD 时间 ^FS" +
//                "^FO470,300^AF^ABN,30,30^FD 16.11.02 ^FS" + "^PQ" + "1" + ",,,^XZ";
//
//        String str1 = BitmapString.convertIconToString(BitmapFactory.decodeResource(context.getResources(), R.mipmap.logo)) +
//                BitmapString.convertStringToIcon("广东省粤电集团有限公司珠海发电厂", "DC") +
//                BitmapString.convertStringToIcon("脱硫循环" + "", "TLXH") +
//                BitmapString.convertStringToIcon("风机型号:" + "", "FJXH") +
//                BitmapString.convertStringToIcon("专业:" + "码头专业", "ZY") +
//                BitmapString.convertStringToIcon("申请:" + "码头专业", "SQ") +
//                "^XA" +
//                "^FO30,20" + "^XGR:AA.GRF,1,1^FS" +
//                "^FO80,20" + "^XGR:DC.GRF,1,1^FS" +
//                "^FO80,60^AF^ABN,10,10^FD ZHUHAI POWER STATION OF GUANGDONG YUDEANGROUPCO,LTD ^FS" +
//                "^FO40,80" + "^XGR:TLXH.GRF,1,1^FS" +
//                "^FO40,120" + "^XGR:FJXH.GRF,1,1^FS" +
//                "^FO400,80^AF^ABN,30,30^FD PO:p1602009 ^FS" +
//                "^FO200,160^BY2,3,50^BCN,90,N,N,N,A^FD" + "IT51242" + "^FS" +//条码
//                "^FO40,300" + "^XGR:ZY.GRF,1,1^FS" +
//                "^FO240,300" + "^XGR:SQ.GRF,1,1^FS" +
//                "^FO400,280^AF^ABN,30,30^FD 接收 ^FS" +
//                "^FO400,315^AF^ABN,30,30^FD 时间 ^FS" +
//                "^FO470,300^AF^ABN,30,30^FD 16.11.02 ^FS" + "^PQ" + "1" + ",,,^XZ";
//
//
//        String test = BitmapString.convertIconToString(BitmapFactory.decodeResource(context.getResources(), R.mipmap.logo));
//
//        String aa =
//                "^XA" +
//                        "^FO80,20^AF^ABN,40,40^FD 广东省粤电集团有限公司珠海发电厂 ^FS" +
//                        "^FO80,60^AF^ABN,10,10^FD ZHUHAI POWER STATION OF GUANGDONG YUDEANGROUPCO,LTD ^FS" +
//                        "^FO40,80^AF^ABN,30,30^FD脱硫循环XXXXXXX^FS" +
//                        "^FO40,120^AF^ABN,30,30^FD风机型号:SWF-T^FS" +
//                        "^FO400,80^AF^ABN,30,30^FD PO:p1602009 ^FS" +
//                        "^FO200,160^BY2,3,50^BCN,90,N,N,N,A^FDIT25154^FS" +
//                        "^FO40,300^AF^ABN,30,30^FD 专业：电器专业 ^FS" +
//                        "^FO240,300^AF^ABN,30,30^FD 申请：MEL ^FS" +
//                        "^FO400,280^AF^ABN,30,30^FD 接收 ^FS" +
//                        "^FO400,315^AF^ABN,30,30^FD 时间 ^FS" +
//                        "^FO470,300^AF^ABN,30,30^FD 16.11.02 ^FS" +
//                        "^XZ";
//
//        String bb = "^XA" +
//                "^LH0,0" +
//                "^FO203,203" +
//                "^ABN,30,30" +
//                "^FDExample^FS" +
//                "^XZ";
//
//        String cc = BitmapString.convertIconToString(BitmapFactory.decodeResource(context.getResources(), R.mipmap.logo)) +
//                "^XA" +
//                "^F050,50^XGR:AA.GRF,3,3^FS" +
//                "^XZ";
//        Logger.v(cc);
//
//        String cesi = BitmapString.convertStringToIcon("广东省粤电集团有限公司珠海发电厂", "DC") +
//                "^XA" +
//                "^F050,50^XGR:DC.GRF,3,3^FS" +
//                "^XZ";
//        return cc;
//    }

    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(context, sound);
        r.play();
    }

}