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

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.gingersoft.gsa.cloud.common.utils.CollectionUtils;
import com.gingersoft.gsa.cloud.common.utils.FileUtils;
import com.gingersoft.gsa.cloud.common.utils.MoneyUtil;
import com.gingersoft.gsa.cloud.common.utils.glide.GlideUtils;
import com.gingersoft.gsa.cloud.common.utils.inputFilter.InputFilterUtils;
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.toast.ToastUtils;
import com.gingersoft.gsa.cloud.ui.adapter.multi.RemarkProvider;
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.DaggerOrderDetailsComponent;
import com.gingersoft.supply_chain.mvp.bean.DeputyUnitBean;
import com.gingersoft.supply_chain.mvp.bean.PurchaseFoodBean;
import com.gingersoft.supply_chain.mvp.bean.PurchaseFoodEncodeSn;
import com.gingersoft.supply_chain.mvp.bean.PurchaseOrderDetailsBean;
import com.gingersoft.supply_chain.mvp.contract.OrderDetailsContract;
import com.gingersoft.supply_chain.mvp.presenter.OrderDetailsPresenter;
import com.gingersoft.supply_chain.mvp.ui.adapter.ImageAdapter;
import com.gingersoft.supply_chain.mvp.ui.adapter.OrderDetailsFoodAdapter;
import com.gingersoft.supply_chain.mvp.ui.adapter.SnNameAdapter;
import com.gingersoft.supply_chain.mvp.ui.fragment.BaseSupplyChainFragment;
import com.gingersoft.supply_chain.mvp.ui.widget.CenterLayoutManager;
import com.gingersoft.supply_chain.mvp.ui.widget.ChooseUnitPopup;
import com.gingersoft.supply_chain.mvp.ui.widget.PurchaseListMorePopup;
import com.gingersoft.supply_chain.mvp.ui.widget.ScanSnPopup;
import com.gingersoft.supply_chain.mvp.utils.SelectPicture;
import com.gingersoft.supply_chain.mvp.utils.ViewUtils;
import com.google.android.material.checkbox.MaterialCheckBox;
import com.google.android.material.textfield.TextInputLayout;
import com.jess.arms.di.component.AppComponent;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.enums.PopupPosition;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.lxj.xpopup.interfaces.XPopupImageLoader;
import com.qmuiteam.qmui.alpha.QMUIAlphaTextView;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.yalantis.ucrop.UCrop;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.yalantis.ucrop.UCrop.REQUEST_CROP;


/**
 * ================================================
 * Description: 訂單詳情，收貨操作頁面
 */
public class OrderDetailsFragment extends BaseSupplyChainFragment<OrderDetailsPresenter> implements OrderDetailsContract.View, View.OnClickListener {

    @BindView(R2.id.supply_top_bar)
    QMUITopBar supplyTopBar;
    @BindView(R2.id.tv_order_details_supplier_name)
    TextView tvOrderDetailsSupplierName;
    @BindView(R2.id.tv_order_details_create_time)
    TextView tvOrderDetailsCreateTime;
    @BindView(R2.id.tv_order_details_order_no)
    TextView tvOrderDetailsOrderNo;
    @BindView(R2.id.tv_warehouse_order_no)
    TextView tvWarehouseOrderNo;
    @BindView(R2.id.layout_remarks)
    LinearLayout layoutRemarks;
    @BindView(R2.id.iv_order_state)
    ImageView ivOrderState;
    @BindView(R2.id.rv_order_details_pictures)
    RecyclerView rvOrderDetailsPictures;
    @BindView(R2.id.rv_order_details_food_name)
    RecyclerView rvOrderDetailsFoodName;
    @BindView(R2.id.rv_order_details_food_list)
    RecyclerView rvOrderDetailsFoodList;
    @BindView(R2.id.cb_order_details_all_selected)
    MaterialCheckBox cbOrderDetailsAllSelected;
    @BindView(R2.id.tv_order_details_food_type_total)
    TextView tvOrderDetailsFoodTypeTotal;
    @BindView(R2.id.tv_order_details_total_amount)
    TextView tvOrderDetailsTotalAmount;
    @BindView(R2.id.tv_order_details_partial_receipt)
    QMUIAlphaTextView tvOrderDetailsPartialReceipt;
    @BindView(R2.id.tv_order_details_receipt)
    QMUIAlphaTextView tvOrderDetailsReceipt;
    @BindView(R2.id.layout_input_remark)
    TextInputLayout layoutInputRemark;
    @BindView(R2.id.ed_warehouse_order_remark)
    EditText edRemark;
    @BindView(R2.id.card_show_more_food_name)
    CardView cardMoreFoodName;

