package com.example.chemical.weidith.prin_label_dialog;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatDialog;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.caysn.autoreplyprint.AutoReplyPrint;
import com.example.chemical.R;
import com.example.chemical.databinding.DialogPrintLabelBinding;
import com.example.chemical.receiver.UsbReceiver;
import com.example.chemical.ui.PrintBean;
import com.example.chemical.ui.adapter.LabelDialogAdapter;
import com.example.chemical.ui.plan.room.bean.input_add.InventoryItemBean;
import com.example.chemical.utils.AudioPlayer;
import com.example.chemical.utils.BitmapUtils;
import com.rc.httpcore.HttpConfig;
import com.rc.httpcore.bean.BelongingPersonBean;
import com.rc.httpcore.bean.HxpChemicalVo;
import com.rc.httpcore.bean.StockDetailsModel;
import com.sun.jna.Pointer;

import java.util.ArrayList;
import java.util.List;

public class PrintLabelDialog extends AppCompatDialog {
    // RFID广播接收器
    private Context context;
    private DialogPrintLabelBinding binding;
    private PrintLabelCallBack printLabelCallBack;
    // 待存储清单Item
    private InventoryItemBean inventoryItemBean;
    // 存储位置
    private String planPath;

    private List<StockDetailsModel> labelList = new ArrayList<>();
    private LabelDialogAdapter labelDialogAdapter;

    private Pointer pointer = Pointer.NULL;
    private boolean isPrint;

    /**
     * @param inventoryItemBean 清单item
     * @param planPath          存储位置
     */
    public PrintLabelDialog(@NonNull Context context, InventoryItemBean inventoryItemBean, String planPath, boolean isPrint, PrintLabelCallBack printLabelCallBack) {
        super(context);
        this.context = context;
        this.inventoryItemBean = inventoryItemBean;
        this.planPath = planPath;
        this.printLabelCallBack = printLabelCallBack;
        this.isPrint = isPrint;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        binding = DialogPrintLabelBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        Window window = getWindow();
        if (null != window) {
            window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            window.setGravity(Gravity.CENTER);
            window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
        }
        setCanceledOnTouchOutside(false);
        setCancelable(false);

        HxpChemicalVo hxpChemicalVo = inventoryItemBean.getHxpChemicalVo();
        // 化学品名
        String chemicalName = hxpChemicalVo.getChemicalName();
        binding.chemicalName.setText(TextUtils.isEmpty(chemicalName) ? "" : chemicalName);
        // 总标签数
        binding.sumTV.setText("共  " + inventoryItemBean.getSize() + "  张");
        // 净含量
        double netWt = hxpChemicalVo.getNetWt();
        binding.netWtTV.setText("净含量:" + netWt + hxpChemicalVo.getSpecUnit());
        // 存储位置
        binding.layerTV.setText(planPath);
        ThreadUtils.executeByCached(new ThreadUtils.SimpleTask<Object>() {
            @Override
            public Object doInBackground() throws Throwable {
                // 数量
                int size = inventoryItemBean.getSize();
                for (int i = 0; i < size; i++) {
                    String code = "ZJ" + System.currentTimeMillis();
                    String wxCode = HttpConfig.Companion.getAPI_BASE_QC_URL() + "?code=" + code + "&type=9";
                    int no = i + 1;
                    labelList.add(new StockDetailsModel(null, null, code, no, wxCode));
                    Thread.sleep(10);
                }
                LogUtils.d(labelList);
                return null;
            }

            @Override
            public void onSuccess(Object result) {
                binding.rvView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
                labelDialogAdapter = new LabelDialogAdapter();
                binding.rvView.setAdapter(labelDialogAdapter);
                labelDialogAdapter.setList(labelList);
                // 删除条目
                labelDialogAdapter.setOnItemChildClickListener((adapter, view, position) -> {
                    if (view.getId() == R.id.imgDelete) {
                        try {
                            if (labelList.size() == 1) {
                                throw new Exception();
                            }
                            labelList.remove(position);
                            for (int i = 0; i < labelList.size(); i++) {
                                labelList.get(i).setNo(++i);
                            }
                            labelDialogAdapter.setList(labelList);
                            binding.sumTV.setText("共  " + labelList.size() + "  张");
                        } catch (Exception e) {
                            LogUtils.e(Log.getStackTraceString(e));
                            ToastUtils.showLong("删除失败!");
                        }
                    }
                });
            }
        });

        // 关闭
        binding.butClos.setOnClickListener(v -> {
            dismiss();
            printLabelCallBack.close();
        });

        // 确定
        binding.determine.setOnClickListener(v -> {
            printState(true);
            ThreadUtils.executeByCached(new ThreadUtils.SimpleTask<Object>() {
                @Override
                public Object doInBackground() throws Throwable {
                    for (int i = 0; i < labelList.size(); i++) {
                        StockDetailsModel stockDetailsModel = labelList.get(i);
                        PrintBean printBean = new PrintBean();
                        // 化学品编码
                        String tagCode = stockDetailsModel.getTagCode();
                        printBean.setTag(TextUtils.isEmpty(tagCode) ? "" : tagCode);
                        // 二维码
                        String wxCode = stockDetailsModel.getWxCode();
                        printBean.setWxCode(TextUtils.isEmpty(wxCode) ? "" : wxCode);
                        // 化学品名
                        printBean.setName(TextUtils.isEmpty(chemicalName) ? "" : chemicalName);
                        // CAS
                        String casNum = hxpChemicalVo.getCasNum();
                        printBean.setCasNo(TextUtils.isEmpty(casNum) ? "" : casNum);
                        // 归属人
                        BelongingPersonBean belongingPersonBean = inventoryItemBean.getBelongingPersonBean();
                        String belongingPersonUserName = belongingPersonBean.getUserName();
                        printBean.setPerson(TextUtils.isEmpty(belongingPersonUserName) ? "" : belongingPersonUserName);
                        // 管控非管控
                        int chemicalLevel = hxpChemicalVo.getChemicalLevel();
                        printBean.setLevel(1 == chemicalLevel ? "管控" : "非管控");
                        // 化学品类型
                        CharSequence chemicalCategory = hxpChemicalVo.getChemicalCategoryName();
                        printBean.setTypes(TextUtils.isEmpty(chemicalCategory) ? "" : chemicalCategory.toString());
                        // 打印
                        if (isPrint) {
                            printLabel(printBean);
                        }
                    }
                    return null;
                }

                @Override
                public void onSuccess(Object result) {
                    printState(false);
                    printLabelCallBack.confirm();
                    dismiss();
                }
            });
        });
        // 请扫描标签音频播放
        AudioPlayer.getInstance().play(R.raw.saomiaobiaoqian);
    }

