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

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Environment;
import android.os.Looper;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.example.administrator.zhapp.BuildConfig;
import com.example.administrator.zhapp.R;
import com.example.administrator.zhapp.activity.BaseActivity;
import com.example.administrator.zhapp.activity.PhotoActivity;
import com.example.administrator.zhapp.adapter.TmdyAdapter;
import com.example.administrator.zhapp.contans.Contans;
import com.example.administrator.zhapp.entity.PrintInfos;
import com.example.administrator.zhapp.entity.PrintIns;
import com.example.administrator.zhapp.entity.StatusInfo;
import com.example.administrator.zhapp.entity.TmdyInfo;
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.SPUtils;
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.yolanda.nohttp.FileBinary;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.RequestMethod;
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.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;


/**
 * 移动仓库管理-条码打印
 */
public class TmdyActivity extends BaseActivity implements TmdyAdapter.CallBack {

    EditText et_wzbm;
    Button btn_query;
    Button btn_print;
    ListView lv;
    ImageView iv_result;
    Button btn_pz;
    Button btn_sc;
    LinearLayout ll;

    private static final int STPZ = 101;

    private void findView() {
        et_wzbm = findViewById(R.id.et_wzbm);
        btn_query = findViewById(R.id.btn_query);
        btn_print = findViewById(R.id.btn_print);
        lv = findViewById(R.id.lv);
        iv_result = findViewById(R.id.iv_result);
        btn_pz = findViewById(R.id.btn_pz);
        btn_sc = findViewById(R.id.btn_sc);
        ll = findViewById(R.id.ll);
        btn_query.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UiUtlis.hideInput(et_wzbm, context);
                if (!TextUtils.isEmpty(UiUtlis.getText(et_wzbm))) {
                    requestData();
                } else {
                    showToast("请输入采购验收单号/物资编号");
                }
            }
        });
        btn_print.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                prints.clear();
                strs.clear();
                if (adapter != null) {
                    //StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < tmdys.size(); i++) {
                        if (tmdys.get(i).isCheck()) {
                            prints.add(tmdys.get(i));
                            //sb.append("项目：" + tmdys.get(i).getItemnum() + "     打印数量：" + tmdys.get(i).getCount() + "\n");
                        }
                    }
                    if (prints.size() != 0) {

                        final PrintSelect printSelect = new PrintSelect(context);
                        printSelect.setCancelOnClick(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                printSelect.close();
                            }
                        });
                        printSelect.setSaveOnClick(v1 -> {
                            if (printSelect.getChecked() == 1) {
                                //办公室打印机的IP
                                printFlag = true;
                                Contans.PRINTIP = "10.19.110.19";
                            } else if (printSelect.getChecked() == 2) {
                                //1号仓库是打印机的IP
                                printFlag = true;
                                Contans.PRINTIP = "10.19.110.220";
                            } else if (printSelect.getChecked() == 3) {
                                //便携打印机的IP
                                printFlag = false;
                                Contans.PRINTIP = "10.19.110.24";
                            }
                            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");
                                }
                            }
                        });
                    } else {
                        showToast("你没有选择要打印的项目");
                    }
                } else {
                    showToast("你没有选择要打印的项目");
                }
            }
        });
        btn_pz.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //"点击了照相";
                //  6.0之后动态申请权限 摄像头调取权限,SD卡写入权限
                if (ContextCompat.checkSelfPermission(TmdyActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(TmdyActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(TmdyActivity.this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, STPZ);
                } else {
                    //有权限,去打开摄像头
                    cropFromTake();
                }
            }
        });
        btn_sc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (tmdys.get(0).isCheck()) {
                    if (flag) {
                        UploadFiles();
                    } else {
                        showToast("你还没有拍照");
                    }
                } else {
                    showToast("你还没有选择项目");
                }
            }
        });
        iv_result.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, PhotoActivity.class);
                intent.putExtra("fileName", lastFileName);
                intent.putExtra("path", path + lastFileName);
                startActivity(intent);
            }
        });
    }

    private View headView;
    private EditText et;
    private TmdyAdapter adapter;
    private List<TmdyInfo.Tmdy> tmdys;

    private String path;
    private String fileName;
    private String lastFileName;

    private boolean flag = false;

    private ZebraPrinterConnection zebraPrinterConnection;
    private ZebraPrinter printer;

    private WaitDialog dialog;
    private List<TmdyInfo.Tmdy> prints;
    private List<PrintIns> strs;

    private boolean printFlag;

    private CheckBox cb;


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

    protected void initView() {
        findView();
    }

    public void initData() {

        setTitle("条码打印");
        setBack();

        et_wzbm.setText("IT");

        strs = new ArrayList<>();
        tmdys = new ArrayList<>();
        prints = new ArrayList<>();
        dialog = new WaitDialog(context, "打印中...");
        //et_wzbm.setText("IT26206");
        headView = View.inflate(this, R.layout.tmdy_item, null);
        et = (EditText) headView.findViewById(R.id.et_dysl);
        et.setVisibility(View.GONE);
        headView.findViewById(R.id.tv_dysl).setVisibility(View.VISIBLE);
        headView.findViewById(R.id.head).setVisibility(View.VISIBLE);
        cb = (CheckBox) headView.findViewById(R.id.cb_isprint);

        cb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (cb.isChecked()) {
                    for (int i = 0; i < tmdys.size(); i++) {
                        tmdys.get(i).setCheck(true);
                        adapter.notifyDataSetChanged();
                    }
                } else {
                    for (int i = 0; i < tmdys.size(); i++) {
                        tmdys.get(i).setCheck(false);
                        adapter.notifyDataSetChanged();
                    }
                }
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {

            flag = true;
            switch (requestCode) {
                case 9:
                    carpImageUri();
                    break;
                case 8:
                    Bitmap bitmap = BitmapFactory.decodeFile(path + fileName);
                    iv_result.setImageBitmap(bitmap);
                    lastFileName = fileName;
                    break;
            }
        }
    }

    /**
     * 剪切图片
     */
    private void carpImageUri() {

//        Uri uri = Uri.fromFile(new File(path + fileName));
        Uri uri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileProvider", new File(path + fileName));
        Uri outPutUri = Uri.fromFile(new File(path + fileName));
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 3);
        intent.putExtra("aspectY", 4);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outPutUri);
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        startActivityForResult(intent, 8);
    }

    private void cropFromTake() {

        fileName = DateFormat.format("yyyyMMdd_HHmmss", Calendar.getInstance(Locale.CANADA)) + ".jpg";
        // 跳转至拍照界面
        path = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "/com.rehome.ydapp/images/";
        File fos = new File(path + fileName);
//        Uri u = Uri.fromFile(fos);
        Uri u = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileProvider", fos);
        Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        i.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
        i.putExtra(MediaStore.EXTRA_OUTPUT, u);
        startActivityForResult(i, 9);
    }

    private void requestData() {
        Request<String> request = NoHttp.createStringRequest(Contans.IP + Contans.TMDY);
        request.add("PONUM", UiUtlis.getText(et_wzbm));
        NohttpUtils.getInstance().add(TmdyActivity.this, 0, request, callback, true, true, "加载中...");
    }

    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(this, 2, request, callback, false, false, " ");
    }

    private void UploadFiles() {
        Request<String> request = NoHttp.createStringRequest(Contans.IP + Contans.TMDYSC + "fname=" + lastFileName +
                "&ponum=" + tmdys.get(0).getPonum() + "&itemnum=" + tmdys.get(0).getItemnum() +
                "&uname=" + SPUtils.get(context, Contans.USERNAME, ""), RequestMethod.POST);
        request.add(Contans.FILEPS, new FileBinary(new File(path + lastFileName)));
        NohttpUtils.getInstance().add(TmdyActivity.this, 1, request, callback, true, true, "上传中...");
    }


    private HttpListener<String> callback = new HttpListener<String>() {
        @Override
        public void onSucceed(int what, Response<String> response) {

            switch (what) {
                case 0:
                    TmdyInfo info = GsonUtils.GsonToBean(response.get(), TmdyInfo.class);
                    if (info != null) {
                        if (info.getTotal() != 0) {
                            tmdys.clear();
                            ll.setVisibility(View.VISIBLE);
                            tmdys.addAll(info.getRows());
                            setListData();
                        } else {
                            ll.setVisibility(View.GONE);
                            showToast("没有查到该条数据");
                            tmdys.clear();
                            if (lv.getHeaderViewsCount() == 1) {
                                lv.removeHeaderView(headView);
                            }
                            if (adapter != null) {
                                adapter.notifyDataSetChanged();
                            }
                        }
                    } else {
                        showToast(UiUtlis.getString(context, R.string.data_error));
                    }
                    break;
                case 1:
                    StatusInfo info1 = GsonUtils.GsonToBean(response.get(), StatusInfo.class);

                    if (info1 != null) {
                        String status = info1.getRows().get(0).getStatus();
                        if (status.equals("1")) {
                            showToast(UiUtlis.getString(context, R.string.upload_success));
                        } else if (status.equals("0")) {
                            showToast(UiUtlis.getString(context, R.string.upload_error));
                        }
                    } else {
                        showToast("解析数据出错");
                    }
                    break;

                case 2:
                    try {
                        PrintInfos printInfos = GsonUtils.GsonToBean(response.get(), PrintInfos.class);
                        if (printInfos != null) {
                            if (printInfos.getTotal() == 1) {
                                PrintIns ins = new PrintIns();
                                ins.setStr(printInfos.getRows().get(0).getStr());
                                ins.setItemnum(printInfos.getRows().get(0).getItemnum());
                                strs.add(ins);
                            }
                        }

                        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();
                        }

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

                    //Logger.v("打印数据" + response.get());
                    //showToast(response.get());
                    break;
            }
        }

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

    //显示查询结果
    private void setListData() {

        if (lv.getHeaderViewsCount() != 1) {
            lv.addHeaderView(headView, null, false);
        }
        if (adapter == null) {
            adapter = new TmdyAdapter(tmdys, TmdyActivity.this, TmdyActivity.this);
            lv.setAdapter(adapter);
            adapter.notifyDataSetChanged();
        } else {
            adapter.notifyDataSetChanged();
        }
    }


    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();
            showToast("打印成功");
        }
        try {
            if (zebraPrinterConnection != null) {
                zebraPrinterConnection.close();
            }

            showToast("没有连接");
        } catch (ZebraPrinterConnectionException e) {
            showToast("连接错误，无连接");
        } finally {
        }
    }


    private void sendTestLabel() {
        try {
            for (int i = 0; i < prints.size(); i++) {
                byte[] configLabel = getConfigLabel(prints.get(i).getStr(), prints.get(i).getCount(), prints.get(i).getItemnum());
                // 打印。测试
//                byte[] configLabel = getConfigLabel(strs.get(i).getStr(), "1", strs.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) {
            String count = page.isEmpty() ? "1" : page;
            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" + count + ",,,^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" + count + ",,,^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;
    }

    @Override
    public void Click(View view) {

        CheckBox checkBox = (CheckBox) view;
        int index = (int) checkBox.getTag();
        tmdys.get(index).setCheck(checkBox.isChecked());
        int count = 0;
        for (int a = 0; a < tmdys.size(); a++) {
            if (tmdys.get(a).isCheck()) {
                count++;
            }
        }
        cb.setChecked(count == tmdys.size());
        adapter.notifyDataSetChanged();
    }

    @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();
        }
    }

}