package com.philisense.rdgo.ui.putOut;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.text.method.DigitsKeyListener;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.xrecyclerview.XRecyclerView;
import com.philisense.rdgo.R;
import com.philisense.rdgo.adapter.delteAdapter;
import com.philisense.rdgo.adapter.digaoAddAdapter;
import com.philisense.rdgo.base.BaseActivity;
import com.philisense.rdgo.bean.MyOutBoxBean;
import com.philisense.rdgo.bean.OError;
import com.philisense.rdgo.bean.response.BaseBean;
import com.philisense.rdgo.bean.response.BoxInfoBean;
import com.philisense.rdgo.bean.response.OrderDetailBean;
import com.philisense.rdgo.bean.response.PileBoxBean;
import com.philisense.rdgo.bean.response.PileInfoBean;
import com.philisense.rdgo.databinding.ActivityPutOutOrderBinding;
import com.philisense.rdgo.http.RequestImpl;
import com.philisense.rdgo.http.cache.ACache;
import com.philisense.rdgo.ui.lineIn.LineInActivity;
import com.philisense.rdgo.util.CodeParsingUtil;
import com.philisense.rdgo.util.TreeNodeInsertListener;
import com.philisense.rdgo.view.OrderBoxViewHolder;
import com.philisense.rdgo.view.OrderViewHolder;
import com.philisense.rdgo.viewModel.PutOutOrderViewModel;
import com.scandecode.ScanDecode;
import com.scandecode.inf.ScanInterface;
import com.unnamed.b.atv.model.TreeNode;
import com.unnamed.b.atv.view.AndroidTreeView;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import io.reactivex.functions.Consumer;

public class PutOutOrderActivity extends BaseActivity<ActivityPutOutOrderBinding> implements Toolbar.OnMenuItemClickListener {

    // 本页面扫描选项
    enum ScanOption {
        SCAN_OPTION_DELETE,
        SCAN_OPTION_ADD
    }

    public PutOutOrderViewModel viewModel;
    public AndroidTreeView tView;
    private ScanDecode scanDecode;
    private String orderId;

    private ScanOption scanOption;
    private TreeNodeInsertListener insertListener;
    public Map<String, TreeNode> nodeMap; // key 为油种类+订单号，val 为 node
    public Map<String, List<String>> oilMap; // key 为油种类，val 为 nodeMap 的keys
    public Map<String, TreeNode> boxMap; // key 油的 Id，val 无所谓，主要用于判断是否有重复
    private Map<String, BoxInfoBean> bendi;

    private int assistValue = 0; // 用于生成虚拟码后缀
    private ProgressDialog progressDialog;
    private AlertDialog alertDialog;
    ACache aCache;
//    private boolean bten = false;


    private List<MyOutBoxBean> mydelte;