    private OrderDetailsFoodAdapter orderDetailsFoodAdapter;

    ImageAdapter imageAdapter;
    private int typesOfFood = 0;
    private double totalAmount = 0;
    /**
     * 記錄全選當前遍歷到的下標，因為有sn食材，需要去異步查詢
     */
    private int currentFoodIndex = 0;
    private boolean checkState = false;
    //    private int orderState = PurchaseOrderDetailsBean.WAIT_RECEIVED;
    private final static String ORDER_DETAILS_ORDER_ID = "orderId";
    private final static String ORDER_STATE = "orderState";
    private int orderState;

    public static OrderDetailsFragment newInstance(int orderId, int orderState) {
        OrderDetailsFragment fragment = new OrderDetailsFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(ORDER_DETAILS_ORDER_ID, orderId);
        bundle.putInt(ORDER_STATE, orderState);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerOrderDetailsComponent //如找不到该类,请编译一下项目
                .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_order_details_new, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        initTopBar(supplyTopBar, getString(R.string.str_warehousing_order));
        supplyTopBar.addRightImageButton(R.drawable.ic_white_more, R.id.id_more).setOnClickListener(this);
        edRemark.setFilters(new InputFilter[]{InputFilterUtils.getLengthFilter(mContext, RemarkProvider.REMARK_TEXT_LENGTH), InputFilterUtils.getChAndEnNumPtWrapInputFilter(mContext)});
        Bundle arguments = getArguments();
        if (arguments != null) {
            int orderId = arguments.getInt(ORDER_DETAILS_ORDER_ID, 0);
            orderState = arguments.getInt(ORDER_STATE, PurchaseOrderDetailsBean.WAIT_RECEIVED);
            int isShow = orderState == PurchaseOrderDetailsBean.COMPLETE_RECEIVED ? View.GONE : View.VISIBLE;
            tvOrderDetailsPartialReceipt.setVisibility(isShow);
            tvOrderDetailsReceipt.setVisibility(isShow);
            mPresenter.getOrderDetailsById(orderId);
        } else {
            showMessage("未獲取到訂單編號，請退出重試");
            killMyself();
        }
    }


    @OnClick({R2.id.tv_order_details_partial_receipt, R2.id.tv_order_details_receipt, R2.id.layout_remarks, R2.id.card_show_more_food_name})
    @Override
    public void onClick(View v) {
        int viewId = v.getId();
        if (viewId == R.id.id_take_pictures) {
            //拍照
            if (mPresenter.getPicSize() < 4) {
                SelectPicture.getInstance().showSelectType(this);
            } else {
                ToastUtils.show(requireContext(), "最多只能上傳四張圖片");
            }
        } else if (viewId == R.id.id_more) {
            //更多：刪除。發送。再次購買
            String[] functions;
            if (orderState == PurchaseOrderDetailsBean.COMPLETE_RECEIVED) {
                functions = new String[]{"再來一單"};
            } else {
                functions = new String[]{"再來一單", "删除訂單", "部分收貨", "全部收貨"};
            }
            new XPopup.Builder(mContext)
                    .atView(v)
                    .hasShadowBg(false)
                    .popupPosition(PopupPosition.Left)
                    .asCustom(new PurchaseListMorePopup(mContext)
                            .setStringData(functions, new int[]{R.drawable.ic_purchase_buy_again, R.drawable.ic_purchase_delete, R.drawable.ic_small_partial_receipt, R.drawable.ic_receipt})
                            .setOnSelectListener(mOnSelectListener))
                    .show();
        } else if (viewId == R.id.tv_order_details_partial_receipt) {
            //部分收貨
            addWarehouse(PurchaseOrderDetailsBean.PART_RECEIVED);
        } else if (viewId == R.id.tv_order_details_receipt) {
            //收貨
            addWarehouse(PurchaseOrderDetailsBean.COMPLETE_RECEIVED);
        } else if (viewId == R.id.layout_remarks) {
            //備註，顯示備註輸入框
            layoutInputRemark.setVisibility(layoutInputRemark.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE);
        } else if (viewId == R.id.card_show_more_food_name) {
            //展開食品名稱彈窗

        }
    }

