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

import android.app.Application;
import android.graphics.Color;
import android.text.TextUtils;
import android.widget.BaseAdapter;

import com.billy.cc.core.component.CC;
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.database.bean.FoodCombo;
import com.gingersoft.gsa.cloud.database.bean.Food;
import com.gingersoft.gsa.cloud.database.bean.Modifier;
import com.gingersoft.gsa.cloud.database.utils.FoodDaoUtils;
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.request.OrderRequest;
import com.gingersoft.gsa.cloud.table.mvp.model.constant.MealConstant;
import com.gingersoft.gsa.cloud.table.mvp.ui.activity.MealStandActivity;
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.SelectMealAdapter;
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.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.List;

import javax.inject.Inject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
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;


/**
 * ================================================
 * 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 FoodAdapter mFoodAdapter;
    private ComboAdapter mComboAdapter;
    //食品数据
    private List<Food> mFoodGroupList = new ArrayList<>();
    private List<Food> mFoodList = new ArrayList<>();
    //套餐细项数据
    private List<FoodCombo> mFoodComboList = new ArrayList<>();

    private List<FoodCombo> mCurrentFoodComboList;
    private OrderDetail mCurrentOrderDetailBean;

    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);
            //默認選中第一組
            mFoodGroupList.get(0).setSelected(true);

            IActivity.initFoodGroupView(mFoodGroupList);

            changedMealByParentId(mFoodGroupList.get(0).getId());
        }
    }

    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);
            mRootView.setFoodAdapter(mFoodAdapter);
        }
        if (mComboAdapter == null) {
            mComboAdapter = new ComboAdapter(IActivity, mFoodComboList);
            mRootView.setComboAdapter(mComboAdapter);
        }
    }

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

            @Override
            public void onItemClick(OrderDetail datasBean, int position) {
                RvMealClicked = true;
                mRootView.recordOperat(true);
                mSelectMealAdapter.setMyOrderManageSelectPosition();
                loadComboData(datasBean, true);
            }

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

            }

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

            }
        });
        mFoodAdapter.setOnItemClickListener(new FoodAdapter.OnItemClickListener() {

            @Override
            public void onItemClick(Food datasBean, int position) {
                mRootView.recordOperat(true);
                if (!foodConditionFilter(datasBean)) {
                    return;
                }
                RvMealClicked = false;
                mCurrentOrderDetailBean = OrderDetail.foodTransOrderDetails(datasBean, 1);
                addFoodItemBefore(mCurrentOrderDetailBean);
                updateOrderFoodNumber();
            }
        });
        mComboAdapter.setOnItemClickListener(new ComboAdapter.OnItemClickListener() {

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

                mRootView.recordOperat(true);

                RvMealClicked = false;

//                Food orderBean = isParentFood(datasBean.getFID());
//                if (orderBean != null && !foodConditionFilter(orderBean)) {
//                    return;
//                }

//                if (datasBean.isModKeyboard()) {
//                    addModalKeyBoardModfier(datasBean.getModifier());
//                    displayModalKeyBoardDialog();
//                } else {
                if (datasBean.isModifier()) {
                    addModifierItem(datasBean.getModifier());
                } else {
                    //设置当前操作的套餐细项
                    mCurrentOrderDetailBean = OrderDetail.comboTransOrderDetail(datasBean, 1, "combo", RvMealClicked);
                    //先清除上一次选择的子项最大数
//                        mModel.clearComboQty();
                    //添加子项
                    addComboItem(mCurrentOrderDetailBean);
                }
//                }
            }
        });
    }

    private void addFoodItemBefore(OrderDetail datasBean) {

        loadComboData(mCurrentOrderDetailBean, false);

        int addPosition = addFoodItem(datasBean);

        //这里主食品作为选中主体
        mRootView.setMealRvScrollToPosition(addPosition);
    }

    private int addFoodItem(OrderDetail orderDetail) {

        int addPosition = mSelectMealAdapter.addFoodItem(orderDetail);

        if (orderDetail.getComboLevel() > 0) {
            //自动添加组合子食品
            if (mCurrentFoodComboList != null && mCurrentFoodComboList.size() > 0) {
                for (int i = 0; i < mCurrentFoodComboList.size(); i++) {
                    FoodCombo foodComboItem = mCurrentFoodComboList.get(i);
                    mCurrentOrderDetailBean = OrderDetail.comboTransOrderDetail(foodComboItem, 1, "combo", RvMealClicked);
                    addPosition = addComboItem(mCurrentOrderDetailBean);
                }
            }
        }

//        if (mAutoModifierList != null && mAutoModifierList.size() > 0) {
//            //自动添加mixqty>1細項
//            for (int i = 0; i < mAutoModifierList.size(); i++) {
//                Modifier.DatasBean modfier = mAutoModifierList.get(i);
//                mSelectMealAdapter.addFoodItem(myOrderManage.modifierConvertOrderDetail(modfier));
//            }
//        }

        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) {
        mCurrentOrderDetailBean = OrderDetail.modifierTransOrderDetail(datasBean, 1);
        int addPosition = mSelectMealAdapter.addFoodItem(mCurrentOrderDetailBean);
        mRootView.setMealRvScrollToPosition(addPosition);
    }

    private void loadComboData(OrderDetail food, boolean isSelectedMeal) {

        long fid = food.getProductId();
        if (mCurrentFoodComboList == null) {
            mCurrentFoodComboList = new ArrayList<>();
        } else {
            mCurrentFoodComboList.clear();
        }

        if (food.getItemType() == 1) {
            //获取套餐细项数据
            mCurrentFoodComboList = mModel.queryDB_ComboList(fid);
        }

        List<Modifier> modifierList = mModel.queryDB_ModifierList(fid);

        for (int i = 0; i < modifierList.size(); i++) {
            Modifier modfier = modifierList.get(i);
            /**
             * 这里套餐细项和备注使用同一个rv显示，统一数据源
             */
            {
                //设置备注细项背景、字体颜色
                modfier.setBgColor(Color.parseColor("#ffeb3b"));

                FoodCombo foodComboItem = new FoodCombo();
                foodComboItem.setModifier(true);
//                if (modfier.isParent()) {
//                    foodComboItem.setModKeyboard(modfier.isModKeyboard());
//                }
                foodComboItem.setModifier(modfier);

                mCurrentFoodComboList.add(foodComboItem);
            }
        }
        //更新套餐细项数据
        updateComboData(mCurrentFoodComboList);

