package com.gingersoft.supply_chain.mvp.ui.fragment.warehouse;

import android.animation.LayoutTransition;
import android.app.Dialog;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.print.PrintHelper;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;

import com.gingersoft.gsa.cloud.common.core.restaurant.RestaurantInfoManager;
import com.gingersoft.gsa.cloud.common.core.user.UserContext;
import com.gingersoft.gsa.cloud.common.loadsir.EmptyCallback;
import com.gingersoft.gsa.cloud.common.utils.CollectionUtils;
import com.gingersoft.gsa.cloud.common.utils.MoneyUtil;
import com.gingersoft.gsa.cloud.common.utils.glide.GlideUtils;
import com.gingersoft.gsa.cloud.common.utils.other.TextUtil;
import com.gingersoft.gsa.cloud.common.utils.time.TimeUtils;
import com.gingersoft.gsa.cloud.common.utils.view.LayoutToBitmapUtils;
import com.gingersoft.gsa.cloud.ui.utils.AppDialog;
import com.gingersoft.supply_chain.R;
import com.gingersoft.supply_chain.R2;
import com.gingersoft.supply_chain.di.component.DaggerWarehouseDetailsComponent;
import com.gingersoft.supply_chain.mvp.bean.ConsumeReasonBean;
import com.gingersoft.supply_chain.mvp.bean.OutboundOrderBean;
import com.gingersoft.supply_chain.mvp.bean.PurchaseFoodBean;
import com.gingersoft.supply_chain.mvp.bean.PurchaseFoodEncodeSn;
import com.gingersoft.supply_chain.mvp.bean.PurchaseWarehousingOrderDetailsVO;
import com.gingersoft.supply_chain.mvp.bean.WarehouseDetailsBean;
import com.gingersoft.supply_chain.mvp.contract.WarehouseDetailsContract;
import com.gingersoft.supply_chain.mvp.presenter.WarehouseDetailsPresenter;
import com.gingersoft.supply_chain.mvp.ui.adapter.OutboundOrderAdapter;
import com.gingersoft.supply_chain.mvp.ui.adapter.PurchasePageAdapter;
import com.gingersoft.supply_chain.mvp.ui.adapter.WareHousingDetailsAdapter;
import com.gingersoft.supply_chain.mvp.ui.fragment.BaseSupplyChainFragment;
import com.gingersoft.supply_chain.mvp.ui.widget.InventoryConsumptionView;
import com.gingersoft.supply_chain.mvp.ui.widget.ScanSnView;
import com.jess.arms.di.component.AppComponent;
import com.kingja.loadsir.core.LoadSir;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import org.jetbrains.annotations.NotNull;

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

import butterknife.BindView;
import butterknife.OnClick;


/**
 * Description: 入庫詳情
 *
 * @author admin
 */
public class WarehouseDetailsFragment extends BaseSupplyChainFragment<WarehouseDetailsPresenter> implements WarehouseDetailsContract.View, View.OnClickListener {

    @BindView(R2.id.supply_top_bar)
    QMUITopBar supplyTopBar;
    @BindView(R2.id.iv_warehouse_img)
    ImageView ivFoodImg;
    @BindView(R2.id.tv_warehouse_inventory_number)
    TextView tvWarehouseInventoryNumber;
    @BindView(R2.id.tv_warehouse_specifications)
    TextView tvWarehouseSpecifications;
    @BindView(R2.id.tv_warehouse_unit_price)
    TextView tvWarehouseUnitPrice;
    @BindView(R2.id.tv_warehouse_total_amount)
    TextView tvWarehouseTotalAmount;
    @BindView(R2.id.tv_warehousing_record)
    TextView tvWarehousingRecord;
    @BindView(R2.id.tv_outbound_record)
    TextView tvOutboundRecord;
    @BindView(R2.id.vp_warehouse_viewpager)
    ViewPager2 vpWarehouseViewpager;
    @BindView(R2.id.srl_warehouse_details_list)
    SmartRefreshLayout smartRefreshLayout;
    @BindView(R2.id.tv_food_unit)
    TextView tvUnit;
    @BindView(R2.id.layout_warehousing_root)
    LinearLayout layoutRoot;