    /**
     * 收貨操作
     *
     * @param state 狀態，全部收貨還是部分收貨
     */
    private void addWarehouse(int state) {
        for (PurchaseOrderDetailsBean.PurchaseOrderDetailsInfoVosBean data : orderDetailsFoodAdapter.getData()) {
            //只要有一個是選中的，就不循環了，開始收貨
            if (data.isChecked()) {
                AppDialog.getInstance().showTipDialog(requireContext(), getString(R.string.str_confirm_receipt), () -> {
                    mPresenter.addWarehouse(state, edRemark.getText() + "", totalAmount, orderDetailsFoodAdapter.getData());
                    setBackResult();
                });
                return;
            }
        }
        //循環完了，沒有一個選中的，提示用戶
        showMessage(getString(R.string.str_select_least_one_product));
    }

    private OnSelectListener mOnSelectListener = (position, text) -> {
        if (position == 0) {
            //再來一單
            mPresenter.buyAgainByFoodIds(orderDetailsFoodAdapter.getData());
        } else if (position == 1) {
            //刪除訂單
            if (orderDetailsFoodAdapter != null && !mPresenter.allWaitReceived(orderDetailsFoodAdapter.getData())) {
                showMessage("有已收貨食材，訂單不可刪除");
                return;
            }
            setBackResult();
            AppDialog.getInstance().showWaringDialog(mContext, "是否刪除訂單", () -> mPresenter.deleteOrder());
        } else if (position == 2) {
            //部分收貨
            addWarehouse(PurchaseOrderDetailsBean.PART_RECEIVED);
        } else if (position == 3) {
            //收貨
            addWarehouse(PurchaseOrderDetailsBean.COMPLETE_RECEIVED);
        }
    };

