package xn.hxp.weidith.prin_label_dialog;

import android.content.Context;
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.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.ClickUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.kongzue.dialogx.dialogs.PopTip;
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.rc.httpcore.bean.TopicDataBean;

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

import xn.hxp.R;
import xn.hxp.databinding.DialogPrintLabelBinding;
import xn.hxp.ui.PrintBean;
import xn.hxp.ui.adapter.LabelDialogAdapter;
import xn.hxp.ui.plan.room.bean.input_add.InventoryItemBean;
import xn.hxp.utils.PrintTool;

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 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.getNetContent();
        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);
                }
                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));
                            PopTip.show("删除失败!");
                        }
                    }
                });
            }
        });

        // 关闭
        binding.butClos.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
            @Override
            public void onDebouncingClick(View v) {
                dismiss();
                printLabelCallBack.close();
            }
        });

        // 确定
        binding.determine.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
            @Override
            public void onDebouncingClick(View 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);
                            int belongType = hxpChemicalVo.getBelongType();
                            String name = "";
                            // 归属人
                            if (belongType == 2) {
                                BelongingPersonBean belongingPersonBean = inventoryItemBean.getBelongingPersonBean();
                                name = belongingPersonBean.getUserName();
                            }
                            // 课题组
                            else if (belongType == 1) {
                                TopicDataBean topicDataBean = inventoryItemBean.getTopicDataBean();
                                name = topicDataBean.getTopicName();
                            }
                            printBean.setPerson(TextUtils.isEmpty(name) ? "" : name);
                            // 管控非管控
//                        int chemicalLevel = hxpChemicalVo.getChemicalLevel();
//                        printBean.setLevel(1 == chemicalLevel ? "管控" : "非管控");
                            // 化学品类型
                            CharSequence chemicalCategory = hxpChemicalVo.getChemicalCategoryName();
                            printBean.setTypes(TextUtils.isEmpty(chemicalCategory) ? "" : chemicalCategory.toString());
                            // 打印
                            if (isPrint) {
                                LogUtils.json("打印机前", labelList);
                                PrintTool.INSTANCE.print(hxpChemicalVo.isGr(), belongType == 2, printBean);
                            }
                            Thread.sleep(200);
                        }
                        return null;
                    }

                    @Override
                    public void onSuccess(Object result) {
                        printState(false);
                        hxpChemicalVo.setStockDetailsModelList(labelList);
                        printLabelCallBack.confirm();
                        dismiss();
                    }

                    @Override
                    public void onFail(Throwable t) {
                        super.onFail(t);
                        PopTip.show("打印失败,已打印标签无效,请重试!");
                        printLabelCallBack.close();
                        dismiss();
                        LogUtils.e(Log.getStackTraceString(t));
                    }
                });
            }
        });
    }

    /**
     * 打印状态切换
     */
    private void printState(boolean isPrinting) {
        if (isPrinting) {
            binding.loadingLL.setVisibility(View.VISIBLE);
            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);
        }
    }

    public interface PrintLabelCallBack {
        void confirm();

        void close();
    }

}
