package com.gingersoft.gsa.cloud.table.mvp.presenter;

import android.app.Application;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.View;

import com.billy.cc.core.component.CC;
import com.gingersoft.gsa.cloud.aspectj.XClickUtil;
import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication;
import com.gingersoft.gsa.cloud.base.common.bean.BaseResult;
import com.gingersoft.gsa.cloud.base.common.bean.OrderBean;
import com.gingersoft.gsa.cloud.base.common.bean.OrderDetail;
import com.gingersoft.gsa.cloud.base.common.bean.mealManage.MyOrderManage;
import com.gingersoft.gsa.cloud.base.common.bean.mealManage.OpenTableManage;
import com.gingersoft.gsa.cloud.base.utils.JsonUtils;
import com.gingersoft.gsa.cloud.base.utils.LanguageUtils;
import com.gingersoft.gsa.cloud.base.utils.MoneyUtil;
import com.gingersoft.gsa.cloud.base.utils.gson.GsonUtils;
import com.gingersoft.gsa.cloud.constans.PrintConstans;
import com.gingersoft.gsa.cloud.database.bean.ComboItem;
import com.gingersoft.gsa.cloud.database.bean.Discount;
import com.gingersoft.gsa.cloud.database.bean.Food;
import com.gingersoft.gsa.cloud.database.bean.FoodCombo;
import com.gingersoft.gsa.cloud.database.bean.Modifier;
import com.gingersoft.gsa.cloud.database.utils.FoodDaoUtils;
import com.gingersoft.gsa.cloud.database.utils.ModifierDaoUtils;
import com.gingersoft.gsa.cloud.table.R;
import com.gingersoft.gsa.cloud.table.mvp.contract.MealStandContract;
import com.gingersoft.gsa.cloud.table.mvp.model.bean.BaseRespose;
import com.gingersoft.gsa.cloud.table.mvp.model.bean.FoodReason;
import com.gingersoft.gsa.cloud.table.mvp.model.bean.SoldoutCtrFood;
import com.gingersoft.gsa.cloud.table.mvp.model.bean.request.AddOrderRequest;
import com.gingersoft.gsa.cloud.table.mvp.model.bean.request.CreateOrderRequest;
import com.gingersoft.gsa.cloud.table.mvp.model.bean.request.DeleteOrderRequest;
import com.gingersoft.gsa.cloud.constans.MealConstant;
import com.gingersoft.gsa.cloud.table.mvp.model.utils.OrderAssemblyUtil;
import com.gingersoft.gsa.cloud.table.mvp.ui.activity.MealStandActivity;
import com.gingersoft.gsa.cloud.table.mvp.ui.adapter.meal.DiscountAdapter;
import com.gingersoft.gsa.cloud.table.mvp.ui.adapter.meal.SelectMealAdapter;
import com.gingersoft.gsa.cloud.table.mvp.ui.widget.CancelFoodDialog;
import com.gingersoft.gsa.cloud.table.mvp.ui.adapter.meal.ComboAdapter;
import com.gingersoft.gsa.cloud.table.mvp.ui.adapter.meal.FoodAdapter;
import com.gingersoft.gsa.cloud.table.mvp.ui.adapter.meal.FoodGroupAdapter;
import com.gingersoft.gsa.cloud.table.mvp.ui.adapter.meal.ModifierAdapter;
import com.gingersoft.gsa.cloud.ui.widget.dialog.CommonTipDialog;
import com.jess.arms.base.DefaultAdapter;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.utils.RxLifecycleUtils;
import com.jess.arms.utils.ZipHelper;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.RequestBody;

import static com.gingersoft.gsa.cloud.table.mvp.ui.activity.SoldoutCtrlActivity.FOOD_GROUP_TYPE;
import static com.gingersoft.gsa.cloud.table.mvp.ui.activity.SoldoutCtrlActivity.FOOD_TYPE;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 12/27/2019 19:17
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
@ActivityScope
public class MealStandPresenter extends BaseOrderPresenter<MealStandContract.Model, MealStandContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    private MealStandActivity IActivity;

    private CancelFoodDialog.Builder mCancelFoodDialog;