//        if (food.getAutoMod() == 1) {
        if (isSelectedMeal) {
            mRootView.showViewModeVisibility(MealConstant.combo_ViewMode);
        }
//        }
    }

    public void createOrder() {
        OrderRequest request = getCreateOrderRequest(getNewOrderFoodLists());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), JsonUtils.toJson(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()) {
                            mRootView.showMessage("送單成功");
                            printSendOrder(MyOrderManage.getInstance().getOrderFoodList());
                            IActivity.returnTableActivity(true);
                        } else {
                            mRootView.showMessage("送單失敗");
                        }
                    }
                });
    }

    public void addOrderFood() {
        List<OrderDetail> newFoods = getNewOrderFoodLists();
        for (OrderDetail food : newFoods) {
            food.setOrderId(MyOrderManage.getInstance().getOrderId());
        }
        List<OrderBean.OrderDetailsBean> orderBeans = OrderBean.transOrderDetails(newFoods);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), JsonUtils.toJson(orderBeans));
        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(newFoods);
                            mRootView.killMyself();
                        } else {
                            if (getNewOrderFoodLists().size() == 0) {
                                //未新增食品點擊送單 後台不讓過直接提示即可
                                mRootView.showMessage("送單成功");
                                if (OpenTableManage.getDefault() != null) {
                                    //通知更新餐台状态
                                    EventBus.getDefault().post(OpenTableManage.getDefault().getTableBean().getId(), "initTable_status_event");
                                }
                                printSendOrder(newFoods);
                                mRootView.killMyself();
                            } else {
                                mRootView.showMessage("送單失敗");
                            }
                        }
                    }
                });
    }

    /**
     * 打印上菜紙
     */
    private void printSendOrder(List<OrderDetail> newFoods) {
        MyOrderManage.getInstance().setNewFoodList(newFoods);
        CC.obtainBuilder("Component.Print")
                .setActionName("printActivity")
                .addParam("type", 3)
                .build()
                .callAsync((cc, result) -> {
                    if (result.isSuccess()) {
                        //打印成功
                    }
                });


        //打印上菜紙
//        CC.obtainBuilder("Component.Print")
//                .setActionName("printActivity")
//                .addParam("NewFoods", newFoods)
//                .addParam("type", 0)
//                .build()
//                .callAsync((cc, result) -> {
//                    if (result.isSuccess()) {
//                        //打印成功
//                        mRootView.killMyself();
//                    }
//                });
    }

    public void deleteFood() {

        String ids = getDeleteFoodIds();
        if (TextUtils.isEmpty(ids)) {
            return;
        }
        RequestBody requestBody = new FormBody.Builder()
                .add("ids", ids)
                .build();

        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 && 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 = OrderDetail.orderTransOrderDetails(info.getData().getOrderDetails());
                                orderFoodList.addAll(orderDetailList);
                            }

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

                            mSelectMealAdapter.notifyDataSetChanged();
                            mSelectMealAdapter.setIndex();
                        } else {
                            mRootView.showMessage("刪除失敗");
                        }
                    }
                });
    }

    public void sendOrder() {
        if (MyOrderManage.getInstance().getOrderId() == -1) {
            createOrder();
        } else {
            addOrderFood();
        }
    }

    private void deleteWithOrderedFoodById(long id) {
        QMUIDialog.MessageDialogBuilder dialogBuilder = new QMUIDialog.MessageDialogBuilder(IActivity);
        dialogBuilder.setTitle("溫馨提示");
        dialogBuilder.setMessage("是否確認刪除該食品?");
        dialogBuilder.addAction("取消", (dialog, index) -> dialog.dismiss());
        dialogBuilder.addAction(0, "確認", QMUIDialogAction.ACTION_PROP_NEGATIVE, (dialog, index) -> {
            dialog.dismiss();
//            int deletePosition = mSelectMealAdapter.removeFoodItem();
//            mRootView.setMealRvScrollToPosition(deletePosition);
            deleteFood();
        });
        dialogBuilder.create(R.style.QMUI_Dialog).show();
    }

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

        if (getOrderFoodLists().size() == 0 || mSelectMealAdapter.getSelect_position() >= getOrderFoodLists().size()) {
            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 刪除已下單食品
            deleteWithOrderedFoodById(deleteFood.getId());
        } else {
            if (deleteStyle == 2) {
                mSelectMealAdapter.removeAllNewFoodItem();
            } else {
                int deletePosition = mSelectMealAdapter.removeFoodItem();
                mRootView.setMealRvScrollToPosition(deletePosition);
            }
        }
        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().equals("discount")) {
            //當點選折扣操作 不可删除食品
            return;
        }
        if (!getOrderFoodLists().get(mSelectMealAdapter.getSelect_position()).isNew()) {
            //已下单子项不可删除
            return;
        }
        if (getOrderFoodLists().get(mSelectMealAdapter.getSelect_position()) != null) {
            mSelectMealAdapter.removeChildItem();
            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);
        }
        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();
    }

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

        int currentSelectNumber = 0;

        for (int i = 0; i < getOrderFoodLists().size(); i++) {
            OrderDetail orderFood = getOrderFoodLists().get(i);
            if (orderFood.getId() == foodBean.getId()) {
                currentSelectNumber += orderFood.getNumber();
            }
        }