    private void setBackResult(){
        setFragmentResult(RESULT_OK, null);
    }
    /**
     * 加載訂單詳情
     *
     * @param orderDetailsBean 訂單詳情
     */
    @Override
    public void loadOrderDetails(PurchaseOrderDetailsBean orderDetailsBean) {
        //判斷有沒有SN食材，如果沒有，就顯示全選按妞
        if (orderDetailsBean.getStatus() == PurchaseOrderDetailsBean.COMPLETE_RECEIVED) {
            //全部收貨，顯示備註，備註不可編輯
            layoutRemarks.setVisibility(View.GONE);
            edRemark.setEnabled(false);
            edRemark.setFocusable(false);
            edRemark.setBackground(null);
            cbOrderDetailsAllSelected.setVisibility(View.VISIBLE);
            if (TextUtil.isNotEmptyOrNullOrUndefined(orderDetailsBean.getWarehousingRemarks())) {
                layoutInputRemark.setVisibility(View.VISIBLE);
                layoutInputRemark.setCounterEnabled(false);
            }
        } else {
            cbOrderDetailsAllSelected.setVisibility(mPresenter.hasSnFood(orderDetailsBean.getPurchaseOrderDetailsInfoVOS()) ? View.GONE : View.VISIBLE);
            supplyTopBar.addRightImageButton(R.drawable.ic_take_pictures, R.id.id_take_pictures).setOnClickListener(this);
        }
        if (TextUtil.isNotEmptyOrNullOrUndefined(orderDetailsBean.getWarehousingRemarks())) {
            edRemark.setText(orderDetailsBean.getWarehousingRemarks());
        }
        tvOrderDetailsSupplierName.setText(orderDetailsBean.getSupplierName());
        tvOrderDetailsOrderNo.setText(String.format(getString(R.string.str_format_purchase_no), orderDetailsBean.getOrderNo()));
        if (TextUtil.isNotEmptyOrNullOrUndefined(orderDetailsBean.getWarehousingOrderNo())) {
            tvWarehouseOrderNo.setText(String.format(getString(R.string.str_format_warehouse_no), orderDetailsBean.getWarehousingOrderNo()));
            tvWarehouseOrderNo.setVisibility(View.VISIBLE);
        } else {
            tvWarehouseOrderNo.setVisibility(View.GONE);
        }
        tvOrderDetailsCreateTime.setText(TimeUtils.getStringByFormat(orderDetailsBean.getCreateTime(), TimeUtils.DEFAULT_DATE_FORMAT_YMDHM));
        switch (orderDetailsBean.getStatus()) {
            case PurchaseOrderDetailsBean.WAIT_RECEIVED:
                ivOrderState.setVisibility(View.INVISIBLE);
                break;
            case PurchaseOrderDetailsBean.PART_RECEIVED:
                ivOrderState.setVisibility(View.VISIBLE);
                ivOrderState.setImageResource(R.drawable.ic_partial_receipt);
                break;
            case PurchaseOrderDetailsBean.COMPLETE_RECEIVED:
                ivOrderState.setImageResource(R.drawable.ic_all_receipt);
                break;
            case PurchaseOrderDetailsBean.REFUSE_RECEIVED:
                //拒收
                ivOrderState.setImageResource(R.drawable.ic_refuse_accept);
                break;
            default:
                break;
        }
        setTypesOfFood();

        initRecyclerView(orderDetailsBean);
        //全選按鈕狀態切換
        cbOrderDetailsAllSelected.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (buttonView.isPressed()) {
                //重新計算總價
                totalAmount = 0;
                typesOfFood = 0;
                //修改所有食品的選中狀態，計算所有實付金額
                currentFoodIndex = 0;
                checkState = isChecked;
                //遍歷去執行全選，
                checkAllForEach();
                orderDetailsFoodAdapter.notifyDataSetChanged();
                setTotalAmount();
                setTypesOfFood();
            }
        });
    }

    /**
     * 全選，以前的需求，全選時要一個一個遍歷，掃SN碼的就彈窗，掃完一個又彈下一個
     */
    private void checkAllForEach() {
        int itemCount = orderDetailsFoodAdapter.getItemCount();
        if (currentFoodIndex >= itemCount) {
            //沒有更多食品了，判斷是否全選
            cbOrderDetailsAllSelected.setChecked(typesOfFood == itemCount);
            setTypesOfFood();
        }
        if (mPresenter.orderState == PurchaseOrderDetailsBean.COMPLETE_RECEIVED) {
            //全部收貨的全選
            for (PurchaseOrderDetailsBean.PurchaseOrderDetailsInfoVosBean datum : orderDetailsFoodAdapter.getData()) {
                selectFood(datum);
            }
        } else {
            for (int i = currentFoodIndex; i < itemCount; i++) {
                PurchaseOrderDetailsBean.PurchaseOrderDetailsInfoVosBean datum = orderDetailsFoodAdapter.getItem(i);
                // 如果是sn，判斷這個食品是否已選中，並且本次狀態要為選中
                // 判斷不是已經全部收貨的食品
                // 再判斷這個食品的sn數量和入庫數量是否一致，不一致則再次選擇
                // 判斷是否需要去查詢已經保存的sn碼。
                if (datum.getFoodMarkSn() == PurchaseFoodBean.HAS_SN && checkState && datum.getStatus() != PurchaseOrderDetailsBean.COMPLETE_RECEIVED) {
                    DeputyUnitBean showUnit = datum.getShowUnit();
                    int newSnCodeSize = mPresenter.getNewSnCodeSize(datum.getPurchaseFoodEncodeSns());
                    if (showUnit.getDeputyValue() != newSnCodeSize) {
                        isNeedQuerySn(orderDetailsFoodAdapter.getItemPosition(datum), datum, false);
                        currentFoodIndex = i;
                    } else {
                        selectFood(datum);
                        //收貨數量等於sn數量，就不用再彈窗了
                        nextFood();
                    }
                    break;
                } else {
                    selectFood(datum);
                }
            }
        }
    }

    private void selectFood(PurchaseOrderDetailsBean.PurchaseOrderDetailsInfoVosBean datum) {
        datum.setChecked(checkState);
        if (checkState) {
            typesOfFood++;
            DeputyUnitBean unit = datum.getShowUnit();
            totalAmount = MoneyUtil.sum(totalAmount, MoneyUtil.priceCalculation(unit.getDeputyValue(), unit.getUnitPrice()));
        }
    }

    @Override
    public void nextFood() {
        hideSoftInput();
//        currentFoodIndex++;
//        checkAllForEach();
    }

    @Override
    public void uploadPicSuccess(String imgUrl) {
        if (imageAdapter == null) {
            imageAdapter = new ImageAdapter(mPresenter.orderState == PurchaseOrderDetailsBean.COMPLETE_RECEIVED);
            rvOrderDetailsPictures.setAdapter(imageAdapter);
            rvOrderDetailsPictures.setLayoutManager(new GridLayoutManager(requireContext(), 4));
            imageAdapter.setOnItemChildClickListener((adapter, view, position) -> {
                if (view.getId() == R.id.iv_img_delete) {
                    imageAdapter.removeAt(position);
                    mPresenter.deletePic(position);
                } else if (view.getId() == R.id.iv_img) {
                    //預覽大圖
                    new XPopup.Builder(requireContext())
                            .isDestroyOnDismiss(true)
                            .isDarkTheme(false)
                            .enableDrag(false)
                            .asImageViewer((ImageView) view, position, mPresenter.getImgs(), false, false, Color.parseColor("#f1f1f1"), -1, -1, false, Color.parseColor("#f0f0f0"), null, new ImageLoader())
                            .show();
                }
            });
        }
        imageAdapter.addData(imgUrl);
    }

    @Override
    public void buyAgain() {
        setBackResult();
        startWithPop(ShoppingCatFragment.newInstance());
    }

    @Override
    public void querySnCodeSuccess(int position, PurchaseOrderDetailsBean.PurchaseOrderDetailsInfoVosBean infoVosBean, boolean singerFood) {
        showScanPopup(position, infoVosBean, singerFood);
    }

    public static class ImageLoader implements XPopupImageLoader {
        @Override
        public void loadImage(int position, @NonNull Object url, @NonNull ImageView imageView) {
            //必须指定Target.SIZE_ORIGINAL，否则无法拿到原图，就无法享用天衣无缝的动画
            Glide.with(imageView).load(url).apply(new RequestOptions().override(Target.SIZE_ORIGINAL)).into(imageView);
        }

        @Override
        public File getImageFile(@NonNull Context context, @NonNull Object uri) {
            try {
                return Glide.with(context).downloadOnly().load(uri).submit().get();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    }

    private void setTypesOfFood() {
        tvOrderDetailsFoodTypeTotal.setText(String.valueOf(typesOfFood));
    }

    private void setTotalAmount() {
        tvOrderDetailsTotalAmount.setText(String.valueOf(totalAmount));
    }

    private void initRecyclerView(PurchaseOrderDetailsBean orderDetailsBean) {
        rvOrderDetailsFoodName.setLayoutManager(new CenterLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false));
        SnNameAdapter snNameAdapter = new SnNameAdapter(orderDetailsBean.getPurchaseOrderDetailsInfoVOS());

        rvOrderDetailsFoodName.setAdapter(snNameAdapter);

        orderDetailsFoodAdapter = new OrderDetailsFoodAdapter(mContext, orderDetailsBean.getPurchaseOrderDetailsInfoVOS());
        rvOrderDetailsFoodList.setAdapter(orderDetailsFoodAdapter);
        rvOrderDetailsFoodList.setLayoutManager(new CenterLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false));
        orderDetailsFoodAdapter.setOnAmountChangeListener((position, value) -> {
            totalAmount = MoneyUtil.sum(totalAmount, value);
            setTotalAmount();
        });
        //食材點擊事件
        orderDetailsFoodAdapter.setOnItemClickListener((adapter, view, position) -> {
            PurchaseOrderDetailsBean.PurchaseOrderDetailsInfoVosBean infoVosBean = orderDetailsFoodAdapter.getData().get(position);
            if (infoVosBean.getFoodMarkSn() == PurchaseFoodBean.HAS_SN) {
                //sn食材，如果是選中狀態，改為未選中
                //如果未選中，查看食材是否已經收過貨，信息里是否有sn碼，如果有，就直接顯示掃碼彈窗，如果沒有，就通過接口獲取這個食材的sn碼
                if (infoVosBean.isChecked()) {
                    setFoodCheckState(adapter, position, infoVosBean);
                } else {
                    isNeedQuerySn(position, infoVosBean, true);
                }
            } else {
                //不是sn食材，選中
                setFoodCheckState(adapter, position, infoVosBean);
            }
        });
        orderDetailsFoodAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            int id = view.getId();
            //食材單位點擊事件
            if (id == R.id.layout_order_details_unit) {
                //切換單位
                PurchaseOrderDetailsBean.PurchaseOrderDetailsInfoVosBean purchaseOrderDetailsInfoVosBean = orderDetailsFoodAdapter.getData().get(position);
                List<DeputyUnitBean> foodUnits = purchaseOrderDetailsInfoVosBean.getFoodUnits();
                List<String> units = new ArrayList<>();
                if (foodUnits != null) {
                    for (int i = 0; i < foodUnits.size(); i++) {
                        units.add(foodUnits.get(i).getDeputyUnit());
                    }
                }
                if (units.size() > 1) {
                    ChooseUnitPopup popup = new ChooseUnitPopup(requireContext()).setStringData(units).setOnSelectListener((position1, text) -> {
                        //將用戶之前輸入的值，修改到新選擇的單位匯中
                        DeputyUnitBean showUnit = purchaseOrderDetailsInfoVosBean.getShowUnit();
                        if (foodUnits != null && position1 < foodUnits.size()) {
                            DeputyUnitBean deputyUnitBean = foodUnits.get(position1);
                            deputyUnitBean.setDeputyValue(showUnit.getDeputyValue());
                            deputyUnitBean.setUnitPrice(showUnit.getUnitPrice());
                            purchaseOrderDetailsInfoVosBean.setShowUnit(deputyUnitBean);
                            orderDetailsFoodAdapter.notifyItemChanged(position1);
                        }
                    });
                    new XPopup.Builder(getContext())
                            .hasShadowBg(false)
                            .atView(view)  // 依附于所点击的View，内部会自动判断在上方或者下方显示
                            .asCustom(popup)
                            .show();
                }
            }
        });