//    private FoodReason[] mFoodReasons = {
//            new FoodReason.DataBean(1, 1, "漏單"),
//            new FoodReason.DataBean(2, 1, "沽清"),
//            new FoodReason.DataBean(3, 1, "試機"),
//            new FoodReason.DataBean(4, 1, "重單"),
//            new FoodReason.DataBean(5, 1, "落錯單"),
//            new FoodReason.DataBean(6, 1, "客人取消"),
//            new FoodReason.DataBean(7, 1, "問題食品"),
//            new FoodReason.DataBean(8, 1, "資料錯誤"),
//            new FoodReason.DataBean(9, 1, "部分轉移"),
//            new FoodReason.DataBean(10, 1, "其他"),
//    };

    private FoodAdapter mFoodAdapter;
    private ComboAdapter mComboAdapter;
    private ModifierAdapter mModifierAdapter;
    private DiscountAdapter mDiscountAdapter;
    //食品数据
    private List<Food> mFoodGroupList = new ArrayList<>();
    //當前食品組下食品
    private List<Food> mFoodList = new ArrayList<>();

    //套餐细项数据
    private List<ComboItem> mFoodComboList = new ArrayList<>();
    private List<Modifier> mModifierList = new ArrayList<>();
    //折扣数据
    private List<Discount> mDiscountList = new ArrayList<>();

    //沽清食品數據
    private List<SoldoutCtrFood> mSoldoutCtrList = new ArrayList<>();

    private boolean RvMealClicked;

    @Inject
    public MealStandPresenter(MealStandContract.Model model, MealStandContract.View rootView) {
        super(model, rootView);
        this.IActivity = (MealStandActivity) rootView;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }

    public void initMealData() {

        List<Food> foodGroupList = mModel.queryDB_FoodGroupList();

        if (foodGroupList != null && foodGroupList.size() > 0) {

            mFoodGroupList.addAll(foodGroupList);

            Food defalutFoodGroup = getDefalutFoodGroup(mFoodGroupList);
            if (defalutFoodGroup != null) {
                //默認選中第一組
                defalutFoodGroup.setSelected(true);
            }

            IActivity.initFoodGroupView(mFoodGroupList);

            if (defalutFoodGroup != null) {
                changedMealByParentId(defalutFoodGroup.getId());
            }
        }
    }

    private Food getDefalutFoodGroup(List<Food> foodGroupList) {
        Food defalutFoodGroup = null;
        for (Food food : foodGroupList) {
            if (food.getInvisible() == 0) {
                defalutFoodGroup = food;
                break;
            }
        }
        return defalutFoodGroup;
    }


    public void initAdapter() {
        if (mSelectMealAdapter != null) {
            mRootView.setSelectFoodAdapter(mSelectMealAdapter);
        }
//        myOrderManage.setSelectMealAdapter(mSelectMealAdapter);
//        if (mFoodGroupAdapter == null) {
//            mFoodGroupAdapter = new FoodGroupAdapter(IActivity, mFoodGroupList);
//            mRootView.setFoodGroupAdapter(mFoodGroupAdapter);
//        }
        if (mFoodAdapter == null) {
            mFoodAdapter = new FoodAdapter(IActivity, mFoodList, 1);
            mRootView.setFoodAdapter(mFoodAdapter);
        }
        if (mComboAdapter == null) {
            mComboAdapter = new ComboAdapter(IActivity, mFoodComboList);
            mRootView.setComboAdapter(mComboAdapter);
        }
        if (mModifierAdapter == null) {
            mModifierAdapter = new ModifierAdapter(IActivity, mModifierList);
            mRootView.setModifierAdapter(mModifierAdapter);
        }
        if (mDiscountAdapter == null) {
            mDiscountAdapter = new DiscountAdapter(IActivity, mDiscountList);
            mRootView.setDiscountAdapter(mDiscountAdapter);
        }
    }

    public void initItemClickListener() {
        mSelectMealAdapter.setOnItemClickListener(new SelectMealAdapter.OnItemClickListener() {

            @Override
            public void onItemClick(OrderDetail datasBean, int position) {

                mRootView.recordOperat(true);

                if (mSelectMealAdapter.getSelectedMode() == SelectMealAdapter.MULTIPLE_SELECTED) {
                    return;
                }

                RvMealClicked = true;
                //设置当前操作的食品
                mCurrentOrderDetailBean = datasBean;
                mSelectMealAdapter.setMyOrderManageSelectPosition();
                loadComboData(datasBean, true);
            }

            @Override
            public void onMealCountDelete(OrderDetail datasBean, int position) {
            }

            @Override
            public void onMealCountAdd(OrderDetail datasBean, int position) {
            }

            @Override
            public void onCurrentOrderDetail(OrderDetail datasBean, int position) {
                mCurrentOrderDetailBean = datasBean;
            }
        });
        mFoodAdapter.setOnItemClickListener(new FoodAdapter.OnItemClickListener() {

            @Override
            public void onItemClick(Food datasBean, int position) {
                mRootView.recordOperat(true);
                if (mSelectMealAdapter.getSelectedMode() == SelectMealAdapter.MULTIPLE_SELECTED) {
                    return;
                }
                if (!foodConditionFilter(datasBean)) {
                    return;
                }
                RvMealClicked = false;
                mCurrentOrderDetailBean = OrderDetail.foodTransOrderDetails(datasBean, 1);
                //加載套餐食品
                loadComboData(mCurrentOrderDetailBean, false);
                addFoodItemBefore(mCurrentOrderDetailBean);
                //更新最大可選數
                setFoodMaxQty(datasBean);
                updateOrderFoodNumber();
            }
        });
        mComboAdapter.setOnItemClickListener(new ComboAdapter.OnItemClickListener() {

            @Override
            public void onItemClick(ComboItem datasBean, int position) {

                mRootView.recordOperat(true);

                RvMealClicked = false;

                if (!comboConditionFilter(datasBean)) {
                    return;
                }
                if (cutOutCombo(datasBean) == -100) {
                    //已送單數量已等於最大數，不能繼續添加
                    return;
                }
                //设置当前操作的套餐细项
                long id = mCurrentOrderDetailBean.isNew() ? mCurrentOrderDetailBean.getProductId() : mCurrentOrderDetailBean.getId();
                mCurrentOrderDetailBean = OrderDetail.comboTransOrderDetail(datasBean, id, mCurrentOrderDetailBean.getProductId(), 1, OrderDetail.COMBO_PROP, RvMealClicked);
                //添加子项
                addComboItem(mCurrentOrderDetailBean);
                //更新賬單金額
                updateOrderMoneyItem();
            }
        });
        mModifierAdapter.setOnItemClickListener(new ModifierAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(Modifier datasBean, int position) {

                mRootView.recordOperat(true);

                RvMealClicked = false;

//                Food orderBean = isParentFood(datasBean.getFID());
//                if (orderBean != null && !foodConditionFilter(orderBean)) {
//                    return;
//                }
                if (cutOutModifier(datasBean) == -100) {
                    //已送單數量已等於最大數，不能繼續添加
                    return;
                }
//                if (datasBean.isModKeyboard()) {
//                    addModalKeyBoardModfier(datasBean.getModifier());
//                    displayModalKeyBoardDialog();
//                } else {
//                if (datasBean.isParent()) {
//                    loadModifierData(mCurrentOrderDetailBean.getProductId());
//                } else {
                addModifierItem(datasBean);
                //更新賬單金額
                updateOrderMoneyItem();
//                }
            }
        });
        mDiscountAdapter.setOnItemClickListener(new DefaultAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int viewType, Object data, int position) {

                Discount datasBean = (Discount) data;

                mRootView.recordOperat(true);

                if (XClickUtil.isFastDoubleClick(view, 1000)) {
                    return;
                }
//                if (!discountConditionFilter(datasBean)) {
//                    return;
//                }

                addDiscountItem(datasBean);
            }
        });
    }

    private void addFoodItemBefore(OrderDetail datasBean) {
        int addPosition = addFoodItem(datasBean);
        //这里主食品作为选中主体
        mRootView.setMealRvScrollToPosition(addPosition);
    }

    private int addFoodItem(OrderDetail orderDetail) {
        int addPosition = mSelectMealAdapter.addFoodItem(orderDetail);
        if (orderDetail.getComboLevel() > 0) {
            if (mFoodComboList != null && mFoodComboList.size() > 0) {
                for (int i = 0; i < mFoodComboList.size(); i++) {
                    //自动添加组合子食品
                    ComboItem comboItem = mFoodComboList.get(i);
                    if (comboItem.isSold()) {
                        String msg = "[" + comboItem.getName() + "]" + comboItem.getCurrentMaxNumber();
                        CommonTipDialog.showSurpisedDialog(IActivity, msg, null, null, null, null, null);
                        continue;
                    }
                    if (comboItem.getInvisible() != 2) {
                        int defNumber = Integer.parseInt(comboItem.getDefmodifier());
                        if (defNumber != 0) {
                            long id = mCurrentOrderDetailBean.isNew() ? mCurrentOrderDetailBean.getProductId() : mCurrentOrderDetailBean.getId();
                            mCurrentOrderDetailBean = OrderDetail.comboTransOrderDetail(comboItem, id, mCurrentOrderDetailBean.getProductId(), defNumber, OrderDetail.COMBO_PROP, RvMealClicked);
                            addPosition = addComboItem(mCurrentOrderDetailBean);
                        }
                    }
                }
            }
        }
        //自动添加mixqty>1細項
        for (int i = 0; i < mModifierList.size(); i++) {
            Modifier modfier = mModifierList.get(i);
            if (modfier.isSold()) {
                String msg = "[" + modfier.getModifierName() + "]" + modfier.getCurrentMaxNumber();
                CommonTipDialog.showSurpisedDialog(IActivity, msg, null, null, null, null, null);
                continue;
            }
            if (modfier.getInvisible() != 2) {
                int defNumber = Integer.parseInt(modfier.getDefmodifier());
                if (defNumber != 0) {
                    long id = mCurrentOrderDetailBean.isNew() ? mCurrentOrderDetailBean.getProductId() : mCurrentOrderDetailBean.getId();
                    addPosition = mSelectMealAdapter.addFoodItem(OrderDetail.modifierTransOrderDetail(modfier, id, mCurrentOrderDetailBean.getProductId(), defNumber));
                }
            }
        }
        return addPosition;
    }

    private int addComboItem(OrderDetail datasBean) {
        int addPosition = mSelectMealAdapter.addFoodItem(datasBean);
        mRootView.setMealRvScrollToPosition(addPosition);
        return addPosition;
    }

    @Subscriber(tag = MealConstant.ADD_FOOD_MODIFIER)
    private void addModifierItem(Modifier datasBean) {

        int addPosition = mOrderFoodList.size();
        if (mSelectMealAdapter.getSelectedMode() == SelectMealAdapter.MULTIPLE_SELECTED) {
            addPosition = addMultipleModifierItems(datasBean, addPosition);
        } else {
            long id = mCurrentOrderDetailBean.isNew() ? mCurrentOrderDetailBean.getProductId() : mCurrentOrderDetailBean.getId();
            mCurrentOrderDetailBean = OrderDetail.modifierTransOrderDetail(datasBean, id, mCurrentOrderDetailBean.getProductId(), 1);
            addPosition = mSelectMealAdapter.addFoodItem(mCurrentOrderDetailBean);
        }

        IActivity.setFineItemSlodoutListFull(mSoldoutCtrList);

        mRootView.setMealRvScrollToPosition(addPosition);
    }

    private void addDiscountItem(Discount datasBean) {
        //主食品ID
        long id = 0;
        if (mSelectMealAdapter.getCurrentMainOrderDetail() != null) {
            if (mCurrentOrderDetailBean.isNew()) {
                id = mSelectMealAdapter.getCurrentMainOrderDetail().getProductId();
            } else {
                id = mSelectMealAdapter.getCurrentMainOrderDetail().getId();
            }
        }
        mCurrentOrderDetailBean = OrderDetail.discountTransOrderDetail(datasBean, true, id, getDisountSourcePrice());
        int addPosition = mSelectMealAdapter.addFoodItem(mCurrentOrderDetailBean);
        mRootView.setMealRvScrollToPosition(addPosition);
    }

    private void loadComboData(OrderDetail food, boolean isSelectedMeal) {

        long fid = food.getProductId();

        List<ComboItem> comboItemList = new ArrayList<>();
        if (food.getItemType() == 1) {
            //获取套餐细项数据
            List<ComboItem> comboItems = mModel.queryDB_ComboList(fid);
            comboItemList.addAll(comboItems);
            //设置套餐沽清數據
            setComboItemSoldoutCtrData(comboItemList, mSoldoutCtrList);
        }
        List<Modifier> modifierList = mModel.queryDB_ModifierList(fid, ModifierDaoUtils.modifierMode_All);
        if (modifierList.size() > 0) {
            //设置细项沽清數據
            setModifierSoldoutCtrData(modifierList, mSoldoutCtrList);
        }
        //設置默認選中套餐食品
        setComboDefModifier(comboItemList);
        //設置默認選中細項
        setModifierDefModifier(modifierList);
        //更新套餐数据
        updateComboData(comboItemList);
        //更新细项数据
        updateModifierData(modifierList);

        if (comboItemList.size() > 0) {
            mRootView.setModifierTop(10);
        } else {
            mRootView.setModifierTop(0);
        }

//        isSelectedMeal = isSelectedMeal && (comboItemList.size() > 0 || modifierList.size() > 0);
        boolean autoMod = food.getAutoMod() == 1 && (comboItemList.size() > 0 || modifierList.size() > 0);
        if (IActivity.getCurrentViewMode() != MealConstant.fine_ViewMode && isSelectedMeal || autoMod) {
            mRootView.showViewModeVisibility(MealConstant.combo_ViewMode, MealConstant.modifier_ViewMode);
        }
    }

    /**
     * 裁減掉已超出的細項
     *
     * @param datasBean
     * @return
     */
    private int cutOutModifier(Modifier datasBean) {
        int cutPosition = getCutPositionByOutLimitModifier(datasBean);
        if (cutPosition != -1 && cutPosition != -100) {
            mSelectMealAdapter.removeFoodItemByPosition(cutPosition);
        }
        return cutPosition;
    }

    /**
     * 裁減掉已超出的套餐食品
     *
     * @param datasBean
     * @return
     */
    private int cutOutCombo(ComboItem datasBean) {
        int cutPosition = getCutPositionOutLimitCombo(datasBean);
        if (cutPosition != -1 && cutPosition != -100) {
            mSelectMealAdapter.removeFoodItemByPosition(cutPosition);
        }
        return cutPosition;
    }

    private int getCutPositionByOutLimitModifier(Modifier modifier) {
        int oldCount = 0;
        SparseArray<String> numberAndCutPositionMap = new SparseArray<>();
        OrderDetail currentMainOrderDetail = mSelectMealAdapter.getCurrentMainOrderDetail();
        if (currentMainOrderDetail != null) {
            int start_position = mSelectMealAdapter.getSelect_full_start_position();
            int end_position = mSelectMealAdapter.getSelect_full_end_position();
            for (int i = mOrderFoodList.size() - 1; i >= 0; i--) {
                if (start_position <= i && i <= end_position) {
                    OrderDetail item = mOrderFoodList.get(i);
                    if (item.getItemType() == 3 && item.getTopId() == modifier.getTopId()) {
                        //同一食品下的細項
                        String comboIdAndNumber = numberAndCutPositionMap.get((int) item.getTopId());
                        int cutPosition = i;
                        String value;
                        if (comboIdAndNumber != null) {
                            String[] splitStr = numberAndCutPositionMap.get((int) item.getTopId()).split("_");
                            if (item.isNew()) {
                                value = (Integer.parseInt(splitStr[0]) + item.getNumber()) + "_" + cutPosition;
                            } else {
                                //已下單不可替換刪除
                                if (splitStr.length > 1) {
                                    value = (Integer.parseInt(splitStr[0]) + item.getNumber()) + "_" + splitStr[1];
                                } else {
                                    value = (Integer.parseInt(splitStr[0]) + item.getNumber()) + "_";
                                }
                                oldCount++;
                            }
                        } else {
                            if (item.isNew()) {
                                value = item.getNumber() + "_" + cutPosition;
                            } else {
                                //已下單不可替換刪除
                                value = item.getNumber() + "_";
                                oldCount++;
                            }
                        }
                        numberAndCutPositionMap.put((int) item.getTopId(), value);
                    }
                }
            }
        }
        for (int i = 0; i < numberAndCutPositionMap.size(); i++) {
            String[] numberAndCutPositionStr = numberAndCutPositionMap.valueAt(i).split("_");
            int number = Integer.parseInt(numberAndCutPositionStr[0]);
            int maxQty = Integer.parseInt(modifier.getMaxNumber());
            if (numberAndCutPositionStr.length > 1 && !TextUtils.isEmpty(numberAndCutPositionStr[1])) {
                int cutPosition = Integer.parseInt(numberAndCutPositionStr[1]);
                if (maxQty <= number && cutPosition < mOrderFoodList.size()) {
                    return cutPosition;
                }
            } else {
                if (oldCount == maxQty) {
                    return -100;
                }
            }
        }
        return -1;
    }

    private int getCutPositionOutLimitCombo(ComboItem comboItem) {
        int oldCount = 0;
        SparseArray<String> numberAndCutPositionMap = new SparseArray<>();
        OrderDetail currentMainOrderDetail = mSelectMealAdapter.getCurrentMainOrderDetail();
        if (currentMainOrderDetail != null) {
            int start_position = mSelectMealAdapter.getSelect_full_start_position();
            int end_position = mSelectMealAdapter.getSelect_full_end_position();
            for (int i = mOrderFoodList.size() - 1; i >= 0; i--) {
                if (start_position <= i && i <= end_position) {
                    OrderDetail item = mOrderFoodList.get(i);
                    if (item.getItemType() == 2 && item.getTopId() == comboItem.getComId()) {
                        //同一套餐下的子食品
                        String comboIdAndNumber = numberAndCutPositionMap.get((int) item.getTopId());
                        int cutPosition = i;
                        String value;
                        if (comboIdAndNumber != null) {
                            String[] splitStr = numberAndCutPositionMap.get((int) item.getTopId()).split("_");
                            if (item.isNew()) {
                                value = (Integer.parseInt(splitStr[0]) + item.getNumber()) + "_" + cutPosition;
                            } else {
                                //已下單不可替換刪除
                                if (splitStr.length > 1) {
                                    value = (Integer.parseInt(splitStr[0]) + item.getNumber()) + "_" + splitStr[1];
                                } else {
                                    value = (Integer.parseInt(splitStr[0]) + item.getNumber()) + "_";
                                }
                                oldCount++;
                            }
                        } else {
                            if (item.isNew()) {
                                value = item.getNumber() + "_" + cutPosition;
                            } else {
                                //已下單不可替換刪除
                                value = item.getNumber() + "_";
                                oldCount++;
                            }
                        }
                        numberAndCutPositionMap.put((int) item.getTopId(), value);
                    }
                }
            }
        }
        for (int i = 0; i < numberAndCutPositionMap.size(); i++) {
            String[] numberAndCutPositionStr = numberAndCutPositionMap.valueAt(i).split("_");
            int number = Integer.parseInt(numberAndCutPositionStr[0]);
            int maxQty = comboItem.getSelectQty();
            if (numberAndCutPositionStr.length > 1 && !TextUtils.isEmpty(numberAndCutPositionStr[1])) {
                int cutPosition = Integer.parseInt(numberAndCutPositionStr[1]);
                if (maxQty <= number && cutPosition < mOrderFoodList.size()) {
                    return cutPosition;
                }
            } else {
                if (oldCount == maxQty) {
                    return -100;
                }
            }
        }
        return -1;
    }


    public void getCurrentSoldoutFood() {
        long restaurantId = GsaCloudApplication.getRestaurantId(mApplication);
        RequestBody requestBody = new FormBody.Builder()
                .add("restaurantId", String.valueOf(restaurantId))
                .build();
        mModel.getCurrentSoldoutFood(requestBody)
                .subscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BaseResult>(mErrorHandler) {

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        updateFoodSoldoutCtrData(mSoldoutCtrList);
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        updateFoodSoldoutCtrData(mSoldoutCtrList);
                    }

                    @Override
                    public void onNext(@NonNull BaseResult info) {
                        if (info != null && info.isSuccess() && info.getData() != null) {
                            List<SoldoutCtrFood> soldoutCtrFoods = JsonUtils.parseArray(info.getData(), SoldoutCtrFood.class);
                            if (soldoutCtrFoods != null && soldoutCtrFoods.size() > 0) {
                                if (mSoldoutCtrList.size() > 0) {
                                    mSoldoutCtrList.clear();
                                }
                                mSoldoutCtrList.addAll(soldoutCtrFoods);

//                                updateFoodSoldoutCtrData(mSoldoutCtrList);
                                //設置細項沽清數
                                IActivity.setFineItemSlodoutListFull(mSoldoutCtrList);
                            } else {
                                if (mSoldoutCtrList.size() > 0) {
                                    mSoldoutCtrList.clear();
                                }
                            }
                        } else {
                            if (mSoldoutCtrList.size() > 0) {
                                mSoldoutCtrList.clear();
                            }
                        }
                    }
                });
    }

    public void createOrder() {
        CreateOrderRequest request = getCreateOrderRequest(getOrderFoodLists());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), GsonUtils.GsonString(request));
        String json = GsonUtils.GsonString(request);
        mModel.createOrder(requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(null))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BaseResult>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull BaseResult info) {
                        if (info != null && info.isSuccess()) {
                            saveCreateTime(info.getSysTime());
                            if (info.getData() != null) {
                                setOrderId((Double) info.getData());
                            }
                            mRootView.showMessage("送單成功");
                            MyOrderManage.getInstance().setNewFoodList(getOrderFoodLists());
                            printSendOrder(true);
                        } else {
                            mRootView.showMessage(info.getErrMsg());
                        }
                    }
                });
    }

    public void addOrderFood() {
        List<OrderDetail> foodLists = getOrderFoodLists();
        for (OrderDetail food : foodLists) {
            food.setOrderId(MyOrderManage.getInstance().getOrderId());
        }
        AddOrderRequest addOrderRequest = getAddOrderRequest(foodLists);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), GsonUtils.GsonString(addOrderRequest));
        String json = GsonUtils.GsonString(addOrderRequest);
        mModel.addFood(requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(null))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BaseResult>(mErrorHandler) {
                    @Override
                    public void onNext(@NonNull BaseResult info) {
                        if (info != null && info.isSuccess()) {
                            mRootView.showMessage("送單成功");
                            if (OpenTableManage.getDefault() != null) {
                                //通知更新餐台状态
                                EventBus.getDefault().post(OpenTableManage.getDefault().getTableBean().getId(), "initTable_status_event");
                            }
                            printSendOrder(false);
                        } else {
                            if (!hasNesOrderFoods()) {
                                //TODO 未新增食品點擊送單 後台不讓過直接提示即可
                                mRootView.showMessage("送單成功");
                                if (OpenTableManage.getDefault() != null) {
                                    //通知更新餐台状态
                                    EventBus.getDefault().post(OpenTableManage.getDefault().getTableBean().getId(), "initTable_status_event");
                                }
                                printSendOrder(false);
                            } else {
                                mRootView.showMessage(info.getErrMsg());
                            }
                        }
                    }
                });
    }

    /**
     * 打印上菜紙
     *
     * @param initTable 是否是開台
     */
    private void printSendOrder(boolean initTable) {
        CC.obtainBuilder("Component.Print")
                .setActionName("printActivity")
                .addParam(PrintConstans.PRINT_TYPE, 3)
                .build()
                .callAsyncCallbackOnMainThread((cc, result) -> {
//                    if (result.isSuccess()) {
                    //打印成功
                    if (initTable) {
                        IActivity.returnBeforeActivity(initTable);
                    } else {
                        mRootView.killMyself();
                    }
//                    } else {
//                        mRootView.showMessage("打印失敗");
//                    }
                });
        //打印上菜紙
//        CC.obtainBuilder("Component.Print")
//                .setActionName("printActivity")
//                .addParam("NewFoods", newFoods)
//                .addParam("type", 0)
//                .build()
//                .callAsyncCallbackOnMainThread((cc, result) -> {
//                    if (result.isSuccess()) {
//                        //打印成功
//                        mRootView.killMyself();
//                    }
//                });
    }

    /**
     * 問題：刪除數量 1.賬單小數未更新 世維調整
     * 刪除已送單食品
     *
     * @param maxNumber
     * @param deleteNumber
     * @param reasonId
     */
    public void deleteFood(int maxNumber, int deleteNumber, long reasonId) {

        String ids = getSelectedOldFoodIds();
        if (TextUtils.isEmpty(ids)) {
            return;
        }

        DeleteOrderRequest.Request request = getDeleteOrderRequest(ids, reasonId, maxNumber, deleteNumber);
        String deleteOrderRequest = GsonUtils.GsonString(request);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), deleteOrderRequest);

        mModel.deleteFood(requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(null))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BaseRespose>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull BaseRespose info) {

                        if (info == null) {
                            mRootView.showMessage("刪除失敗");
                            return;
                        }

                        if (info.isSuccess()) {

                            mRootView.showMessage("刪除成功");

                            //删除所有已下单信息
                            deleteOldFood();

                            if (info.getData() != null && info.getData().getOrderDetails() != null) {

                                OpenTableManage.getDefault().setPeopleNumber(info.getData().getPerson());
                                //緩存訂單信息
                                MyOrderManage.getInstance().setOrderBean(new OrderBean(info.getData()));
                                //緩存食品信息
                                List<OrderDetail> orderDetailList = OrderAssemblyUtil.assemblyOrder(OrderDetail.orderTransOrderDetails(info.getData().getOrderDetails()));

                                mOrderFoodList.addAll(orderDetailList);
                            }

                            //重新排序食品 将已下单食品放到前面
                            sortSelectMealByIsNew();

                            mSelectMealAdapter.notifyDataSetChanged();
                            mSelectMealAdapter.setIndex();

                            //重新獲取沽清數據
                            getCurrentSoldoutFood();

                            mRootView.showViewModeVisibility(MealConstant.food_group_ViewMode, MealConstant.food_ViewMode);
                        } else {
                            mRootView.showMessage("獲取訂單數據失敗");
                        }
                    }
                });
    }

    public void getRestaurantFoodReason() {
        int brandId = GsaCloudApplication.getBrandId(mApplication);
        int restaurantId = GsaCloudApplication.getRestaurantId(mApplication);
        int type = 1;
        mModel.getRestaurantFoodReason(brandId, restaurantId, type)
                .subscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<FoodReason>(mErrorHandler) {

                    @Override
                    public void onSubscribe(Disposable d) {
                        super.onSubscribe(d);
                        mCancelFoodDialog.setProgressVisibility(true);
                    }

                    @Override
                    public void onNext(@NonNull FoodReason info) {
                        if (info != null && info.isSuccess()) {
                            if (info.getData() != null && info.getData().size() > 0) {
                                mCancelFoodDialog.addItems(info.getData());
                                mCancelFoodDialog.notifyDataSetChanged();
                            } else {
                                mCancelFoodDialog.showEmptyView(true, 0, null);
                            }
                        } else {
                            mCancelFoodDialog.showEmptyView(false, 0, null);
                        }
                        mCancelFoodDialog.setProgressVisibility(false);
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        mCancelFoodDialog.setProgressVisibility(false);
                        mCancelFoodDialog.showEmptyView(false, 0, t);
                    }
                });
    }

    private void showDeleteFoodDialog(int maxNumber, int deleteNumber, int reasonId, String reason) {
        QMUIDialog.MessageDialogBuilder dialogBuilder = new QMUIDialog.MessageDialogBuilder(IActivity);
        dialogBuilder.setTitleIcon(R.drawable.qmui_icon_dialog_doubt);
        dialogBuilder.setMessage("是否確認取消該食品?" + "\n取消原因 [" + reason + "]");
        dialogBuilder.addAction("取消", (dialog, index) -> dialog.dismiss());
        dialogBuilder.addAction(0, "確認", QMUIDialogAction.ACTION_PROP_NEGATIVE, (dialog, index) -> {
            dialog.dismiss();
            if (mCancelFoodDialog != null) {
                mCancelFoodDialog.build().dismiss();
                mCancelFoodDialog = null;
            }
            deleteFood(maxNumber, deleteNumber, reasonId);
        });
        dialogBuilder.create(R.style.MyDialogTheme2).show();
    }

    private void deleteWithOrderedFood(OrderDetail deleteFood) {
        if (mCancelFoodDialog == null) {
            mCancelFoodDialog = new CancelFoodDialog.Builder(IActivity);
            mCancelFoodDialog.setOnClickListener(new CancelFoodDialog.Builder.OnClickListener() {
                @Override
                public void onItemClick(FoodReason.DataBean item, int position, int deleteNumber) {
                    showDeleteFoodDialog(deleteFood.getNumber(), deleteNumber, item.getId(), item.getContent());
                }

                @Override
                public void onRetryClick() {
                    getRestaurantFoodReason();
                }
            });
        }
        mCancelFoodDialog.setMaxCancelNumber(deleteFood.getNumber());
        mCancelFoodDialog.build().show();

        getRestaurantFoodReason();
    }

    /**
     * 刪除食品
     *
     * @param deleteStyle 1=點擊刪除、2=長按刪除
     */
    public void deleteFoodItem(int deleteStyle) {

        if (!mSelectMealAdapter.canDeleteFood()) {
            return;
        }

        //未選擇食品時，設置默認選擇最後一個
        if (mSelectMealAdapter.getSelect_position() == -1) {
            if (getOrderFoodLists().size() > 0) {
                mSelectMealAdapter.setSelectPosition(getOrderFoodLists().size() - 1);
            }
        }

        OrderDetail deleteFood = getOrderFoodLists().get(mSelectMealAdapter.getSelect_position());

        if (!deleteFood.isNew()) {
            //TODO 刪除已下單食品
            deleteWithOrderedFood(deleteFood);
        } else {
            if (deleteStyle == 2) {
                mSelectMealAdapter.removeAllNewFoodItem();
            } else {
                int deletePosition = mSelectMealAdapter.removeFoodItem();
                mRootView.setMealRvScrollToPosition(deletePosition);
                //更新最大可選數
                if (deleteFood != null) {
                    Food orderBean = getFoodByFid(deleteFood.getProductId());
                    if (orderBean != null) {
                        setFoodMaxQty(orderBean);
                    }
                }
            }
        }
        updateOrderFoodNumber();
    }

    public void deleteChildItem() {
        if (getOrderFoodLists().size() == 0) {
            mRootView.showViewModeVisibility(MealConstant.food_group_ViewMode, MealConstant.food_ViewMode);
            return;
        }
        if (IActivity.getCurrentViewMode() == MealConstant.discount_ViewMode && getOrderFoodLists().get(mSelectMealAdapter.getSelect_position()).getProp() == OrderDetail.DISCOUNT_PROP) {
            //當點選折扣操作 不可删除食品
            return;
        }
        if (!mSelectMealAdapter.canDeleteChildItem()) {
            return;
        }
        if (getOrderFoodLists().get(mSelectMealAdapter.getSelect_position()) != null) {

            mSelectMealAdapter.removeChildItem();

            //更新細項沽清數
            IActivity.setFineItemSlodoutListFull(mSoldoutCtrList);
            //更新賬單金額
            updateOrderMoneyItem();

            updateOrderFoodNumber();
        }
    }

    public void deleteOldFood() {
        List<Integer> removeFoodIndex = new ArrayList<>();
        //記錄删除所有已下单食品
        for (int i = 0; i < getOrderFoodLists().size(); i++) {
            OrderDetail myOrder = getOrderFoodLists().get(i);
            if (!myOrder.isNew()) {
                removeFoodIndex.add(myOrder.getMyIndex());
            } else {
                //未下單单食品下新加的子项 一起删除
                if (removeFoodIndex.indexOf(myOrder.getParentIndex()) != -1) {
                    removeFoodIndex.add(myOrder.getMyIndex());
                }
            }
        }
        List<OrderDetail> orderFoodList = getOrderFoodLists();
        //删除所有已下单食品下子食品
        for (int i = removeFoodIndex.size() - 1; i >= 0; i--) {
            int removeIndex = removeFoodIndex.get(i) - 1;
            if (removeIndex > -1 && removeIndex < orderFoodList.size()) {
                orderFoodList.remove(removeIndex);
            }
        }
        if (removeFoodIndex.size() > 0) {
            removeFoodIndex.clear();
            mSelectMealAdapter.notifyDataSetChanged();
        }
    }

    public void changedMealByParentId(long parentId) {
        List<Food> foodList = mModel.queryDB_FoodList(parentId);
        mFoodAdapter.resetSelect(-1, null);
        if (foodList != null) {
            updateFoodData(foodList, parentId);
        }
        mRootView.showViewModeVisibility(MealConstant.food_ViewMode, MealConstant.food_group_ViewMode);
    }

    /**
     * 按键入的食品号查找食品
     * meal_uid:即可以是食品的fid也可以是PLU码。
     * 未有此商品，弹出提示框并且清除录入
     * 有此商品，把商品上屏并且清除录入
     *
     * @param plu
     */
    public void toFindMeal(String plu) {

        FoodDaoUtils foodDaoUtils = new FoodDaoUtils(IActivity);
        Food food = foodDaoUtils.queryFoodByQueryBuilder(plu);

        //查找成功清除输入框
        IActivity.clearInput();

        if (food == null) {
            mRootView.showMessage("未找到該食品!");
            return;
        }

        setFoodComboStatus(food);

        int addPosition = mSelectMealAdapter.addFoodItem(OrderDetail.foodTransOrderDetails(food, 1));
        mRootView.setMealRvScrollToPosition(addPosition);

        updateOrderFoodNumber();
    }


    private void setComboItemSoldoutCtrData(List<ComboItem> comboItemList, List<SoldoutCtrFood> soldoutCtrFoods) {
        addFoodSoldoutCtrItem(soldoutCtrFoods);
        for (SoldoutCtrFood scc : soldoutCtrFoods) {
            for (ComboItem comboItem : comboItemList) {
                if (scc.getType() == FOOD_TYPE && scc.getFoodId() != null && comboItem.getFid() != null && comboItem.getFid().equals(scc.getFoodId())) {
                    String qtyName;
                    if (comboItem.getInvisible() == 2) {
                        qtyName = "暫停";
                        comboItem.setMaxNumber(qtyName);
                        comboItem.setCurrentMaxNumber(qtyName);
                    } else {
                        qtyName = scc.getQtyName();
                        comboItem.setMaxNumber(qtyName);
                        comboItem.setCurrentMaxNumber(qtyName);
                    }
                }
            }
        }
    }

    private void setModifierSoldoutCtrData(List<Modifier> modifierList, List<SoldoutCtrFood> soldoutCtrFoods) {
        addFoodSoldoutCtrItem(soldoutCtrFoods);
        for (SoldoutCtrFood scc : soldoutCtrFoods) {
            for (Modifier modifier : modifierList) {
                if (scc.getType() == FOOD_TYPE && scc.getFoodId() != null && modifier.getMid() != 0 && modifier.getMid() == scc.getFoodId()) {
                    String qtyName;
                    if (modifier.getInvisible() == 2) {
                        qtyName = "暫停";
                        modifier.setMaxNumber(qtyName);
                        modifier.setCurrentMaxNumber(qtyName);
                    } else {
                        qtyName = scc.getQtyName();
                        modifier.setMaxNumber(qtyName);
                        modifier.setCurrentMaxNumber(qtyName);
                    }
                }
            }
        }
    }

    /**
     * 更新沽清數據
     *
     * @param soldoutCtrFoods
     */
    public void updateFoodSoldoutCtrData(List<SoldoutCtrFood> soldoutCtrFoods) {
        addFoodSoldoutCtrItem(soldoutCtrFoods);
        setFoodSoldoutCtrData(soldoutCtrFoods);
    }

    /**
     * 添加食品組 食品沽清項
     *
     * @param soldoutCtrFoods
     */
    private void addFoodSoldoutCtrItem(List<SoldoutCtrFood> soldoutCtrFoods) {
        for (Food foodGroupBean : mFoodGroupList) {
            if (foodGroupBean.getInvisible() == 2) {
                SoldoutCtrFood soldoutCtrFood = new SoldoutCtrFood();
                soldoutCtrFood.setType((byte) FOOD_GROUP_TYPE);
                soldoutCtrFood.setStop(true);
                soldoutCtrFood.setFoodName(foodGroupBean.getFoodName());
                soldoutCtrFood.setFoodName1(foodGroupBean.getFoodName1());
                soldoutCtrFood.setFoodName2(foodGroupBean.getFoodName2());
                soldoutCtrFood.setFoodId(foodGroupBean.getId());
                soldoutCtrFoods.add(soldoutCtrFood);
            }
        }
        for (Food foodBean : mFoodList) {
            if (foodBean.getInvisible() == 2) {
                SoldoutCtrFood soldoutCtrFood = new SoldoutCtrFood();
                soldoutCtrFood.setType((byte) FOOD_TYPE);
                soldoutCtrFood.setStop(true);
                soldoutCtrFood.setFoodName(foodBean.getFoodName());
                soldoutCtrFood.setFoodName1(foodBean.getFoodName1());
                soldoutCtrFood.setFoodName2(foodBean.getFoodName2());
                soldoutCtrFood.setFoodId(foodBean.getId());
                soldoutCtrFoods.add(soldoutCtrFood);
            }
        }
    }

    /**
     * 設置食品沽清數據
     */
    public void setFoodSoldoutCtrData(List<SoldoutCtrFood> soldoutCtrFoods) {
        clearFoodSoldoutCtrData();
        for (SoldoutCtrFood scc : soldoutCtrFoods) {
            for (Food foodGroupBean : mFoodGroupList) {
                if (scc.getType() == FOOD_GROUP_TYPE && scc.getFoodId() != null && foodGroupBean.getId() != null && foodGroupBean.getId().equals(scc.getFoodId())) {
                    String qtyName;
                    if (foodGroupBean.getInvisible() == 2) {
                        qtyName = "暫停";
                        foodGroupBean.setMaxNumber(qtyName);
                        foodGroupBean.setCurrentMaxNumber(qtyName);
                    } else {
                        qtyName = scc.getQtyName();
                        foodGroupBean.setMaxNumber(qtyName);
                        foodGroupBean.setCurrentMaxNumber(qtyName);
                    }
                }
            }
            for (Food foodBean : mFoodList) {
                if (scc.getType() == FOOD_TYPE && scc.getFoodId() != null && foodBean.getId() != null && foodBean.getId().equals(scc.getFoodId())) {
                    String qtyName;
                    if (foodBean.getInvisible() == 2) {
                        qtyName = "暫停";
                        foodBean.setMaxNumber(qtyName);
                        foodBean.setCurrentMaxNumber(qtyName);
                    } else {
                        qtyName = scc.getQtyName();
                        foodBean.setMaxNumber(qtyName);
                        foodBean.setCurrentMaxNumber(qtyName);
                    }
                }
            }
        }
        if (IActivity.getFoodGroupGridViewAdapter() != null) {
            IActivity.getFoodGroupGridViewAdapter().notifyDataSetChanged();
        }
        mFoodAdapter.notifyDataSetChanged();
    }


    private void clearFoodSoldoutCtrData() {
        for (Food foodGroupBean : mFoodGroupList) {
            foodGroupBean.setMaxNumber("");
            foodGroupBean.setCurrentMaxNumber("");
        }
        for (Food foodBean : mFoodList) {
            foodBean.setMaxNumber("");
            foodBean.setCurrentMaxNumber("");
        }
    }

    /**
     * 设置当前食品还可最多选几份
     *
     * @param foodBean
     */
    public boolean setFoodMaxQty(Food foodBean) {

        int currentSelectNumber = 0;

        for (int i = 0; i < getNewOrderFoodLists().size(); i++) {
            OrderDetail orderFood = getNewOrderFoodLists().get(i);
            if (orderFood.getProductId() == foodBean.getId()) {
                currentSelectNumber += orderFood.getNumber();
            }
        }
        String User_Qty = foodBean.getMaxNumber();
        if (!User_Qty.equals("") && !User_Qty.equals("售罄") && !User_Qty.equals("暫停")) {
            int maxQty = Integer.parseInt(User_Qty);
            if (maxQty > 0) {
                int Currrent_OR_Qty = maxQty - currentSelectNumber;
                if (Currrent_OR_Qty < 1) {
                    foodBean.setCurrentMaxNumber("售罄");
                    return false;
                } else {
                    foodBean.setCurrentMaxNumber(Currrent_OR_Qty + "");
                }
            }
        }
        return true;
    }

    /**
     * 添加食品条件过滤
     * 1：售罄、最大选择数
     * 2：是否需要会员积分
     * 3：
     */
    public boolean foodGroupConditionFilter(Food foodBean, boolean init) {

        if (init) {
            return true;
        }

        String User_Qty = foodBean.getCurrentMaxNumber();
        if (!TextUtils.isEmpty(User_Qty)) {
            String msg = "[" + foodBean.getFoodName() + "]" + LanguageUtils.get_language_system(IActivity, "Comm.pause", "已暫停");
            CommonTipDialog.showSurpisedDialog(IActivity, msg, null, null, null, null, null);
            return false;
        }

        return true;
    }

    private boolean foodConditionFilter(Food foodBean) {
        long Invisible = foodBean.getInvisible();
        if (Invisible == 2) {
            String msg = "[" + foodBean.getFoodName() + "]" + LanguageUtils.get_language_system(IActivity, "Comm.pause", "已暫停");
            CommonTipDialog.showSurpisedDialog(IActivity, msg, null, null, null, null, null);
            return false;
        }
        String User_Qty = foodBean.getCurrentMaxNumber();
        if (!TextUtils.isEmpty(User_Qty)) {
            if (User_Qty.equals("售罄") || User_Qty.equals("暫停")) {
                String msg = "[" + foodBean.getFoodName() + "]" + User_Qty;
                CommonTipDialog.showSurpisedDialog(IActivity, msg, null, null, null, null, null);
                return false;
            }
        }
        return true;
    }

    private boolean comboConditionFilter(ComboItem comboItem) {
        long Invisible = comboItem.getInvisible();
        if (Invisible == 2) {
            String msg = "[" + comboItem.getName() + "]" + LanguageUtils.get_language_system(IActivity, "Comm.pause", "已暫停");
            CommonTipDialog.showSurpisedDialog(IActivity, msg, null, null, null, null, null);
            return false;
        }
        String User_Qty = comboItem.getCurrentMaxNumber();
        if (!TextUtils.isEmpty(User_Qty)) {
            if (User_Qty.equals("售罄") || User_Qty.equals("暫停")) {
                String msg = "[" + comboItem.getName() + "]" + User_Qty;
                CommonTipDialog.showSurpisedDialog(IActivity, msg, null, null, null, null, null);
                return false;
            }
        }
        return true;
    }

    public void updateOrderFoodNumber() {
        setFoodBtnNumber();
        setFoodGroupBtnNumber(IActivity.getFoodGroupGridViewAdapter(), mFoodGroupList);
        mRootView.setOrderFoodCount(getOrderFoodNumber());
    }

    private void setFoodBtnNumber() {
        for (int i = 0; i < mFoodList.size(); i++) {
            Food foodBean = mFoodList.get(i);
            foodBean.setNumber(0);
            int iNumber = 0;
            for (int j = 0; j < mOrderFoodList.size(); j++) {
                OrderDetail datasBean = mOrderFoodList.get(j);
                if (datasBean.isNew() && datasBean.getProductId() == foodBean.getId()) {
                    iNumber = iNumber + datasBean.getNumber();
                    foodBean.setNumber(iNumber);
                }
            }
        }
        mFoodAdapter.notifyDataSetChanged();
    }

    private void setFoodGroupBtnNumber(FoodGroupAdapter adapter, List<Food> foodGroupList) {
        List<OrderDetail> orderDetailList = getOrderFoodLists();
        for (int i = 0; i < foodGroupList.size(); i++) {
            Food foodBean = foodGroupList.get(i);
            foodBean.setNumber(0);
            int iNumber = 0;
            if (orderDetailList != null) {
                for (int j = 0; j < orderDetailList.size(); j++) {
                    OrderDetail food = orderDetailList.get(j);
                    if (food.isNew() && food.getTopId() == foodBean.getId()) {
                        iNumber = iNumber + food.getNumber();
                        foodBean.setNumber(iNumber);
                    }
                }
            }
        }
        if (adapter != null)
            adapter.notifyDataSetChanged();
    }

    private String getOrderFoodNumber() {
        int i = 0;
        if (getOrderFoodLists() != null) {
            for (int j = 0; j < getOrderFoodLists().size(); j++) {
                OrderDetail order = getOrderFoodLists().get(j);
                if (order.isNew()) {
                    i = i + order.getNumber();
                }
            }
        }
        return String.valueOf(i);
    }

    private void setTopId(List<Food> foodList, long topId) {
        for (int i = 0; i < foodList.size(); i++) {
            Food datasBean = foodList.get(i);
            datasBean.setTopId(topId);
        }
    }

    public Food getFoodByFid(long fid) {
        for (int i = 0; i < mFoodList.size(); i++) {
            Food foodBean = mFoodList.get(i);
            if (fid == foodBean.getId()) {
                return foodBean;
            }
        }
        return null;
    }

    public Modifier getModifierByMid(long mid) {
        for (int i = 0; i < mModifierList.size(); i++) {
            Modifier modifier = mModifierList.get(i);
            if (mid == modifier.getMid()) {
                return modifier;
            }
        }
        return null;
    }

    /**
     * 標識食品是否为组合食品
     *
     * @param foodList
     */
    private void setFoodComboListStatus(List<Food> foodList) {
        for (int i = 0; i < foodList.size(); i++) {
            Food datasBean = foodList.get(i);
            List<FoodCombo> foodFoodComboList = mModel.isComboFood(datasBean.getId());
            if (foodFoodComboList.size() > 0) {
                datasBean.setComboFood(true);
            }
        }
    }

    /**
     * 標識食品是否为组合食品
     *
     * @param food
     */
    private void setFoodComboStatus(Food food) {
        List<FoodCombo> foodFoodComboList = mModel.isComboFood(food.getId());
        if (foodFoodComboList.size() > 0) {
            food.setComboFood(true);
        }
    }

    /**
     * 細項默認選中
     *
     * @param modifierList
     */
    private void setModifierDefModifier(List<Modifier> modifierList) {
        String defmodifier = null;
        for (int i = 0; i < modifierList.size(); i++) {
            Modifier item = modifierList.get(i);
            if (item.getInvisible() != 2) {
                //過濾掉已暫停細項
                String modifier = item.getDefmodifier().trim();
                if (!TextUtils.isEmpty(modifier)) {
                    defmodifier = modifier + ",";
                }
            }
        }
        if (!TextUtils.isEmpty(defmodifier)) {
            if (defmodifier.startsWith(",")) {
                defmodifier = defmodifier.substring(1, defmodifier.length());
            }
            if (defmodifier.endsWith(",")) {
                defmodifier = defmodifier.substring(0, defmodifier.length() - 1);
            }
            String[] defmodifiers = defmodifier.split(",");
            for (int j = 0; j < defmodifiers.length; j++) {
                long def = Long.parseLong(defmodifiers[j]);
                for (int k = 0; k < modifierList.size(); k++) {
                    Modifier modifier = modifierList.get(k);
                    long mid = modifier.getMid();
                    if (def == mid) {
                        modifier.setDefmodifier("1");
                    } else {
                        modifier.setDefmodifier("0");
                    }
                }
            }
        }
    }

    /**
     * 套餐默認選中
     *
     * @param comboItemList
     */
    private void setComboDefModifier(List<ComboItem> comboItemList) {
        String defmodifier = null;
        for (int i = 0; i < comboItemList.size(); i++) {
            ComboItem comboItem = comboItemList.get(i);
            if (comboItem.getInvisible() != 2) {
                //過濾掉已暫停食品
                String modifier = comboItem.getDefmodifier().trim();
                if (!TextUtils.isEmpty(modifier)) {
                    defmodifier = modifier + ",";
                }
            }
        }
        if (!TextUtils.isEmpty(defmodifier)) {
            if (defmodifier.startsWith(",")) {
                defmodifier = defmodifier.substring(1, defmodifier.length());
            }
            if (defmodifier.endsWith(",")) {
                defmodifier = defmodifier.substring(0, defmodifier.length() - 1);
            }
            String[] defmodifiers = defmodifier.split(",");
            for (int j = 0; j < defmodifiers.length; j++) {
                long def = Long.parseLong(defmodifiers[j]);
                for (int k = 0; k < comboItemList.size(); k++) {
                    ComboItem comboItem = comboItemList.get(k);
                    long fid = comboItem.getFid();
                    if (def == fid) {
                        comboItem.setDefmodifier("1");
                    } else {
                        comboItem.setDefmodifier("0");
                    }
                }
            }
        }
    }

    /**
     * 更新食品數據
     *
     * @param foodList
     * @param parentId
     */
    private void updateFoodData(List<Food> foodList, long parentId) {
        setTopId(foodList, parentId);
        setFoodComboListStatus(foodList);
        mFoodList.clear();
        mFoodList.addAll(foodList);
        //根据Item个数显示每一行的个数
        mRootView.setFoodRecycleSpanCount(mFoodList.size());
        mFoodAdapter.notifyDataSetChanged();
    }

    /**
     * 更新套餐數據
     *
     * @param foodComboList
     */
    private void updateComboData(List<ComboItem> foodComboList) {
        mFoodComboList.clear();
        mFoodComboList.addAll(foodComboList);
        //根据Item个数显示每一行的个数
        mRootView.setComboRecycleSpanCount(mFoodComboList.size());
        mComboAdapter.notifyDataSetChanged();
    }

    /**
     * 更新細項數據
     *
     * @param modifiers
     */
    private void updateModifierData(List<Modifier> modifiers) {
        mModifierList.clear();
        mModifierList.addAll(modifiers);
        //根据Item个数显示每一行的个数
        mRootView.setModifierRecycleSpanCount(mModifierList.size());
        mComboAdapter.notifyDataSetChanged();
    }

    /**
     * 全選
     */
    public void setSelectAll() {
        for (OrderDetail item : mOrderFoodList) {
            item.setSelected(1);
        }
        mSelectMealAdapter.notifyDataSetChanged();
    }

    /**
     * 反選
     */
    public void setAntiSelect() {
        for (OrderDetail item : mOrderFoodList) {
            if (item.getSelected() == 0) {
                item.setSelected(1);
            } else {
                item.setSelected(0);
            }
        }
        mSelectMealAdapter.notifyDataSetChanged();
    }

    /**
     * 添加多選細項
     */
    public int addMultipleModifierItems(Modifier modifierItem, int addPosition) {
        for (int i = 0; i < mOrderFoodList.size(); i++) {
            OrderDetail item = mOrderFoodList.get(i);
            if (item.getSelected() != 0) {
                if (item.getItemType() == 1) {
                    int insertPosition = getEndInsertPosition(item);
                    if (insertPosition != -1) {
                        i = insertPosition + 1;
                    } else {
                        i++;
                    }
                    long id = item.isNew() ? item.getProductId() : item.getId();
                    OrderDetail modifierTransOrderDetail = OrderDetail.modifierTransOrderDetail(modifierItem, id, item.getProductId(), 1);
                    mOrderFoodList.add(i, modifierTransOrderDetail);
                }
            }
        }
        mSelectMealAdapter.notifyDataSetChanged();
        return addPosition;
    }

    private int getEndInsertPosition(OrderDetail orderDetail) {
        for (int i = 0; i < mOrderFoodList.size(); i++) {
            OrderDetail item = mOrderFoodList.get(i);
            //往下找
            int nextIndex = i + 1;
            if (mOrderFoodList.size() == (nextIndex - 1) && mOrderFoodList.get(nextIndex).getItemType() == 3) {
                //最後一個並且是第三層
                return i;
            }
            if (item.getItemType() == 3 && item.getParentProductId() == orderDetail.getProductId() && mOrderFoodList.get(nextIndex).getItemType() != 3) {
                //添加到主食品細項最後面
                return i;
            }
        }
        return -1;
    }

    /**
     * 加載折扣數據
     */
    public void loadDiscountData() {
        if (getOrderFoodLists().size() == 0 || mSelectMealAdapter.getSelect_position() == -1) {
            return;
        }
        OrderDetail currentOrderBean = mSelectMealAdapter.getCurrentOrderDetail();
        if (currentOrderBean == null) {
            return;
        }
        mCurrentOrderDetailBean = currentOrderBean;

        List<Discount> discountList = mModel.queryDB_DiscountList();

        mDiscountList.clear();
        mDiscountList.addAll(discountList);
        //根据Item个数显示每一行的个数
        mRootView.setDiscountRecycleSpanCount(mDiscountList.size());
        mDiscountAdapter.notifyDataSetChanged();
    }

    /**
     * 獲取所要折扣金額
     *
     * @return
     */
    private double getDisountSourcePrice() {
        double discount = 0.0;
        int start_position = mSelectMealAdapter.getSelect_full_start_position();
        int end_position = mSelectMealAdapter.getSelect_full_end_position();
        for (int i = 0; i < mOrderFoodList.size(); i++) {
            if (start_position <= i && i <= end_position) {
                OrderDetail orderDetailsBean = mOrderFoodList.get(i);
                if (orderDetailsBean.getProp() == OrderDetail.DISCOUNT_PROP) {
                    //折上折減去以折扣金額
                    discount = MoneyUtil.sub(discount, orderDetailsBean.getPrice());
                } else {
                    discount = MoneyUtil.sum(discount, orderDetailsBean.getPrice());
                }
                //參與折扣
                orderDetailsBean.setAblediscount(1);
                if (!orderDetailsBean.isNew()) {
                    if (orderDetailsBean.getDiscountStatus() == 0) {
                        //此食品新增折扣
                        orderDetailsBean.setDiscountStatus(1);
                    }
                }
            }
        }
        return discount;
    }

    /**
     * 取消食品請求實體
     *
     * @param ids
     * @param reasonId
     * @param maxNumber
     * @param deleteNumber
     * @return
     */
    private DeleteOrderRequest.Request getDeleteOrderRequest(String ids, long reasonId, int maxNumber, int deleteNumber) {
        List<Map<Byte, DeleteOrderRequest.DeleteBean>> mapsDelete = getMapsDelete(ids, maxNumber, deleteNumber);
        byte type = (byte) (myOrderManage.isModifyOrder() ? 2 : 1);
        long orderId = MyOrderManage.getInstance().getOrderId();

        DeleteOrderRequest.Request request = new DeleteOrderRequest.Request();
        request.setMapsDelete(mapsDelete);
        request.setOrderId(orderId);
        request.setTableId(OpenTableManage.getDefault().getTableBean().getId());
        request.setType(type);
        request.setReasonId(reasonId);
        return request;
    }

    /**
     * 取消食品對應 id + number
     *
     * @param ids
     * @param maxNumber
     * @param deleteNumber
     * @return
     */
    private List<Map<Byte, DeleteOrderRequest.DeleteBean>> getMapsDelete(String ids, int maxNumber, int deleteNumber) {
        List<Map<Byte, DeleteOrderRequest.DeleteBean>> deleteMaps = new ArrayList<>();
        //取消食品id
        String[] idsArray = ids.split(",");
        //取消食品數量
        String[] quantitys = getQuantitys(idsArray.length, maxNumber, deleteNumber).split(",");
        for (int i = 0; i < idsArray.length; i++) {
            String[] quantitysStr = quantitys[i].split("_");
            Map<Byte, DeleteOrderRequest.DeleteBean> map = new HashMap<>();
            DeleteOrderRequest.DeleteBean request = new DeleteOrderRequest.DeleteBean();
            request.setId(Long.parseLong(idsArray[i]));
            request.setNumber(Integer.parseInt(quantitysStr[1]));
            map.put(Byte.parseByte(quantitysStr[0]), request);
            deleteMaps.add(map);
        }
        return deleteMaps;
    }


    /***
     * 取消食品數量
     * @param length
     * @param maxNumber
     * @param deleteNumber
     * @return 數量_後台定義（1=刪除全部,2=修改數量）
     */
    private String getQuantitys(int length, int maxNumber, int deleteNumber) {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < length; i++) {
            if (maxNumber == deleteNumber) {
                builder.append(1 + "_" + (maxNumber - deleteNumber));
            } else {
                builder.append(2 + "_" + (maxNumber - deleteNumber));
            }
            builder.append(",");
        }
        String str = builder.toString();
        if (str.endsWith(",")) {
            str = str.substring(0, str.length() - 1);
        }
        return str;
    }


    public boolean isRvMealClicked() {
        return RvMealClicked;
    }

    public void setRvMealClicked(boolean rvMealClicked) {
        RvMealClicked = rvMealClicked;
    }

    public OrderDetail getCurrentOrderDetailBean() {
        return mCurrentOrderDetailBean;
    }

    public SelectMealAdapter getSelectMealAdapter() {
        return mSelectMealAdapter;
    }

    public List<SoldoutCtrFood> getSoldoutCtrList() {
        return mSoldoutCtrList;
    }
}