    @BindView(R2.id.layout_warehousing_title)
    LinearLayout layoutTitle;
    /**
     * 庫存消耗view
     */
    private InventoryConsumptionView inventoryConsumptionView;
    /**
     * 掃碼sn碼view
     */
    private ScanSnView scanSnView;
    private WareHousingDetailsAdapter wareHousingDetailsAdapter;
    private PurchasePageAdapter adapter;

    public final static String FOOD_INFO_KEY = "purchaseWarehousingBean";
    private PurchaseWarehousingOrderDetailsVO purchaseWarehousingOrderDetailsVO;
    /**
     * 入庫
     */
    public final static int WAREHOUSE_TYPE = 0;
    /**
     * 出庫
     */
    public final static int OUT_STOCK_TYPE = 1;

    public static WarehouseDetailsFragment newInstance(PurchaseWarehousingOrderDetailsVO purchaseWarehousingOrderDetailsVosBean) {
        WarehouseDetailsFragment fragment = new WarehouseDetailsFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(FOOD_INFO_KEY, purchaseWarehousingOrderDetailsVosBean);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerWarehouseDetailsComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_warehouse_details, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        Bundle arguments = getArguments();
        smartRefreshLayout.setPrimaryColorsId(R.color.trans, R.color.black);

        loadService = LoadSir.getDefault().register(smartRefreshLayout);
        LayoutTransition layoutTransition = new LayoutTransition();
        layoutTransition.enableTransitionType(LayoutTransition.CHANGING);
        layoutRoot.setLayoutTransition(layoutTransition);
        smartRefreshLayout.setOnRefreshListener(refreshLayout -> getPageInfo());
        if (arguments != null) {
            purchaseWarehousingOrderDetailsVO = (PurchaseWarehousingOrderDetailsVO) arguments.getSerializable(FOOD_INFO_KEY);
            if (purchaseWarehousingOrderDetailsVO == null) {
                killMyself();
                showMessage("食材信息獲取失敗，請稍候重試");
            }
            initTopBar(supplyTopBar, purchaseWarehousingOrderDetailsVO.getName());

            tvUnit.setText(purchaseWarehousingOrderDetailsVO.getUnitName());
            String foodImageUrl = purchaseWarehousingOrderDetailsVO.getImages();
            if (TextUtil.isNotEmptyOrNullOrUndefined(foodImageUrl)) {
                GlideUtils.display(requireContext(), ivFoodImg, foodImageUrl);
            } else {
                ivFoodImg.setImageResource(R.drawable.img_small_default);
            }
            tvWarehouseInventoryNumber.setText(String.valueOf(purchaseWarehousingOrderDetailsVO.getFoodNum()));
            tvWarehouseUnitPrice.setText(String.format(getString(R.string.str_latest_unit_price_colon), purchaseWarehousingOrderDetailsVO.getFoodPrice()));
            tvWarehouseTotalAmount.setText(String.format(getString(R.string.str_total_amount_colon), purchaseWarehousingOrderDetailsVO.getFoodAmount()));
            tvWarehouseSpecifications.setText(purchaseWarehousingOrderDetailsVO.getUnitName());
            getWarehouseDetails();
            if (purchaseWarehousingOrderDetailsVO.getFoodNum() > 0) {
                //獲取庫存消耗的原因列表
                mPresenter.getWarehouseInventoryReason();
            }
            initViewPager();
        }
    }

    /**
     * 獲取入庫詳情
     */
    private void getWarehouseDetails() {
        mPresenter.getWarehousingOrderDetails(purchaseWarehousingOrderDetailsVO.getFoodNo());
    }

    /**
     * 獲取出庫詳情
     */
    private void getOutStockDetails() {
        mPresenter.getOutStockDetails(purchaseWarehousingOrderDetailsVO.getFoodNo());
    }

