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

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

import androidx.recyclerview.widget.RecyclerView;

import com.billy.cc.core.component.CC;
import com.gingersoft.gsa.cloud.common.bean.BaseResult;
import com.gingersoft.gsa.cloud.common.constans.ExpandConstant;
import com.gingersoft.gsa.cloud.common.constans.MealConstant;
import com.gingersoft.gsa.cloud.common.constans.PrintConstans;
import com.gingersoft.gsa.cloud.common.core.member.MemberInfo;
import com.gingersoft.gsa.cloud.common.core.restaurant.RestaurantInfoManager;
import com.gingersoft.gsa.cloud.common.core.restaurant.utils.RestaurantExpandInfoUtils;
import com.gingersoft.gsa.cloud.common.logan.LoganManager;
import com.gingersoft.gsa.cloud.common.rxjava.ErrorHandleSingleSubscriber;
import com.gingersoft.gsa.cloud.common.utils.JsonUtils;
import com.gingersoft.gsa.cloud.common.utils.LanguageUtils;
import com.gingersoft.gsa.cloud.common.utils.MoneyUtil;
import com.gingersoft.gsa.cloud.common.utils.gson.GsonUtils;
import com.gingersoft.gsa.cloud.component.ComponentName;
import com.gingersoft.gsa.cloud.database.AbstractDiscount;
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.ModifierDaoUtils;
import com.gingersoft.gsa.cloud.order.bean.discount.MemberWalletCoupon;
import com.gingersoft.gsa.cloud.order.bean.request.DeleteOrderRequest;
import com.gingersoft.gsa.cloud.order.commodity.OrderDetail;
import com.gingersoft.gsa.cloud.order.order.BaseOrder;
import com.gingersoft.gsa.cloud.order.order.MealOrder;
import com.gingersoft.gsa.cloud.print.bean.PrintContent;
import com.gingersoft.gsa.cloud.print.bean.adapter.PrintContentAdapter;
import com.gingersoft.gsa.cloud.table.mvp.action.discount.MealCouponAction;
import com.gingersoft.gsa.cloud.table.mvp.action.discount.MealDiscountAction;
import com.gingersoft.gsa.cloud.table.mvp.action.meal.PrinterAction;
import com.gingersoft.gsa.cloud.table.mvp.contract.MealStandContract;
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.event.LoadFineEvent;
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.ui.adapter.meal.MealCartAdapter;
import com.gingersoft.gsa.cloud.table.mvp.ui.fragment.mealstand.MealFineAllFragment;
import com.gingersoft.gsa.cloud.table.mvp.ui.widget.CancelFoodDialog;
import com.gingersoft.gsa.cloud.ui.widget.dialog.CommonTipDialog;
import com.google.gson.internal.LinkedTreeMap;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.integration.AppManager;
import com.jess.arms.http.imageloader.ImageLoader;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.RequestBody;

import javax.inject.Inject;
import javax.inject.Named;

import com.jess.arms.utils.RxLifecycleUtils;
import com.xuexiang.rxutil2.rxjava.RxSchedulerUtils;

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

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