    private List<OrderDetailBean.DataBean> distributions;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_put_out_order);
        if (getIntent() != null) {
            orderId = getIntent().getStringExtra("orderId");
        }


        aCache = ACache.get(PutOutOrderActivity.this);


        distributions = (List<OrderDetailBean.DataBean>) aCache.getAsObject("distributions");
        if (distributions == null) {
            distributions = new ArrayList<>();
        }


        // 初始化箱字典
        boxMap = new HashMap<>();

        // 初始化各类弹窗
        progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("提示");
        progressDialog.setMessage("读取中");


        // 初始化 toolbar
        Toolbar toolbar = bindingView.include.toolbar;
        toolbar.setTitle("扫码出库");
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                showExitAlert();
            }
        });
        toolbar.setOnMenuItemClickListener(this);

        // 初始化扫描类型
        scanOption = ScanOption.SCAN_OPTION_ADD;

        // 初始化扫描
        try {
            scanDecode = new ScanDecode(this);
            scanDecode.initService("true");
        } catch (Exception e) {
            Snackbar.make(bindingView.orderRootLayout, "本机没有扫码功能", Snackbar.LENGTH_LONG).show();
        }

        bindingView.orderCompleteButton.setEnabled(false);


        //初始化viewModel
        viewModel = new PutOutOrderViewModel(this);
        viewModel.completeAvailable.subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {

                bindingView.orderCompleteButton.setEnabled(aBoolean);

            }
        });

        initOrderDetail();

        scanDecode.getBarCode(new ScanInterface.OnScanListener() {
            @Override
            public void getBarcode(String s) {
                scanDecode.stopScan();
                if (viewModel.enableEdit) {
                    // 可操作状态（订单未配送）
                    s = s.substring(s.lastIndexOf("/") + 1);
                    if (scanOption == ScanOption.SCAN_OPTION_ADD) {
                        // 添加方法
                        handBarCode(CodeParsingUtil.boxParasing(s));
                    } else {
                        // 删除方法
                        if (flag == 0) {
                            add(CodeParsingUtil.boxParasing(s));
                        } else {
                            shanchuyiduo(CodeParsingUtil.boxParasing(s));
                        }


                    }
                } else {
                    // 不可操作状态（订单已配送）
                    Snackbar.make(bindingView.orderRootLayout, "该配送单已出货", Snackbar.LENGTH_LONG).show();
                }
            }
        });

        myList = new HashMap<>();
        mydelte = new ArrayList<>();


        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(PutOutOrderActivity.this);
        dialogBuilder.setTitle("提示");
        dialogBuilder.setMessage("请扫描箱码");

        // 4-0、如果不加入，则直接添加该条信息
        dialogBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                scanOption = ScanOption.SCAN_OPTION_ADD;

            }
        });

        diago = dialogBuilder.create();
        diago.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialogInterface) {
                scanOption = ScanOption.SCAN_OPTION_ADD;
            }
        });

    }

    /**
     * 初始化
     */
    private OrderDetailBean.DataBean disbean;

    public void initOrderDetail() {
        disbean = new OrderDetailBean.DataBean();

        viewModel.getOrderDetail(orderId, new RequestImpl<OrderDetailBean>() {
            @Override
            public void loadSuccess(OrderDetailBean bean) {

                bindingView.setOder(bean);
                bean.getData().setOrderId(orderId);
                initNodeView(bean.getData().getProduct());
                showContentView();
                disbean = bean.getData();

                starts = bean.getData().getStatus();
                if (starts != 0) {
                    bindingView.orderCompleteButton.setVisibility(View.GONE);
                    mymenu.findItem(R.id.action_search).setVisible(false);
                    mymenu.findItem(R.id.action_add).setVisible(false);
                    new AlertDialog.Builder(PutOutOrderActivity.this).setTitle("该配送单已出货")
                            .setPositiveButton("确定", null)
                            .show();

                } else {

                    remove();//保存配送单的信息
                }

            }

            @Override
            public void loadFailed(OError error) {
                showError(error);
            }
        });

        bindingView.orderCompleteButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                check(1);


            }
        });

        bindingView.orderCompleteButton.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {

                check(2);

                return true;
            }
        });

    }

    /**
     * 初始化树
     */
    public void initNodeView(List<OrderDetailBean.DataBean.ProductBean> productBeanList) {
        nodeMap = new HashMap<>();
        oilMap = new HashMap<>();

        bendi = (Map<String, BoxInfoBean>) aCache.getAsObject(orderId + "1");
        if (bendi == null) {
            bendi = new HashMap<>();
        }


        TreeNode root = TreeNode.root();

        for (OrderDetailBean.DataBean.ProductBean bean : productBeanList) {
            OrderViewHolder viewHolder = new OrderViewHolder(this);
            TreeNode child1 = new TreeNode(new OrderViewHolder.OrderInfo(bean.getTypeName(),
                    bean.getOrderChildId(),
                    bean.getOrderId(),
                    bean.get_id(),
                    bean.getSendId(),
                    bean.getName(),
                    bean.getProductCode(),
                    bean.getSendBox(),
                    bean.getSendBox())).setViewHolder(viewHolder);
            nodeMap.put(bean.getProductCode() + bean.getOrderChildId(), child1);
//            System.out.println(bean.getProductCode()+"ppp");

            // 储存键值
            if (oilMap.containsKey(bean.getProductCode())) {
                oilMap.get(bean.getProductCode()).add(bean.getProductCode() + bean.getOrderChildId());

            } else {
                List<String> list = new ArrayList<>();
                list.add(bean.getProductCode() + bean.getOrderChildId());
                oilMap.put(bean.getProductCode(), list);
            }

            viewHolder.setListenner(new OrderViewHolder.AddListenner() {
                @Override
                public void add(OrderViewHolder.OrderInfo order) {
                    addVirtualBox(order);
                }
            });

            root.addChildren(child1);
        }

        tView = new AndroidTreeView(this, root);
        tView.setDefaultAnimation(false);
        bindingView.orderRootView.addView(tView.getView());

        viewModel.setRoot(root);


        Map<String, MyOutBoxBean> mlist = (Map<String, MyOutBoxBean>) aCache.getAsObject(orderId + "2");

        if (mlist == null) {
            mlist = new HashMap<>();
            List<MyOutBoxBean> list = (ArrayList<MyOutBoxBean>) aCache.getAsObject(orderId);
            if (list != null && list.size() > 0) {
                int a = list.size();
                for (int i = 0; i < a; i++) {
                    String boxId = list.get(i).getBoxId();
                    addListNode(boxId, list.get(i).getBoxInfo(), list.get(i).getPileId(), list.get(i).getType(), list.get(i).getPileAdd(), list.get(i).getBoxIn());
                    if (boxId.length() > 2 && "xn".equals(boxId.substring(0, 2))) {
                        assistValue += 1;
                    }
                }
            }
        }
        getMapVauleThreeMethod(mlist);

    }

    public void getMapVauleThreeMethod(Map<String, MyOutBoxBean> map) {
        if (map != null) {
            for (Map.Entry entry : map.entrySet()) {
                String key = (String) entry.getKey();
                MyOutBoxBean value = (MyOutBoxBean) entry.getValue();
                addListNode(key, value.getBoxInfo(), value.getPileId(), value.getType(), value.getPileAdd(), value.getBoxIn());
                if (key.length() > 2 && "xn".equals(key.substring(0, 2))) {
                    assistValue += 1;
                }

            }
        }
    }

    Menu mymenu;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.order_complete_menu, menu);

        mymenu = menu;
        return true;
    }

    private int starts = 1;

    @Override
    public boolean onMenuItemClick(MenuItem item) {

        switch (item.getItemId()) {
            case R.id.action_add:
                tan();

                break;
            case R.id.action_search:

                xaunze();


                break;
            default:
                break;

        }


        return true;
    }

    /**
     * 删除类弹出框
     */

    //选择
    private int flag = 0;

    private void xaunze() {
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(PutOutOrderActivity.this);
        dialogBuilder.setTitle("提示");
        dialogBuilder.setMessage("请选择删除方式");

        // 4-0、如果不加入，则直接添加该条信息
        dialogBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });

        // 4-1、如果不加入，则直接添加该条信息
        dialogBuilder.setNegativeButton("删除一箱", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                scanOption = ScanOption.SCAN_OPTION_DELETE;
                diagodelte();
                flag = 0;
            }
        });

        // 4-2、如果加入，则添加所有信息
        dialogBuilder.setPositiveButton("删除一垛", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                scanOption = ScanOption.SCAN_OPTION_DELETE;
                diago.show();
                flag = 1;
            }
        });
        dialogBuilder.show();
    }

    //删整垛
    private AlertDialog diago;

    private void shanchuyiduo(String s) {
        diago.hide();
        if (!progressDialog.isShowing()) {
            progressDialog.show();
            viewModel.getBoxInfo(s, new RequestImpl<BoxInfoBean>() {
                @Override
                public void loadSuccess(BoxInfoBean bean) {
                    progressDialog.dismiss();

                    List<String> list = bean.getData().getBoxIn();
                    if (list != null) {
                        for (String s : list) {
                            deleteListNode(s);
                        }
                    }
                    scanOption = ScanOption.SCAN_OPTION_ADD;
                    Snackbar.make(bindingView.orderRootLayout, "删除成功", Snackbar.LENGTH_LONG).show();

                }

                @Override
                public void loadFailed(OError error) {
                    progressDialog.dismiss();
                    Snackbar.make(bindingView.orderRootLayout, error.getErrorMsg(), Snackbar.LENGTH_LONG).show();
                }
            });
        }

    }

    //删单箱
    private AlertDialog.Builder builder;
    private EditText edit;

    private void add(String ss) {
        edit.setText("");
        int aa = mydelte.size();
        if (!"".equals(ss)) {

            for (int i = 0; i < aa; i++) {

                if (ss.equals(mydelte.get(i).getBoxId())) {

                    Snackbar.make(bindingView.orderRootLayout, "需要删的箱码在列表中已存在", Snackbar.LENGTH_LONG).show();
                    return;
                }
            }

            if (boxMap.containsKey(ss)) {

                MyOutBoxBean bean = myList.get(ss);
                mydelte.add(bean);
                adapter.setData(mydelte);

                if (numm != null) {
                    int a = mydelte.size();
                    numm.setText("已扫" + a + "箱");
                }


            } else {
                Snackbar.make(bindingView.orderRootLayout, "订单中不存在该箱号", Snackbar.LENGTH_LONG).show();
            }


        }
    }

    private delteAdapter adapter;
    private TextView numm;

    private void diagodelte() {

        PutOutOrderActivity context = PutOutOrderActivity.this;
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
        View layout = inflater.inflate(R.layout.deltediago, null);


        XRecyclerView myListView = (XRecyclerView) layout.findViewById(R.id.xiangma);

        myListView.setLayoutManager(new LinearLayoutManager(this));

        adapter = new delteAdapter(this);
        myListView.setAdapter(adapter);

        myListView.setPullRefreshEnabled(false);

        TextView quXiao = layout.findViewById(R.id.quxiao);
        TextView queding = layout.findViewById(R.id.queding);
        numm = layout.findViewById(R.id.numm);

        edit = layout.findViewById(R.id.edit);

        Button bt = layout.findViewById(R.id.determine);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String s = edit.getText().toString();
                if (!"".equals(s)) {
                    add(s);

                }

            }
        });


        quXiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
                scanOption = ScanOption.SCAN_OPTION_ADD;
                mydelte.clear();
            }
        });

        queding.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {


                int a = mydelte.size();
                for (int i = 0; i < a; i++) {
                    getChange(mydelte.get(i));
                    getbendichange(mydelte.get(i));
                    deleteListNode(mydelte.get(i).getBoxId());

                }
                aCache.put(orderId + "1", (Serializable) bendi);
                scanOption = ScanOption.SCAN_OPTION_ADD;
                mydelte.clear();
                alertDialog.dismiss();

                Snackbar.make(bindingView.orderRootLayout, "删除成功", Snackbar.LENGTH_LONG).show();

            }
        });

        builder = new AlertDialog.Builder(context);
        builder.setView(layout);
        alertDialog = builder.create();
        alertDialog.show();

        alertDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialogInterface) {
                scanOption = ScanOption.SCAN_OPTION_ADD;
                mydelte.clear();
            }
        });

    }


    private void getChange(MyOutBoxBean bean) {

        String boxid = bean.getBoxId();
        boolean PileAdd = bean.getPileAdd();
        List<String> box = bean.getBoxIn();
        if (box == null) {
            box = new ArrayList<>();
            return;
        }
        if (boxMap.containsKey(boxid)) {
            if (PileAdd) {
                change(box);

            } else {

                return;
            }

        }

    }

    private void change(List<String> box) {

        for (String s : box) {
//
            MyOutBoxBean bean = myList.get(s);
            bean.setPileAdd(false);
            myList.put(s, bean);

        }


    }

    private void getbendichange(MyOutBoxBean bean) {
        String boxid = bean.getBoxId();
        if (bendi.containsKey(boxid)) {

//            if(box==null){
//                return;
//            }


            // for(String s:box){
            bendi.remove(boxid);

            //}
        }

    }


    /**
     * 添加类弹出框
     */
    private void tan() {
        final EditText editText = new EditText(PutOutOrderActivity.this);

        AlertDialog.Builder builder = new AlertDialog.Builder(PutOutOrderActivity.this);
        builder.setView(editText);
        builder.setTitle("提示");
        builder.setMessage("请输入箱码");
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                String s = editText.getText().toString();
                if (!"".equals(s)) {
                    handBarCode(s);

                }
            }
        });
        builder.setNegativeButton("取消", null);
        AlertDialog alertDialog = builder.create();
        alertDialog.show();

    }

    /**
     * 添加虚拟箱子
     *
     * @param orderInfo 订单信息
     */
    public void addVirtualBox(OrderViewHolder.OrderInfo orderInfo) {
        final EditText et = new EditText(this);
        et.setInputType(InputType.TYPE_NUMBER_FLAG_SIGNED);
        et.setKeyListener(DigitsKeyListener.getInstance("0123456789"));

        new AlertDialog.Builder(this).setTitle("请输入添加无箱码的箱数量")
                .setView(et)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        onClickBoxInput(et, orderInfo);
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }

    /**
     * 确认添加箱码
     *
     * @param et        输入框
     * @param orderInfo 订单号
     */
    public void onClickBoxInput(EditText et, OrderViewHolder.OrderInfo orderInfo) {
        if (isNumeric(et.getText().toString()) && !et.getText().toString().equals("")) {
            int number = Integer.parseInt(et.getText().toString());
            if (number == 0) {
                Toast.makeText(PutOutOrderActivity.this, "输入的内容不能为0", Toast.LENGTH_LONG).show();
            } else if (number > orderInfo.getBoxNum()) {
                Toast.makeText(PutOutOrderActivity.this, "输入的内容不能超过订单数量", Toast.LENGTH_LONG).show();
            } else {
                for (int i = number; i > 0; i--) {
                    assistValue += 1;
                    addListNode("xn00000" + assistValue, "", "", orderInfo.getTypeCode(), false, null);
                }
                save();
            }
        } else {
            Toast.makeText(this, "输入了非法数值", Toast.LENGTH_LONG).show();
        }
    }

    public boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

    /**
     * 处理 barcode
     *
     * @param s barcode
     */
    public void handBarCode(String s) {
        // 如果已经存在该 key，提示用户已经有这个箱子录入了
        if (boxMap.containsKey(s)) {
            Snackbar.make(bindingView.orderRootLayout, "该箱已经录入（" + s + "）", Snackbar.LENGTH_LONG).show();
            return;
        }


//
        if (bendi.containsKey(s)) {
            BoxInfoBean bean = bendi.get(s);

            if (oilMap.containsKey(bean.getData().getTypeCode()) && !boxMap.containsKey(s)) {

                List<String> typeNodes = oilMap.get(bean.getData().getTypeCode());
                for (String typeNode : typeNodes) {
                    // 3、获取树的 View， 并获取其中的数据
                    TreeNode rootNode = nodeMap.get(typeNode);
                    OrderViewHolder viewHolder = (OrderViewHolder) rootNode.getViewHolder();
                    OrderViewHolder.OrderInfo data = viewHolder.getData();

                    if (data.getBoxNum() <= 0) {
                        if (typeNode.equals(typeNodes.get(typeNodes.size() - 1))) {
                            Snackbar.make(bindingView.orderRootLayout, "订单已满，请检查！", Snackbar.LENGTH_LONG).show();
                        }
                        continue;
                    }


                    addListNode(s, bean.getData().getLine(), bean.getData().getPileId(), bean.getData().getTypeCode(), false, bean.getData().getBoxIn());
                    save();

                }

            } else {
                Snackbar.make(bindingView.orderRootLayout, "订单中不存在该品种或已经录入", Snackbar.LENGTH_LONG).show();

            }


            return;
        }


        if (!progressDialog.isShowing()) {
            progressDialog.show();
            viewModel.getBoxInfo(s, new RequestImpl<BoxInfoBean>() {
                @Override
                public void loadSuccess(BoxInfoBean bean) {
                    progressDialog.dismiss();
                    checkPile(bean, s);
                }

                @Override
                public void loadFailed(OError error) {
                    progressDialog.dismiss();
                    Snackbar.make(bindingView.orderRootLayout, error.getErrorMsg(), Snackbar.LENGTH_LONG).show();
                }
            });
        }
    }


    /**
     * 检查是否需要垛信息
     *
     * @param bean  箱子信息
     * @param boxId 订单Id
     */
    public void checkPile(BoxInfoBean bean, String boxId) {
        int stats = bean.getData().getStatus();
        if (stats != 0) {
            Snackbar.make(bindingView.orderRootLayout, "该箱不是入库状态！", Snackbar.LENGTH_LONG).show();
            return;

        }


        // 1、判断值是否存在
        if (oilMap.containsKey(bean.getData().getTypeCode()) && !boxMap.containsKey(boxId)) {
            // 2、遍历所有的 key
            List<String> typeNodes = oilMap.get(bean.getData().getTypeCode());
            for (String typeNode : typeNodes) {
                // 3、获取树的 View， 并获取其中的数据
                TreeNode rootNode = nodeMap.get(typeNode);
                OrderViewHolder viewHolder = (OrderViewHolder) rootNode.getViewHolder();
                OrderViewHolder.OrderInfo data = viewHolder.getData();

                if (data.getBoxNum() <= 0) {
                    if (typeNode.equals(typeNodes.get(typeNodes.size() - 1))) {
                        Snackbar.make(bindingView.orderRootLayout, "订单已满，请检查！", Snackbar.LENGTH_LONG).show();
                    }
                    continue;
                }

                // 4、如果垛中剩余的数量小于订单中还剩余的数量，并且剩余箱数不等于0，询问是否将整垛存入

//
                if (bean.getData().getPileBoxNumber() <= data.getBoxNum() && bean.getData().getPileBoxNumber() != 0) {


                    ShowDialog(boxId, bean, "还差" + data.getBoxNum() + "箱，需要将整垛加入订单吗？", 1, bean.getData().getBoxIn());


                } else if (bean.getData().getPileBoxNumber() > data.getBoxNum() && bean.getData().getPileBoxNumber() != 0) {

                    ShowDialog(boxId, bean, "还差" + data.getBoxNum() + "箱，需要将整垛加入订单吗？", 2, bean.getData().getBoxIn());

                } else {
                    addListNode(boxId, bean.getData().getLine(), bean.getData().getPileId(), bean.getData().getTypeCode(), false, bean.getData().getBoxIn());
                    save();
                }


                break;
            }
        } else {
            Snackbar.make(bindingView.orderRootLayout, "订单中不存在该品种或已经录入", Snackbar.LENGTH_LONG).show();
        }
    }

    private AlertDialog dialog;

    public void ShowDialog(String boxId, BoxInfoBean bean, String ss, int flag, List<String> boxIn) {

        PutOutOrderActivity context = PutOutOrderActivity.this;
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
        View layout = inflater.inflate(R.layout.outdigao, null);
        TextView myName = layout.findViewById(R.id.name);
        TextView myNum = layout.findViewById(R.id.duoshu);
        TextView myStart = layout.findViewById(R.id.duokaishi);
        TextView myEnd = layout.findViewById(R.id.duokaijieshu);
        TextView zhuyi = layout.findViewById(R.id.zhuyi);
        TextView quxiao = layout.findViewById(R.id.quxiao);
        RelativeLayout rel = layout.findViewById(R.id.rel_quxiao);
        RelativeLayout add = layout.findViewById(R.id.rel_add);

        if (bean != null) {

            String nama = bean.getData().getName();


            if ("".equals(nama)) {
                myName.setText("产品名称：" + bean.getData().getTypeName());
            } else {
                myName.setText("产品名称：" + nama);
            }

            List<String> s = bean.getData().getBoxIn();
            if (s == null) {
                s = new ArrayList<>();
            }
            int n = s.size();
            myNum.setText("垛总箱数：" + n);

            if (n == 0) {
                myStart.setText("起始箱码：无");
                myEnd.setText("结束箱码：无");
                rel.setVisibility(View.VISIBLE);
                add.setVisibility(View.GONE);
                zhuyi.setVisibility(View.VISIBLE);
            } else if (n == 1) {
                myStart.setText("起始箱码：" + s.get(0));
                myEnd.setText("结束箱码：无");
            } else {
                myStart.setText("起始箱码：" + s.get(0));
                myEnd.setText("结束箱码：" + s.get(n - 1));
            }

        } else {

            rel.setVisibility(View.VISIBLE);
            add.setVisibility(View.GONE);
            zhuyi.setVisibility(View.VISIBLE);

        }

        TextView tishi = layout.findViewById(R.id.tishi);

        tishi.setText(ss);


        TextView xiang = layout.findViewById(R.id.yixiang);
        TextView duo = layout.findViewById(R.id.yiduo);

        xiang.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                addListNode(boxId, bean.getData().getLine(), bean.getData().getPileId(), bean.getData().getTypeCode(), false, boxIn);
                saveBendi(bean);
                save();
                dialog.dismiss();

            }
        });

        duo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {


                getAllBoxes(boxId, bean, flag, boxIn);


                dialog.dismiss();

            }
        });
        quxiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(PutOutOrderActivity.this);
        dialogBuilder = new AlertDialog.Builder(context);
        dialogBuilder.setView(layout);

        dialog = dialogBuilder.create();
        dialog.show();
    }

    private void saveBendi(BoxInfoBean bean) {
        List<String> box = bean.getData().getBoxIn();
        for (String s : box) {
            bendi.put(s, bean);
        }


    }


    /**
     * 获取垛中所有的箱子
     *
     * @param
     */
    public void getAllBoxes(String boxId, BoxInfoBean bean, int flag, List<String> boxIn) {
        if (boxIn == null) {
            boxIn = new ArrayList<>();
        }

        loadAllBoxes(bean, bean.getData().getPileId(), flag, boxIn);


//        if (!progressDialog.isShowing()) {
//            progressDialog.show();
//            viewModel.getPileInfo(boxId, new RequestImpl<PileInfoBean>() {
//                @Override
        //               public void loadSuccess(PileInfoBean bean) {
//                    progressDialog.dismiss();
//                    loadAllBoxes(bean, pileId,flag,boxIn);
//                }
//
//                @Override
//                public void loadFailed(OError error) {
//                    progressDialog.dismiss();
//                    Snackbar.make(bindingView.orderRootLayout, error.getErrorMsg(), Snackbar.LENGTH_LONG).show();
//                }
//            });
//        }


    }


    /**
     * 垛中所有数据进行处理
     *
     * @param bean   垛中垛数据
     * @param pileId 垛Id
     */
    public void loadAllBoxes(BoxInfoBean bean, String pileId, int flag, List<String> boxIn) {

        List<String> boxId = new ArrayList<>();

        for (String id : boxIn) {
            // 只录入没有出现的箱子
            if (!boxMap.containsKey(id)) {
                boxId.add(id);
            }
        }


        if (boxId.size() != 0) {
            int a = boxId.size();

            if (flag == 1) {

                for (int i = 0; i < a; i++) {
                    addListNode(
                            boxId.get(i),
                            bean.getData().getLine(),
                            pileId,
                            bean.getData().getTypeCode(),
                            boxId.size() == bean.getData().getPileBoxNumber(), boxIn
                    );
                }

            } else {

                for (int i = 0; i < a; i++) {
                    addListNode(
                            boxId.get(i),
                            bean.getData().getLine(),
                            pileId,
                            bean.getData().getTypeCode(),
                            false, boxIn
                    );

                }
            }
            save();


        } else {
            Snackbar.make(bindingView.orderRootLayout, "此垛中没有可用的产品", Snackbar.LENGTH_LONG).show();
        }
    }


    /**
     * 处理添加 node
     *
     * @param boxId 箱码
     * @param boxInfo 箱的信息
     */

    private MyOutBoxBean myOutBoxBean;
    private Map<String, MyOutBoxBean> myList;

    public void addListNode(String boxId, String boxInfo, String pileId, String type, Boolean isPileAdd, List<String> boxIn) {

        // 判断类型是否存在
        if (oilMap.containsKey(type) && !boxMap.containsKey(boxId)) {


            myOutBoxBean = new MyOutBoxBean();
            myOutBoxBean.setBoxId(boxId);
            myOutBoxBean.setBoxInfo(boxInfo);
            myOutBoxBean.setPileAdd(isPileAdd);
            myOutBoxBean.setPileId(pileId);
            myOutBoxBean.setType(type);
            myOutBoxBean.setBoxIn(boxIn);
            myList.put(boxId, myOutBoxBean);

            List<String> typeNodes = oilMap.get(type);

            for (String typeNode : typeNodes) {
                // 获取树的 View
                TreeNode rootNode = nodeMap.get(typeNode);
                OrderViewHolder viewHolder = (OrderViewHolder) rootNode.getViewHolder();

                // 获取当前树中的数据,检查数据
                OrderViewHolder.OrderInfo data = viewHolder.getData();
//                if (data.getBoxNum() == 0) {
//                    if (typeNode.equals(typeNodes.get(typeNodes.size() - 1))) {
//                        Snackbar.make(bindingView.orderRootLayout, "订单已满，请检查！", Snackbar.LENGTH_LONG).show();
//                    }
//                    continue;
//                }
                OrderBoxViewHolder boxViewHolder = new OrderBoxViewHolder(this);
                TreeNode boxNode = new TreeNode(new OrderBoxViewHolder.OrderBox(boxId, pileId, boxInfo, isPileAdd ? null : boxId)).setViewHolder(boxViewHolder);
                tView.addNode(nodeMap.get(typeNode), boxNode);
                // 添加一个箱子
                viewHolder.addBox();

                if (insertListener != null) {
                    insertListener.onInsert();
                }

                // 缓存箱子信息
                boxMap.put(boxId, boxNode);

                // 删除动作监听
                boxViewHolder.setListenner(new OrderBoxViewHolder.DeleteListenner() {
                    @Override
                    public void deleteAction(String boxId) {

                        deleteListNode(boxId);

                        //


                    }
                });
                break;
            }
        } else {
            Snackbar.make(bindingView.orderRootLayout, "订单中不存在该品种或已经录入", Snackbar.LENGTH_LONG).show();
        }
    }


    private void delte(String boxId) {

        myList.remove(boxId);


        save();

    }

    /**
     * 删除 node
     *
     * @param boxId 箱码
     */
    public void deleteListNode(String boxId) {

        if (boxMap.containsKey(boxId)) {
            TreeNode node = boxMap.get(boxId);
            OrderBoxViewHolder.OrderBox data = (OrderBoxViewHolder.OrderBox) node.getValue();
            // 删除箱子
            boxMap.remove(data.getBoxId());
            // 父节点删除一个
            TreeNode parentNode = node.getParent();
            OrderViewHolder viewHolder = (OrderViewHolder) parentNode.getViewHolder();
            viewHolder.removeBox();
            tView.removeNode(node);

            delte(boxId);


            bindingView.orderCompleteButton.setEnabled(viewModel.getnum());

        } else {
            //  Snackbar.make(bindingView.orderRootLayout, "订单中不存在该箱号", Snackbar.LENGTH_LONG).show();
        }
    }

    /**
     * 确认信息
     */
    public void check(int n) {
        if (n == 1) {
            new AlertDialog.Builder(this).setTitle("确认要出库吗？")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {

                            onComplete(1);

                        }
                    })
                    .setNegativeButton("取消", null)
                    .show();

        } else {
            new AlertDialog.Builder(this).setTitle("确认要强制出库吗？")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {

                            onComplete(2);

                        }
                    })
                    .setNegativeButton("取消", null)
                    .show();
        }


    }

    public void save() {

//        aCache.remove(orderId);
        aCache.put(orderId + "2", (Serializable) myList);
        aCache.put(orderId + "1", (Serializable) bendi);

    }


    private void remove() {
//        aCache.remove("distributions");
        int a = distributions.size() - 1;

        for (int i = a; i >= 0; i--) {
            String b = distributions.get(i).getOrderId();

            if (b.equals(disbean.getOrderId())) {
                distributions.remove(i);
                break;
            }
        }

        distributions.add(disbean);
        aCache.put("distributions", (Serializable) distributions);

    }


    /**
     * 完成订单
     */
    public void onComplete(int n) {


        final ProgressDialog dialog = ProgressDialog.show(PutOutOrderActivity.this, "提示", "正在录入系统..");

        viewModel.submitOrder(nodeMap, orderId, myList, n, new RequestImpl<BaseBean>() {
            @Override
            public void loadSuccess(BaseBean bean) {

                dialog.dismiss();
                if (bean.getSuccess() == 0) {
                    Toast.makeText(PutOutOrderActivity.this, "成功", Toast.LENGTH_LONG).show();
                    aCache.remove(orderId + "2");
                    aCache.remove(orderId);
                    aCache.remove(orderId + "1");
//
                    int a = distributions.size() - 1;
                    for (int i = a; i >= 0; i--) {
                        String b = distributions.get(i).getOrderId();
                        if (b.equals(disbean.getOrderId())) {
                            distributions.remove(i);
                            break;
                        }
                    }
                    aCache.put("distributions", (Serializable) distributions);
                    finish();

                } else if (bean.getSuccess() == 7) {
                    removelist(bean.getList());
                    Toast.makeText(PutOutOrderActivity.this, bean.getMessage() + "现已删除", Toast.LENGTH_LONG).show();

                }


            }

            @Override
            public void loadFailed(OError error) {

                dialog.dismiss();
                Snackbar.make(bindingView.orderRootLayout, error.getErrorMsg(), Snackbar.LENGTH_LONG).show();

            }
        });
    }


    private void removelist(List<String> s) {
        if (s != null) {
            int a = s.size();

            for (int i = 0; i < a; i++) {

                getdou(s.get(i));

            }

        }


    }

    private void getdou(String pileId) {

        viewModel.getpileBox(pileId, new RequestImpl<PileBoxBean>() {
            @Override
            public void loadSuccess(PileBoxBean bean) {

                List<String> s = bean.getBoxes();

                if (s != null) {

                    for (String ss : s) {
                        deleteListNode(ss);
                    }

                }


            }

            @Override
            public void loadFailed(OError error) {
                Snackbar.make(bindingView.orderRootLayout, error.getErrorMsg(), Snackbar.LENGTH_LONG).show();


            }
        });

    }


    public static void start(Activity context, String orderId) {
        Intent intent = new Intent(context, PutOutOrderActivity.class);
        intent.putExtra("orderId", orderId);
        ActivityCompat.startActivity(context, intent, null);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        try {
            scanDecode.onDestroy();
        } catch (Exception e) {
        }
    }

    public void setInsertListener(TreeNodeInsertListener insertListener) {
        this.insertListener = insertListener;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            showExitAlert();
        }
        return false;
    }


    /**
     * 退出提醒
     */
    private void showExitAlert() {
//        new AlertDialog.Builder(this).setTitle("确认要返回吗？")
//                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
//                    public void onClick(DialogInterface dialog, int which) {
//                        finish();
//                    }
//                })
//                .setNegativeButton("取消", null)
//                .show();
        finish();
    }
}