    /**
     * 打印状态切换
     */
    private void printState(boolean isPrinting) {
        if (isPrinting) {
            binding.loadingLL.setVisibility(View.VISIBLE);
            binding.loadingLL.setOnClickListener(v1 -> {
            });
            binding.determine.setClickable(false);
            binding.butClos.setClickable(false);
        } else {
            binding.loadingLL.setVisibility(View.GONE);
            binding.loadingLL.setOnClickListener(null);
            binding.determine.setClickable(true);
            binding.butClos.setClickable(true);
        }
    }

    // 打印
    private void printLabel(PrintBean printBean) {
        try {
            if (pointer == Pointer.NULL) {
                pointer = AutoReplyPrint.INSTANCE.CP_Port_OpenUsb("VID:0x0FE6,PID:0x811E", 1);
            }
            Bitmap bitmap = BitmapUtils.INSTANCE.generateBitmap(printBean);
            AutoReplyPrint.INSTANCE.CP_Label_BackPaperToPrintPosition(pointer);
            AutoReplyPrint.CP_Pos_PrintRasterImageFromData_Helper.PrintRasterImageFromBitmap(pointer,
                    bitmap.getWidth(),
                    bitmap.getHeight(),
                    bitmap,
                    AutoReplyPrint.CP_ImageBinarizationMethod_Thresholding,
                    AutoReplyPrint.CP_ImageCompressionMethod_None
            );
            AutoReplyPrint.INSTANCE.CP_Label_PagePrint(pointer, 1);
            if (AutoReplyPrint.INSTANCE.CP_Pos_HalfCutPaper(pointer)) {
                AudioPlayer.getInstance().play(R.raw.huaxuepinbiaoqian);
            }
        } catch (Exception e) {
            LogUtils.e(Log.getStackTraceString(e));
        }
    }

    public interface PrintLabelCallBack {
        void confirm();

        void close();
    }
}