//        setMoreNameCard();
        snNameAdapter.setOnItemClickListener((adapter, view, position) -> {
            //點擊滑動到對應的食品
            rvOrderDetailsFoodList.smoothScrollToPosition(position);
            ViewUtils.moveToCenterByHorizontal(rvOrderDetailsFoodName, position);
//            ViewUtils.moveToCenterByVertical(rvOrderDetailsFoodList, position);
            LinearLayoutManager layoutManager = (LinearLayoutManager) rvOrderDetailsFoodList.getLayoutManager();
            layoutManager.scrollToPositionWithOffset(position, 0);
            View childAt = layoutManager.findViewByPosition(position);
            if (childAt != null) {
                Animation alphaAnimation = new AlphaAnimation(1.0f, 0.2f);
                alphaAnimation.setDuration(600);
                alphaAnimation.setFillBefore(true);
                alphaAnimation.setInterpolator(new LinearInterpolator());
                alphaAnimation.setRepeatCount(2);
                alphaAnimation.setRepeatMode(Animation.REVERSE);
                childAt.startAnimation(alphaAnimation);
            }
        });
    }

    /**
     * 設置展開更多名稱的view高度
     */
    private void setMoreNameCard() {
        cardMoreFoodName.post(() -> {
            int measuredHeight = cardMoreFoodName.getMeasuredHeight();
            ViewGroup.LayoutParams layoutParams = cardMoreFoodName.getLayoutParams();
            layoutParams.width = measuredHeight;
            cardMoreFoodName.setLayoutParams(layoutParams);
        });
    }

    /**
     * 是否需要查詢sn碼
     *
     * @param position    下標
     * @param infoVosBean 食材信息
     */
    private void isNeedQuerySn(int position, PurchaseOrderDetailsBean.PurchaseOrderDetailsInfoVosBean infoVosBean, boolean singerFood) {
        if (infoVosBean.getStatus() == PurchaseOrderDetailsBean.WAIT_RECEIVED || CollectionUtils.isNotNullOrEmpty(infoVosBean.getPurchaseFoodEncodeSns())) {
            //沒收過貨的，並且有SN碼
            showScanPopup(position, infoVosBean, singerFood);
        } else {
            //收過貨的，需要查詢sn碼
            mPresenter.querySnCodes(position, infoVosBean, singerFood);
        }
    }

    /**
     * 顯示掃碼popupwindow
     *
     * @param position    下標
     * @param infoVosBean 食品信息
     * @param singerFood  是否是對單個食品操作
     */
    private void showScanPopup(int position, PurchaseOrderDetailsBean.PurchaseOrderDetailsInfoVosBean infoVosBean, boolean singerFood) {
        List<PurchaseFoodEncodeSn> foodEncodeSns = infoVosBean.getPurchaseFoodEncodeSns();

        ScanSnPopup scanSnPopup = new ScanSnPopup(this, infoVosBean.getName(), CollectionUtils.deepCopy(foodEncodeSns), infoVosBean.getStatus() != PurchaseOrderDetailsBean.COMPLETE_RECEIVED)
                .setOnDeleteListener((snCode, snPosition) -> {
                    if (!snCode.newAdd) {
                        mPresenter.deleteSn(infoVosBean.getOrderNo(), infoVosBean.getFoodNo(), snCode.getEncodeSnNo());
                        foodEncodeSns.remove(snCode);
                    }
                });
        scanSnPopup.setOnScanResultListener((popup, scanResult) -> {
            //當前食材infoVosBean裡面有個sn碼集合，將scanResult添加進去
            if (scanResult != null && scanResult.size() > 0) {
                //过滤出新增的
                List<PurchaseFoodEncodeSn> newAddSnCodes = new ArrayList<>(scanResult.size());
                for (PurchaseFoodEncodeSn purchaseFoodEncodeSn : scanResult) {
                    if (foodEncodeSns == null || (purchaseFoodEncodeSn.newAdd && !foodEncodeSns.contains(purchaseFoodEncodeSn))) {
                        //判斷這個snCode是不是已經收過貨了，沒收過貨，新增的就為true
                        PurchaseFoodEncodeSn newSnCodeBean = new PurchaseFoodEncodeSn();
                        newSnCodeBean.setEncodeFoodNo(infoVosBean.getFoodNo());
                        newSnCodeBean.setEncodeOrderNo(infoVosBean.getOrderNo());
                        newSnCodeBean.setEncodeSnNo(purchaseFoodEncodeSn.getEncodeSnNo());
                        newSnCodeBean.newAdd = true;
                        newAddSnCodes.add(newSnCodeBean);
                    }
                }
                if (CollectionUtils.isNotNullOrEmpty(foodEncodeSns)) {
                    //扫描完后的所有sn和之前的sn比较，如果之前的sn没了，说明删除了，就从食品对象中移除掉
                    Iterator<PurchaseFoodEncodeSn> iterator = foodEncodeSns.iterator();
                    while (iterator.hasNext()) {
                        PurchaseFoodEncodeSn next = iterator.next();
                        if (!scanResult.contains(next)) {
                            //将不存在的移除掉
                            iterator.remove();
                        }
                    }
                }
                //添加到食品中去
                if (foodEncodeSns != null) {
                    foodEncodeSns.addAll(newAddSnCodes);
                } else {
                    infoVosBean.setPurchaseFoodEncodeSns(newAddSnCodes);
                }
                int newAddSize = 0;
                //在這裡遍歷，防止用戶多次添加，卻沒有點擊收貨
                for (PurchaseFoodEncodeSn purchaseFoodEncodeSn : infoVosBean.getPurchaseFoodEncodeSns()) {
                    if (purchaseFoodEncodeSn.newAdd) {
                        newAddSize++;
                    }
                }
                //本次收貨數量=新增掃sn碼數量
                DeputyUnitBean showUnit = infoVosBean.getShowUnit();
                showUnit.setDeputyValue(newAddSize);
//                if (newAddSize > 0) {
                    setFoodCheckState(orderDetailsFoodAdapter, position, infoVosBean);
//                } else {
//                    showMessage("收貨數量必須大於0");
//                }
                scanSnPopup.dismissOrHideSoftInput();
                if (!scanSnPopup.isDismiss()) {
                    scanSnPopup.dismiss();
                }
            } else {
                showMessage("請掃描食材sn碼");
            }
        });
        new XPopup.Builder(requireContext())
                .asCustom(scanSnPopup)
                .show();
//        if (!singerFood) {
//            scanSnPopup.setOnDismissListener(this::nextFood);
//        }
    }

    /**
     * 設置食材選中狀態
     *
     * @param adapter     適配器
     * @param position    食材下標
     * @param infoVosBean 食材信息
     */
    private void setFoodCheckState(BaseQuickAdapter<?, ?> adapter, int position, PurchaseOrderDetailsBean.PurchaseOrderDetailsInfoVosBean infoVosBean) {
        infoVosBean.setChecked(!infoVosBean.isChecked());
        adapter.notifyItemChanged(position);
        //修改選中狀態後，重新計算入庫總價
        DeputyUnitBean showUnit = infoVosBean.getShowUnit();
        if (infoVosBean.isChecked()) {
            totalAmount = MoneyUtil.sum(totalAmount, MoneyUtil.priceCalculation(showUnit.getDeputyValue(), showUnit.getUnitPrice()));
            typesOfFood += 1;
        } else {
            totalAmount = MoneyUtil.sub(totalAmount, MoneyUtil.priceCalculation(showUnit.getDeputyValue(), showUnit.getUnitPrice()));
            typesOfFood -= 1;
        }
        //全選
        cbOrderDetailsAllSelected.setChecked(typesOfFood == orderDetailsFoodAdapter.getData().size());
        setTotalAmount();
        setTypesOfFood();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SelectPicture.CHOOSE_PHOTO && resultCode == RESULT_OK) {
            //從相冊選取完圖片之後
            if (data != null) {
                Uri uri = data.getData();
                if (uri != null) {
//                    File file = SelectPicture.getInstance().uriToFileApiQ(requireContext(), uri);
//                    SelectPicture.getInstance().crop(Uri.fromFile(file), this);
                    String filePath = FileUtils.getFilePathByUri(mContext, uri);
                    if (!TextUtils.isEmpty(filePath)) {
                        mPresenter.uploadPic(filePath);
                    }
                }
            }
        } else if (requestCode == SelectPicture.TAKE_PHOTO && resultCode == RESULT_OK) {
            //拍照
            Uri cameraUri = SelectPicture.getInstance().getmCameraUri();
            if (cameraUri != null) {
                String filePath = FileUtils.getFilePathByUri(mContext, cameraUri);
                if (!TextUtils.isEmpty(filePath)) {
                    mPresenter.uploadPic(filePath);
                }
            }
            //拍照完成後需要裁剪
//            SelectPicture.getInstance().crop(SelectPicture.getInstance().getmCameraUri(), this);
        } else if (requestCode == REQUEST_CROP && resultCode == RESULT_OK && data != null) {
            final Uri resultUri = UCrop.getOutput(data);
            if (resultUri != null) {
                String filePath = FileUtils.getFilePathByUri(mContext, resultUri);
                if (!TextUtils.isEmpty(filePath)) {
                    mPresenter.uploadPic(filePath);
                }
            }
        }
    }
}