//        String User_Qty = foodBean.getOR_Qty();
//        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.setCurrrent_OR_Qty("售罄");
//                    return false;
//                } else {
//                    foodBean.setCurrrent_OR_Qty(Currrent_OR__Qty + "");
//                }
//            }
//        }
        return true;
    }

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

        if (init) {
            return true;
        }

//        String User_Qty = foodBean.getOR_Qty();
//        if (!TextUtils.isEmpty(User_Qty)) {
//            TitleDialog.showTitledialog(IActivity, foodBean.getName()
//                            + LanguageUtils.get_language_system(IActivity, "Comm.pause", "已暫停(Comm.pause)"),
//                    "", LanguageUtils.get_language_system(IActivity, "comm.ok", "ok(comm.ok)"), "", null);
//            return false;
//        }

        return true;
    }

    private boolean foodConditionFilter(Food foodBean) {

        long Invisible = foodBean.getInvisible();

        if (Invisible == 2) {
            mRootView.showMessage("已售罄");
            return false;
        }

//        String User_Qty = foodBean.getCurrrent_OR_Qty();
//
//        if (!TextUtils.isEmpty(User_Qty)) {
//            if (User_Qty.equals("售罄") || User_Qty.equals("暫停")) {
//                TitleDialog.showTitledialog(IActivity, foodBean.getName()
//                                + LanguageUtils.get_language_system(IActivity, "Comm.pause", "已暫停(Comm.pause)"),
//                        "", LanguageUtils.get_language_system(IActivity, "comm.ok", "ok(comm.ok)"), "", null);
//                return false;
//            }
//        }
//
//        if (GSAApplication.tableContract.getMember() == null) {
//            //当前食品需要会员积分
//            if (foodBean.getPointsRedeem() > 0) {
//                mRootView.showMessage(LanguageUtils.get_language_system(mApplication, "unused_members_can.not.order.food", "積分食品，未使用會員，不可點選") + "\"" + foodBean.getName() + "\"");
//                return false;
//            }
//        } else {
//            if (GSAApplication.tableContract.getMember().getDatas() != null) {
//                //如果没有会员，则pointsadd=5是加5分  pointsredeem=5是減5分
//                //當一張臺號沒有會員登錄時判定積分為0 不能為負數
//                //	此時call pointsredeem=5  的食物   不給過
//                //點選pointsadd=5的食物  0+5 是正數  這個給過
//                if (foodBean.getPointsRedeem() > 0 && GSAApplication.tableContract.getMember().getDatas().getData().getMemberPoint() < foodBean.getPointsRedeem()) {
//                    mRootView.showMessage(LanguageUtils.get_language_system(mApplication, "insufficient.points.can.not.selected", "積分食品，會員積分不足，不可點選") + "\"" + foodBean.getName() + "\"");
//                    return false;
//                }
//            }
//        }

        return true;
    }

    private 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 < orderFoodList.size(); j++) {
                OrderDetail datasBean = orderFoodList.get(j);
                if (datasBean.isNew() && datasBean.getId() == foodBean.getId()) {
                    iNumber = iNumber + datasBean.getNumber();
                    foodBean.setNumber(iNumber);
                }
            }
        }
        mFoodAdapter.notifyDataSetChanged();
    }

    private void setFoodGroupBtnNumber(FoodGroupAdapter adapter, List<Food> foodGroupList) {
        for (int i = 0; i < foodGroupList.size(); i++) {
            Food foodBean = foodGroupList.get(i);
            foodBean.setNumber(0);
            int iNumber = 0;
            if (getOrderFoodLists() != null) {
                for (int j = 0; j < getOrderFoodLists().size(); j++) {
                    OrderDetail food = getOrderFoodLists().get(j);
                    if (food.isNew() && food.getId() == 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);
    }

    /**
     * 標識食品是否为组合食品
     *
     * @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);
        }
    }

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

    private void updateFoodData(List<Food> foodList) {
        setFoodComboListStatus(foodList);
        mFoodList.clear();
        mFoodList.addAll(foodList);
        //根据Item个数显示每一行的个数
        mRootView.setFoodRecycleSpanCount(mFoodList.size());
        mFoodAdapter.notifyDataSetChanged();
    }

    private void updateComboData(List<FoodCombo> foodComboList) {
        mFoodComboList.clear();
        mFoodComboList.addAll(foodComboList);
        //根据Item个数显示每一行的个数
        mRootView.setComboRecycleSpanCount(mFoodComboList.size());
        mComboAdapter.notifyDataSetChanged();
    }

    public boolean isRvMealClicked() {
        return RvMealClicked;
    }

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

    public OrderDetail getCurrentOrderDetailBean() {
        return mCurrentOrderDetailBean;
    }
}