import static com.gingersoft.gsa.cloud.table.mvp.ui.activity.meal.MealSoldoutActivity.FOOD_GROUP_TYPE;
import static com.gingersoft.gsa.cloud.table.mvp.ui.activity.meal.MealSoldoutActivity.FOOD_TYPE;
import static com.gingersoft.gsa.cloud.table.mvp.ui.activity.meal.MealSoldoutActivity.MODIFIER_TYPE;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 04/17/2021 10:40
 * <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 BaseMealPresenter<MealStandContract.Model, MealStandContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    @Inject
    @Named("foodGroupList")
    List<Food> mFoodGroupList;
    @Inject
    @Named("foodList")
    List<Food> mFoodList;
    @Inject
    List<ComboItem> mComboList; //套餐细项数据
    @Inject
    List<Modifier> mModifierList; //细项数据

    @Inject
    List<SoldoutCtrFood> mSoldoutCtrList;//沽清食品數據

    private PrinterAction mPrinterAction;
    /**
     * 食品折扣
     */
    private MealDiscountAction mMealDiscountAction;
    /**
     * 食品優惠券
     */
    private MealCouponAction mMealCouponAction;

    private OrderDetail mCurrentOrderDetailBean;
    private boolean RvMealClicked;

    @Inject
    public MealStandPresenter(MealStandContract.Model model, MealStandContract.View rootView) {
        super(model, rootView);
        initAction();
    }

    private void initAction() {
        mMealDiscountAction = MealDiscountAction.builder()
                .context(mRootView.getActivity())
                .cashStr(cashStr)
                .listener(new MealDiscountAction.OnCallBackListener() {

                    @Override
                    public void exclusiveRemoveOthers() {
                        //獨佔折扣刪除其他折扣
                        int start_position = mMealCartAdapter.getSelect_full_start_position();
                        int end_position = mMealCartAdapter.getSelect_full_end_position();
                        for (int i = mOrderMealList.size() - 1; i >= 0; i--) {
                            if (start_position <= i && i <= end_position) {
                                OrderDetail orderMealItem = mOrderMealList.get(i);
                                if (orderMealItem.getDiscount() != null) {
                                    mOrderMealList.remove(i);
                                }
                            }
                        }
                    }

                    @Override
                    public void preformAddDiscount(Discount discount) {
                        addDiscountItem(discount);
                    }
                })
                .build();
        mMealCouponAction = MealCouponAction.builder()
                .context(mRootView.getActivity())
                .cashStr(cashStr)
                .listener((discount) -> {
                    addCouponItem(discount);
                    mRootView.updateCouponSelects(false);
                })
                .build();
    }

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

    @Override
    public void createOrder(boolean isPrint, Class<?> afterToActivity) {
        CreateOrderRequest request = getCreateOrderRequest(getOrderFoodLists());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), GsonUtils.GsonString(request));
        String json = GsonUtils.GsonString(request);
        mModel.createOrder(requestBody)
                .doOnSubscribe(disposable -> mRootView.showLoading(null))
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSingleSubscriber<BaseResult>(mErrorHandler) {

                    @Override
                    public void onSuccess(BaseResult info) {
                        if (info != null && info.isSuccess()) {
                            saveCreateTime(info.getSysTime());
                            if (info.getData() != null) {
                                if (info.getData() instanceof Double) {
                                    //未上線，避免正式版閃退
                                    setOrderId((double) info.getData());
                                    setOrderNo(((Double) info.getData()).longValue() + "");
                                } else {
                                    LinkedTreeMap tm = (LinkedTreeMap) info.getData();
                                    for (Object o : tm.keySet()) {
                                        String key = (String) o;
                                        if (key.equals("id")) {
                                            setOrderId((double) tm.get(key));
                                        } else if (key.equals("orderNo")) {
                                            setOrderNo((String) tm.get(key));
                                        }
                                    }
                                }
                            }
                            mRootView.showMessage("送單成功");
                            mMealOrder.setNewFoodList(getOrderFoodLists());
                            printSendOrder();
                        } else {
                            mRootView.showMessage(info.getErrMsg());
                        }
                    }
                });
    }

    @Override
    public void addOrderFood(boolean isPrint, Class<?> afterToActivity) {
        List<OrderDetail> foodLists = getOrderFoodLists();
        for (OrderDetail food : foodLists) {
            food.setOrderId(mMealOrder.getOrderId());
        }
        AddOrderRequest addOrderRequest = getAddOrderRequest(foodLists);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), GsonUtils.GsonString(addOrderRequest));
        String json = GsonUtils.GsonString(addOrderRequest);
        mModel.addOrderFood(requestBody)
                .doOnSubscribe(disposable -> mRootView.showLoading(null))
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSingleSubscriber<BaseResult>(mErrorHandler) {

                    @Override
                    public void onSuccess(BaseResult info) {
                        if (info != null && info.isSuccess()) {
                            mRootView.showMessage("送單成功");
                            printSendOrder();
                        } else {
                            if (!hasNesOrderFoods()) {
                                //TODO 未新增食品點擊送單 後台不讓過直接提示即可
                                mRootView.showMessage("送單成功");
                                printSendOrder();
                            } else {
                                mRootView.showMessage(info.getErrMsg());
                            }
                        }
                    }
                });
    }

    public void getCurrentSoldoutFood() {
        long restaurantId = RestaurantInfoManager.newInstance().getRestaurantId();
        RequestBody requestBody = new FormBody.Builder()
                .add("restaurantId", String.valueOf(restaurantId))
                .build();
        mModel.getCurrentSoldoutFood(requestBody)
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSingleSubscriber<BaseResult>(mErrorHandler) {

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

                    @Override
                    public void onSuccess(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);
                            } else {
                                if (mSoldoutCtrList.size() > 0) {
                                    mSoldoutCtrList.clear();
                                }
                            }
                        } else {
                            if (mSoldoutCtrList.size() > 0) {
                                mSoldoutCtrList.clear();
                            }
                        }
                        updateFoodSoldoutCtrData();
                    }
                });
    }

    public void getRestaurantFoodReason() {
        int brandId = RestaurantInfoManager.newInstance().getBrandId();
        int restaurantId = RestaurantInfoManager.newInstance().getRestaurantId();
        int type = 1;
        CancelFoodDialog cancelFoodDialog = mRootView.getCancelFoodDialog();
        mModel.getRestaurantFoodReason(brandId, restaurantId, type)
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSingleSubscriber<BaseResult>(mErrorHandler) {

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

                    @Override
                    public void onSuccess(@io.reactivex.annotations.NonNull BaseResult info) {
                        if (info != null && info.isSuccess()) {
                            List<FoodReason> foodReasonList = JsonUtils.parseArray(info.getData(), FoodReason.class);
                            if (info.getData() != null && foodReasonList.size() > 0) {
                                cancelFoodDialog.addItems(foodReasonList);
                                cancelFoodDialog.notifyDataSetChanged();
                            } else {
                                cancelFoodDialog.showEmptyView(true, 0, null);
                            }
                        } else {
                            cancelFoodDialog.showEmptyView(false, 0, null);
                        }
                        cancelFoodDialog.setProgressVisibility(false);
                    }

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

    public void initSelectMealAdapter(RecyclerView rvSelectMeal) {
        if (mMealCartAdapter != null) {
            //設置子父級下標
            mMealCartAdapter.setIndex();
            rvSelectMeal.setAdapter(mMealCartAdapter);
            mMealCartAdapter.setOnItemClickListener(new MealCartAdapter.OnItemClickListener() {

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

                @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;
                }
            });
        }
    }

    public void initMealData() {
        List<Food> foodGroupList = mModel.queryDB_FoodGroupList(BaseOrder.orderType);
        if (foodGroupList.size() > 0) {
            mFoodGroupList.addAll(foodGroupList);
            setDefalutFoodGroup(foodGroupList);
            mRootView.initFoodGroupAdapter(foodGroupList);
            updateFoodSoldoutCtrData();
        }
    }

    private void setDefalutFoodGroup(List<Food> foodGroupList) {
        for (Food food : foodGroupList) {
            if (food.getInvisible() == 0) {
                //默認選中第一組
                food.setSelected(true);
                switchFoodByParentId(food.getId());
                break;
            }
        }
    }

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

    private void mealCartItemClick(OrderDetail datasBean) {
        LoganManager.w_tableMode(TAG, LoganManager.EVENT_SELECTED, "食品【" + datasBean.getProductName() + "】");
        //有取消的食品不能操作
        OrderDetail currentOrderDetail = mMealCartAdapter.getCurrentOrderDetail();
        if (currentOrderDetail != null && currentOrderDetail.isModify()) {
            return;
        }
        if (mMealCartAdapter.getSelectedMode() == MealCartAdapter.MULTIPLE_SELECTED) {
            return;
        }
        RvMealClicked = true;
        //设置当前操作的食品
        mCurrentOrderDetailBean = datasBean;
        loadComboData(datasBean, true);
    }

    public void foodGroupItemClick(Food datasBean) {
        RvMealClicked = false;
        if (!foodGroupConditionFilter(datasBean, false)) {
            return;
        }
        datasBean.setSelected(true);
        switchFoodByParentId(datasBean.getId());
        updateOrderFoodNumber();
        updateFoodSoldoutCtrData();
    }

    public void foodItemClick(Food datasBean) {
        RvMealClicked = false;
        if (mMealCartAdapter.getSelectedMode() == MealCartAdapter.MULTIPLE_SELECTED) {
            return;
        }
        if (!foodConditionFilter(datasBean)) {
            return;
        }
        if (datasBean.getIsParent() == 0) {
            switchFoodByParentId(datasBean.getId());
        } else {
            mCurrentOrderDetailBean = OrderDetail.foodTransOrderDetails(datasBean, 1);
            int customType = datasBean.ableDiscountCastCustomType();
            if (customType != Food.CUSTOM_TYPE_100) {
                //自定義食品
                mRootView.setCustomFoodDialog(customType, mCurrentOrderDetailBean);
            } else {
                //加載套餐食品
                loadComboData(mCurrentOrderDetailBean, false);
            }
        }
    }

    public void modifierItemClick(Modifier datasBean) {
        RvMealClicked = false;
        if (!modifierConditionFilter(datasBean)) {
            return;
        }
        if (cutOutModifier(datasBean) == -100) {
            //已送單數量已等於最大數，不能繼續添加
            return;
        }
        fineItemClick(datasBean);
        //更新賬單數
        updateOrderFoodNumber();
        //沽清細項沽清數
        updateModifierSoldoutCtrData();
    }

    public void comboItemClick(ComboItem datasBean) {
        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);
        //沽清子食品沽清數
        updateComboItemSoldoutCtrData();
        //更新賬單金額
        updateBillInfo();
        //更新賬單數
        updateOrderFoodNumber();
    }

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

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

        //更新賬單金額
        updateBillInfo();

        updateFineFragmentSoldoutList();

        mRootView.setMealRvScrollToPosition(addPosition);
    }

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

        Food food = mModel.queryFoodByFlu(plu);

        if (food == null) {
            mRootView.showMessage("未找到該食品!");
            return;
        }
        //查找成功清除输入框
        mRootView.clearKeyBoardInput();

        setFoodComboStatus(food);

        //添加食品到購物車
        int addPosition = mMealCartAdapter.addFoodItem(OrderDetail.foodTransOrderDetails(food, 1));
        mRootView.setMealRvScrollToPosition(addPosition);

        updateOrderFoodNumber();
    }

    public void discountAndCouponClick(AbstractDiscount discountBean) {
        if (!discountAndCouponConditionFilter()) {
            return;
        }
        if (discountBean instanceof MemberWalletCoupon) {
            mMealCouponAction.setSelectMixOrderMealList(getSelectMixOrderMealList());
            mMealCouponAction.action((MemberWalletCoupon) discountBean);
        } else if (discountBean instanceof Discount) {
            mMealDiscountAction.setSelectMixOrderMealList(getSelectMixOrderMealList());
            mMealDiscountAction.action((Discount) discountBean);
        } else {
            //TODO
        }
    }

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

    private int addFoodItem(OrderDetail orderDetail) {
        int addPosition = mMealCartAdapter.addFoodItem(orderDetail);
        if (orderDetail.getComboLevel() > 0) {
            if (mComboList != null && mComboList.size() > 0) {
                for (int i = 0; i < mComboList.size(); i++) {
                    //自动添加组合子食品
                    ComboItem comboItem = mComboList.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 = mMealCartAdapter.addFoodItem(OrderDetail.modifierTransOrderDetail(modfier, id, mCurrentOrderDetailBean.getProductId(), defNumber));
                }
            }
        }
        return addPosition;
    }

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

    private void loadComboData(OrderDetail food, boolean isSelectedMeal) {
        Observable.create(new ObservableOnSubscribe<List>() {
            @Override
            public void subscribe(ObservableEmitter<List> emitter) throws Exception {
                long fid = food.getProductId();
                int itemType = food.getItemType();
                List<ComboItem> comboItemList = new ArrayList<>();
                if (itemType == 1) {
                    //获取套餐细项数据
                    List<ComboItem> comboItems = mModel.queryDB_ComboList(fid, BaseOrder.orderType);
                    comboItemList.addAll(comboItems);
                }
                List<Modifier> modifierList = mModel.queryDB_ModifierList(fid, ModifierDaoUtils.modifierMode_All);

                emitter.onNext(comboItemList);
                emitter.onNext(modifierList);
                emitter.onComplete();
            }
        })
                .compose(RxSchedulerUtils._io_main_o())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new Observer<List>() {

                    private int nextCount = 0;
                    private List<ComboItem> comboItemList;
                    private List<Modifier> modifierList;

                    @Override
                    public void onSubscribe(Disposable d) {
                        addDispose(d);
                        nextCount = 0;
                    }

                    @Override
                    public void onNext(List list) {
                        nextCount++;
                        if (nextCount == 1) {
                            comboItemList = list;
                            //設置默認選中套餐食品
                            setComboDefModifier(comboItemList);
                            //更新套餐数据
                            updateComboData(comboItemList);
                        } else {
                            modifierList = list;
                            //設置默認選中細項
                            setModifierDefModifier(modifierList);
                            //更新细项数据
                            updateModifierData(modifierList);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onComplete() {
                        boolean autoMod = false;
                        if (comboItemList != null) {
                            if (modifierList != null) {
                                autoMod = food.getAutoMod() == 1 && (comboItemList.size() > 0 || modifierList.size() > 0);
                            } else {
                                autoMod = food.getAutoMod() == 1 && comboItemList.size() > 0;
                            }
                        }
                        if (mRootView.getCurrentViewMode() != MealConstant.fine_ViewMode && isSelectedMeal || autoMod) {
                            mRootView.setCurrViewMode(MealConstant.combo_ViewMode);
                        }
                        toAddFoodItem(mCurrentOrderDetailBean);
                    }
                });
    }

    public void toAddFoodItem(OrderDetail foodItem) {
        if (!RvMealClicked) {
            //新增食品
            addFoodItemBefore(foodItem);
            //更新沽清食品數量
            updateFoodSoldoutCtrData();
            //更新賬單金額
            updateBillInfo();
        }
        updateOrderFoodNumber();
    }

    private void addDiscountItem(Discount discount) {
        //主食品ID
        long id = getCurrParentFoodId();
        mCurrentOrderDetailBean = OrderDetail.discountTransOrderDetail(discount, true, id, getDisountSourcePrice());
        int addPosition = mMealCartAdapter.addFoodItem(mCurrentOrderDetailBean);
        mRootView.setMealRvScrollToPosition(addPosition);
        //更新賬單金額
        updateBillInfo();
    }

    private void addCouponItem(MemberWalletCoupon walletCoupon) {
        //主食品ID
        long id = getCurrParentFoodId();
        mCurrentOrderDetailBean = OrderDetail.couponTransOrderDetail(walletCoupon, true, id, getDisountSourcePrice());
        int addPosition = mMealCartAdapter.addFoodItem(mCurrentOrderDetailBean);
        mRootView.setMealRvScrollToPosition(addPosition);
        //更新賬單金額
        updateBillInfo();
    }

    /**
     * 刪除食品
     *
     * @param deleteStyle 1=點擊刪除、2=長按刪除
     */
    public void deleteFoodItem(int deleteStyle) {
        if (mMealCartAdapter.getSelectedMode() == MealCartAdapter.MULTIPLE_SELECTED) {
            //只有單選操作的時候可以刪除子項
            return;
        }
        if (!mMealCartAdapter.canDeleteFood()) {
            return;
        }
        //未選擇食品時，設置默認選擇最後一個
        if (mMealCartAdapter.getSelect_position() == -1) {
            if (getOrderFoodLists().size() > 0) {
                mMealCartAdapter.setSelectPosition(getOrderFoodLists().size() - 1);
            }
        }
        OrderDetail deleteFood = getOrderFoodLists().get(mMealCartAdapter.getSelect_position());
        if (!deleteFood.isNew()) {
            //TODO 刪除已下單食品
            if (!deleteFood.isModify()) {
                LoganManager.w_tableMode(TAG, LoganManager.EVENT_CLICK + "已下單食品【" + deleteFood.getProductName() + "】");
                mRootView.showCancelFoodDialog(deleteFood);
            }
        } else {
            if (deleteStyle == 2) {
                LoganManager.w_tableMode(TAG, LoganManager.EVENT_DELETE + "食品【" + deleteFood.getProductName() + "】");
                mMealCartAdapter.removeAllNewFoodItem();
            } else {
                LoganManager.w_tableMode(TAG, LoganManager.EVENT_DELETE + "食品【" + deleteFood.getProductName() + "】");
                int deletePosition = mMealCartAdapter.removeFoodItem();
                mRootView.setMealRvScrollToPosition(deletePosition);
                //更新最大可選數
                if (deleteFood != null) {
                }
            }
            updateMealSoldoutCtrData();
        }
        updateOrderFoodNumber();
    }

    /**
     * 刪除子項
     */
    public void deleteChildItem() {
        if (mMealCartAdapter.getSelectedMode() != MealCartAdapter.SINGLE_SELECTED) {
            //只有單選操作的時候可以刪除子項
            return;
        }
        final List<OrderDetail> orderFoodLists = getOrderFoodLists();
        if (orderFoodLists.size() == 0) {
            mRootView.showViewModeVisibility(MealConstant.food_group_ViewMode, MealConstant.food_ViewMode);
            return;
        }
        final OrderDetail selectOrderItem = orderFoodLists.get(mMealCartAdapter.getSelect_position());
        if (selectOrderItem == null) {
            return;
        }
        if (mRootView.getCurrentViewMode() == MealConstant.discount_ViewMode && selectOrderItem.getProp() == OrderDetail.DISCOUNT_PROP) {
            //當點選折扣操作 不可删除食品
            return;
        }
        if (!mMealCartAdapter.canDeleteChildItem()) {
            return;
        }
        final OrderDetail selectComboEndItem = orderFoodLists.get(mMealCartAdapter.getSelect_full_end_position());

        //刪除子項
        mMealCartAdapter.removeChildItem();

        updateCouponSelects(selectComboEndItem);
        //更新細項沽清數
        updateFineFragmentSoldoutList();
        updateComboItemSoldoutCtrData();
        updateModifierSoldoutCtrData();
        //更新賬單金額
        updateBillInfo();
        //更新選中數量
        updateOrderFoodNumber();
    }

    /**
     * 更新會員優惠券選中數
     */
    private void updateCouponSelects(OrderDetail selectComboEndItem) {
        if (selectComboEndItem != null && selectComboEndItem.getWalletCoupon() != null) {
            //刪除會員優惠券
            mRootView.updateCouponSelects(false);
        }
    }

    /**
     * 標記需刪除食品
     *
     * @param maxNumber
     * @param deleteNumber
     * @param reasonId
     */
    public void markDeleteFood(int maxNumber, int deleteNumber, int reasonId, String reason) {
        String ids = getSelectedOldFoodIds();
        if (TextUtils.isEmpty(ids)) {
            return;
        }
        List<OrderDetail> oldOrders = getSelectedOldFoodAndDiscount();
        for (OrderDetail item : oldOrders) {
            //保存取消前的數量
            item.setModifyBeforeNumber(item.getNumber());
            //將數量標記成已刪除
            int afterDeleteNumber = item.getNumber() - deleteNumber;
            if (afterDeleteNumber > 0) {
                item.setNumber(afterDeleteNumber);
            } else {
                item.setNumber(0);
            }
            if (item.getNumber() != 0) {
                //更新食品金额
                item.setPrice(item.getNumber() * item.getUnit_price());
            }
            item.setCancelReason(reason);
            item.setReasonId(reasonId);
            item.setCancelNumber(deleteNumber);
        }
        mMealCartAdapter.notifyDataSetChanged();

        //將取消信息保存到訂單信息類中
        DeleteOrderRequest request = getDeleteOrderRequest(ids, reasonId, maxNumber, deleteNumber);
        mMealOrder.addDeleteMealOrder(request);

        //更新賬單金額
        updateBillInfo();
    }

    /**
     * 恢復標記刪除的食品
     */
    public void restoreDeleteFood() {
        for (OrderDetail item : mOrderMealList) {
            if (!item.isModify()) {
                continue;
            }
            item.setNumber(item.getModifyBeforeNumber());
            item.setModifyBeforeNumber(0);
            item.setCancelReason("");
            item.setReasonId(0);
            item.setCancelNumber(0);
            if (item.getNumber() != 0) {
                //恢复食品金额
                item.setPrice(item.getNumber() * item.getUnit_price());
            }
        }
        mMealOrder.setDeleteMealOrders(null);
        mMealCartAdapter.notifyDataSetChanged();
        //更新賬單金額
        updateBillInfo();
    }

    /**
     * 更新公共細項頁沽清數據
     */
    private void updateFineFragmentSoldoutList() {
        EventBus.getDefault().post(mSoldoutCtrList, MealFineAllFragment.UPDATE_FINE_DATA_EVENT);
    }

    /**
     * 打印上菜紙
     */
    private void printSendOrder() {
        if (MealOrder.getInstance().getNewFoodList() == null || MealOrder.getInstance().getNewFoodList().size() <= 0) {
            //沒有新的食品時，不打印送單
            mRootView.returnBeforeActivity(true);
            return;
        }
        if (RestaurantExpandInfoUtils.getValue(ExpandConstant.AutoPrinterPaper, true)) {
            if (RestaurantExpandInfoUtils.getValue(ExpandConstant.MergeSendFood, true)) {
                //合并主食品
                mergeMainFoodNumber(mOrderMealList);
            }
            PrintContent printContent = new PrintContentAdapter().adaptationSendOrderPaperContent(MealOrder.getInstance(), mTableInfo);
            CC.obtainBuilder(ComponentName.COMPONENT_PRINT)
                    .setActionName("printActivity")
                    .addParam(PrintConstans.PRINT_TYPE, PrintConstans.PRINT_SERVE)
                    .addParam(PrintConstans.PRINT_CONTENT, printContent)
                    .addParam(PrintConstans.PRINT_ORDER_NO, MealOrder.getInstance().getOrderNo())
                    .build()
                    .callAsyncCallbackOnMainThread((cc, result) -> {
                        if (result.isSuccess()) {
                        } else {
                            mRootView.showMessage(printError);
                        }
                        //打印成功
                        mRootView.returnBeforeActivity(true);
                    });
        } else {
            mRootView.returnBeforeActivity(true);
        }
    }

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

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

    private int getCutPositionByOutLimitModifier(Modifier modifier) {
        int mainOrderNumber = 1;
        int oldCount = 0;
        SparseArray<String> numberAndCutPositionMap = new SparseArray<>();
        OrderDetail currentMainOrderDetail = mMealCartAdapter.getCurrentMainOrderDetail();
        if (currentMainOrderDetail != null) {
            int start_position = mMealCartAdapter.getSelect_full_start_position();
            int end_position = mMealCartAdapter.getSelect_full_end_position();
            for (int i = mOrderMealList.size() - 1; i >= 0; i--) {
                if (start_position <= i && i <= end_position) {
                    OrderDetail item = mOrderMealList.get(i);
                    if (item.getItemType() == 1) {
                        mainOrderNumber = item.getNumber();
                    }
                    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 = modifier.getSelectQty() * mainOrderNumber;
            if (numberAndCutPositionStr.length > 1 && !TextUtils.isEmpty(numberAndCutPositionStr[1])) {
                int cutPosition = Integer.parseInt(numberAndCutPositionStr[1]);
                if (maxQty <= number && cutPosition < mOrderMealList.size()) {
                    return cutPosition;
                }
            } else {
                if (oldCount == maxQty) {
                    return -100;
                }
            }
        }
        return -1;
    }

    private int getCutPositionOutLimitCombo(ComboItem comboItem) {
        int mainOrderNumber = 1;
        int oldCount = 0;
        SparseArray<String> numberAndCutPositionMap = new SparseArray<>();
        OrderDetail currentMainOrderDetail = mMealCartAdapter.getCurrentMainOrderDetail();
        if (currentMainOrderDetail != null) {
            int start_position = mMealCartAdapter.getSelect_full_start_position();
            int end_position = mMealCartAdapter.getSelect_full_end_position();
            for (int i = mOrderMealList.size() - 1; i >= 0; i--) {
                if (start_position <= i && i <= end_position) {
                    OrderDetail item = mOrderMealList.get(i);
                    if (item.getItemType() == 1) {
                        mainOrderNumber = item.getNumber();
                    }
                    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() * mainOrderNumber;
            if (numberAndCutPositionStr.length > 1 && !TextUtils.isEmpty(numberAndCutPositionStr[1])) {
                int cutPosition = Integer.parseInt(numberAndCutPositionStr[1]);
                if (maxQty <= number && cutPosition < mOrderMealList.size()) {
                    return cutPosition;
                }
            } else {
                if (oldCount == maxQty) {
                    return -100;
                }
            }
        }
        return -1;
    }

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

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

    /**
     * 添加多選細項
     */
    public int addMultipleModifierItems(Modifier modifierItem, int addPosition) {
        int overIndex = 0;
        for (int i = 0; i < mOrderMealList.size(); i++) {
            if (overIndex > i) {
                continue;
            }
            OrderDetail item = mOrderMealList.get(i);
            if (item.getSelected() != 0) {
                if (item.getItemType() == 1) {
                    int j = i;
                    int insertPosition = getEndInsertPosition(mOrderMealList, item, i);
                    if (insertPosition != -1) {
                        if (insertPosition < mOrderMealList.size()) {
                            j = insertPosition + 1;
                        } else {
                            j = insertPosition;
                        }
                    }
                    overIndex = j;
                    long id = item.isNew() ? item.getProductId() : item.getId();
                    OrderDetail modifierTransOrderDetail = OrderDetail.modifierTransOrderDetail(modifierItem, id, item.getProductId(), 1);
                    mOrderMealList.add(j, modifierTransOrderDetail);
                    setIndex(mOrderMealList);
                }
            }
        }
        //重新更新下標
        mMealCartAdapter.setIndex();
        mMealCartAdapter.notifyDataSetChanged();
        return addPosition;
    }

    private int getEndInsertPosition(List<OrderDetail> newOrderList, OrderDetail orderDetail,
                                     int currentI) {
        boolean hasChildFood = false;
        for (int i = currentI; i < newOrderList.size(); i++) {
            OrderDetail item = newOrderList.get(i);
            if (item.getItemType() == 2) {
                continue;
            }
            //往下找
            int nextIndex = i + 1;
            if (newOrderList.size() == nextIndex) {
                //最後一個
                return nextIndex;
            }
            if (item.getItemType() == 1) {
                hasChildFood = mMealCartAdapter.hasChildFood(item);
            }
            OrderDetail nextItem = newOrderList.get(nextIndex);
            if (item.getItemType() == 1) {
                if (hasChildFood) {
                    if (nextItem.getItemType() != 3) {
                        return i;
                    }
                } else {
                    return i;
                }
            } else {
                if (hasChildFood) {
                    if (nextItem.getItemType() == 1 || nextItem.getItemType() == 2) {
                        return i;
                    }
                } else {
                    if (nextItem.getItemType() == 1) {
                        return nextIndex;
                    }
                }

            }
        }
        return -1;
    }

    /**
     * 设置关联父子项Index
     */
    public void setIndex(List<OrderDetail> mInfos) {
        // 调整myorder中的parent_index及my_index
        int parent_index = 0;
        int my_index = 0;
        int my_index2 = 0;
        int t = 0;
        // 调整myorder中的顺序位
        // 获取旧项目的最后的seqno不是新项目开始
        int iseqno = 1;
        int isseq = 0;
        int imseq = 0;
        for (int i = 0; i < mInfos.size(); i++) {
            OrderDetail myorder = mInfos.get(i);
            t = t + 1;
            if (myorder != null) {
                switch (myorder.getItemType()) {
                    case 1:
                        parent_index = parent_index + 1;
                        my_index = t;
                        my_index2 = t;
                        myorder.setParentIndex(0);
                        myorder.setMyIndex(t);
                        break;
                    case 2:
                        myorder.setParentIndex(my_index);
                        myorder.setMyIndex(t);
                        my_index2 = t;
                        break;
                    case 3:
                        myorder.setParentIndex(my_index2);
                        myorder.setMyIndex(t);
                        break;
                }
            }
        }
    }

    /**
     * 更新食品數據
     *
     * @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());
    }

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

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

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

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

    /**
     * 標識食品是否为组合食品
     *
     * @param foodList
     */
    private void setFoodComboListStatus(List<Food> foodList) {
        for (int i = 0; i < foodList.size(); i++) {
            Food datasBean = foodList.get(i);
            List<FoodCombo> foodComboList = mModel.isComboFood(datasBean.getId());
            if (foodComboList.size() > 0) {
                datasBean.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 {
                        if (!modifier.getDefmodifier().equals("1")) {
                            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 {
                        if (!comboItem.getDefmodifier().equals("1")) {
                            comboItem.setDefmodifier("0");
                        }
                    }
                }
            }
        }
    }

    /**
     * 更新食品，子項，細項沽清數據
     */
    public void updateMealSoldoutCtrData() {
        updateFoodSoldoutCtrData();
        updateComboItemSoldoutCtrData();
        updateModifierSoldoutCtrData();
    }

    /**
     * 更新食品沽清數據
     */
    public void updateFoodSoldoutCtrData() {
        if (mSoldoutCtrList.size() > 0) {
            clearFoodSoldoutCtrData();
            addFoodSoldoutCtrItem(mSoldoutCtrList);
            setFoodSoldoutCtrData(mSoldoutCtrList);
        }
    }

    /**
     * 更新套餐食品沽清数据
     */
    public void updateComboItemSoldoutCtrData() {
        if (mSoldoutCtrList.size() > 0) {
            updateFoodSoldoutCtrData();
            mRootView.notifyComboAdapterAdapter();
        }
    }

    /**
     * 更新細項沽清數據
     */
    public void updateModifierSoldoutCtrData() {
        if (mSoldoutCtrList.size() > 0) {
            clearModifierSoldoutCtrData();
            addModifierCtrItem(mSoldoutCtrList);
            setModifierSoldoutCtrData(mModifierList, mSoldoutCtrList);
            mRootView.notifyModifierAdapterAdapter();
        }
    }

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

    public void setFoodSoldoutCtrData(List<SoldoutCtrFood> soldoutCtrFoods) {
        for (SoldoutCtrFood scc : soldoutCtrFoods) {
            for (Food foodGroupBean : mFoodGroupList) {
                if (scc.getType() == FOOD_TYPE && scc.getFoodId() != null && foodGroupBean.getId() != null && foodGroupBean.getId().equals(scc.getFoodId())) {
                    String qtyName = scc.getQtyName();
                    foodGroupBean.setMaxNumber(qtyName);
                    foodGroupBean.setCurrentMaxNumber(qtyName);
                    setFoodMaxQty(foodGroupBean);
                }
            }
            for (Food foodBean : mFoodList) {
                if (scc.getType() == FOOD_TYPE && scc.getFoodId() != null && foodBean.getId() != null && foodBean.getId().equals(scc.getFoodId())) {
                    String qtyName = scc.getQtyName();
                    foodBean.setMaxNumber(qtyName);
                    foodBean.setCurrentMaxNumber(qtyName);
                    setFoodMaxQty(foodBean);
                }
            }
        }
        for (Food foodGroupBean : mFoodGroupList) {
            if (foodGroupBean.getInvisible() == 2) {
                String qtyName = "暫停";
                foodGroupBean.setMaxNumber(qtyName);
                foodGroupBean.setCurrentMaxNumber(qtyName);
                setFoodMaxQty(foodGroupBean);
            }
        }
        for (Food foodBean : mFoodList) {
            if (foodBean.getInvisible() == 2) {
                String qtyName = "暫停";
                foodBean.setMaxNumber(qtyName);
                foodBean.setCurrentMaxNumber(qtyName);
                setFoodMaxQty(foodBean);
            }
        }

        if (mComboList != null) {
            for (SoldoutCtrFood scc : soldoutCtrFoods) {
                for (ComboItem comboItem : mComboList) {
                    if (scc.getType() == FOOD_TYPE && scc.getFoodId() != null && comboItem.getFid() != null && comboItem.getFid().equals(scc.getFoodId())) {
                        String qtyName = scc.getQtyName();
                        comboItem.setMaxNumber(qtyName);
                        comboItem.setCurrentMaxNumber(qtyName);
                        setComboItemMaxQty(comboItem);
                    }
                }
            }
            for (ComboItem comboItem : mComboList) {
                if (comboItem.getInvisible() == 2) {
                    String qtyName = "暫停";
                    comboItem.setMaxNumber(qtyName);
                    comboItem.setCurrentMaxNumber(qtyName);
                    setComboItemMaxQty(comboItem);
                }
            }
        }
        mRootView.notifyFoodGroupAdapter();
        mRootView.notifyFoodAdapter();
    }

    private void addModifierCtrItem(List<SoldoutCtrFood> soldoutCtrFoods) {
        if (mModifierList != null) {
            for (Modifier modifier : mModifierList) {
                if (modifier.getInvisible() == 2) {
                    SoldoutCtrFood soldoutCtrFood = new SoldoutCtrFood();
                    soldoutCtrFood.setType((byte) MODIFIER_TYPE);
                    soldoutCtrFood.setStop(true);
                    soldoutCtrFood.setFoodName(modifier.getModifierName());
                    soldoutCtrFood.setFoodName1(modifier.getModifierName1());
                    soldoutCtrFood.setFoodName2(modifier.getModifierName2());
                    soldoutCtrFood.setModifierId(modifier.getMid());
                    if (!isContainModifier(soldoutCtrFoods, modifier)) {
                        soldoutCtrFoods.add(soldoutCtrFood);
                    }
                }
            }
        }
    }

    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());
                if (!isContainFood(soldoutCtrFoods, foodGroupBean)) {
                    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);
                if (!isContainFood(soldoutCtrFoods, foodBean)) {
                    soldoutCtrFoods.add(soldoutCtrFood);
                }
            }
        }
    }

    private void clearFoodSoldoutCtrData() {
        for (Food foodGroupBean : mFoodGroupList) {
            foodGroupBean.setMaxNumber("");
            foodGroupBean.setCurrentMaxNumber("");
        }
        for (Food foodBean : mFoodList) {
            foodBean.setMaxNumber("");
            foodBean.setCurrentMaxNumber("");
        }
        if (mComboList != null) {
            for (ComboItem comboItem : mComboList) {
                comboItem.setMaxNumber("");
                comboItem.setCurrentMaxNumber("");
            }
        }
    }

    private void clearModifierSoldoutCtrData() {
        if (mModifierList != null) {
            for (Modifier modifier : mModifierList) {
                modifier.setMaxNumber("");
                modifier.setCurrentMaxNumber("");
            }
        }
    }

    private boolean isContainFood(List<SoldoutCtrFood> soldoutCtrFoods, Food food) {
        for (SoldoutCtrFood soldoutCtrFood : soldoutCtrFoods) {
            if (soldoutCtrFood.getType() == FOOD_TYPE && soldoutCtrFood.getFoodId() == food.getId()) {
                return true;
            }
        }
        return false;
    }

    private boolean isContainModifier(List<SoldoutCtrFood> soldoutCtrFoods, Modifier
            modifier) {
        for (SoldoutCtrFood soldoutCtrFood : soldoutCtrFoods) {
            if (soldoutCtrFood.getType() == MODIFIER_TYPE && soldoutCtrFood.getModifierId() == modifier.getMid()) {
                return true;
            }
        }
        return false;
    }

    /**
     * 设置当前食品还可最多选几份
     *
     * @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;
    }

    public void setComboItemMaxQty(ComboItem comboItem) {

        int currentSelectNumber = 0;

        for (int i = 0; i < getNewOrderFoodLists().size(); i++) {
            OrderDetail orderFood = getNewOrderFoodLists().get(i);
            if (orderFood.getProductId() == comboItem.getFid()) {
                currentSelectNumber += orderFood.getNumber();
            }
        }
        String User_Qty = comboItem.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) {
                    comboItem.setCurrentMaxNumber("售罄");
                } else {
                    comboItem.setCurrentMaxNumber(Currrent_OR_Qty + "");
                }
            }
        }
        mRootView.notifyComboAdapterAdapter();
    }

    public void setModifierMaxQty(Modifier modfier) {

        int currentSelectNumber = 0;

        for (int i = 0; i < getNewOrderFoodLists().size(); i++) {
            OrderDetail orderFood = getNewOrderFoodLists().get(i);
            if (orderFood.getMid() == modfier.getMid()) {
                currentSelectNumber += orderFood.getNumber();
            }
        }
        String User_Qty = modfier.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) {
                    modfier.setCurrentMaxNumber("售罄");
                } else {
                    modfier.setCurrentMaxNumber(Currrent_OR_Qty + "");
                }
            }
        }
        mRootView.notifyModifierAdapterAdapter();
    }

    /**
     * 添加食品条件过滤
     * 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("Comm.pause", "已暫停");
            CommonTipDialog.showSurpisedDialog(mRootView.getActivity(), 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("Comm.pause", "已暫停");
            CommonTipDialog.showSurpisedDialog(mRootView.getActivity(), 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(mRootView.getActivity(), msg, null, null, null, null, null);
                return false;
            }
        }
        if (!memberPointsCondition(foodBean.getPointsRedeem(), foodBean.getFoodName())) {
            return false;
        }
        return true;
    }

    private boolean comboConditionFilter(ComboItem comboItem) {
        long Invisible = comboItem.getInvisible();
        if (Invisible == 2) {
            String msg = "[" + comboItem.getName() + "]" + LanguageUtils.get_language_system("Comm.pause", "已暫停");
            CommonTipDialog.showSurpisedDialog(mRootView.getActivity(), 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(mRootView.getActivity(), msg, null, null, null, null, null);
                return false;
            }
        }
        if (!memberPointsCondition(comboItem.getPointsRedeem(), comboItem.getName())) {
            return false;
        }
        return true;
    }

    /**
     * 積分是否滿足條件
     *
     * @param pointsRedeem
     * @return
     */
    public boolean memberPointsCondition(double pointsRedeem, String foodName) {
        if (mTakeawayOrder != null) {
            //外賣新訂單 不需要驗證
            return true;
        }
        MemberInfo memberInfo = mMealOrder.getMemberInfo();
        if (memberInfo == null) {
            //当前食品需要会员积分
            if (pointsRedeem > 0) {
                mRootView.showMessage(LanguageUtils.get_language_system("unused_members_can.not.order.food", "積分食品，未使用會員，不可點選") + "\"" + foodName + "\"");
                return false;
            }
        } else {
            //如果没有会员，则pointsadd=5是加5分  pointsredeem=5是減5分
            //當一張臺號沒有會員登錄時判定積分為0 不能為負數
            //此時call pointsredeem=5  的食物   不給過
            //點選pointsadd=5的食物  0+5 是正數  這個給過
            if (pointsRedeem > 0 && memberInfo.getMemberPoint() < pointsRedeem) {
                mRootView.showMessage(LanguageUtils.get_language_system("insufficient.points.can.not.selected", "積分食品，會員積分不足，不可點選") + "\"" + foodName + "\"");
                return false;
            }
        }
        return true;
    }

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

    private boolean discountAndCouponConditionFilter() {
        //折扣金額是否>0
        if (Double.doubleToLongBits(getDisountSourcePrice()) == 0) {
            return false;
        }
        return true;
    }

    /**
     * 獲取所要折扣金額
     *
     * @return
     */
    private double getDisountSourcePrice() {
        double discount = 0.0;
        int start_position = mMealCartAdapter.getSelect_full_start_position();
        int end_position = mMealCartAdapter.getSelect_full_end_position();
        for (int i = 0; i < mOrderMealList.size(); i++) {
            if (start_position <= i && i <= end_position) {
                OrderDetail orderDetailsBean = mOrderMealList.get(i);
                if (orderDetailsBean.getProp() == OrderDetail.DISCOUNT_PROP) {
                    //折上折減去以折扣金額
                    discount = MoneyUtil.sum(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;
    }

    /**
     * 獲取當前選中的套餐食品組
     *
     * @return
     */
    private List<OrderDetail> getSelectMixOrderMealList() {
        List<OrderDetail> mixOrderMealList = new ArrayList<>();
        int start_position = mMealCartAdapter.getSelect_full_start_position();
        int end_position = mMealCartAdapter.getSelect_full_end_position();
        for (int i = 0; i < mOrderMealList.size(); i++) {
            if (start_position <= i && i <= end_position) {
                mixOrderMealList.add(mOrderMealList.get(i));
            }
        }
        return mixOrderMealList;
    }

    /**
     * 獲取當前選擇主食品ID
     *
     * @return
     */
    private long getCurrParentFoodId() {
        long id = 0;
        if (mMealCartAdapter.getCurrentMainOrderDetail() != null) {
            if (mCurrentOrderDetailBean.isNew()) {
                id = mMealCartAdapter.getCurrentMainOrderDetail().getProductId();
            } else {
                id = mMealCartAdapter.getCurrentMainOrderDetail().getId();
            }
        }
        return id;
    }

    /**
     * 更新食品組，食品選中數量
     */
    public void updateOrderFoodNumber() {
        updateFoodBtnNumber();
        updateFoodGroupBtnNumber();
        mRootView.setOrderFoodCount(getOrderFoodNumber());
    }

    private void updateFoodBtnNumber() {
        for (int i = 0; i < mFoodList.size(); i++) {
            Food foodBean = mFoodList.get(i);
            foodBean.setNumber(0);
            int iNumber = 0;
            for (int j = 0; j < mOrderMealList.size(); j++) {
                OrderDetail datasBean = mOrderMealList.get(j);
                if (datasBean.isNew() && datasBean.getProductId() == foodBean.getId()) {
                    iNumber = iNumber + datasBean.getNumber();
                    foodBean.setNumber(iNumber);
                }
            }
        }
        mRootView.notifyFoodAdapter();
    }

    private void updateFoodGroupBtnNumber() {
        List<OrderDetail> orderDetailList = getOrderFoodLists();
        for (int i = 0; i < mFoodGroupList.size(); i++) {
            Food foodGroupBean = mFoodGroupList.get(i);
            foodGroupBean.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() == foodGroupBean.getId()) {
                        iNumber = iNumber + food.getNumber();
                        foodGroupBean.setNumber(iNumber);
                    }
                }
            }
        }
        mRootView.notifyFoodGroupAdapter();
    }

    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() && order.getItemType() != 3) {
                    i = i + order.getNumber();
                }
            }
        }
        return String.valueOf(i);
    }

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

        DeleteOrderRequest request = new DeleteOrderRequest();
        request.setMapsDelete(mapsDelete);
        request.setOrderId(orderId);
        request.setTableId(mTableInfo.getId());
        request.setTableNumber(mTableInfo.getTableNumber());
        request.setType(type);
        request.setReasonId(reasonId);
        return request;
    }

    /**
     * 取消食品對應 id + number
     *
     * @param ids
     * @param maxNumber
     * @param deleteNumber
     * @return
     */
    private List<DeleteOrderRequest.DeleteBean> getMapsDelete(String ids, int maxNumber,
                                                              int deleteNumber) {
        List<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(request);
        }
        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 LoadFineEvent getLoadFineData(int currFinePage) {
        long productId = 0;
        if (mCurrentOrderDetailBean != null) {
            productId = mCurrentOrderDetailBean.getProductId();
        }
        //加載細項數據
        List<SoldoutCtrFood> soldoutCtrList = mSoldoutCtrList;
        int selectedMode = mMealCartAdapter.getSelectedMode();
        LoadFineEvent fineEvent = new LoadFineEvent();
        fineEvent.setProductId(productId);
        fineEvent.setCurrFinePage(currFinePage);
        fineEvent.setSelectedMode(selectedMode);
        fineEvent.setSoldoutCtrFoods(soldoutCtrList);
        return fineEvent;
    }

    public OrderDetail getCurrentOrderDetailBean() {
        return mCurrentOrderDetailBean;
    }

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

}