    private void initViewPager() {
        vpWarehouseViewpager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels);
            }

            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                setBtnSelectState(position);
                if (position == WAREHOUSE_TYPE) {
                    //查詢入庫
                    getWarehouseDetails();
                } else {
                    //查詢出庫
                    getOutStockDetails();
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                super.onPageScrollStateChanged(state);
            }
        });
    }

    private void setBtnSelectState(int position) {
        if (wareHousingDetailsAdapter != null) {
            wareHousingDetailsAdapter.setList(new ArrayList<>());
        }
        if (position == WAREHOUSE_TYPE) {
            tvWarehousingRecord.setTextColor(ContextCompat.getColor(requireContext(), R.color.white));
            tvWarehousingRecord.setBackground(ContextCompat.getDrawable(requireContext(), R.drawable.shape_left_themecolor_radius_btn));
            tvOutboundRecord.setTextColor(ContextCompat.getColor(requireContext(), R.color.color_3c));
            tvOutboundRecord.setBackground(ContextCompat.getDrawable(requireContext(), R.drawable.shape_right_white_radius_btn));
        } else {
            tvOutboundRecord.setTextColor(ContextCompat.getColor(requireContext(), R.color.white));
            tvOutboundRecord.setBackground(ContextCompat.getDrawable(requireContext(), R.drawable.shape_right_themecolor_radius_btn));
            tvWarehousingRecord.setTextColor(ContextCompat.getColor(requireContext(), R.color.color_3c));
            tvWarehousingRecord.setBackground(ContextCompat.getDrawable(requireContext(), R.drawable.shape_left_white_radius_btn));
        }
    }

    @Override
    public void loadAdapter(List<WarehouseDetailsBean> warehouseDetailsBeans) {
        smartRefreshLayout.finishRefresh();
        smartRefreshLayout.finishLoadMore();
        if (warehouseDetailsBeans.size() <= 0) {
            loadService.showCallback(EmptyCallback.class);
        } else {
            loadService.showSuccess();
            if (wareHousingDetailsAdapter == null) {
                wareHousingDetailsAdapter = new WareHousingDetailsAdapter(warehouseDetailsBeans, vpWarehouseViewpager.getCurrentItem());
                if (adapter == null) {
                    adapter = new PurchasePageAdapter(wareHousingDetailsAdapter, 2);
                    vpWarehouseViewpager.setAdapter(adapter);
                }
                wareHousingDetailsAdapter.setOnItemClickListener((adapter, view, position) -> {
                    if (purchaseWarehousingOrderDetailsVO.getFoodMarkSn() == PurchaseFoodBean.HAS_SN) {
                        //SN食材
//                        if (view.getId() == R.id.tv_warehouse_details_food_num) {
                        //查詢消耗，收貨Sn碼詳情

                        start(SnCodeListFragment.newInstance(vpWarehouseViewpager.getCurrentItem(), wareHousingDetailsAdapter.getItem(position)));
//                            if (vpWarehouseViewpager.getCurrentItem() == WAREHOUSE_TYPE) {
//                                mPresenter.querySnCodeList(vpWarehouseViewpager.getCurrentItem(), item.getFoodQuantity(), "", item.getWarehousingOrderDetailsIds());
//                            } else {
//                                mPresenter.querySnCodeList(vpWarehouseViewpager.getCurrentItem(), item.getFoodQuantity(), "", item.getPurchaseConsumeNoId());
//                            }
//                        }
                    }
                });
            } else {
                wareHousingDetailsAdapter.setType(vpWarehouseViewpager.getCurrentItem());
                wareHousingDetailsAdapter.setList(warehouseDetailsBeans);
            }
        }
    }

    @Override
    public void loadConsumeReason(List<ConsumeReasonBean> consumeReasonBeans) {
        Button button = supplyTopBar.addRightTextButton(R.string.str_inventory_consumption, R.id.id_inventory_consumption);
        button.setTextColor(ContextCompat.getColor(requireContext(), R.color.white));
        button.setOnClickListener(v -> showInventory(consumeReasonBeans));
    }


    /**
     * 顯示庫存消耗
     *
     * @param consumeReasonBeans 庫存消耗原因
     */
    private void showInventory(List<ConsumeReasonBean> consumeReasonBeans) {
        if (vpWarehouseViewpager.getVisibility() == View.VISIBLE) {
            //隱藏庫存消耗記錄列表
            showList(View.GONE);
            //移除掉
            if (inventoryConsumptionView != null) {
                layoutRoot.removeView(inventoryConsumptionView);
                layoutRoot.removeView(scanSnView);
            }
            //初始化消耗view
            inventoryConsumptionView = new InventoryConsumptionView(requireContext(), consumeReasonBeans, purchaseWarehousingOrderDetailsVO.getFoodNum());
            layoutRoot.addView(inventoryConsumptionView);
            //如果不是sn食材
            if (purchaseWarehousingOrderDetailsVO.getFoodMarkSn() == PurchaseFoodBean.NOT_HAS_SN) {
                inventoryConsumptionView.setShowBtn();
                inventoryConsumptionView.setOnConfirmClickListener((consumptionNum, reasonIndex, remarks) -> inventory(consumeReasonBeans, null, inventoryConsumptionView.getIsPrint()))
                        .setOnCancelListener(() -> showList(View.VISIBLE));
                return;
            }
            inventoryConsumptionView.setEdit(false).setHint(getString(R.string.str_sn_not_edit));
            //初始化掃碼view
            scanSnView = new ScanSnView(this).setOnScanResultListener((popup, scanResult) -> {
                if (scanResult.isEmpty()) {
                    showMessage("請掃碼SN碼");
                    return;
                }
                if (scanResult.size() != inventoryConsumptionView.getConsumptionNum()) {
                    showMessage("SN碼數量和消耗庫存數必須保持一致");
                    return;
                }
                List<String> snCodes = new ArrayList<>();
                for (PurchaseFoodEncodeSn purchaseFoodEncodeSn : scanResult) {
                    snCodes.add(purchaseFoodEncodeSn.getEncodeSnNo());
                }
                inventory(consumeReasonBeans, snCodes, inventoryConsumptionView.getIsPrint());
            }).setOnCancelListener(() -> {
                //取消
                showList(View.VISIBLE);
            }).init();
            scanSnView.setOnSingerResultListener((isAdd, snCode, currentSnCodeNumber) -> {
                //inventoryConsumptionView.setConsumptionNumber(currentSnCodeNumber)
                //添加sn碼
                scanSnView.setConfirmBtnState();
                inventoryConsumptionView.setConsumptionNumber(currentSnCodeNumber);
            }).setOnDeleteSnCodeListener((snCode, position) -> {
                //刪除SN碼
                inventoryConsumptionView.setConsumptionNumber(inventoryConsumptionView.getConsumptionNum() - 1);
            });
            inventoryConsumptionView.setOnNumberChangeListener(num -> {
                //輸入數量發生變化時
                scanSnView.setMinCodeSize(num);
                scanSnView.setConfirmBtnState();
            });
            //設置LayoutParam
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
            int dimensionPixelOffset = requireContext().getResources().getDimensionPixelOffset(R.dimen.dp_10);
            layoutParams.leftMargin = dimensionPixelOffset;
            layoutParams.rightMargin = dimensionPixelOffset;
            layoutParams.bottomMargin = dimensionPixelOffset;
            scanSnView.setBackground(ContextCompat.getDrawable(requireContext(), R.drawable.shape_white_eight_corners_bg));
            layoutRoot.addView(scanSnView, layoutParams);
        } else {
            showList(View.VISIBLE);
        }
    }

    /**
     * 移除显示消耗的view
     */
    private void removeInventoryView() {
        layoutRoot.removeView(inventoryConsumptionView);
        layoutRoot.removeView(scanSnView);
        inventoryConsumptionView = null;
        scanSnView = null;
        smartRefreshLayout.setEnableRefresh(true);
        smartRefreshLayout.setEnableLoadMore(true);
    }

    /**
     * 消耗方法
     *
     * @param consumeReasonBeans 消耗原因
     * @param snCodes            snCode集合
     * @param whetherPrint       是否打印
     */
    private void inventory(List<ConsumeReasonBean> consumeReasonBeans, List<String> snCodes, boolean whetherPrint) {
        //獲取用戶輸入的消耗數量
        int consumptionNum = inventoryConsumptionView.getConsumptionNumAndTip();
        if (consumptionNum == -1) {
            return;
        }
        //調用消耗接口
        mPresenter.consumeWareHousing(purchaseWarehousingOrderDetailsVO, consumptionNum, consumeReasonBeans.get(inventoryConsumptionView.getReasonIndex()), inventoryConsumptionView.getRemark(), snCodes, whetherPrint);
        setFragmentResult(RESULT_OK, null);
    }

    @Override
    public void printConsumeOrder(List<String> snCodes, String consumeReasonDesc, int consumptionNum) {
        onPrintPdf(snCodes, consumeReasonDesc, inventoryConsumptionView.getRemark(), consumptionNum);
    }

    private void onPrintPdf(List<String> snCodes, String consumptionReason, String remarks, int foodNum) {
        PrintHelper printHelper = new PrintHelper(requireContext());
        boolean b = PrintHelper.systemSupportsPrint();
        if (b) {
            //設置縮放模式
            printHelper.setScaleMode(PrintHelper.SCALE_MODE_FIT);
            //設置打印方向
            //橫向 PrintHelper.ORIENTATION_LANDSCAPE
            //縱向 PrintHelper.ORIENTATION_PORTRAIT
            printHelper.setOrientation(PrintHelper.ORIENTATION_PORTRAIT);
            //設置打印顏色
            printHelper.setColorMode(PrintHelper.COLOR_MODE_MONOCHROME);
            printHelper.printBitmap(String.format(getString(R.string.str_restaurant_outbound_order), purchaseWarehousingOrderDetailsVO.getName()), generatePrintBitmap(snCodes, consumptionReason, remarks, foodNum), () -> {
                //打印完成回調
                getPageInfo();
                //重新獲取庫存數量
                mPresenter.getWarehousingNum(purchaseWarehousingOrderDetailsVO.getFoodNo());
            });
        } else {
            //不支持打印
            showMessage(getString(R.string.str_device_not_print));
        }
    }

    private Bitmap generatePrintBitmap(List<String> snCodes, String consumptionReason, String remarks, int foodNum) {
        View view = LayoutInflater.from(requireContext()).inflate(R.layout.layout_print_consume, null);
        TextView restaurantName = view.findViewById(R.id.tv_print_consume_restaurant_name);
        TextView tvDate = view.findViewById(R.id.tv_print_consume_date);
        TextView tvFoodNo = view.findViewById(R.id.tv_print_consume_no);
        RecyclerView rvInfo = view.findViewById(R.id.rv_print_consume_info);
        TextView tvUserName = view.findViewById(R.id.tv_print_consume_user_name);
        TextView tvSnCodes = view.findViewById(R.id.tv_print_sn);
        LinearLayout layoutSn = view.findViewById(R.id.layout_sn_list);

        restaurantName.setText(String.format(getString(R.string.str_restaurant_outbound_order), RestaurantInfoManager.newInstance().getRestaurantName()));
        tvDate.setText(TimeUtils.getCurrentDate(TimeUtils.DEFAULT_DATE_FORMAT_YMDHM));
        tvFoodNo.setText(String.format(getString(R.string.str_goods_no), purchaseWarehousingOrderDetailsVO.getFoodNo()));
        tvUserName.setText(String.format(getString(R.string.str_prepared), UserContext.newInstance().getMemberName()));
        List<OutboundOrderBean> outboundOrderBeans = new ArrayList<>();
        outboundOrderBeans.add(new OutboundOrderBean(getString(R.string.str_product_name), purchaseWarehousingOrderDetailsVO.getName()));
        outboundOrderBeans.add(new OutboundOrderBean(getString(R.string.str_unit), purchaseWarehousingOrderDetailsVO.getUnitName()));
        outboundOrderBeans.add(new OutboundOrderBean(getString(R.string.str_number), String.valueOf(foodNum)));
        outboundOrderBeans.add(new OutboundOrderBean(getString(R.string.str_unit_prices), String.valueOf(purchaseWarehousingOrderDetailsVO.getFoodPrice())));
        outboundOrderBeans.add(new OutboundOrderBean(getString(R.string.str_amount), String.valueOf(MoneyUtil.priceCalculation(purchaseWarehousingOrderDetailsVO.getFoodPrice(), foodNum))));
        outboundOrderBeans.add(new OutboundOrderBean(getString(R.string.str_inventory_reason), consumptionReason));
        outboundOrderBeans.add(new OutboundOrderBean(getString(R.string.str_remark), remarks));
        if (CollectionUtils.isNotNullOrEmpty(snCodes)) {
            layoutSn.addView(getSnView(getString(R.string.str_serial_number), getString(R.string.str_sn_code)));
            int size = snCodes.size();
            for (int i = 0; i < size; i++) {
                LinearLayout layout = getSnView(i + 1 + "", snCodes.get(i));
                layoutSn.addView(layout);
            }
            //sn碼不為空
            tvSnCodes.setText(String.format(getString(R.string.str_sn_codes), CollectionUtils.listToCommaString(snCodes)));
            layoutSn.setVisibility(View.VISIBLE);
        } else {
            tvSnCodes.setVisibility(View.GONE);
            layoutSn.setVisibility(View.GONE);
        }
        OutboundOrderAdapter outboundOrderAdapter = new OutboundOrderAdapter(outboundOrderBeans);
        rvInfo.setAdapter(outboundOrderAdapter);
        return LayoutToBitmapUtils.getBitmapByView(requireContext(), view);
    }

    @NotNull
    private LinearLayout getSnView(String no, String snCode) {
        LinearLayout layout = new LinearLayout(requireContext());
        layout.setOrientation(LinearLayout.HORIZONTAL);
        //序號
        TextView tvNo = new TextView(requireContext());
        tvNo.setTextSize(14);
        tvNo.setTextColor(ContextCompat.getColor(requireContext(), R.color.black));
        tvNo.setText(no);

        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.weight = 1;
        layoutParams.setMargins(0, 5, 0, 0);
        layout.addView(tvNo, layoutParams);

        TextView tvSnCode = new TextView(requireContext());
        tvSnCode.setTextColor(ContextCompat.getColor(requireContext(), R.color.black));
        tvSnCode.setTextSize(14);
        tvSnCode.setText(snCode);

        LinearLayout.LayoutParams snCodeParams = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT);
        snCodeParams.weight = 2;
        snCodeParams.setMargins(0, 5, 0, 0);
        layout.addView(tvSnCode, snCodeParams);
        return layout;
    }

    /**
     * 顯示消耗列表
     *
     * @param visible 是否顯示
     */
    @Override
    public void showList(int visible) {
        vpWarehouseViewpager.setVisibility(visible);
        layoutTitle.setVisibility(visible);
        loadService.showSuccess();
        if (visible == View.VISIBLE) {
            removeInventoryView();
        } else {
            smartRefreshLayout.setEnableRefresh(false);
            smartRefreshLayout.setEnableLoadMore(false);
        }
    }

    @Override
    public void getPageInfo() {
        if (vpWarehouseViewpager.getCurrentItem() == WAREHOUSE_TYPE) {
            //獲取入庫流水
            getWarehouseDetails();
        } else {
            //獲取出庫流水
            getOutStockDetails();
        }
    }

    @Override
    public void setWarehousingNum(int num) {
        purchaseWarehousingOrderDetailsVO.setFoodNum(num);
        tvWarehouseInventoryNumber.setText(String.valueOf(num));
    }

    @OnClick({R2.id.tv_warehousing_record, R2.id.tv_outbound_record, R2.id.tv_warehouse_inventory_number})
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.tv_warehousing_record) {
            //入庫流水
            vpWarehouseViewpager.setCurrentItem(WAREHOUSE_TYPE);
            //查詢入庫
            getWarehouseDetails();
        } else if (v.getId() == R.id.tv_outbound_record) {
            //出庫流水
            vpWarehouseViewpager.setCurrentItem(OUT_STOCK_TYPE);
            //查詢出庫
            getOutStockDetails();
        } else if (v.getId() == R.id.tv_warehouse_inventory_number) {
            if (purchaseWarehousingOrderDetailsVO.getFoodMarkSn() == PurchaseFoodBean.HAS_SN) {
                //是sn食材，查詢庫中剩餘的sn碼
                start(SnCodeListFragment.newInstance(-1, new WarehouseDetailsBean(purchaseWarehousingOrderDetailsVO.getName(), purchaseWarehousingOrderDetailsVO.getFoodNum(), purchaseWarehousingOrderDetailsVO.getFoodNo())));
            }
        }
    }

    /**
     * 因為關閉頁面也是調用的onBackPressedSupport，所以用戶選擇了關閉頁面，那麼就用修改這個值
     */
    boolean isLeave = false;

    @Override
    public boolean onBackPressedSupport() {
        if (isLeave) {
            return super.onBackPressedSupport();
        }
        if (inventoryConsumptionView != null) {
            if (scanSnView != null && scanSnView.getSnSize() > 0) {
                //當前顯示著掃SN碼消耗，判斷有沒有SN碼，有的話提示是否保存
                AppDialog.getInstance().showTipDialog(requireContext(), getString(R.string.str_info_not_save_about_to_leave), (view, dialog) -> {
                    isLeave = true;
                    showList(View.VISIBLE);
                }, (view, dialog) -> isLeave = false);
            } else {
                showList(View.VISIBLE);
            }
            return true;
        }
        return super.onBackPressedSupport();
    }
}
